Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if a variable is defined in rails?

<% if dashboard_pane_counter.remainder(3) == 0 %>   do something <% end> 

If dasboard_pane_counter wasn't defined, how can I get this to evaluate to false rather than throw an exception?

like image 240
cjm2671 Avatar asked Oct 18 '11 10:10

cjm2671


People also ask

How do you check if a variable has been defined?

Use the typeof operator to check if a variable is defined or initialized, e.g. if (typeof a !== 'undefined') {} . If the the typeof operator doesn't return a string of "undefined" , then the variable is defined.

How declare variable in Rails?

@title is an instance variable - and is available to all methods within the class. In Ruby on Rails - declaring your variables in your controller as instance variables ( @title ) makes them available to your view.

How do you define a class variable in Ruby?

Ruby Class VariablesClass variables begin with @@ and must be initialized before they can be used in method definitions. Referencing an uninitialized class variable produces an error. Class variables are shared among descendants of the class or module in which the class variables are defined.


2 Answers

<% if defined?(:dashboard_pane_counter) && dashboard_pane_counter.remainder(3) == 0  %>   # do_something here, this assumes that dashboard_pane_counter is defined, but not nil <% end %> 
like image 115
Matt Avatar answered Sep 28 '22 03:09

Matt


When using rails and instance variables, nil has a try method defined, so you can do:

<% if @dashboard_pane_counter.try(:remainder(3)) == 0  %>    #do something <% end %> 

so if the instance variable is not defined, try(:anything) will return nil and therefore evaluate to false. And nil == 0 is false

like image 43
Yule Avatar answered Sep 28 '22 05:09

Yule