Skip to content

Instantly share code, notes, and snippets.

@sinsoku
Last active October 5, 2022 13:10
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 sinsoku/e64f1bd8edf35b05eb0c64e87f1bb979 to your computer and use it in GitHub Desktop.
Save sinsoku/e64f1bd8edf35b05eb0c64e87f1bb979 to your computer and use it in GitHub Desktop.
An instance that switches between two implementations
module As
class Proxy
def initialize(this, mod)
@this = this
@mod = mod
end
def method_missing(name, *args)
raise NoMethodError unless @mod.instance_methods.include?(name)
@mod.instance_method(name).bind_call(@this, *args)
end
end
def as(mod)
raise NoMethodError unless self.class.ancestors.include?(mod)
Proxy.new(self, mod)
end
end
module A
def call = puts "A"
end
module B
def call = puts "B"
end
class Foo
include As
include A
include B
end
foo = Foo.new
foo.call #=> B
foo.as(A).call #=> A
foo.as(B).call #=> B
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment