I have a scenario where I'm specifically looking for a String with the value of "nil". In short, I have a conditional where I want to pass nil if the user selects that option in the dropdown and not pass "nil", which is what gets passed in the params:
My Select:
<select name="parent_id">
<option name="All">All</option>
<option name="None" value="nil">None</option>
</select>
My condition:
if params[ :parent_id ].present?
Child.where( parent_id: params[ :parent_id ] ) # I want this to be IS NULL when params[ :parent_id ] == "nil"
end
Typically, you would use .nil? or .blank? on a String to check for a nil value or an empty String. But "nil".nil? and "nil".blank? both equal false, as they should.
So I'm curious if there's a good way to check for a String being "nil".
Currently I'm using myString == "nil" but that leads to things like ( myString == "nil" ? nil : myString ).
if params[ :parent_id ].present?
parent_id = params[ :parent_id ] == "nil" ? nil : params[ :parent_id ]
Child.where( parent_id: parent_id )
end
That's fine when it's used once in a while but if this is being used frequently, it's not ideal.
This a fairly rare occurrence, I know, but it was particularly difficult to Google so I thought I would ask SO.
My initial thoughts are:
- Add a method to
Stringso you could do something like"nil".nil_literal? #=> true. - Monkey patch
.presence?so that"nil".presence?returnsnilinstead of"nil".