require 'logger'
class AuditDecorator
def initialize (object)
@object = object
@logger = Logger.new(STDOUT)
@object.public_methods.each do |name|
define_singleton_method(name) do |*args, &block|
@logger.info("calling '#{name}' on #{@object.inspect}")
@object.send(name, *args, &block)
end
end
end
end
s1 = AuditDecorator.new("ruby!")
#puts s1.downcase
puts s1.class
运行报错:
I, [2016-04-04T22:07:43.357305 #1575] INFO -- : calling 'define_singleton_method' on "ruby!"
I, [2016-04-04T22:07:43.357316 #1575] INFO -- : calling 'define_singleton_method' on "ruby!"
audit_decorator.rb:11: warning: instance variable @logger not initialized
audit_decorator.rb:11: warning: instance variable @object not initialized
audit_decorator.rb:11:in `block (2 levels) in initialize': undefined method `info' for nil:NilClass (NoMethodError)
from audit_decorator.rb:12:in `block (2 levels) in initialize'
from audit_decorator.rb:9:in `block in initialize'
from audit_decorator.rb:8:in `each'
from audit_decorator.rb:8:in `initialize'
from audit_decorator.rb:18:in `new'
from audit_decorator.rb:18:in `<main>'
求助,谢谢,不知道问题出在哪。书中例子是通过 define_singleton_method 实现 decorator pattern.