Search code examples
ruby-on-rails-3activerecordmodelextending

Writing a custom attr_special function in Rails 3


Apologies in advance - I'm very much a learner, and writing projects as a means to learn. In this one, I'm trying to extend ActiveRecord so that I can do the following...

In my model definition, call ...

attr_special :field, :field

Then, elsewhere, be able to access this list through something like

Model.special_attributes

Probably something really obvious. I'm fine extending ActiveRecord, but I'm not even sure what I'm searching for for guidance beyond this (constructor?)...


Solution

  • You can define something like the code below to create custom DSL in your models:

    module SpecialAttributes
      module ClassMethods
        def attr_special(*attrs)
          class_attribute :special_attributes
          self.special_attributes = attrs
        end
    
        def special_attributes
          self.special_attributes
        end
      end
    
      module InstanceMethods
        # some code here
      end
    
      def self.included(base)
        base.extend ClassMethods
        base.send :include, InstanceMethods
      end
    
    end
    
    class ActiveRecord::Base
      include SpecialAttributes
    end
    

    I reopen ActiveRecord::Base class instead of use inheritance because it's more common in Ruby that inheritance.

    I like to use submodules called ClassMethods and InstanceMethods in my module and use self.included method to add them in the base class. So you can use 'include MyModule' without have to know if you add instance or class methods.

    I hope I can help you.