Skip to content

Instantly share code, notes, and snippets.

@benlangfeld
Created June 29, 2012 22:57
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 benlangfeld/2fc26d60d59fd64ea72e to your computer and use it in GitHub Desktop.
Save benlangfeld/2fc26d60d59fd64ea72e to your computer and use it in GitHub Desktop.
# An A is intended to securely encapsulate a B, so that any attempts to access the B must go via the A
class A
def initialize
@b = B.new # This is supposed to be completely encapsulated, and inaccessible to the outside world
end
def foo
puts "Foo"
end
def method_missing(name, *args, &block)
# Maybe implement some sort of authorisation here. This is the motivation for the tight encapsulation.
@b.send name, *args, &block
end
end
class B
def ask
C.new.ask { foo }
end
def foo
puts "Bar"
end
end
class C
def ask
yield # When the block is yielded, self is the B instance, allowing direct access to B from outside, thus breaking the encapsulation
end
end
A.new.ask # This returns 'Bar', where I really want 'Foo'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment