Created
October 10, 2014 15:08
-
-
Save msievers/d02c6cbc513a39d3de2c to your computer and use it in GitHub Desktop.
Prepend module code to subclasses by prepending to it's instances singleton_class via inherited
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
module InheritedHandler | |
def inherited(subclass) | |
subclass.instance_eval do | |
alias :original_new :new | |
def self.inherited(subsubclass) | |
subsubclass.extend(InheritedHandler) | |
end | |
def self.new(*args, &block) | |
(obj = original_new(*args, &block)).singleton_class.prepend(BarkLoud) | |
return obj | |
end | |
end | |
end | |
end | |
module BarkLoud | |
def bark | |
super.upcase + "!!!" | |
end | |
end | |
# Since this works via inherited, there has to be some class in front | |
class Dog < Class.new.extend(InheritedHandler) | |
def bark | |
"wuff" | |
end | |
end | |
puts Dog.new.bark # => "WUFF!!!" | |
class Pug < Dog | |
def bark | |
"aruff" | |
end | |
end | |
puts Pug.new.bark # => "ARUFF!!!" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment