简体   繁体   中英

Separate rails helper methods

I have a couple of controllers with associated helper modules. I got some helper methods that should behave similarly across different modules, meaning:

module UserHelper
  ..
  def destroy(user)
    link_to t(:destroy_user), user ... 
  end
end

module PhotosHelper
  ..
  def destroy(photo)
    link_to t(:destroy_photo), photo ... 
  end
end

I didn't know (realize) that all of these helper modules are included by default, (which is ok, I guess,) and it doesn't matter what view you're calling the helper method from.

What is the best way to separate the rest of the helpers from my current controller/view so that, when controller_name == 'photos' , only Photos and Application helpers are used?

The concept of Helpers is not really clear to me. Why not just have a single ApplicationController if all helpers are already mixed in? Is it just for "logical separation"?

I mean, of course, there's a number of workarounds. But is it just me, or it really feels like there's no reason to include all of the helpers globally?

If you called clear_helpers at ApplicationController class, they won't share among different helper classes

clear_helpers()

Clears up all existing helpers in this class, only keeping the helper with the same name as this class.

ref: http://api.rubyonrails.org/classes/AbstractController/Helpers/ClassMethods.html#method-i-clear_helpers

You could put the common methods on the ApplicationHelper and pass the resource as a parameter.

So then use the specific helper resource for specific methods only.

Methods (helpers) that you can share anyway, goes to ApplicationHelper file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM