Permalink
Browse files

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.
  • Loading branch information...
1 parent cd7688c commit dc15b1c5609bd3a7122dafe30cce3d98ba31614f @ches ches committed Oct 29, 2013
Showing with 18 additions and 1 deletion.
  1. +3 −0 lib/active_resource.rb
  2. +3 −0 lib/active_resource/base.rb
  3. +12 −1 lib/active_resource/railtie.rb
View
@@ -41,3 +41,6 @@ module ActiveResource
autoload :Validations
autoload :Collection
end
+
+require 'active_resource/railtie' if defined? Rails
+
@@ -1560,4 +1560,7 @@ class Base
include ActiveModel::Serializers::Xml
include ActiveResource::Reflection
end
+
+ ActiveSupport.run_load_hooks(:active_resource, Base)
end
+
@@ -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
+end
+

0 comments on commit dc15b1c

Please sign in to comment.