0

I have 2 or more models that have a method in common called CapitalizeEachWord.

Can I access the class ActiveRecord::Base and paste the method inside? or create a model called Application that inherits the ActiveRecord::Base directly and then to do that BreakPoint and BusCompany inherit from it?

       class BreakPoint < ActiveRecord::Base
          attr_accessible :city,:province_id,:province
          belongs_to :province
          before_save :capitalizeEachWord
          validates :city, presence: true,
                           uniqueness: true,
                           format: /^([[:alpha:]]+\s?){1,}$/
          def capitalizeEachWord
           self.city=self.city.downcase.split.map(&:capitalize).join(' ')
          end              
        end

       class BusCompany < ActiveRecord::Base
         attr_accessible :company
         has_many :bus_set_types 
         validates :company, presence: true, 
                      uniqueness: true,
                      format:  /^([[:alpha:]]+\s?){1,}$/

         def capitalizeEachWord
           self.name=self.name.downcase.split.map(&:capitalize).join(' ')
         end
       end

3 Answers 3

1

The way that I've seen this work best is very similar to your second idea.

Create a ApplicationModel < ActiveRecord::Base and go ahead and add any shared logic in there.

With this approach your other models will look something like this (OauthProvider < ApplicationModel) and include any functionality that you put into the ApplicationModel.

Sign up to request clarification or add additional context in comments.

Comments

1

I'd suggest your second option.

(A more advanced option would be to store it outside of an AR-derived class, as it is somewhat more generally applicable, but that might be too much effort in this case. You could always extract it later, if necessary.)

Comments

1

You can't modify ActiveRecord::Base without some significant hacking endeavors.

What you're probably looking for is a decorator. Decorators are a common design pattern that allows you to add functionality to an object dynamically without having to make static subclasses.

This Code Climate Blog lets you know how to do it in Rails: Refactoring Fat Models

If you're interested in some other ways to do this with plain Ruby (eg modules and mixins) check out this ThoughtBot article.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.