can't dup NilClass when using Sanitize gem - ruby-on-rails

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.

Related

What is the difference between find and find_by?

I know from the rails documentation that find will result in a RecordNotFound error. However, the find_by method simply returns nil if a record is not found. Returning nil seems more intuitive to me and safe in general, so I am wondering if there is any benefit in using the find method over the find_by method?
For example, what is the difference between the following:
myRecord.find(1)
and
myRecord.find_by(id: 1)
If the only difference is that find raises an error when a record isn't found, I don't really see the benefit in using find.
EDIT
For all the people that jumped on my question and said that it had been already answered, you are wrong. I clearly stated that I knew find returns an error when a record is not found (which is what everyone else emphasizes in their answers) and that find_by returns nil. I want to know if there are any other differences.
In your specific example there is little difference between the two of them other than the error vs nil which you mention. Whether you want to handle an error or nil is totally up to you.
For a great explanation of understanding when an error is preferable to nil and vice versa read this.
If you are searching by an attribute other than id using find will not work as it can only access elements by their id.

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 to use embedded ruby in ActionMailer subject

I'm trying to use some embedded ruby in the subject line of an email coming from ActionMailer but keep getting different errors.
I couldn't find any documentation on the proper syntax. Any resources to fix this line of code?
mail(to: #user.email, subject: "Your Reservation Confirmation for" + #restaurant.name)
I've passed in all of the variables fine. I just need to see how I can combine text and these inputs.
Thanks
There are two common ways to it:
First:(regarding rep)
"...Confirmation for" + #restaurant.name.to_s
Second:
you can use string interpolation
"...Confirmation for #{#restaurant.name}"
I don't know whether this is intentional, but apparently #restaurant.name is returning a number (as you clarified, you're getting a TypeError: no implicit conversion of Fixnum into String). Calling #restaurant.name.to_s will solve that.
As G.B mentioned in another answer, string interpolation like "...Confirmation for #{#restaurant.name}" works too, since it calls #to_s for you automatically.
I'm putting the solution into an answer, since we found it while clarifying in the comments.

Trouble Accessing Ruby Array and Hash Value

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.

How to DRY up a ruby conditional structure needed for Rails

I'm finding I often have to use a structure to avoid a Rails error of undefined method 'name' for nil:NilClass.
The structure looks like this:
if country.state
country.state.name
end
It seems like a classic case of repeating oneself with country.state appearing twice in one simple block. Is there any way to DRY this up?
Rails adds a try method to object that mimics object#send but does not raise an exception if the object returns nil.
I think the syntax is
country.try(:state).name
Well not really. One option is to install the andand gem, but introducing a dependency for this may be a little much.
Other than using the slightly more concise syntax of:
country.state.name unless country.state.nil?
I don't think there's a DRY way to do this with the information given. I would argue that if you can't be sure whether country.state is nil or not, you may want to look at the code responsible for setting that value and determine whether that's a normal case or whether a validator upstream should be catching that.

Resources