35
<% 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?

cjm2671
  • 18,348
  • 31
  • 102
  • 161

6 Answers6

52
<% 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 %>
Matt
  • 17,290
  • 7
  • 57
  • 71
5

local_assigns can be used for that, since this question is from a few years ago, I verified that it exists in previous versions of rails

<% if local_assigns[:dashboard_pane_counter] 
                 && dashboard_pane_counter.remainder(3) == 0%>
<% end %>

It's in the notes here

http://apidock.com/rails/ActionController/Base/render

katzmopolitan
  • 1,371
  • 13
  • 23
5

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

Yule
  • 9,668
  • 3
  • 51
  • 72
0

Posting this answer for beginner coders like myself. This question can be answered simply using two steps (or one if using &&). It is a longer and less pretty answer but helps new coders to understand what they are doing and uses a very simple technique that is not present in any of the other answers yet. The trick is to use an instance (@) variable, it will not work with a local variable:

if @foo
  "bar"
end

If @foo is defined it will be return "bar", otherwise not (with no error). Therefore in two steps:

if @dashboard_pane_counter
  if @dashboard_plane_counter.remainder(3) == 0
    do something
  end
end
Dennis
  • 100
  • 1
  • 10
-1

Another way, with a neat gem, is 'andand.'

https://github.com/raganwald/andand

andrewpthorp
  • 4,998
  • 8
  • 35
  • 56
-3

Insted of

if !var.nil?

I would use

unless var.nil?

Thats much better ruby code!

davidb
  • 60
  • 1
  • 4
    this only applies if the variable was defined previous to this code. Try if !adallajglaksdkfaj.nil? on the first line of a "function". kablammo :) – baash05 Nov 14 '12 at 00:06