2

Here is some code I'm using just to avoid of hardcoding session variables.

#application_controller
  def redirect_to_new_order?
    session[:redirect_to_new_order]
  end

  def redirect_to_new_order=(value)
    session[:redirect_to_new_order] = value
  end

#another_controller
#.............
def some_action
   redirect_to_new_order = true
   #viewed by debugger
   # redirect_to_new_order? is equal to nil 
   # session[:redirect_to_new_order] is equal to nil as well
end

As you can see, redirect_to_new_order? and session[:redirect_to_new_order] are nil for some reason.

Why is this happening?

UPDATE: Here is a code similar to given above. But it does call a method and doesn't create a local variable. Why?

class SomeClass

    def initialize
        @some_var = "999"
    end
    def var1
        @some_var
    end

    def var1=(value)
        @some_var=value
    end

    def method1
      var1 = 111
      puts var1
      puts @some_var  
    end
end

a = SomeClass.new
a.method1 # prints 111 and 999 but why?
  • Your update also sets a local variable instead calling a method. Try printing `@some_var` in `method1`. You will see it is different from `var1`, which means `var1` is a local variable and not a method call. – Mischa Sep 04 '12 at 03:39
  • 1
    Because it was designed to set a local variable. Ruby doesn't know your intentions and it has to do something. See the two links in my answer below. – Mischa Sep 04 '12 at 04:09

2 Answers2

2

The reason is you are not invoking the redirect_to_new_order= method. Rather you are setting a local variable redirect_to_new_order with a value of true. As a sanity check, add a raise "BOOM" line to the assignment method and you'll see that the method isn't invoked.

You need an explicit receiver or else you are setting a local variable in your controller.

self.redirect_to_new_order = true

will do the trick.

austen
  • 3,314
  • 3
  • 25
  • 26
  • Of couse, it's true. I already know it, but I don't understand yet why. Please, look at my update. –  Sep 04 '12 at 03:09
0

Because it's unclear if you want to set a local variable or call the setter method. Ruby chooses to set a local variable in that case. See these two answers:

Community
  • 1
  • 1
Mischa
  • 42,876
  • 8
  • 99
  • 111