Checking if a "locals" variable is defined

In Rails to check whether a locals has been defined the method local_assigns.has_key has been created.

Trying to use it in MiddleMan generates an exception because the method does not exist. Using the defined(:whatever) doesn’t work as it always believe the variable is there when it is not.

How can I solve this issue?

Middleman’s partials have a locals hash that you can check:

locals            # => {:foo=>"bar"}
locals.key?(:foo) # => true
locals.key?(:baz) # => false

You can also check for the local variables directly:

defined?(foo) # => "local-variable"
defined?(baz) # => nil

Contrast with checking for symbols, which are always defined:

defined?(:foo) # => "expression"
defined?(:baz) # => "expression"
1 Like

Thank you very much Andrew. Your help is precious as usual.

Can you please tell me what’s the difference between :foo and foo then? What the column sign is supposed to do?

Thanks
Andrea

:foo is just a reusable name. You can use it like a number:

1    == 1    # => true
:foo == :foo # => true

1    == 2    # => false
:foo == :bar # => false

foo = 1    # => 1
foo = :foo # => :foo

1    = foo # => SyntaxError
:foo = foo # => SyntaxError

Symbols are often used as the keys in hashes since they’re lightweight and readable.