How do you print JSON from the mongdb ruby driver? - ruby

When I do a find query from the mongodb JavaScript console, I get a beautiful JSON response. However, when I do a find with the ruby driver, it stores the JSON as some Ruby object. How do I convert this back to JSON? Or, better yet, how do I just get the JSON without doing the extra conversions?

I got it working. I was using ruby-1.9.1-p378 with rvm. I removed that. Now, I'm using the system ruby-1.8.7-p174 that came with the SnowLeopard install DVD. But, I was still getting an error with the to_json method except this time it was saying, stack level too deep. I did:
require 'json/pure'
instead of
require 'json'
Then, I changed the code to look something like this:
http://github.com/banker/mongulator/blob/master/mongulator.rb#L53
Here's the relevant part of the code:
cursor = persons.find(
{"loc" => {"$near" => [params[:lat].to_f, params[:lng].to_f]}},
{:limit => 20})
content_type "application/json"
JSON.pretty_generate(cursor.to_a)
The complete file is here:
http://github.com/acani/acani-sinatra/blob/master/acani.rb
And, it worked, even with pretty json like the facebook graph api gives you. To return the JSON all on one line, just do something like:
cursor.to_a.to_json

The JSON Code you get on the javascript console is also converted. It's not the native output of MongoDB, the Native format is BSON. To Get JSON on the javascript console it must be converted. In Ruby you should be able to do the same thing with the .to_json instance method of your Object.

now you can do cursor.find.to_a.inspect

Related

Ruby github api not sending same response as irb?

When I run the following snippet of Ruby code in RubyMine, it responds with #<Github::Search:0x38d5b52>. However, when I run it in the irb shell, it responds appropriately with a large JSON object which is what I'm looking for. Anybody know why this is happening and how to fix it?
require 'github_api'
github= Github.new do |config|
config.endpoint = 'http://my.domain.com/api/v3'
config.site= 'http://github.com'
config.adapter = :net_http
end
puts github.repos.search("pushed:2014-06-20")
In IRB, the console is automatically calling #inspect on all returned objects. This often times confuses developers who are new to Rails, for example, who are led to believe that queries can't be chained together because they see #inspect being called, causing the query to execute.
My guess is that you're witnessing the same thing here.

How to use Bigquery streaming insertall on Ruby Rails

EDIT: Fixed - for ruby use "insert_all" instead of "insertAll" like the api specifies. The api for ruby needs updating.
Im using v 0.6.4 of the google-api-client gem and trying to create a streaming insert, but keep getting the following error:
google_bigquery.rb:233:in undefined method `insertAll' for #<Google::APIClient::Resource:0xcbc974 NAME:tabledata> (NoMethodError)
My code is as follows:
def streaming_insert_data_in_table(table, dataset=DATASET)
body = {"rows"=>[
{"json"=> {"person_id"=>1, "name"=>"john"}},
{"json"=> {"person_id"=>2, "name"=>"doe"}},
]}
result = #client.execute(
:api_method=> #bigquery.tabledata.insert_all,
:parameters=> {
:projectId=> #project_id.to_s,
:datasetId=> dataset,
:tableId=>table},
:body_object=>body,
)
puts result.body
end
Could someone tell me if the insetAll has been created for the google-api-client gem? I have tried 'insert' as that is what table, dataset etc use and get the same error as well.. I can however run tabledata.list perfectly fine.. I've tried digging throught the gem source code and didn't get anywhere with that.
Is the body object that I created correct or do I need to alter it?
Any help is much appreciated.
Thanks in advance and have a great day.
Ok. So fixed it and updated the code in the question. For ruby: the method is called "insert_all". Also note that the table & schema must be created BEFORE the insert_all. This id different when compared to the the "jobs.insert" method which will create the table if it doesn't exist

Render a view's output later via a delayed_job

If I render html I get html to the browser which works great. However, how can I get a route's response (the html) when being called in a module or class.
I need to do this because I'm sending documents to DocRaptor and rather than store the markup/html in a db column I would like to instead store record IDs and create the markup when the job executes.
A possible solution is using Ruby's HTTP library, Httparty or wget or something and open up the route and use the response.body. Before doing so I thought I'd ask around.
Thanks!
-- Update --
Here's something like what I ended up going with:
Quick tip - in case anyone does this and need their helper methods you need to extend AV with ApplicationHelper:
Here's something like what I ended up doing:
av = ActionView::Base.new()
av.view_paths = ActionController::Base.view_paths
av.extend ApplicationHelper #or any other helpers your template may need
body = av.render(:template => "orders/receipt.html.erb",:locals => {:order => order})
Link:
http://www.rigelgroupllc.com/blog/2011/09/22/render-rails3-views-outside-of-your-controllers/
check this question out, it contains the code probably want in an answer:
Rails 3 > Rendering views in rake task

What does HTTParty::get return?

I'm still new to Ruby and trying to use the HTTParty gem to help me write an API Wrapper. I feed HTTParty::get a URI and it parses JSON data. From a quick glance and the way the returned result behaves, it looks like a Hash, but is it? I can't seem to find information online. Another post on StackOverflow shows to use HTTParty::get(...).parsed_response to get the Hash, but this seems outdated.
Do this in the console:
>require 'httparty'
=> true
> response = HTTParty.get( "..." )
....
> response.class
=> HTTParty::Response
So the response from HTTParty.get is an HTTParty::Response object.
See this blogpost titled "It's Time To HTTParty!" to learn more about how to work this response.

How do I parsing data from JSON object?

I'm just starting to dabble in consuming a JSON web service, and I am having a little trouble working out the best way to get to the actual data elements.
I am receiving a response which has been converted into a Ruby hash using the JSON.parse method. The hash looks like this:
{"response"=>{"code"=>2002, "payload"=>{"topic"=>[{"name"=>"Topic Name", "url"=>"http://www.something.com/topic", "hero_image"=>{"image_id"=>"05rfbwV0Nggp8", "hero_image_id"=>"0d600BZ7MZgLJ", "hero_image_url"=>"http://img.something.com/imageserve/0d600BZ7MZgLJ/60x60.jpg"}, "type"=>"PERSON", "search_score"=>10.0, "topic_id"=>"0eG10W4e3Aapo"}]}, "message"=>"Success"}}
What I would like to know, is what is the easiest way to get to the "topic" data so I can do something like:
topic.name = json_resp.name
topic.img = jsob_resp.hero_image_url
etc
You can use Hashie's Mash . One of the best twitter clients for ruby uses it, and the resulting interface is very clean and easy to use. I've wrapped over Delicious rss api with it in less than 60 lines.
As usuall, the specs show very clearly how to use it.

Resources