Search code examples
ruby-on-railsrubymixins

Where to put common code found in multiple models?


I have two models that contain the same method:

def foo
  # do something
end

Where should I put this?

I know common code goes in the lib directory in a Rails app.

But if I put it in a new class in lib called 'Foo', and I need to add its functionality to both of my ActiveRecord models, do I do that like this:

class A < ActiveRecord::Base
includes Foo

class B < ActiveRecord::Base
includes Foo

and then both A and B will contain the foo method just as if I had defined it in each?


Solution

  • Create a module, which you can put in the lib directory:

    module Foo
      def foo
        # do something
      end
    end
    

    You can then include the module in each of your model classes:

    class A < ActiveRecord::Base
      include Foo
    end
    
    class B < ActiveRecord::Base
      include Foo
    end
    

    The A and B models will now have a foo method defined.

    If you follow Rails naming conventions with the name of the module and the name of the file (e.g. Foo in foo.rb and FooBar in foo_bar.rb), then Rails will automatically load the file for you. Otherwise, you will need to use require_dependency 'file_name' to load your lib file.