From dc15b1c5609bd3a7122dafe30cce3d98ba31614f Mon Sep 17 00:00:00 2001 From: Ches Martin Date: Tue, 29 Oct 2013 22:16:00 +0800 Subject: [PATCH] Instantiate observers via Railtie, and run load hooks I spent some time figuring out how to cleanly use the ActiveResource observer support in a Rails app, finding surprisingly little documentation beyond ActiveModel::Observer itself, arriving at the need for this essential boilerplate in an initializer: ActiveResource::Base.observers = # ... ActiveResource::Base.instantiate_observers This change packages it up as neatly as ActiveRecord observers in Rails: # In config/application.rb config.active_resource.observers = [:post_observer, :comment_observer] The Railtie will instantiate observers automatically, and reload them for each request in development just like rails-observers does for ActiveRecord. --- lib/active_resource.rb | 3 +++ lib/active_resource/base.rb | 3 +++ lib/active_resource/railtie.rb | 13 ++++++++++++- 3 files changed, 18 insertions(+), 1 deletion(-) diff --git a/lib/active_resource.rb b/lib/active_resource.rb index b8c77a56e5..ef3490e009 100644 --- a/lib/active_resource.rb +++ b/lib/active_resource.rb @@ -41,3 +41,6 @@ module ActiveResource autoload :Validations autoload :Collection end + +require 'active_resource/railtie' if defined? Rails + diff --git a/lib/active_resource/base.rb b/lib/active_resource/base.rb index f9a66bd7f9..dcac3ae8f2 100644 --- a/lib/active_resource/base.rb +++ b/lib/active_resource/base.rb @@ -1560,4 +1560,7 @@ class Base include ActiveModel::Serializers::Xml include ActiveResource::Reflection end + + ActiveSupport.run_load_hooks(:active_resource, Base) end + diff --git a/lib/active_resource/railtie.rb b/lib/active_resource/railtie.rb index 60f6f88311..6b0a433e97 100644 --- a/lib/active_resource/railtie.rb +++ b/lib/active_resource/railtie.rb @@ -10,5 +10,16 @@ class Railtie < Rails::Railtie ActiveResource::Base.send "#{k}=", v end end + + config.after_initialize do |app| + ActiveSupport.on_load(:active_resource) do + ActiveResource::Base.instantiate_observers + + ActionDispatch::Reloader.to_prepare do + ActiveResource::Base.instantiate_observers + end + end + end end -end \ No newline at end of file +end +