I'm getting a strange error when trying to convert my object to json for an API connection. The following details my experience.
If I call
JSON.generate(self)
the output is
{"validation_context":null,"errors":{},"params":{"number":"123","name":"test"}}
I only need the params in my json object and when I call
JSON.generate(self.params) # or the next line
JSON.generate(#params) #params has been set on the object as an accessor
I get
undefined method `merge' for #<JSON::Ext::Generator::State:0x1043f1a38>
For some reason params is not considered a Hash. It serializes ok when I'm getting the parent object but fails otherwise. How can I serialize just the params?
Turns out I found a relatively simple solution.
Rather than
JSON.generate(object_to_serialize)
Using
object_to_serialize.to_json
Will work as intended.
Related
I've got a large data model in a Rails application that I'm trying to make serializable and output to JSON. I defined the #serializable_hash method on the model and blacklisted a few attributes. My goal is to whitelist attributes on the controller layer to accept back that same structure and simply ignore values that I don't want "accessible".
One such attribute is giving me trouble when I PUT update with the aforementioned JSON. I get an error while parsing request parameters:
SyntaxError (/Users/brad/.rvm/gems/ruby-1.9.3-p194#project-rails32/gems/actionpack-3.2.13/lib/action_dispatch/http/request.rb:261: syntax error, unexpected tINTEGER, expecting $end
...02933", "software_date"=>"09/05/14", "software_version"=>"10...
... ^):
# stack trace...
As far as Rails is concerned, this is just a string right? Why is it expecting an end of input here? For the record, taking this attribute out before submitting my request results in a successful update, so I'm sure this is what's causing the issue.
Turns out I'm the unluckiest guy in the world.
Familiarize yourself with Ruby's %Q() method, and you'll understand where I'm at.
Under my very very specific case, when Rails is parsing params for a request:
in JSON format
which has a key mapping to an Array
and any value under that Array contains a '/'
the parse will fail. Why?
My version of Rails (3.2.13) uses the AwesomePrint library version 0.3.2 when parsing out parameters for the params hash. The #grep method for that version of the gem evaluates matches using:
%Q/#{match}/
Simply because the specified delimiter is a '/', the evaluation fails and parsing crashes. DO NOT LET THIS HAPPEN TO YOU.
I am using tire/elasticsearch for searching with mongoid, when I update the index of my documents I am getting the error undefined method 'as_document':
#document.tire.update_index
undefined method `as_document' for #<Array:0x10a40f870>
I have researched the mongoid method 'as_document' and found out that it only accepts single objects. When my document objects do not have comments, "#document.as_document" returns a single object and there is no error, however when the document has comments, "#document.as_document" seems to return an array and returns the error "undefined method `as_document' for #".
It seems that when #document has comments, it returns an array of hashes.
Is there any way that I can return the array (Array:0x10a40f870) so I can see where it is coming from?
How can I convert #document (which seems to be an array) back into a single object so that it can pass through as_document?
Why am I getting an 'undefined method as_document'
I have a Document model with a has_many relationship to comments
Rails: 3.2.12,
Mongoid: 3.1.4
1. Logger is your homie. I would recommend printing this wherever your logic exists so you can see exactly what array you are returning.
Something like this:
# your logic here
#your_array = ..set
logger.debug "MY ARRAY: #{#your_array}"
This will give you at least a good look at what you are dealing with if you can take a look at Webrick or whatever setup you have.
2+3. Mongoid stores Documents as an array of hashes so that is what you are probably looking at (but I haven't seen the exact code).
I dont believe there is anything wrong with your document definitions but I would take a better look at the [Relations Sections] of the Mongoid docs1
More specifically to question 2: take a look at the operations section.
I've tried to use ActiveSupport's (2.3-stable) try() on an instance of HttpParty::Response. I've got a pretty strange behavior:
> ro.parsed_response
{"error"=>"RecordInvalid", "description"=>"Record validation errors", "details"=>{"email"=> [{"description"=>"Email: foo#bar.com is already taken by another user"}]}}
> ro.try(:parsed_response)
NoMethodError Exception: undefined method `parsed_response' for #<Hash:0x11397d5d8>
In the first example, I send the parsed_response message to ro by using the dot notation. It works fine. In the second one, I try to call it using ActiveSupport's try(), and it (surprisingly) raises the NoMethodError exception.
Shouldn't try() have returned nil in this case? And why doesn't it find the "parsed_response" method, if I can call it using the dot notation, as seen in the first example?
Thanks in advance!
Have no idea how, but seems like ro object was "transfered" into a hash that has been sent a parsed_response method.
In Rails 2.3#ruby 1.8 undefined method for object raises an exception.
Besides, docs stay only for calling try on nil object and nothing about the object that doesn't have a specific method:
Unlike that method however, a NoMethodError exception will not be
raised and nil will be returned instead, if the receiving object is a
nil object or NilClass.
I am trying to work with Recurly ruby client gem but getting frustrated on how to pass its response.
I'm doing a simple call to get a list of all my current plans ie
def plans
#result_object = Recurly::Plan.all
end
I believe its sending me a list of plans as an array as if I inspect the response I'm getting a bunch data ie. http://pastie.org/3086492
But if so how are you meant to parse the setup_fee_in_cents: when I am getting
setup_fee_in_cents: #<Recurly::Money USD: 0_00>
I have tried to convert the response to_hash but getting an error undefined method 'to_hash'
Has anyone used the recurly gem before or can shed some light on how I should parse the response.
Hope someone can advise.
I've never used the gem before but it appears as though it's returning you an object of type Recurly::Money. I would try reading the documentation on the Recurly::Money class to get a better idea of how to use it.
to_hash works fine on Recurly::Money object. Try updating your gem. I am using recurly 2.0.9.
r[0].unit_amount_in_cents.to_hash[:USD] gave me the price in cents.
I have an Activerecord object called Foo:
Foo.attribute_names.each do |attribute|
puts Foo.find(:all)[0].method(attribute.to_sym).call
end
Here I'm calling all attributes on this model (ie, querying for each column value).
However, sometimes, I'll get an undefined method error.
How can ActiveRecord::Base#attribute_names return an attribute name that when converted into its own method call, raises an undefined method error?
Keep in mind this only happens on certain objects for only certain methods. I can't identify a pattern.
Thank you.
The NoMethodError should be telling you which method does not exist for what object. Is it possible that your find returns no record? In that case, [][0] is nil and you will get a NoMethodError for sure.
I would use .fetch(0) instead of [0], and you will get a KeyError if ever there is no element with index 0.
Note: no need for to_sym; all builtin methods accept name methods as strings or symbols (both in 1.8 and 1.9)
Maybe something to do with access? Like if a class has an attr_protected attribute, or something along that line. Or for attributes that are not database columns, which have no accessors defined?