Created
October 20, 2015 19:15
-
-
Save scaint/88b45903b00b7c5865ca to your computer and use it in GitHub Desktop.
This file contains hidden or 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
... | |
private | |
def use_dsl(&block) | |
proxy = Proxy.new(self, @api) | |
proxy.call(&block) | |
end | |
end | |
class Proxy < BasicObject | |
class CallerFrame < BasicObject | |
def initialize(receiver) | |
@receiver = receiver | |
end | |
def eval(&block) | |
@receiver.instance_exec(&block) | |
end | |
end | |
def initialize(*args) | |
@receivers = args | |
end | |
def call(&block) | |
caller_frame = CallerFrame.new(@receivers.first) | |
instance_exec(caller_frame, &block) | |
end | |
def method_missing(method, *args, &block) | |
@receivers.each do |receiver| | |
return receiver.send(method, *args, &block) if receiver.respond_to?(method, true) | |
end | |
end | |
end | |
# Output: | |
# | |
# a: 1 | |
# No method `a` | |
# b: 2 | |
# No method `b` | |
# c: nil | |
# c: 3 | |
# No method `c` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment