Extract a value from an OpenStruct Ruby object - ruby

I get the following Ruby object returned (from a query to the Google Analytics API using the garb gem, comes from the sample call shown on the README.md there, Exits.results(profile, :filters => {:page_path.eql => '/'}))
> data.results
=> [#<OpenStruct page_path="/", exits="3706", pageviews="10440">]
I'd to extract the pageviews value (10440), but cannot figure out how to do it. I see that my object, data.results is class array of length 1, but data.first is class OpenStruct with a return value that looks almost identical:
irb(main):140:0> data.results.class
=> Array
irb(main):141:0> data.results.length
=> 1
irb(main):142:0> data.first
=> #<OpenStruct page_path="/", exits="3706", pageviews="10440">
irb(main):143:0> data.first.class
=> OpenStruct
while data itself seems to be a custom return type called ResultsSet:
irb(main):144:0> data.class
=> Garb::ResultSet
irb(main):145:0> data
=> #<Garb::ResultSet:0x00000002411070 #results=[#<OpenStruct page_path="/", exits="3706", pageviews="10440">], #total_results=1, #sampled=false>
irb(main):146:0>
Lots of data structures, but no idea how to get my desired value out. I gathered OpenStruct was related to a hash, so I thought data.first["pageviews"] would do it,
NoMethodError: undefined method `[]' for #<OpenStruct page_path="/", exits="3706", pageviews="10440">
from (irb):146
from /usr/bin/irb:12:in `<main>'
Meanwhile data.first.keys returns nil. No idea how to get my data out, (short of converting the length-1 array, data.results to a string and parsing with grep, which seems crazy. Any ideas?

Please try this:
data.first.pageviews

Related

Why the object returned is Enumerable?

I don't understand why do I get an Enumerable instead of an object. When I run this code :
- #posts.each do |post|
= Comment.find(id: post.id).title
I've got this error :
undefined method `title' for #Enumerator: Comment:find({:id=>1})>
If I check in the console I get also Enumerator :
[2] pry(#<Sinatra::Application>)> Comment.find 1
=> #<Enumerator: ...>
I just want to have my object like #<Comment #id=1 #content="great" #post_id=1>
I'm working with Sinatra and Datamapper.
The query you're looking for is:
Comment.first(id: post.id).title
Which is a short version of:
Comment.all(id: post.id).first.title
There is no find in Datamapper (that I know of). What you're actually seeing is the result of Ruby's Enumerable#find: http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-find, which must be a part of Datamapper objects.

http_request.set_form_data : Getting undefined method map for string for the json parameter

I am trying to pass a json representation to a set_form_data and am running into following error:
undefined method `map' for "{\"first_name\":\"bill\",\"last_name\":\"gates\"}":String
Here is how I create the request:
Net::HTTP::Post.new(uri.request_uri).set_form_data({"first_name" => "steve","last_name" => "jobs"}.to_json)
Anything I am missing ?
The error comes from the line:
/jruby/jruby-1.6.2/lib/ruby/1.9/net/http.rb:1593:in `set_form_data'
I used request.body=form_data instead of request.set_form_data and that worked.
However I dont know for sure why set_form_data did not work.
Marking this as an answer, since that's the one that worked for me so far.
set_form_data wants a hash, not a json, so skip the to_json and it should work better.
ie:
some_data = {:foo => :bar, :meh => :muh}
Net::HTTP::Post.new(uri.request_uri).set_form_data(some_data)

TypeError: can't convert Builder::XmlMarkup to Array

I'm having issues with getting access to the raw xml from a Builder::XmlMarkup object.
irb> xml = Builder::XmlMarkup.new(:target => '')
=> <pretty_inspect/>
irb> xml.foo("bar")
=> "<pretty_inspect/><foo>bar</foo>"
irb> puts xml
TypeError: can't convert Builder::XmlMarkup to Array (Builder::XmlMarkup#to_ary gives String)
from (pry):122:in `puts'
In a script where I'm using Builder to create the XML, I'm passing #xml to a POST:
response = HTTParty.post(API_ENDPOINT, :body => #xml)
This gives the same error:
TypeError (can't convert Builder::XmlMarkup to Array (Builder::XmlMarkup#to_ary gives String)):
Of course, if I do #xml.to_xml, it doesn't return an error, but it adds </to_xml> to the xml, meaning it isn't actually converting the XML object to xml. That's not what I want.
So how can I get access access to the xml so that I can pass it to my post without it adding extra nodes to my xml?
Edit: possible solution
Doing #xml.target! seems to resolve the issue, but I'm not sure I understand why.
response = HTTParty.post(API_ENDPOINT, :body => #xml.target!)
Perhaps someone can help me understand what is happening here.
Using
puts xml
is outputting the Builder::XmlMarkup object and hence give the error
Using
puts xml.target!
outputs the current xml string, which is what you want

How to get to_json work on BSON::Code object as well in mongo-ruby-driver

I am trying 'mongo-ruby-driver' for some project. It's working fine except when I call to_json on mongo object. It gives well formed json but it's not converting BSON::Code into readable value i resulting JSON.
Instead of showing code text, it show something like
#<BSON::Code:0x00000100af6fa8>
Did anyone tried it. Any help id highly appreciated.
UPDATE
here is some code snippet:
#records is variable that contains Array of MongoDB documents in hash.
#records.to_json
When I call to_json on it it gives everything as expected. except for the key that contain BSON::Code (means javascript code). for example consider following doc:
{
"_id" : "contains",
"value" : function( obj, target ) { return obj.indexOf(target) != -1; };
}
Querying same doc from ruby gives output like:
{
"_id"=>"contains",
"value"=><BSON::Code:2160165280 #data="function( obj, target ) { return obj.indexOf(target) != -1; };" #scope="{}">
}
and calling to_json on this gives following:
{"_id":"contains","value":"#<BSON::Code:0x00000100b54658>"}
this is what the problem is. Instead of getting actual code for 'value' key I am getting ruby object as string.
Calling code method on BSON::Code we can get it converted into code. But for that I need to loop mongo docs, check values for each key, calling code on it if it is an object of BSON::Code and then assigning it back to key. And at last we can call to_json on it. But I dont want this much overhead. I need to_json itself should take care of it.
The serializer that is iterating over the attributes of the objects in the array is probably calling the to_s method which would cause the output you are seeing.
You can either monkey patch the BSON::Code class to include a to_s method which calls inspect (the method that produces the output you want) or modify the serializer to detect when it encounters a BSON::Code instance and call inspect on it rather than to_s.
The code to mokey patch the BSON::Code class would look like this:
module BSON
class Code
def to_s
inspect
end
end
end
This would have the same behavior as inspect. If you just wanted the code you could monkey patch this in:
module BSON
class Code
def to_s
#code
end
end
end
I might make this the default behavior for to_s in the driver but for now just include that in your code and it should work like a champ.
Which Mongo object, do you mean the module? If you could, please post the code and what you are trying to do.
The only to_json I see in the driver is BSON::ObjectId#to_json which (from the docs) is described as a method that does the following:
Convert to MongoDB extended JSON format. Since JSON includes type information, but lacks an ObjectId type, this JSON format encodes the type using an $oid key.
I get the same results when I use it:
1.9.3-p0 :001 > require 'mongo'
=> true
1.9.3-p0 :002 > BSON::ObjectId
=> BSON::ObjectId
1.9.3-p0 :003 > BSON::ObjectId.new()
=> BSON::ObjectId('4f17350eadd361e91d000001')
1.9.3-p0 :004 > BSON::ObjectId.new().to_json
=> "{\"$oid\": \"4f173512add361e91d000002\"}"
BSON ( http://bsonspec.org/ ) is a binary representation of JSON ( http://www.json.org/ ) . JSON is not meant to be used to describe functions, as it is meant to be portable. Functions in this manner are not portable to other systems. So there is no way to serialize it. There is some hacks defined here that may get you what you need, but ultimately, BSON/JSON may be a weird tool for the job if your trying to serialize functions.

JSON object for just an integer

Silly question, but I'm unable to figure out..
I tried the following in Ruby:
irb(main):020:0> JSON.load('[1,2,3]').class
=> Array
This seems to work. While neither
JSON.load('1').class
nor this
JSON.load('{1}').class
works. Any ideas?
I'd ask the guys who programmed the library. AFAIK, 1 isn't a valid JSON object, and neither is {1} but 1 is what the library itself generates for the fixnum 1.
You'd need to do: {"number" : 1} to be valid json. The bug is that
a != JSON.parse(JSON.generate(a))
I'd say it's a bug:
>> JSON.parse(1.to_json)
JSON::ParserError: A JSON text must at least contain two octets!
from /opt/local/lib/ruby/gems/1.8/gems/json-1.1.3/lib/json/common.rb:122:in `initialize'
from /opt/local/lib/ruby/gems/1.8/gems/json-1.1.3/lib/json/common.rb:122:in `new'
from /opt/local/lib/ruby/gems/1.8/gems/json-1.1.3/lib/json/common.rb:122:in `parse'
from (irb):7
I assume you're using this: (http://json.rubyforge.org/)
JSON only supporting objects is simply not true -- json.org also does not suggest this imo. it was derived from javascript and thus especially strings and numbers are also valid JSON:
var json_string = "1";
var p = eval('(' + json_string + ')');
console.log(p);
// => 1
typeof p
// => "number"
ActiveSupport::JSON properly understands raw value JSON:
require 'active_support/json'
p = ActiveSupport::JSON.decode '1'
# => 1
p.class
# => Fixnum
and so does MultiJson:
require 'multi_json'
p = MultiJson.load '1'
# => 1
p.class
# => Fixnum
so, as a2800276 mentioned, this must be a bug.
but as of this writing, ruby 2's JSON has quirks_mode enabled by default when using the load method.
require 'json'
p = JSON.load '1'
# => 1
p.class
# => Fixnum
The first example is valid. The second two are not valid JSON data. go to json.org for details.
As said only arrays and objects are allowed at the top level of JSON.
Maybe wrapping your values in an array will solve your problem.
def set( value ); #data = [value].to_json; end
def get; JSON.parse( #data )[0]; end
From the very basics of what JSON is:
Data types in JSON can be:
Number
String
Json Object ... (and some more)
Reference to see complete list of Json data types
Now any Json data has to be encapsulated in 'Json Object' at the top level.
To understand why is this so, you can see that without a Json Object at the top level, everything would be loose and you could only have only one of the data type in the whole of Json. i.e. Either a number, a string, a array, a null value etc... but only one.
'Json Object' type has a fixed format of 'key' : 'value' pair.
You cannot store just the value. Thus you cannot have something like {1}.
You need to put in the correct format, i.e. 'key' : 'value' pair.

Resources