0

How can I make something like this?

1.9.3p286 :006 > defined? activated_flag
 => nil 
1.9.3p286 :007 > puts (activated_flat ? "activated!" : "no activated")

I would like to see here no activated, but instead I have:

NameError: undefined local variable or method `activated_flat' for main:Object
  from (irb):7
  from /Users/fguillen/.rvm/rubies/ruby-1.9.3-p286/bin/irb:16:in `<main>'
fguillen
  • 36,125
  • 23
  • 149
  • 210

2 Answers2

2

why not using defined?:

puts (defined?(activated_flat) ? "activated!" : "no activated")
#=> no activated
0

The simplest way I have found is adding a fallback initialization like:

activated_flag ||= false

But as I'm using this variable in erb partials this fallback initialization looks ugly.

fguillen
  • 36,125
  • 23
  • 149
  • 210
  • Why not make the partial's caller pass everything? A partial is a method and methods have defined interfaces, if someone calls a method without supplying all the parameters that its interface demands then the caller will get the errors that they deserve. – mu is too short Nov 28 '12 at 17:03
  • Exactly @muistooshort, and what I'm missing is the [param default value functionality](http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Method_Calls#Default_Values) but for the partial definition, which would be very helpful in this case. – fguillen Nov 28 '12 at 17:13
  • 1
    Unfortunately, Rails likes to pretend that partials aren't functions so you have to do it the [dumb ugly way](http://api.rubyonrails.org/classes/ActionView/Base.html#label-Passing+local+variables+to+sub+templates). And a similar question (which might even be a duplicate): http://stackoverflow.com/q/2060561/479863. Shame that partials (and ERB templates in general) aren't explicitly functions (hmm, am I reverting to Lisp in my old age? Ha!). – mu is too short Nov 28 '12 at 17:57