Skip to content

Instantly share code, notes, and snippets.

@bestie
Created February 13, 2014 16:20
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 bestie/8978251 to your computer and use it in GitHub Desktop.
Save bestie/8978251 to your computer and use it in GitHub Desktop.
Ruby demo: extending modules with other modules
module Base
extend self
def hi
puts "Base says hi"
end
end
module Ext1
def hi
puts "Ext1 says hi"
super
end
end
module Ext2
def hi
puts "Ext2 says hi"
super
end
end
Base
.extend(Ext1)
.extend(Ext2)
.hi
# =>
# Ext2 says hi
# Ext1 says hi
# Base says hi
p Base.class.ancestors
# =>
# [Module, Object, Kernel, BasicObject]
p class << Base; ancestors; end
# =>
# [Ext2, Ext1, Base, Module, Object, Kernel, BasicObject]
@bestie
Copy link
Author

bestie commented Feb 13, 2014

Have the hip Ruby kids found a cooler way of getting at the singleton class or is that hack on 39 still how it's done?

@myronmarston
Copy link

Have the hip Ruby kids found a cooler way of getting at the singleton class or is that hack on 39 still how it's done?

Ruby 1.9+ has Object#singleton_class.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment