Created
May 8, 2014 11:51
-
-
Save ifyouseewendy/113bc829e70f9da478e0 to your computer and use it in GitHub Desktop.
Replace `method_missing` with dynamic method definition.
This file contains 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 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