Last active
August 20, 2016 18:53
-
-
Save halilim/353ebfd29a82ba5b2e0d to your computer and use it in GitHub Desktop.
Demonstrating Ruby class/module method inheritance hierarcy
This file contains hidden or 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 Extendable # :nodoc: | |
def self.extended(base) | |
base.include InstanceMethods | |
end | |
module InstanceMethods # :nodoc: | |
def hello | |
puts 'hello from Extendable' | |
super | |
end | |
end | |
def hello | |
puts 'classy hello from Extendable' | |
super | |
end | |
end | |
module Includable # :nodoc: | |
def self.included(base) | |
base.singleton_class.include ClassMethods | |
end | |
module ClassMethods # :nodoc: | |
def hello | |
puts 'classy hello from Includable' | |
super | |
end | |
end | |
def hello | |
puts 'hello from Includable' | |
super | |
end | |
end | |
module Prependable # :nodoc: | |
def self.prepended(base) | |
base.singleton_class.prepend ClassMethods | |
end | |
# :nodoc: | |
module ClassMethods | |
def hello | |
puts 'classy hello from Prependable' | |
super | |
end | |
end | |
def hello | |
puts 'hello from Prependable' | |
super | |
end | |
end | |
class Parent # :nodoc: | |
def self.hello | |
puts 'classy hello from Parent' | |
# super | |
end | |
def hello | |
puts 'hello from Parent' | |
# super | |
end | |
end | |
class Class1 < Parent # :nodoc: | |
# Note that changing the order of +extend+ and +include+ changes the order of method calls | |
extend Extendable | |
include Includable | |
prepend Prependable | |
def self.hello | |
puts 'classy hello from Class1' | |
super | |
end | |
def hello | |
puts 'hello from Class1' | |
super | |
end | |
end | |
puts "Ancestors: #{Class1.ancestors}" | |
puts '---' | |
Class1.hello | |
puts '---' | |
Class1.new.hello |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment