开发者

Enforce an Order to Rails Callbacks

How can one enforce an order of callbacks? For example, how do you ensure that Step 1 happens before Step 2:

after_save d开发者_StackOverflowo
  logger.info "Step 1"
end

after_save do
  logger.info "Step 2"
end

My actual example relates to using third party gems and ensuring that they have completed (they work on callbacks) before my own callbacks. I must use the same callback (i.e. cannot use a before and after combination).

Thanks!


If you use class-level callbacks, they are called in the order they are defined.

class Foo < ActiveRecord::Base

  after_save :step1
  after_save :step2

private

  def step1
    # stuff
  end

  def step2
    # stuff
  end
end

For the third-party gem, it depends on how you interact with the gem, but odds are they will be called first because they were loaded first.

I would not recommend using the def after_save style at all, particularly when dealing with a third-party gem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜