是否可以确定代码是否在某个块中运行?下面描述了我的用例,其中混入了一些伪代码,这演示了我的想法。欢迎任何建议!我希望从WatchTower.bulk_operation do; end
内部调用模型上的任何动作时,模型上的一个块都不会运行。
# watch_tower.rb
module WatchTower
extend ActiveSupport::Concern
class_methods do
def not_safe_for_bulk
yield if block_given? && # not called from within bulk_operation block
end
end
def self.bulk_operation
yield if block_given?
end
end
# Inside some other file, callbacks on number shouldn't run
WatchTower.bulk_operation do
5.times { Number.create }
end
# Inside some other file, callbacks on number SHOULD run
Number.create
# number.rb
class Number < ActiveRecord::Base
include WatchTower
not_safe_for_bulk do
after_commit :something_destructive
end
end
答案 0 :(得分:0)
只要您不从多个线程进行调用,就可以进行以下工作:
def self.bulk_operation
@block_op = true
yield if block_given?
@block_op = false
end
然后在您的方法调用中,只需检查@block_op
标志。