Skip to content

Instantly share code, notes, and snippets.

@shime
Forked from rkh/hack.rb
Created May 20, 2012 16:21
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 shime/2758666 to your computer and use it in GitHub Desktop.
Save shime/2758666 to your computer and use it in GitHub Desktop.
Overriding a class instance method with a module
class Base
def call
'call'
end
end
p Base.new.call #=> "call"
# Monkeypatching "works" but doesn't provide access to #super
class Base
def call
'monkeypatched'
end
end
module Prepending
def append_features(base)
return super unless base.is_a? Class
prepend = self
base.extend Module.new { define_method(:new) { |args,&block| super(args,&block).extend(prepend) }}
end
end
p Base.new.call #=> "monkeypatched"
# This is the spirit of what I'd like, but methods defined on the class will be
# preferred over those in ancestors.
module Override
extend Prepending
def call
[ 'overridden', super ]
end
end
class Base
include Override
end
p Base.new.call #=> ["overridden", "monkeypatched"]
# This works but I don't have access to the class instances to apply this method.
instance = Base.new
class << instance
def call
[ 'overridden', super ]
end
end
p instance.call #=> ["overridden", ["overridden", "monkeypatched"]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment