Skip to content

Instantly share code, notes, and snippets.

@msievers
Created October 10, 2014 15:08
Show Gist options
  • Save msievers/d02c6cbc513a39d3de2c to your computer and use it in GitHub Desktop.
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
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