Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to call method in one application from another application in ruby on rails

I want to call the method and get the response in my application from another application in Ruby on Rails technology, but here cross site scripting problem is there. so, i can i resolve this issue please help me it would be great.

http://video_tok.com/courses/get_course

def get_course
  @course = Course.find(params[:id])
end

now i want to call this above method from this application which is running in edupdu.com domain

http://edupdu.com/call_course_method

def call_course_method
  @course = redirect_to "http://video_tak.com/courses/get_course/1"
end

but it would be redirect into video_tak.com application. i want to call get_course method and get @course object internally without redirect to another site.

Thanks in advance.

like image 699
user1328875 Avatar asked Oct 21 '22 03:10

user1328875


1 Answers

Cross-domain AJAX is indeed a problem, but none that could not be solved. In your get_course method you could return the course objects as a JSON response like so:

render json: @course

From there on you could either retrieve the course through JavaScript (AJAX), here you should use JSONP or inside Rails by issuing a HTTP GET request.

  1. AJAX with JSONP

    There is JSONP (JSON with padding), which is a communication technique for JavaScript programs to provide a method to request data from a server in a different domain. Look at the documentation of jQuery.getJSON() and scroll down to the JSONP section.

    If the URL includes the string "callback=?" (or similar, as defined by the server-side API), the request is treated as JSONP instead. See the discussion of the jsonp data type in $.ajax() for more details.

  2. HTTP GET request

    Simply use the Net::HTTP class:

    require 'net/http'
    require 'json'
    
    url = URI.parse('http://video_tak.com/courses/get_course/1')
    req = Net::HTTP::Get.new(url.to_s)
    res = Net::HTTP.start(url.host, url.port) do |http|
      http.request(req)
    end
    course_json = JSON.parse(res.body)
    

    If you provide methods for your model to convert JSON into a domain object of yours, you can take it from there.


RPC

You can also use RPC to invoke methods between different Ruby processes, although I recommend this the least I do not want to omit it. There are several remote procedure call (RPC) libraries. The Ruby standard library provides DRb, but there are also implementations based on Ruby on Rails, for instance the rails-xmlrpc gem which allows you to implement RPC based on the XML-RPC protocol or the alternative protocol using JSON with json-rpcj

You will probably find even more libraries when searching for Rails RPC. From whatever library you pick, the concrete solution will differ.

like image 93
Konrad Reiche Avatar answered Oct 24 '22 05:10

Konrad Reiche