Parsing JSON feed with Ruby on Rails - ruby-on-rails

I know this has been covered over and over but I just can't understand how to get started. Am too much of a JSON virgin to know what's going on.
I'm trying to get some data from a json feed on a remote server into a rails3 application.
I understand I need the json gem but I have no idea how to pull the data.
If the url is something like this:
http://my-feed.com/json?res=service&s=table&table=User&start=0&max=5&sort=id&desc=true
How do I go about getting that from my application?
Any help, walk-throughs, tutorials appreciated

You are going to need to make an HTTP request for the resource, grab the response, and (potentially) parse it yourself - although I think HTTParty will do the JSON parsing for you. HTTParty would be my suggestion for making requests, though.
If you read the README, it links to examples of how to use HTTParty which you should find helpful. The basic example includes how to make a get request, inspect the headers and body, etc. I believe you can also use response.parsed_response to get the parsed response of whatever HTTParty's default parser is. There is also an example of using your own custom parsers (if you prefer another to HTTParty's).

I don't really know the json gem - does it only handle the parsing?
If yes, and you only need to pull in the information, try this:
require 'open-uri'
begin
json = open 'http://my-feed.com/json?res=service&s=table&table=User&start=0&max=5&sort=id&desc=true'
rescue
# a multitude of HTTP-related errors can occur
end
json_string = json.read
# parse

Related

ACRCloud webapi in Rails

I'm a newb hobbyist developer. Can I just throw this repo of their ACRCloud's ruby example code into a controller? I'd like to use an audio fingerprinting song recognition database as a name validation for songs users are uploading using paperclip. Not sure if it's possible, just starting to research it, any hints or suggestions would be appreciated.
Obviously I'd have to replace
file_name = ARGV[0]
etc, but I'm also wondering about the require 'openssl' etc
Definitely! But there are few points to be taken care of. That's a pure ruby script, when it comes to rails there are certain rules/best practices. One of which is thin controller and fat model..
You need to create a route/action in your app which will ask the app to execute this request with required params.
Write a method in your model which contains the code and call it from controller and pass the permitted params to it.
Instead of hardcoding your credentials in the model, make them environment variables.
Would suggest using Httparty gem wgich will reduce many lines of your code and you just need to pass headers, params, etc. as hash in the arguments.
Last, but not the least...if you notice..there's a puts in the end however, rails uses mvc and so you need to have a view for the controller action you created in step1. Return and save the response.body in the class variable like #response = res.body and you can play with the body depending on the response type.
Hope it helps..
P.S. I wish I could write few lines of code/optimise it for you but i m using my mobile right now. But I think this much information should be enough to convert that script to mvc rails structure..

Generate XML dynamically and post it to a web service in Rails

I am currently developing a Rails app in which I need to dynamically send XML request to an external web service. I've never done this before and I a bit lost.
More precisely I need to send requests to my logistic partner when the status of an order is updated. For instance when an order is confirmed I need to send data such as the customer's address, the pickup address, etc...
I intended to use the XML builder to dynamically generate the request and Net:HTTP or HTTParty to post the request, based on this example.
Is that the right way to do so? How can I generate the XML request outside the controller and then use it in HTTParty or Net:HTTP?
Thanks for your help,
Clem
That method will work just fine.
As for how to get the XML where you need it, just pass it around like any other data. You can use the Builder representation, which will automatically convert to a String as appropriate, or you can pass around a stringified (to_s) version of the Builder object.
If, for example, it makes sense for your model (which we'll call OrderStatus) to generate the XML, and for your controller to post the request:
# Model (order_status.rb)
def to_xml
xml = Builder::XmlMarkup.new
... # Your code here
xml
end
# Controller (order_statuses_controller.rb)
def some_method
#order_status = OrderStatus.find(:some_criteria)
... # Your code here
http = Net::HTTP.new("www.thewebservicedomain.com")
response = http.post("/some/path/here", #order_status.to_xml)
end
You may want to wrap the HTTP calls in a begin/rescue/end block and do something with the response, but otherwise it's all pretty straightforward and simple.
Make XML with Builder, then send it down the wire.
In your case it sounds like you may need to send several different requests as the order evolves; in that case:
Plan out what your possible order states are.
Determine what data needs to be sent for each state.
Decide how to represent that state within your models, so you can send the appropriate request when the state changes.
Where my example uses one method to generate XML, maybe you'll want 5 methods to handle 5 possible order states.

Finding sets in Rails

I'm a Rails noob, but I'd like to use it as a backend for an Ember application with Ember Data. Unfortunately, I have some unknown unknowns.
The RESTAdapter documentation says:
Comments for a post can be loaded by post.get('comments'). The REST
adapter will send a GET request to /comments?ids[]=1&ids[]=2&ids[]=3.
It will generate similar urls if you use something like App.Post.find({title: "Some Title"}), in about the format you'd expect: /posts?title=Some+Title
Is there some option, or gem I can use to handle that sort of simple query, or do I have to go parse parameters in my controllers manually?
To clarify, I'm aware that I can tell my Rails controller to return a set like:
#comments = Comment.find(params[:ids])
respond_with(#comments)
But it seems like querying on ids or accessible attributes like that would be a common enough use case for REST APIs that something would be built in, or have a gem written to handle it.
Can anyone point me in the right direction?
Thanks.
This might be helpful in your case:
https://github.com/ernie/ransack/
Or
https://github.com/ernie/squeel

Make Rails parse JSON from XDR Cross-Domain requests with content-type: nil

I'm building a client side application which cross-domain posts JSON, using CORS, to a Rails 3.2 application on a different server. Unfortunately, we need to support IE9, which means that we're falling back to using XDomainRequest (XDR) to send our cross-domain requests in IE.
The major limitation of XDR is that it doesn't support setting headers like 'Content-type', which means the Rails server doesn't know that it's receiving JSON, so doesn't parse it.
I got around this briefly by using jQuery.param to send the data as url encoded form data. However, some of the data we need to send is nested GeoJSON, which gets garbled by jQuery.param, so I have to send the POST body as JSON.
In config/initializers/wrap_parameters.rb I've set:
ActiveSupport.on_load(:action_controller)
wrap_parameters format: [:json, nil]
end
… so ActionController nests parameters inside model_name when the content-type is nil.
However, I still need Rails to try to JSON.parse() the data from requests where "Content-type" => nil. I could just manually do this in the controllers which need it (which isn't very clean), but I was hoping I would be able to make Rails do it for all {content-type: nil} requests.
I've been looking through the Rails source, and what I've found doesn't make me very hopeful. This method seems to be hard coded to check for :json, and parse if so, meaning I can't modify this from config:
https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/middleware/params_parser.rb#L43
Can anyone come up with a clever solution?

Is there any gem to send request to some service in xml format

I want to send request to some third party service in xml and also expecting response in xml. I'm searching for some gem or any idea how to do this.
Thing which is in my mind is to
make some partail _example.xml.builder
onclick from my view to some button send ajax request to controller action and use render_to_string to render that xml doc and then
Save it in some variable
and then call to that service method in same action
But it is not proper thing as I expect there should be some thing more efficient than my suggested thing
RoR doesn't natively use XML so some degree of conversion is required.
Having said that, XML generation is very simple in RoR applications. There are several ways of doing this, my favourite being constructing the required data as a Hash (which is native to Ruby) then the_hash.to_xml.
The XML conversion can also be defined in a model Class if you wish a consistent result:
class Example < ActiveRecord::Base
# ensure that only column1, column2, etc are output as XML
def to_xml(options = {})
super( options.merge( select(:column1, :column2, etc) ) )
end
end
Then in your controller:
poster = Example.find(123)
request = Net::HTTP.new('www.example.com', 80)
request.post('/path', poster.to_xml)
Hopefully the above demonstrates a simple example of posting XML data to a remote host. As you mentioned, a more complicated XML can be constructed using xml.builder
HTH and good luck.

Resources