这是我的一个小问题。请注意,这是一个简化的示例。假设我有一个包含多个实例方法的类,并且我想使用来记录其中一个实例方法ActiveSupport::Concern
:
class Car
include LogStartEngine
def start_engine
# useful thing
end
def check_oil
# useful thing
end
def open_doors
# useful thing
end
end
这是我首先想到的问题:
module LogStartEngine
extend ActiveSupport::Concern
included do
alias_method_chain :start_engine, :logging
end
def start_engine_with_logging
Rails.logger.info("Starting engine!")
start_engine_without_logging
Rails.logger.info("Engine started!")
end
end
但这将导致
NameError: undefined method `start_engine' for class `Car'
from /Users/david/.gem/ruby/1.9.3/gems/activesupport-4.0.3/lib/active_support/core_ext/module/aliasing.rb:32:in `alias_method'
这是可以理解的,因为当LogStartEngine
包含时,类Car
没有任何称为的方法start_engine
。
我知道我可以解决这种放置include LogStartEngine
方法,start_engine
但是我想保留此语句在原处。
因此约束是:
start_engine
,而不记录所有方法。Car
只需要包括LogStartEngine
关注。我希望避免调用由顾虑添加的任何自定义帮助程序方法,例如log_method :start_engine
。include LogStartEngine
声明的位置。我不希望它位于方法下方start_engine
或课程结束时。Module#prepend
这不是一个有效的解决方案:)这是个老问题,但我找到了答案,然后为某人写信。
module LogStartEngine
extend ActiveSupport::Concern
define_method :start_engine_with_logging do
Rails.logger.info("Starting engine!")
start_engine_without_logging
Rails.logger.info("Engine started!")
end
included do
alias_method_chain :start_engine, :logging
end
end
define_method
这是该方法的重点,它动态地在include上定义了方法(在之前alias_method_chain
)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句