Topic: Sharing code across models

I have four models which are very similar and could share about 4 functions, and I would like to not repeat myself.  I cannot figure out how to implement it, though.  Two are AR related, before_save and after_save, and the other two are property related, delete! and check_send_warning!.  Anybody got any juicy tips?

thanks
brian

BrewControl.com - Brewery and Brewpub management powered by RoR

Re: Sharing code across models

Try this:

in the lib folder, put the common code in a module

lib/my_common_model_code.rb

module MyCommonModelCode

  def after_save
   # your code goes here
  end

  def before_save
   # your code goes here
  end

  def delete!
   # your code goes here
  end

  def check_send_warning
   # your code goes here
  end

end


Restart your app server to load the module

Then, in each of your models, include it

class Product < ActiveRecord::Base
  include MyCustomModelCode


end


That's one way smile Good luck!

Re: Sharing code across models

bphogan's right on. You may need to require the file in environment.rb though.

require 'my_common_model_code'

Railscasts - Free Ruby on Rails Screencasts

Re: Sharing code across models

You shouldn't need to. Last I checked, anything in lib is auto-loaded now.

Re: Sharing code across models

Really? Wow cool!

Railscasts - Free Ruby on Rails Screencasts

Re: Sharing code across models

That looks great.  Thanks guys.

BrewControl.com - Brewery and Brewpub management powered by RoR