这是我用来避免硬编码会话变量的一些代码。
#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
正如你所看到的,并且redirect_to_new_order?
出于某种原因。session[:redirect_to_new_order]
nil
为什么会这样?
更新:这是类似于上面给出的代码。但它确实调用了一个方法并且不创建局部变量。为什么?
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?