Skip to content

Instantly share code, notes, and snippets.

@rgm
Created June 3, 2009 23:13
Show Gist options
  • Save rgm/123320 to your computer and use it in GitHub Desktop.
Save rgm/123320 to your computer and use it in GitHub Desktop.
# see http://blog.jayfields.com/2007/08/ruby-calling-methods-of-specific.html
module Kernel
def as(ancestor, &blk)
@__as ||= {}
unless r = @__as[ancestor]
r = (@__as[ancestor] = As.new(self, ancestor))
end
r.instance_eval(&blk) if block_given?
r
end
end
class As #:nodoc:
private *instance_methods.select { |m| m !~ /(^__|^\W|^binding$)/ }
def initialize(subject, ancestor)
@subject = subject
@ancestor = ancestor
end
def method_missing(sym, *args, &blk)
@ancestor.instance_method(sym).bind(@subject).call(*args,&blk)
end
end
module M
def hello
puts "hello from module"
end
end
class C
include M
alias_method :module_hello,:hello
def hello
puts "hey there from class"
end
end
obj = C.new
obj.hello
obj.as(M).hello
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment