Trouble Accessing Ruby Array and Hash Value - ruby-on-rails

I am making an api call and receiving the following response (it's long, so I'm showing the important part):
... "fields":{"count"_1:["0"],"count_2":["5"]} ...
when I do:
call["fields"]["count_1"]
It returns
["0"]
I need it to give me just the integer. I tried:
call["fields"]["count_1"][0]
And I also tried:
call["fields"]["count_1"][0].to_i
I'm running this in Rails and it gives me the error:
undefined method `[]' for nil:NilClass
But it's not working.

Try as below using String#to_i
call["fields"]["count_1"][0].to_i # => 0

Some tips:
Try wrapping the API response in JSON.parse(...). That is, if you're not making the call via a gem that already does this. This might require 'json'.
Try call['fields']['count_1'].first.to_i
Do some debugging: check the value of call.class, call['fields'].class and call['fields']['count_1'].class. The last one should definitly be an Array.
Add an if clause to check if call['fields'][['count_1'].is_empty?.
Look for typos :)

For some reason the API call was making the zeros nil instead of zero. Thanks for all your help.

Related

NoMethodError undefined method `encoding' for nil:NilClass CGI.escape

came across this problem a little earlier today, anyone know what might be going on? I'm a rookie with api's. Tried Googling but not much luck so far..
Error:
NoMethodError in ArtistsController#index
undefined method `encoding' for nil:NilClass
the problem line is:
response = HTTParty.get("https://api.spotify.com/v1/search?q=#{CGI.escape params[:query]}&type=artist")
which makes me think it might be an issue with CGI.escape.
If I enter the following url with a query already at the end everything works fine:
http://localhost:3000/search?utf8=%E2%9C%93&query=Caribou&commit=Search
However, if enter the following url without a query I get the error mentioned above:
http://localhost:3000/search
Guess that explains the nil part, but I don't no how to get past this..
Think that's all the info I need to give for this issue but let me know if more is needed.
If params[:query] isn't defined, then CGI.escape is receiving a nil argument.
Make sure params[:query] is defined if you're referencing it, and/or don't call CGI.escape when searching by type only, and not keyword. (Assuming that's possible--that's what the empty search above seems to imply.)

How can I get last only if more than one?

In rails I have this:
page_classes.split(/\s/).last
Sometimes page_classes doesn't contain any whitespace and I get the error:
undefined method `last' for nil:NilClass
How can I get the last unless there is only one?
try this
page_classes.split(/\s/).try(:last)
The problem is about your page_classes object.
page_classes.split("\s").last
Calling .last will ALWAYS work with an array (even empty). If you have probems, it means your page_classes object is nil or not a string that can be processed by split().

How to parse response from Recurly ruby client

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.

Why does this Ruby statement throw an exception? (Arrays/Bools)

I'm not a Ruby guy, I just play one on television. I have to modify someone's old Cron job to pull down some JSON and convert it into objects.
Here's the code
raw_json = Net::HTTP.get(URI.parse("url removed to protect the innocent"))
tags = ActiveSupport::JSON.decode(raw_json)
puts tags.count
tags.count will accurately trace as 5, but THAT LINE immediately causes a crash as follows:
5 #the accurate count!
rake aborted!
undefined method `count' for false:FalseClass
What is the dealio?
What is the contents of raw_json? What appears to be happening is that ActiveSupport::JSON#decode is returning false (hence undefined method 'count' for false:FalseClass). I think JSON#decode only returns false when given an empty string, which would mean HTTP#get is returning an empty string. Check on raw_json and see if it contains what you expect.
so I have no idea what is going on here, but JSON.decode should give you a hash, which doesn't have a count method. It does have a size method though
tags.size
if that doesn't work, try doing p tags, or puts tags.class.name to try and figure out what you are working with
Apparently tags is false , which may mean that your Net::HTTP.get failed (I guess your URL is wrong).
Try to print tags to see what it is. (I guess anyway, that you should use a valid URI)
The problem is that:
>> ActiveSupport::JSON::decode("")
=> false
>> ActiveSupport::JSON::decode("false")
=> false
This is a very strange behavior.

can't dup NilClass when using Sanitize gem

Alright this probably is the worst error I have found ever.
I have two projects, both using same code:
Sanitize.clean(string, Sanitize::Config::BASIC)
but one works and another fails.
Problem is similar to this poor guy's post: https://stackoverflow.com/questions/2724342/cant-dup-nilclass-how-to-trace-to-offender
Could anybody help please?
This will happen if you pass nil into clean() instead of a string. Make sure your string variable is really a string.

Resources