views:

41

answers:

2

i have a model. i want import in this model a module. in this module i want insert a validates_presence_of for the models that import it

I want know if and how is possible to do something like this:

class Ele < ActiveRecord::Base
  include Mod
end

module Mod
   validates_presence_of     :field
end

Thanks

+4  A: 

You can use the self.included hook.

class Ele < ActiveRecord::Base
  include Mod
end

module Mod
  def self.included(base)
    base.class_eval do
      validates_presence_of :field
    end
  end
end
Simone Carletti
A: 

in app/models/awesome_model.rb

class AwesomeModel < ActiveRecord::Base

 inlude ModuleName

end

in lib/module_name.rb

require 'active_record'

module ModuleName
  def self.included(base_class)
    base_class.class_eval do

      include ModuleName::InstanceMethods

      belongs_to :some_model
      before_save :some_method
      .... validations, etc....



    end
  end

  module InstanceMethods

    def some_method
      ....
    end

  end
end

hope that helps!

deb