Note that there are some explanatory texts on larger screens.

plurals
  1. PORuby on Rails: Initializing instance variables with helpers in view
    primarykey
    data
    text
    <p>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.</p> <pre><code>#sample_controller.rb class SampleController &lt; 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 &lt;%= display %&gt; &lt;%= display %&gt; &lt;%= @display %&gt; &lt;%= @display.reverse %&gt; </code></pre> <p>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 &lt;%= @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.</p> <p>If the controller is modified so to become (with the original view code):</p> <pre><code>class SampleController &lt; ApplicationController def test display end end </code></pre> <p>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.</p> <p>Is this a bug in Rails or am I misunderstanding and this is for some reason intended functionality?</p> <p>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. </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload