Skip to content

Instantly share code, notes, and snippets.

@citrus
Created August 30, 2016 23:37
Show Gist options
  • Select an option

  • Save citrus/bc406b329e2f112095257dd58ae623e9 to your computer and use it in GitHub Desktop.

Select an option

Save citrus/bc406b329e2f112095257dd58ae623e9 to your computer and use it in GitHub Desktop.
Ruby proxy pattern
class ProxyTest
attr_accessor :scope
class ScopeProxy
def initialize(obj, scope)
@obj = obj
@scope = scope
end
def method_missing(method, *args, &block)
if @obj.respond_to?(method)
with_scope do
@obj.send(method)
end
else
super
end
end
private
def with_scope(&block)
@prev_scope = @obj.scope
@obj.scope = @scope
value = block.call
@obj.scope = @prev_scope
value
end
end
def doubled
ScopeProxy.new(self, :double)
end
def tripled
ScopeProxy.new(self, :tripled)
end
def value
case @scope
when :tripled; 3
when :double; 2
else 1
end
end
end
test = ProxyTest.new
puts test.value # 1
puts test.doubled.value # 2
puts test.tripled.value # 3
puts test.value # 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment