slagyr / statemachine

Ruby Library for statemachines
http://slagyr.github.com/statemachine
Other
41 stars 9 forks source link

Do not perform transitions if context method returns false #11

Closed zombor closed 11 years ago

zombor commented 11 years ago

I have a requirement to abort a transition state change on certain conditions. I've patched the transition file, but didn't see any specs for that specific behavior.

Here's the sample code I'm using:

require 'statemachine'

module Job
  class StateMachine
    def self.factory(job)
      state_machine = Statemachine.build do
        state :new do
          event :expire, :expired, :expired?
          event :accept, :booked
          event :cancel, :canceled
        end

        context Context.new(job)
      end

      state_machine.context.statemachine = state_machine
      state_machine.state = job.state

      state_machine
    end

    class Context
      attr_accessor :statemachine

      def initialize(job)
        @job = job
      end

      def expired?
        if @job.start_date_time > Time.now.utc
          return false
        end
      end
    end
  end
end

If the job start date is not in the past, it will not move to the expired state.

zombor commented 11 years ago

Apparently there are specs for this. I'll fix them up.

slagyr commented 11 years ago

Thanks for the pull request. I'm curious, have you tried the technique documented here? http://slagyr.github.com/statemachine/example3.html

Was is unsatisfactory?

zombor commented 11 years ago

If you mean using on_entry, we did discuss this option, but we are logging all state changes for objects, and didn't want excess noise related to this. We also considered inspecting the objects before performing the state change, but that violates tell don't ask.

slagyr commented 11 years ago

statemachine-2.1.0.gem released.