Validates_presence_of in module

I have a model. I want to import a module into this model. in this module I want to insert validates_presence_of for models that import it

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

class Ele < ActiveRecord::Base include Mod end module Mod validates_presence_of :field end 

thanks

+4
source share
2 answers

in the application / 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 this helps!

+2
source

You can use 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 
+6
source

Source: https://habr.com/ru/post/1300968/


All Articles