Skip to content

Commit

Permalink
prepending actions so they can be added later yet still run first
Browse files Browse the repository at this point in the history
  • Loading branch information
will committed Aug 20, 2008
1 parent df0b22d commit 6dbf8db
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
13 changes: 12 additions & 1 deletion lib/switchbox.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,11 @@ def condition(name, &block)
end

def action(*conditions, &block)
@actions << [lambda{ conditions.all?{|cond| self[cond]} }, block]
@actions << action_item( conditions, block )
end

def prepend_action(*conditions, &block)
@actions.unshift action_item( conditions, block )
end

def [](name)
Expand All @@ -37,5 +41,12 @@ def go
action = @actions.find {|conds,act| conds.call }
action.last.call if action
end

private
def action_item(*args)
action = args.pop
conditions = args.flatten
[ lambda{ conditions.all? { |cond| self[cond] } }, action ]
end
end

8 changes: 8 additions & 0 deletions spec/switchbox_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,14 @@
@mango.should_not_receive :not_action
@mango.should_not_receive :not_action_2
end

it "should be able to prepend actions so that they get checked and ran first" do
@box.action(:true_cond) { @mango.first_action }
@box.prepend_action(:true_cond_2) { @mango.second_action }

@mango.should_receive :second_action
@mango.should_not_receive :first_action
end
end

describe SwitchBox, "#new" do
Expand Down

0 comments on commit 6dbf8db

Please sign in to comment.