Skip to content

Instantly share code, notes, and snippets.

@amomchilov
Last active March 4, 2020 22:09
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 amomchilov/ef1c84325fe6bb4ce01e0f0780837a82 to your computer and use it in GitHub Desktop.
Save amomchilov/ef1c84325fe6bb4ce01e0f0780837a82 to your computer and use it in GitHub Desktop.
Temporarily by-pass access modifiers on an object.
#!/usr/bin/ruby
def disrespect_privacy(symbol, &block) # access private methods in a block
raise ArgumentError, 'Block must be specified' unless block_given?
block_binding = block.binding
target_object = block_binding.local_variable_get(symbol)
block_binding.local_variable_set(symbol, PrivacyViolator.new(target_object))
yield
ensure
block_binding.local_variable_set(symbol, target_object)
end
class PrivacyViolator
def initialize(object_or_class)
@object = object_or_class
end
def method_missing(method, *args)
@object.send(method, *args)
end
end
class C
def foo
puts "foo"
end
private
def bar
puts "foo"
end
end
o = C.new()
disrespect_privacy(:o) do
puts o.bar # works
end
puts o.bar # private method `bar' called
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment