开发者

Factor out application_helper

On my latest Rails application I've decided to only render partials from helper methods.

For example, in application_helper.rb:

def render_header
     render :partial => "partials/header"
end

I'm doing this to make my code a little more dry in case I rename a partial or need to add in additional logic for controlling which partial is displayed.

The drawback to this is that it quickly inflates application_helper.rb, which already inflates pretty rapidly without doing this.

I'm wondering what the cleanest way to break up application_helper is. I was thinking that I should create an application_helpers library in lib/, and include a different module for every type of helper I want, for example partial_helper.rb.

开发者_如何学编程

However, I haven't been able to get this to work. I placed the file in lib/application_helpers/partial_helper.rb, and I called the module "ApplicationHelpers::PartialHelper". I thought this would get loaded by Rails automatically, and that in my views I could do "PartialHelper.render_header", but I get an error that that method is undefined on PartialHelper.

Another idea was to just include/require the helper in application_helper.rb, and call it normally in my views, but that also didn't work.

Any ideas/solutions?

Thanks, Zach


You can place any <whatever>_helper.rb file in app/helpers and Rails will pick it up. You could have partials_helper.rb, for example. You're not restricted to the application helper or helpers generated by controllers.

Example partials_helper.rb:

module PartialsHelper
  def render_header
    ...
  end
end
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜