Trying to do something simple in my view:
1: <% @rating = ratable.rating unless ratable.nil? -%>
2: <% @rating = rating unless rating.nil? %>
but whenever ratable is undefined, this fails with "undefined local
variable or method `ratable' ". How can I check if a variable is
defined? Shouldn't the .nil? do that for me?
I do this kind of stuff all the time, and the only cases which result
in what you describe are those in which I don't actually have the
local variable defined. Oftentimes, this occurs in a partial, but
I've done it elsewhere, too.
So referencing a non-existent variable will do it, but referencing a
variable set to nil will be fine.
Unlike instance variables, local variables don't spring into existence when referenced. If you're trying to pass information between the controller and a view, you can use instance variables which Rails arranges to magically "copy" into the new view object that it instantiates. If you don't assign the variable, the it springs to life in the view and has a value of nil.
If you really want to check, you can say:
@rating = ratable.rating if defined?(ratable) && ratable
which tells you something:
hi = "Hello"
def who; "World"; end
Rob Biedenharn http://agileconsultingllc.com