Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Merge pull request patmaddox#8 from dbalatero/master
Added support for custom notify_observers() calls
  • Loading branch information
Pat Maddox committed Apr 28, 2012
2 parents b39544b + 4c97f5d commit a0978d5
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 2 deletions.
1 change: 1 addition & 0 deletions .gitignore
Expand Up @@ -3,3 +3,4 @@
Gemfile.lock
pkg/*
spec/debug.log
.*.sw?
6 changes: 6 additions & 0 deletions lib/no_peeping_toms.rb
Expand Up @@ -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)
Expand Down
36 changes: 34 additions & 2 deletions spec/no_peeping_toms_spec.rb
Expand Up @@ -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

Expand All @@ -12,7 +27,7 @@ def before_create(person)
self.class.called += 1
end
end

class AnotherObserver < ActiveRecord::Observer
observe Person
cattr_accessor :called
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit a0978d5

Please sign in to comment.