defined? method in Ruby and Rails defined? method in Ruby and Rails ruby ruby

defined? method in Ruby and Rails


First: actually, defined? is an operator.

Second: if I understand your question correctly, the way to do it is with this Ruby idiom:

perex ||= true

That'll assign true to perex if it's undefined or nil. It's not exactly what your example does, since yours doesn't evaluate the assignment when the value is nil, but if you are relying on that then, in my opinion, without seeing it, you're not writing clear code.

Edit: As Honza noted, the statement above will replace the value of perex when it's false. Then I propose the following to rewrite the minimum number of lines:

perex ||= perex.nil?  # Assign true only when perex is undefined or nil


The safest way of testing if a local is defined in a Rails template is:

local_assigns[:perex]

This is documented in the Rails API together with the explanation that defined? cannot be used because of a implementation restriction.


Per mislav's answer, I went looking for that documentation in the Rails API, and found it in Class ActionView::Base (under the heading "Passing local variables to sub templates"). It was hardly worth the search, though, since it barely said anything more than mislav did. Except that it recommends this pattern:

if local_assigns.has_key? :perex