Last active
March 4, 2020 22:09
-
-
Save amomchilov/ef1c84325fe6bb4ce01e0f0780837a82 to your computer and use it in GitHub Desktop.
Temporarily by-pass access modifiers on an object.
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
#!/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