Rails Activerecord 观察器不工作
在 Rails 3.1 应用程序中, 我正在尝试创建一个可观察的 activerecord 观察者,但似乎不起作用。
即使只创建activerecord观察者而不是可观察的,after_create 事件未被调用,字符串“in after create event”永远不会被打印出来。 调用者是一个 rake 任务。
这是代码示例以使其清楚。
class PostTemp < ActiveRecord::Base
end
class PostTempObserver < ActiveRecord::Observer
include Observable
attr_reader :new_data
def initialize
@new_data = 0
end
def after_create(record)
#binding.pry
puts "in after create event"
@new_data = 1
notify_observers(@new_data)
@new_data = 0
end
def reset_new_data
@new_data = 0
end
end
class Notifier
attr_reader :total_new_data
def initialize(model_observer)
model_observer.add_observer(self)
@total_new_data = 0
end
def update(new_data_flag)
@total_new_data = @total_new_data + new_data_flag
end
def perform
if @total_new_data > 0
#send notification
puts "notify to bar app..."
@total_new_data = 0
else
puts "no new data"
end
end
end
#in config/application.rb
config.active_record.observers = :post_temp_observer
在task1.rake中
namespace :foo do
desc "crawl message and notify if there's new data"
task :get_message => :environment do
post_temp_observer = PostTempObserver.instance
notifier = Notifier.new(post_temp_observer)
#..
#do some crawling
#..
notifier.perform
end
end
In rails 3.1 app,
I am trying to create an observable activerecord observer, but seems it doesn't work.
Even creating only activerecord observer without being observable, the after_create
event is not called, the string "in after create event" is never printed out.
The caller is a rake task.
Here's the code sample to make it clear.
class PostTemp < ActiveRecord::Base
end
class PostTempObserver < ActiveRecord::Observer
include Observable
attr_reader :new_data
def initialize
@new_data = 0
end
def after_create(record)
#binding.pry
puts "in after create event"
@new_data = 1
notify_observers(@new_data)
@new_data = 0
end
def reset_new_data
@new_data = 0
end
end
class Notifier
attr_reader :total_new_data
def initialize(model_observer)
model_observer.add_observer(self)
@total_new_data = 0
end
def update(new_data_flag)
@total_new_data = @total_new_data + new_data_flag
end
def perform
if @total_new_data > 0
#send notification
puts "notify to bar app..."
@total_new_data = 0
else
puts "no new data"
end
end
end
#in config/application.rb
config.active_record.observers = :post_temp_observer
in task1.rake
namespace :foo do
desc "crawl message and notify if there's new data"
task :get_message => :environment do
post_temp_observer = PostTempObserver.instance
notifier = Notifier.new(post_temp_observer)
#..
#do some crawling
#..
notifier.perform
end
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我自己想出来了。
我需要在 PostTempObserver 中添加 super 和 changed
I figured it out myself.
I need to add super and changed in PostTempObserver