Skip to content

Instantly share code, notes, and snippets.

@halilim
Last active August 20, 2016 18:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save halilim/353ebfd29a82ba5b2e0d to your computer and use it in GitHub Desktop.
Save halilim/353ebfd29a82ba5b2e0d to your computer and use it in GitHub Desktop.
Demonstrating Ruby class/module method inheritance hierarcy
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