Created
August 21, 2012 08:27
-
-
Save bgipsy/3413487 to your computer and use it in GitHub Desktop.
Aspects of Module included callback
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
# supporting the answer for http://stackoverflow.com/questions/11742890/merge-two-ruby-modules-but-not-include/12036994#12036994 | |
module A | |
def a | |
puts "a" | |
end | |
end | |
module B | |
# note 'self.' part here, which makes method a module method | |
def self.included(base) | |
puts "B.included" | |
base.send(:include, A) | |
end | |
end | |
puts "For C1" | |
class C1 | |
puts "before include B" | |
include B | |
puts "after include B" | |
end | |
puts "C1.new.a" | |
C1.new.a | |
# Output: | |
# | |
# For C1 | |
# before include B | |
# B.included | |
# after include B | |
# C1.new.a | |
# a | |
puts | |
puts "For M" | |
module M | |
puts "before include B" | |
include B | |
puts "after include B" | |
end | |
# Output: | |
# For M | |
# before include B | |
# B.included | |
# after include B | |
puts | |
puts "For C2" | |
class C2 | |
puts "before include M" | |
include M | |
puts "after include M" | |
end | |
puts "C2.new.a" | |
C2.new.a | |
# Output: | |
# For C2 | |
# before include M | |
# after include M | |
# C2.new.a | |
# a | |
class C3 | |
end | |
puts | |
puts "For C3" | |
c3 = C3.new | |
puts "before c3.extend B" | |
c3.extend(B) | |
puts "after c3.extend B" | |
c3.a rescue puts "Exception: ", $!.inspect | |
# Output: | |
# For C3 | |
# before c3.extend B | |
# after c3.extend B | |
# Exception: | |
# #<NoMethodError: undefined method `a' for #<C3:0x100168360>> | |
puts | |
puts "before c3.extend M" | |
c3.extend(M) | |
puts "after c3.extend M" | |
puts "c3.a" | |
c3.a | |
# Output: | |
# before c3.extend M | |
# after c3.extend M | |
# c3.a | |
# a |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment