7

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

3 Answers 3

17

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 -%>."
Sign up to request clarification or add additional context in comments.

1 Comment

pretty much the obvious solution, don't know why I didn't opt for this in the first place
3

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.

1 Comment

while this isn't what I plan to use, it does answer my original question
1

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.