Created
July 9, 2024 12:48
-
-
Save wyodeb/930f231e9b0fd771aea962bacdac0738 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
class DynamicProxy | |
def initialize(subject) | |
@subject = subject | |
end | |
def method_missing(method_name, *args, &block) | |
if @subject.respond_to?(method_name) | |
@subject.send(method_name, *args, &block) | |
else | |
super | |
end | |
end | |
def respond_to_missing?(method_name, include_private = false) | |
@subject.respond_to?(method_name, include_private) || super | |
end | |
end | |
class RealSubject | |
def existing_method | |
"This method exists!" | |
end | |
end | |
real_object = RealSubject.new | |
proxy = DynamicProxy.new(real_object) | |
puts proxy.existing_method # Outputs: "This method exists!" | |
puts proxy.non_existing_method # Raises NoMethodError (trick to handle) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment