Last active
October 5, 2022 13:10
-
-
Save sinsoku/e64f1bd8edf35b05eb0c64e87f1bb979 to your computer and use it in GitHub Desktop.
An instance that switches between two implementations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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