Permalink
Browse files

Merge pull request #8 from dbalatero/master

Added support for custom notify_observers() calls
  • Loading branch information...
2 parents b39544b + 4c97f5d commit a0978d58e131a2f53df337c59a91c0b7dacb70e1 Pat Maddox committed Apr 28, 2012
Showing with 41 additions and 2 deletions.
  1. +1 −0 .gitignore
  2. +6 −0 lib/no_peeping_toms.rb
  3. +34 −2 spec/no_peeping_toms_spec.rb
View
@@ -3,3 +3,4 @@
Gemfile.lock
pkg/*
spec/debug.log
+.*.sw?
View
@@ -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)
@@ -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

0 comments on commit a0978d5

Please sign in to comment.