开发者

validates_presence_of in a module

开发者 https://www.devze.com 2022-12-20 01:16 出处:网络
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 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开发者_如何学Go how is possible to do something like this:

class Ele < ActiveRecord::Base
  include Mod
end

module Mod
   validates_presence_of     :field
end

Thanks


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


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!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号