I have an existing class with many instance methods. I'd like to encapsulate (or subclass) that class, such that the new class can have all those original instance methods called on it, and simply delegate to the inner (or parent) class, but also call its own code before and after the delegation.
For example, here is some pseudocode I'd be looking for:
class Wrapper
def initialize(inner)
@inner = inner
end
def __getattr__(method_name, *method_args) # <-- made up syntax
# do something before
ret = @inner.method_name(*method_args) # <-- made up syntax, call method on inner
# do something after
ret
end
What is the best way to implement this in ruby? Thanks
Something like:
def method_missing(method_name, *method_args, &block) # <-- made up syntax
if @inner.respond_to? method_name
# do something before
ret = @inner.send(method_name, *method_args, &block) # <-- made up syntax, call method on inner
# do something after
ret
else
super(method_name, *method_args, &block)
end
end
Should do the trick.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.