discourse/lib/discourse_observer.rb

48 lines
1.3 KiB
Ruby
Raw Normal View History

2013-02-05 14:16:51 -05:00
#
# Support delegating after_create to an appropriate helper for that class name.
# For example, an observer on post will call after_create_post if that method
# is defined.
#
# It does this after_commit by default, and contains a hack to make this work
# even in test mode.
#
class DiscourseObserver < ActiveRecord::Observer
def after_create_delegator(model)
observer_method = :"after_create_#{model.class.name.underscore}"
2013-02-25 11:42:20 -05:00
send(observer_method, model) if respond_to?(observer_method)
2013-02-05 14:16:51 -05:00
end
2013-02-25 11:42:20 -05:00
2013-02-05 14:16:51 -05:00
def after_destroy_delegator(model)
observer_method = :"after_destroy_#{model.class.name.underscore}"
send(observer_method, model) if respond_to?(observer_method)
end
end
if Rails.env.test?
# In test mode, call the delegator right away
class DiscourseObserver < ActiveRecord::Observer
alias_method :after_create, :after_create_delegator
2013-02-25 11:42:20 -05:00
alias_method :after_destroy, :after_destroy_delegator
2013-02-05 14:16:51 -05:00
end
else
# Outside of test mode, use after_commit
class DiscourseObserver < ActiveRecord::Observer
def after_commit(model)
2014-02-17 11:44:28 -05:00
if model.send(:transaction_include_any_action?, [:create])
after_create_delegator(model)
2013-02-05 14:16:51 -05:00
end
2013-02-25 11:42:20 -05:00
2014-02-17 11:44:28 -05:00
if model.send(:transaction_include_any_action?, [:destroy])
after_destroy_delegator(model)
end
2013-02-05 14:16:51 -05:00
end
end
end