Here is how to do it:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Foo | |
def self.included(base) | |
base.extend ClassMethods | |
end | |
module ClassMethods | |
def bar | |
end | |
end | |
def baz | |
end | |
end | |
class Test | |
include Foo | |
end | |
Test.bar # class method | |
Test.new.bar # No method error | |
Test.baz # No method error | |
Test.new.baz # Instance method |
"include" is used to add a module's instance methods as instance methods to the including class, but it doesn't traverse sub modules. "extend" is used to add a module's instance methods as class methods to a class.
When a module is "included" it can register a callback which is passed the class that is doing the including. And calling "extend" on the base and passing a submodule will cause it to put those methods at the class level. This causes a chain reaction of loading both instance and class methods using a single "include".
Pro Tip: It is possible to cause the same behavior using "extend" by using the "extended" callback; however, this is not common and "include 'x'" reads better then "extend 'y'".
When a module is "included" it can register a callback which is passed the class that is doing the including. And calling "extend" on the base and passing a submodule will cause it to put those methods at the class level. This causes a chain reaction of loading both instance and class methods using a single "include".
Pro Tip: It is possible to cause the same behavior using "extend" by using the "extended" callback; however, this is not common and "include 'x'" reads better then "extend 'y'".
No comments:
Post a Comment