Skip to content

Instantly share code, notes, and snippets.

@wyodeb
Created July 9, 2024 12:48
Show Gist options
  • Save wyodeb/930f231e9b0fd771aea962bacdac0738 to your computer and use it in GitHub Desktop.
Save wyodeb/930f231e9b0fd771aea962bacdac0738 to your computer and use it in GitHub Desktop.
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