Skip to content

Commit

Permalink
Added the ability to use conditional callbacks.
Browse files Browse the repository at this point in the history
  • Loading branch information
j0hnds@gmail.com committed Nov 27, 2011
1 parent 26154ef commit de3f80f
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 4 deletions.
8 changes: 4 additions & 4 deletions lib/ayl-rails/railtie.rb
Expand Up @@ -31,13 +31,13 @@ def ayl_#{hook}(*args, &block)
def add_ayl_hook(hook, *args, &block)
if args && args.first.is_a?(Symbol)
method = args.shift
ayl_hooks[hook] << lambda{|o| o.send(method)}
ayl_hooks(*args)[hook] << lambda{|o| o.send(method)}
else
ayl_hooks[hook] << block
ayl_hooks(*args)[hook] << block
end
end

def ayl_hooks
def ayl_hooks(*args)
@ayn_hooks ||= Hash.new do |hash, hook|
# Remember: this block is invoked only once for each
# access of a key that has not been used before.
Expand All @@ -58,7 +58,7 @@ def ayl_hooks
# So, the self.class target for the ayl_send is because we
# need to call the ayl_send method at the singleton level.
#
send(hook) { |o| self.class.ayl_send(ahook, o) }
send(hook, *args) { |o| self.class.ayl_send(ahook, o) }

# This is for the worker's benefit
#
Expand Down
43 changes: 43 additions & 0 deletions spec/rails_extensions_spec.rb
Expand Up @@ -60,6 +60,30 @@ def handle_after_create
end
end

module ConditionalCallbacks; end

class ConditionalCallbacks::MyModel < ActiveRecord::Base
attr_accessor :do_callback

ayl_after_create :handle_after_create, :if => :should_do_callback?

ayl_after_update :handle_after_update, :if => :should_do_callback?

private

def handle_after_create
WhatHappened.instance << "handle after create"
end

def handle_after_update
WhatHappened.instance << "handle after update"
end

def should_do_callback?
@do_callback
end
end

describe "Rails Extensions" do

before(:each) do
Expand Down Expand Up @@ -166,4 +190,23 @@ def handle_after_create

end

context "when using conditional callbacks" do

it "should invoke the after_create and after_update callbacks when the flag is true" do
model = ConditionalCallbacks::MyModel.new(:name => "spud")
model.do_callback = true # Should allow after_create to be called, but not after_update
model.save
model.update_attribute(:name, "dog")
WhatHappened.instance.what_ran.should == [ "handle after create", "handle after update" ]
end

it "should not invoke the after_create or after_update callbacks when the flag is false" do
model = ConditionalCallbacks::MyModel.new(:name => "spud")
model.do_callback = false # Should allow after_update to be called, but not after_create
model.save
model.update_attribute(:name, "dog")
WhatHappened.instance.what_ran.should be_blank
end
end

end

0 comments on commit de3f80f

Please sign in to comment.