Sam
Sam

Reputation: 1569

Class variables in rails views?

Is it possible to refer to ruby class variables in a view?

Upvotes: 7

Views: 6080

Answers (3)

Paul Lynch
Paul Lynch

Reputation: 1337

Rosen's answer is nice because it hides what kind of variable "bar" is, but if you have a lot of such variables, the need to define a bunch of helper methods is unappealing. I'm using the following in my controller:

@bar = @@bar ||= some_expensive_call

That way, "some_expensive_call" is only made once, and the result is copied into @bar for each instance (so the view can then access it as @bar).

Upvotes: 1

James A. Rosen
James A. Rosen

Reputation: 65272

The more common approach is to wrap the 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 -%>."

Upvotes: 17

cwninja
cwninja

Reputation: 9778

Unfortunately class (@@variables) are not copied into the view. You may still be able to get at them via:

controller.instance_eval{@@variable}

or

@controller.instance_eval{@@variable}

or something else less gross.

With Rails, 99.9 out of 100 people should never be doing this, or at least I can't think of a good reason.

Upvotes: 3

Related Questions