Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including modules in a class and executing code

Here is a class that I used to have

class Something
    # Defines the validates class methods, which is called upon instantiation
    include Module

    validates :name
    validates :date

end

I now have several objects that are using the same functionalities, and worse, several object that are defining similar things, like this:

class Anotherthing
    # Defines the validates class methods,  which is called upon instantiation
    include Module

    validates :age

end

I want to 're-use' the content of these classes, so I turned them into modules:

module Something
    # Defines the validates class methods  which is called upon instantiation
    include Module

    validates :name
    validates :date

end

module Anotherthing
    # Defines the validates class methods which is called upon instantiation
    include Module

    validates :age

end

And I can now create a class

class ADualClass
   include Something
   include Anotherthing
end

The problem that I have is that the validates method are not called when I create a ADualClass object... It seems that the "validates :thing" is never called. Why is that? How can I force this?

like image 925
Julien Genestoux Avatar asked Jul 01 '09 13:07

Julien Genestoux


Video Answer


1 Answers

In your module you need to define, e.g.

def self.included(base)
  base.validates :name
  base.validates :date
end
like image 64
alex.zherdev Avatar answered Sep 21 '22 15:09

alex.zherdev