Model equivalent for controllers/application.rb

Hi All

I have a couple of functions in my modules which are identical. I would
like to move them into a separate file and have them available in all
modules. For example, the controllers already have one, application.rb.
Do modules have something similar ? If not, what would be the best way
to do this ?

Thnx a lot
LuCa

Create a new file ... call it lib/model_helpers.rb or something like that:

module ModelHelpers
   def identical_method
     # do some stuff
   end
end

Then in your model class:

class MyModel
   include ModelHelpers

   # more stuff
end

This should allow you to get the methods where you need them.

Luca -- modules can include other modules so you can refactor in the
same way you already have.

thanks a lot, I have it working now!!
LuCa

class MyModel
   include ModelHelpers

   # more stuff
end

This should allow you to get the methods where you need them.

Or one step further:

class ActiveRecord::Base
  include ModelHelpers
end

you can just open the big daddy yourself and mess with it if the helpers
are going to be used by most of your models anyways, this will help you
keep your individual model code dryer and give you something to talk
about at your next party.

hth

nice solution, so I just create a helpermodule which extends
ActiveRecords, is that correct ?

Way I would do it

# /config/initializers/record_extender.rb
require 'lib/extensions/active_record_extender'
ActiveRecord::Base.send( :include, ActiveRecordExtender )

# /lib/extensions/active_record_extender.rb
module Extensions
  module ActiveRecordExtender
    def shared_method
      # this method will be in every single model
    end
  end
end

# /app/models/example.rb
class Example < AR:Base
  def some_method
    shared_method # call to method from module
  end
end

Way I would do it

# /config/initializers/record_extender.rb
require 'lib/extensions/active_record_extender'
ActiveRecord::Base.send( :include, ActiveRecordExtender )

# /lib/extensions/active_record_extender.rb
module Extensions
  module ActiveRecordExtender
    def shared_method
      # this method will be in every single model
    end
  end
end

# /app/models/example.rb
class Example < AR:Base
  def some_method
    shared_method # call to method from module
  end
end

Doesn't work for me. Mongrel chokes on startup:

./lib/extensions/active_record_extender.rb:1: Extensions is not a
module (TypeError)

Copied and pasted as is from the post.