Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Possible for a module included somewhere to override a class's instance method?
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
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
def call
[ 'overridden', super ]
end
end
class Base
include Override
end
p Base.new.call #=> "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", "monkeypatched"]
@saturnflyer

This comment has been minimized.

Copy link

commented May 17, 2012

can you alias the existing method?

Base.class_eval{
  alias_method :old_call, :call
  def call
    ['aliased', old_call]
  end
}

p Base.new.call

Or is there a reason that wouldn't work for you?

@lmarburger

This comment has been minimized.

Copy link
Owner Author

commented May 17, 2012

No you're right. I forgot to include that in my gist. That works too but I was hoping for a better approach that provides access to #super and avoids the alias_method_chain nightmare.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.