Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ifyouseewendy/113bc829e70f9da478e0 to your computer and use it in GitHub Desktop.
Save ifyouseewendy/113bc829e70f9da478e0 to your computer and use it in GitHub Desktop.
Replace `method_missing` with dynamic method definition.
class Decorator
def initialize(subject)
@subject = subject
end
def method_missing(sym, *args, &block)
@subject.send sym, *args, &block
end
end
# Since the method call is being called on the decorator but the subject is raising the error,
# it may be painful to track down where the problem resides.
#
# These problems can be avoided entirely by using the available data to dynamically define methods at runtime.
#
# Using this technique any invalid method calls will be correctly reported as NoMethodErrors on the decorator.
# Additionally, there’s no method_missing definition, which should help avoid the stack level too deep problem entirely.
# Move subject's methods to Decorator instance's singleton methods.
class Decorator
def initialize(subject)
subject.public_methods(false).each do |meth|
(class << self; self; end).class_eval do
define_method meth do |*args|
subject.send meth, *args
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment