Vlad Khomich
Vlad Khomich

Reputation: 5880

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?

Upvotes: 4

Views: 591

Answers (2)

YOU
YOU

Reputation: 123791

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

Upvotes: 3

Kleber S.
Kleber S.

Reputation: 8240

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.

Upvotes: 2

Related Questions