Class variables in rails views?

Can ruby ​​class variables be referenced in a view?

+6
ruby-on-rails
source share
3 answers

A more general approach is to wrap a class variable in a helper method:

# in /app/controllers/foo_controller.rb: class FooController < ApplicationController @@bar = 'baz' def my_action end helper_method :bar def bar @@bar end end # in /app/views/foo/my_action.html.erb: It might be a class variable, or it might not, but bar is "<%= bar -%>." 
+15
source share

Unfortunately, the class ( @@variables ) is not copied to the view. You can still get them through:

 controller.instance_eval{@@variable} 

or

 @controller.instance_eval{@@variable} 

or something even less rude.

With Rails, 99.9 out of 100 people should never do this, or at least I can't come up with a good reason.

+3
source share

Rosen's answer is good because it hides which bar variable, but if you have many such variables, the need to define a bunch of helper methods is unattractive. I use the following in my controller:

 @bar = @@bar ||= some_expensive_call 

This way, "some_expensive_call" is executed only once, and the result is copied to @bar for each instance (therefore, the view can then be accessed as @bar).

+1
source share

All Articles