0

I have 2 ruby on rails apps. With app A I post app B some data (in the form of a hash). I then want app B to send a hash on this data (with some modifications) back to app A in the response.
I have tried the code below

App A

response = Net::HTTP.post_form(uri, params)
quotes.push(response.body)

and in App B

details = get_details //returns a hash
respond_with details

But its not working. Is what im doing even possible? Is there a way I can place this hash in my response? Any help would be appreciated

2 Answers 2

1

Solution #1

If you use respond_with you need also specify formats which your app should respond to. For this you should use respond_to method.

Example:

class TestController < ApplicationController
    respond_to :json

    def index
        details = get_details
        respond_with(details)
    end
end

Also check this good article about respond_to method.

Solution #2

Just use render json: {...} in your controller action.

Example:

class TestController < ApplicationController
     def index
        details = get_details
        render json: details
    end
end


In your app A response.body will contain a string with the data from your app B. So you need to parse that string.

In your app A:

require 'json' # this is unnecessary if app A is a Rails app

response = Net::HTTP.post_form(uri, params)
parsed_response = JSON.parse(response.body)
quotes.push(parsed_response)
2
  • how would the json object appear in the response? in the response.body or somewhere else?
    – DTC
    Nov 29, 2013 at 18:57
  • Yes, it's correct. The response.body will contain the data. But you need to parse it. I've updated my answer, please check. Nov 30, 2013 at 13:32
0

The rails way to do that is using JSON as an exchange format. have a look at the guides for how to use that: http://guides.rubyonrails.org/layouts_and_rendering.html#rendering-json

It is also possible to use ActiveResource for such a communication. It allows direct access to your rails API.

3
  • 1
    It's not the "Rails" way to do it, it's bigger than that, it's the web-way now days. Frameworks and languages that support JSON do it for cross-language compatibility. Rails does it for that reason. Nov 29, 2013 at 15:15
  • @theTinMan you could also use XML :)
    – phoet
    Nov 29, 2013 at 15:17
  • 1
    Yes, but XML and/or using SOAP, is so 2000's. JSON is a lot more compact and immediately usable. We could use CSV too. Nov 29, 2013 at 15:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.