Include Class Methods and Validation Using Module in RubyOnRails
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class User
  include TestModule
end

module TestModule
  def test_instance_method
    puts "Test Method"
  end

  def self.included(base)
    base.extend ClassMethods
  end

  module ClassMethods
    def my_class_method
      puts "Class Methods"
    end
  end
end

Here my_class_method is Class Method.we can define more class methods in module ClassMethods

Validations and call backs are called without prefix ‘self’. so for validations and call backs we have to explicitly set the class

1
2
3
4
5
6
module TestModule
  def self.included(base)
    base.validates_presence_of :bar
    base.before_save :some_method
  end
end