开发者

Rails helper for views and controllers?

开发者_如何学Go

I know there are ways to make helpers available to controllers, but that this is generally bad form. How should the following be re-worked to avoid this?

I have a Contacts helper called "fullname" that combines a contact's first and last names.

A layout partial called subheader is rendered in the application layout, and contains this code:

<section id="subheader"><%= @subheader %></section>

The controllers set the value of @subheader.

The issue is that I often want "fullname" in @subheader. But this means accessing the helper from the controller. Should this fullname method reside somewhere else?


With something like fullname I usually just define a method on the model itself.

If the fullname method did some type of HTML formatting then I would keep those parts inside a helper.


Since the title of your question might attract viewers looking for a different answer, I'm going to answer the question of "can I use rails helpers in my controllers"? There are legitimate uses for this, so here's the cleanest way to do so:

In the helpers file, wrap the code you want to access in a model like so:

module HelperModuleName
  [helper code here]
end

Wrapping only the code you need to use in your controllers (as opposed to including all helpers using include ApplicationHelper) is a good idea because it reduces the possibility for method name clashes and forces you to be more deliberate about your choice to use helpers in controllers.

Now include the module in your application_controller.rb:

class ApplicationController < ActionController::Base
  protect_from_forgery
  include HelperModuleName
end
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜