Using helper_method from a Mixin Module

Hi,

I have a module with a helper method in it. I want to automatically
declare the method as a helper when I mix the module into a controller
class, so the mixin basically sets itself up. Something like :-

module MyMixin

I want to do helper method here in the module

helper_method :my_helper

def my_helper
puts “foo”
end
end


class MyController < ApplicationController

include MyMixin

I dont’ want to have to do helper_method in the controller

helper_method :my_helper


This does not work as I want, I have to do “helper_method” in the
controller class itself. If I try to do it in the module I get an error
like this :-

undefined method helper method for MyMixin:Module

Is there a way to achieve this?

Hi –

On Sat, 11 Aug 2007, John L. wrote:

helper_method :my_helper
include MyMixin
undefined method helper method for MyMixin:Module

Is there a way to achieve this?

Try this (untested):

module MyMixin
def self.included(c)
c.helper_method :my_helper
end

 def my_helper
   etc.
 end

end

The idea is to call the included callback, which allows you to operate
on the class that’s doing the including.

David

Many thanks for this, it works beautifully!

module MyMixin
def self.included©
c.helper_method :my_helper
end