Forum: Ruby on Rails Newbie Question: The model equivilent of "helpers"

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
D4b246038154d7cc2363256bd25a4fe0?d=identicon&s=25 ljw1001 (Guest)
on 2005-11-25 17:35
(Received via mailing list)
If I have ruby code that I need to share among a number of model
classes,
what's the "right" place to put it form a Ruby standpoint?

The code provides support for various calculations.  It has no data
elements
that are persisted in a database.  It seems like there should be
something
like a helpers directory for models for this kind of supporting code.

thanks for your help.
-larry
05d703f649ef1d07e78d7b479fb4c4ac?d=identicon&s=25 james.adam (Guest)
on 2005-11-25 17:39
(Received via mailing list)
If you have methods that you want to make available in a number of
classes, you should put these methods in a module and have each class
'include' this module, i.e.

in RAILS_ROOT/lib/my_module.rb (you'll want to 'require' this file in
environment.rb too, probably)

  module MyModule
     def calculate_meaning_of_life
        6 * 7
     end
  end

... then in your model objects:

RAILS_ROOT/app/models/model_alpha.rb

  class ModelAlpha <  ActiveRecord::Base
    include MyModule
    ...
  end

RAILS_ROOT/app/models/model_beta.rb

  class ModelBeta < ActiveRecord::Base
    include MyModule
    ...
  end

... and so on.

- james
This topic is locked and can not be replied to.