views:

379

answers:

1

I am trying to add some instance variables in helpers like the following:

module ApplicationHelper
 def title=(title)
   @title = title
 end

 def title
  @title
 end
end

and when I assign title in views/pages/index.html.erb like the following:

<% title = 'Listing Pages' %>

and try to show it in the views/layouts/application.html.erb like the following:

<%= title %>

it is showing as '' and after some debugging, looks like @title is not being set.

Why are the instance variables added in the helpers not available in the views (templates)?

Thanks in advance.

A: 

My guess is that Ruby thinks that what you are doing in

title = 'Listing Pages'

is as assignment to a local variable title.

Try to prefix it with self and see if it helps:

self.title = 'Listing Pages'
Milan Novota
@Milan:thanks a lot, it did solve the problem. Is there any other way to let ruby understand that what we are trying to do is trying to call method instead of appending prepending?
satynos
I don't think there's any better way. That's the way the interpreter works. The best way to avoid this kind of problem is just to watch this "a = b" pattern and have a little thought about it. The rule of thumb is: when assigning through a setter method within an instance always prepend it with self.
Milan Novota
One possible workaround: Name your setter method something like set_title instead of title=. Then you won't need to add self and just use it like this: set_tile "Listing pages"
Milan Novota