Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions lib/stator/transition.rb
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,20 @@ def can_#{@full_name}?
transition = machine.transitions.detect{|t| t.full_name.to_s == #{@full_name.inspect}.to_s }
transition.can?(integration.state)
end

def ensure_#{@full_name}(should_save = true)
integration = _integration(#{@namespace.to_s.inspect})
return true if integration.state == #{@to.inspect}

#{@full_name}(should_save)
end

def ensure_#{@full_name}!
integration = _integration(#{@namespace.to_s.inspect})
return true if integration.state == #{@to.inspect}

#{@full_name}!
end
EV
end

Expand Down
48 changes: 48 additions & 0 deletions spec/model_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,54 @@
}.should raise_error(/cannot transition to \"hyperactivated\" from \"hyperactivated\"/)
end

it "should allow ensure_ transition when already in the target state" do
u = User.new(email: "fred@example.com")
u.activate!
u.hyperactivate!

lambda {
u.ensure_hyperactivate!
}.should_not raise_error

u.state.should eql("hyperactivated")
end

it "should allow ensure_ transition to perform a normal transition when not in the target state" do
u = User.new(email: "fred@example.com")
u.activate!

u.ensure_hyperactivate!

u.state.should eql("hyperactivated")
end

it "should return true from ensure_ methods when already in the target state" do
u = User.new(email: "fred@example.com")
u.activate!
u.hyperactivate!

u.ensure_hyperactivate!.should eql(true)
u.ensure_hyperactivate.should eql(true)
end

it "should allow ensure_ without bang to skip save" do
u = User.new(email: "fred@example.com")
u.activate!

u.ensure_hyperactivate(false)

u.state.should eql("hyperactivated")
u.state_in_database.should eql("activated")
end

it "should raise error from ensure_ bang method when transition is invalid" do
u = User.new(email: "fred@example.com")

lambda {
u.ensure_hyperactivate!
}.should raise_error(ActiveRecord::RecordInvalid)
end

it "should run conditional validations" do
u = User.new
u.state = "semiactivated"
Expand Down