开发者

How to access methods of an arbitrary view helper by an arbitrary erb file?

开发者 https://www.devze.com 2023-03-19 13:58 出处:网络
By convention, Rails only开发者_如何学编程 \"attaches\" the view helper which corresponds to the controller the erb file is called of.

By convention, Rails only开发者_如何学编程 "attaches" the view helper which corresponds to the controller the erb file is called of.

How can I access a view helper's methods of an arbitrary view helper in Rails?


If you need to do that, something is wrong with the organization of your code. Instead, move the helper methods that both of your views need into a common module, and include that module in both.

For example, if you have:

module ApplesHelper
  def flavor_of(fruit)
  end
end

and you want /bananas views to have access to the flavor_of method, then do this:

module Flavored
  def flavor_of(fruit)
    # ...
  end
end

module ApplesHelper
  include Flavored
end

module BananasHelper
  include Flavored
end

Update: I realized that I didn't actually answer the original question directly. The way to include another helper in a view is with helper:

class BananasController ...
  helper ApplesHelper
end

Now all /bananas view also have the ApplesHelper methods available to them.


If I understood well the question, you have to define your method helper with:

module ControllerHelper
   def function_you_have_to_call
      some_code_here
   end
end

When you want to call your method helper by the *.erb file, you have to insert this in the view:

<% function_you_have_to_call %>

If your method has a return value and you want to store it in an local variable defined in your view, try:

<% value_you_want = function_you_have_to_call %>

Remember the code included by <% %> is only interpreted by ruby and not shown by view. In this case you have to use code included by <%= %>.

Now you can access value_you_want and maybe use for statements.

0

精彩评论

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

关注公众号