Ruby 在Rails模型中创建回调的目的是什么?
在什么情况下我们应该使用它?Ruby 在Rails模型中创建回调的目的是什么?,ruby,ruby-on-rails-3,model,callback,Ruby,Ruby On Rails 3,Model,Callback,在什么情况下我们应该使用它?当保存带有new?标志的模型时,将调用around\u create回调代码。它可以用于添加数据以添加/更改模型的值、调用其他方法等。。。我无法为这个回调找到一个特定的用例,但它为创建操作完成了一组“before,after,around”回调。对于查找、更新、保存和删除事件,有一个类似的“before、after、around”回调集。也有这个问题,现在找到了答案:around\u create允许您在一种方法中基本上执行创建之前的和创建之后的。您必须使用yield
当保存带有new?
标志的模型时,将调用around\u create回调代码。它可以用于添加数据以添加/更改模型的值、调用其他方法等。。。我无法为这个回调找到一个特定的用例,但它为创建操作完成了一组“before,after,around”回调。对于查找、更新、保存和删除事件,有一个类似的“before、after、around”回调集。也有这个问题,现在找到了答案:around\u create
允许您在一种方法中基本上执行创建之前的和创建之后的。您必须使用yield
来执行中间的保存
class MyModel < ActiveRecord::Base
around_create :my_callback_method
private
def my_call_back_method
# do some "before_create" stuff here
yield # this makes the save happen
# do some "after_create" stuff here
end
end
classmymodel
一个“环绕”过滤器的经典用例是测量性能、记录或执行其他状态监视或修改。我刚刚找到了一个用例:
想象一个多态观察者的情况,观察者在某些情况下需要在保存之前执行操作,在其他情况下需要在保存之后执行操作
使用around filter,您可以捕获块中的保存操作,并在需要时运行它
class SomeClass < ActiveRecord::Base
end
class SomeClassObserver < ActiveRecord::Observer
def around_create(instance, &block)
Watcher.perform_action(instance, &block)
end
end
# polymorphic watcher
class Watcher
def perform_action(some_class, &block)
if condition?
Watcher::First.perform_action(some_class, &block)
else
Watcher::Second.perform_action(some_class, &block)
end
end
end
class Watcher::First
def perform_action(some_class, &block)
# update attributes
some_class.field = "new value"
# save
block.call
end
end
class Watcher::Second
def perform_action(some_class, &block)
# save
block.call
# Do some stuff with id
Mailer.delay.email( some_class.id )
end
end
class-SomeClass
除了日志记录和监控之外,我发现关键的区别在于控制操作是否运行。否则,您可以在*
之前和*
之后执行自己的回调,以执行相同的操作
以更新前后的为例。假设您不希望运行更新。例如,我正在构建一个gem,它将草稿保存在另一个drafts
表中,但不将某些更新保存到“master”表中
这里引用的update\u base\u record?
方法的细节并不重要。您可以看到,如果该方法的计算结果不为true
,那么更新操作就不会运行。下面给出了关于我找到的around callback的更简单、简洁的解释
around_*回调在操作周围以及before_*和after_*操作内部调用。例如:
class User
def before_save
puts 'before save'
end
def after_save
puts 'after_save'
end
def around_save
puts 'in around save'
yield # User saved
puts 'out around save'
end
end
User.save
before save
in around save
out around save
after_save
=> true
原贴
class User
def before_save
puts 'before save'
end
def after_save
puts 'after_save'
end
def around_save
puts 'in around save'
yield # User saved
puts 'out around save'
end
end
User.save
before save
in around save
out around save
after_save
=> true