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

On Mar 2, 2008, at 9:25 AM, Luca S. wrote:

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.

On Mar 2, 12:25 pm, Luca S. [email protected]

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

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

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

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

  # 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.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs