I'm running into some type of a scope issue that's preventing instance variables from being properly initialized by helpers called from the view.
#sample_controller.rb
class SampleController < ApplicationController
def test
end
end
#application_controller.rb
helper_method :display
def display
if not defined? @display
return @display = "a"
else
return @display += "a"
end
end
#test.html.erb
<%= display %>
<%= display %>
<%= @display %>
<%= @display.reverse %>
When sample/test is displayed, it dies with an error "while evaluating nil.reverse". This is surprising because the first two calls to display should have initialized @display I would have thought. If <%= @display.reverse %> is removed the output is "a aa", indicating that the @display instance variable is getting set by the helper method, but there is no access to it in the view.
If the controller is modified so to become (with the original view code):
class SampleController < ApplicationController
def test
display
end
end
The output becomes "aa aaa a a". If I make it 2 calls to display in the controller, I get, "aaa aaaa aa aa". So it seems like only the calls made in the controller will modify the SampleController instance variable, whereas calls in the view will modify an instance variable for the ApplicationController that the view has no access to.
Is this a bug in Rails or am I misunderstanding and this is for some reason intended functionality?
The context in which I ran into this bug is trying to create a logged_in? ApplicationController method that sets up an @user variable the first time it is called, and returns true or false if a user is logged in. This would not work unless I added an unnecessary call in the controller before attempting to use it in the view.