Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Support for intercepting custom notifications.

Any call to notify_observers(:my_custom_message) will now be intercepted
in the way you'd expect.
  • Loading branch information...
commit 4c97f5da5b606da9bb7309f55658594e415d9a75 1 parent 3eda8e4
@dbalatero dbalatero authored
Showing with 40 additions and 2 deletions.
  1. +6 −0 lib/no_peeping_toms.rb
  2. +34 −2 spec/no_peeping_toms_spec.rb
View
6 lib/no_peeping_toms.rb
@@ -67,6 +67,12 @@ def define_callbacks_with_enabled_check(klass)
end
end
+ # Enables interception of custom observer notifications, i.e.
+ # notify_observers(:custom_notification)
+ def update(*args, &block)
+ super if observer_enabled?
+ end
+
# Determines whether this observer should be run
def observer_enabled?
self.class.observer_enabled?(self)
View
36 spec/no_peeping_toms_spec.rb
@@ -3,7 +3,22 @@
module NoPeepingTomsSpec
class Person < ActiveRecord::Base; end
class SpecialPerson < Person; end
-
+ class HungryPerson < Person
+ def eat_dinner!
+ notify_observers(:ate_dinner)
+ end
+ end
+
+ class DinnerObserver < ActiveRecord::Observer
+ observe Person
+ cattr_accessor :called
+
+ def ate_dinner(person)
+ self.class.called ||= 0
+ self.class.called += 1
+ end
+ end
+
class PersonObserver < ActiveRecord::Observer
cattr_accessor :called
@@ -12,7 +27,7 @@ def before_create(person)
self.class.called += 1
end
end
-
+
class AnotherObserver < ActiveRecord::Observer
observe Person
cattr_accessor :called
@@ -26,6 +41,7 @@ def before_create(person)
# Register the observers with the host app
PersonObserver.instance
AnotherObserver.instance
+ DinnerObserver.instance
describe NoPeepingToms, "configuration" do
it "enables observers by default" do
@@ -82,6 +98,22 @@ def before_create(person)
AnotherObserver.called.should be_true
end
+ it "should not call observers with custom notifications if they are disabled" do
+ DinnerObserver.called = 0
+ lambda {
+ HungryPerson.new.eat_dinner!
+ }.should_not change(DinnerObserver, :called)
+ end
+
+ it "should call observers with custom notifications if they are enabled" do
+ DinnerObserver.called = 0
+ ActiveRecord::Observer.with_observers(NoPeepingTomsSpec::DinnerObserver) do
+ lambda {
+ HungryPerson.new.eat_dinner!
+ }.should change(DinnerObserver, :called).by(1)
+ end
+ end
+
it "should ensure peeping toms are reset after raised exception" do
lambda {
ActiveRecord::Observer.with_observers(NoPeepingTomsSpec::PersonObserver) do
Please sign in to comment.
Something went wrong with that request. Please try again.