[英]Alias method chain with method not defined
I have a module that gets included inside an Rails Observer. 我有一个模块,包含在Rails Observer中。
The purpose is: 目的是:
after_save
and after_update
a method named check_integrity
after_save
和after_update
一个名为check_integrity
的方法 check_integrity
at the end of after_save
or/and after_update
if defined in the Observer. after_save
或/和after_update
结束时调用check_integrity
。 So in short it should always call check_integrity
. 所以简而言之,它应该总是调用
check_integrity
。
I tried something that looks like the following code: 我尝试了类似以下代码的东西:
module IntegrityObserver
extend ActiveSupport::Concern
included do
alias_method_chain :after_save, :check_integrity
alias_method_chain :after_update, :check_integrity
end
def check_integrity
# do something
end
end
class UserObserver < ActiveRecord::Observer
include IntegrityObserver
def after_save(object)
# do something
end
end
But it raise an error: activesupport-3.0.17/lib/active_support/core_ext/module/aliasing.rb:31:in alias_method': undefined method after_update' for class TaskObserver' (NameError)
但它引发了一个错误:
activesupport-3.0.17/lib/active_support/core_ext/module/aliasing.rb:31:in alias_method': undefined method after_update' for class TaskObserver' (NameError)
Someone has any idea how I can do what I want? 有人知道我怎么能做我想做的事吗?
Thanks! 谢谢!
ActiveRecord already provides observer functionality to monitor the lifecycle of your models. ActiveRecord已经提供了观察器功能来监控模型的生命周期。 Here is how you can register a generic observer which responds to more than one model:
以下是如何注册响应多个模型的通用观察器:
class AuditObserver < ActiveRecord::Observer
observe :account, :balance
def after_update(record)
AuditTrail.new(record, "UPDATED")
end
end
In your config/application.rb file: 在config / application.rb文件中:
config.active_record.observers = :audit_observer
alias_method_chain doesn't work that way. alias_method_chain不起作用。 If you define something like:
如果你定义类似的东西:
alias_method_chain :after_save, :check_integrity
you'll have to define the following method: 你必须定义以下方法:
def after_save_with_check_integrity(*args)
# do something
# you can call the original after_save by calling:
# after_save_without_check_integrity(*args)
end
just be aware that the alias_method_chain use is in most cases considered a bad practice. 请注意,alias_method_chain的使用在大多数情况下被认为是一种不好的做法。
Not like models, observers don't have predefined callback methods, such as after_save, after_update. 与模型不同,观察者没有预定义的回调方法,例如after_save,after_update。 So you got an "undefined method" error.
所以你得到一个“未定义的方法”错误。
You may do it like this, 你可以这样做,
module IntegrityObserver
extend ActiveSupport::Concern
def after_save(record)
check_integrity
end
def after_update(record)
check_integrity
end
def check_integrity
# do something
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.