J
Jeff Cohen
Making my way through Ruby for Rails (excellent book, David), but am
puzzled by the explanation of why Rails jumps through hoops to turn
Module instance methods into class methods.
On p. 463, David represents the situation sans Rails:
module A
module M
module ClassMethods
def some_method
#...
end
def included(c)
c.extend(ClassMethods)
end
end
end
and then a class later that does this:
class B
include A::M
end
The goal as for M::ClassMethods to become class methods of B. Whew.
Here are my questions:
1. Why can't class B just extend A::M::ClassMethods? Why use include
and therefore necessitate this whole indirect approach? Must be some
advantage that I'm not seeing?
In other words, why couldn't this have worked?
class B
extend A::M::ClassMethods
end
and then there's no need M::included() needed at all?
2. I guess because M::included() was overridden, class B did not get any
instance methods - which I think would have normally been the case with
an include statement. SO what if you wanted the "normal" inclusion
behavior, but also wanted to do something "extra" when your module is
included?
Thanks!
Jeff
puzzled by the explanation of why Rails jumps through hoops to turn
Module instance methods into class methods.
On p. 463, David represents the situation sans Rails:
module A
module M
module ClassMethods
def some_method
#...
end
def included(c)
c.extend(ClassMethods)
end
end
end
and then a class later that does this:
class B
include A::M
end
The goal as for M::ClassMethods to become class methods of B. Whew.
Here are my questions:
1. Why can't class B just extend A::M::ClassMethods? Why use include
and therefore necessitate this whole indirect approach? Must be some
advantage that I'm not seeing?
In other words, why couldn't this have worked?
class B
extend A::M::ClassMethods
end
and then there's no need M::included() needed at all?
2. I guess because M::included() was overridden, class B did not get any
instance methods - which I think would have normally been the case with
an include statement. SO what if you wanted the "normal" inclusion
behavior, but also wanted to do something "extra" when your module is
included?
Thanks!
Jeff