开发者

Class variables in rails views?

Is it possible to refer to ruby class varia开发者_运维百科bles in a view?


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 -%>."


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜