### Testing state machines with TestHelper Source: https://github.com/state-machines/state_machines/blob/master/README.md Setup examples for using the TestHelper module in Minitest and RSpec test suites. ```ruby # For Minitest require 'state_machines/test_helper' class VehicleTest < Minitest::Test include StateMachines::TestHelper def test_initial_state vehicle = Vehicle.new assert_sm_state vehicle, :parked end end # For RSpec require 'state_machines/test_helper' RSpec.describe Vehicle do include StateMachines::TestHelper it "starts in parked state" do vehicle = Vehicle.new assert_sm_state vehicle, :parked end end ``` -------------------------------- ### Usage examples for assert_sm_transition Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/test-helper.md Examples verifying that firing an event results in the expected state. ```ruby vehicle = Vehicle.new # Fire event and check state assert_sm_transition(vehicle, :ignite, :idling) # Multi-machine assert_sm_transition(vehicle, :disable, :off, machine_name: :alarm_state) ``` -------------------------------- ### Usage examples for assert_sm_can_transition Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/test-helper.md Examples verifying that specific events are valid for the current state. ```ruby vehicle = Vehicle.new # In :parked state assert_sm_can_transition(vehicle, :ignite) # True assert_sm_can_transition(vehicle, :ignite, machine_name: :alarm_state) ``` -------------------------------- ### Install State Machines Source: https://github.com/state-machines/state_machines/blob/master/README.md Installation methods for the state_machines gem. ```ruby gem 'state_machines' ``` ```sh bundle ``` ```sh gem install state_machines ``` -------------------------------- ### Usage examples for assert_sm_cannot_transition Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/test-helper.md Examples verifying that specific events are invalid for the current state. ```ruby vehicle = Vehicle.new # In :parked state assert_sm_cannot_transition(vehicle, :shift_up) # No transition from :parked assert_sm_cannot_transition(vehicle, :shift_up, machine_name: :alarm_state) ``` -------------------------------- ### Usage examples for assert_before_transition Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/test-helper.md Demonstrates testing before_transition callbacks with various conditions and machine targets. ```ruby assert_before_transition(Vehicle, from: :parked, do: :put_on_seatbelt) assert_before_transition(Vehicle, on: :ignite, if: :seatbelt_on?) machine = Vehicle.state_machine(:state) assert_before_transition(machine, on: :ignite, do: :ignite_engine) ``` -------------------------------- ### Usage examples for assert_sm_state Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/test-helper.md Examples showing how to verify states for default or specific machines with optional custom messages. ```ruby vehicle = Vehicle.new # Default :state machine assert_sm_state(vehicle, :parked) # Specific machine assert_sm_state(vehicle, :active, machine_name: :alarm_state) # Custom message assert_sm_state(vehicle, :parked, message: "Vehicle should start parked") ``` -------------------------------- ### Configure Callback Options Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/README.md Example of defining a transition callback with conditional logic. ```ruby before_transition from: :state1, to: :state2, on: :event, if: :condition?, do: :method ``` -------------------------------- ### Implement before_transition examples Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/callbacks-guards.md Various ways to implement before_transition callbacks, including global, state-specific, method references, and conditional logic. ```ruby class Vehicle state_machine :state, initial: :parked do # Before any state transition before_transition do |vehicle, transition| vehicle.log_transition(transition) end # Only when leaving parked before_transition parked: any - :parked do |vehicle| vehicle.put_on_seatbelt end # With method reference before_transition on: :ignite, do: :check_fuel # Conditional before_transition unless: :seatbelt_on?, do: :refuse_ignition event :ignite do transition parked: :idling end end def check_fuel # Custom logic end end ``` -------------------------------- ### Usage examples for assert_after_transition Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/test-helper.md Demonstrates testing after_transition callbacks on classes, machines, and specific state transitions. ```ruby # Test after_transition on class assert_after_transition(Vehicle, on: :crash, do: :tow) # Test on machine machine = Vehicle.state_machine(:state) assert_after_transition(machine, on: :crash, do: :tow) # Test with from/to assert_after_transition(Vehicle, from: :stalled, to: :parked, do: :log_repair) ``` -------------------------------- ### Usage examples for assert_sm_state_persisted Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/test-helper.md Demonstrates verifying state persistence for ActiveRecord models. ```ruby # ActiveRecord example vehicle = Vehicle.create(state: 'parked') vehicle.ignite vehicle.save assert_sm_state_persisted(vehicle, 'idling') assert_sm_state_persisted(vehicle, :active, machine_name: :alarm_state) ``` -------------------------------- ### Implement single state guard system Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/callbacks-guards.md A complete example demonstrating how to coordinate two state machines using :if_state and :unless_state. ```ruby class TorpedoSystem state_machine :bay_doors, initial: :closed do event :open do transition closed: :open end event :close do transition open: :closed end end state_machine :torpedo_status, initial: :loaded do event :fire_torpedo do # Can only fire if bay doors are open transition loaded: :fired, if_state: { bay_doors: :open } end event :reload do # Can only reload if bay doors are closed transition fired: :loaded, unless_state: { bay_doors: :open } end end end system = TorpedoSystem.new system.fire_torpedo # => false (bay_doors: :closed) system.open_bay_doors! system.fire_torpedo # => true (bay_doors: :open) system.reload # => false (unless_state failed) system.close_bay_doors! system.reload # => true (bay_doors: :closed) ``` -------------------------------- ### Implement after_transition examples Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/callbacks-guards.md Various ways to implement after_transition callbacks, including global, event-specific, and state-specific triggers. ```ruby class Vehicle state_machine :state, initial: :parked do # After every transition after_transition do |vehicle, transition| vehicle.notify_observers(transition) end # Specific event after_transition on: :crash, do: :tow # Specific transition after_transition any => :parked do |vehicle| vehicle.seatbelt_on = false end event :ignite do transition parked: :idling end event :crash do transition any - [:parked, :stalled] => :stalled end end def tow # Tow the vehicle end end ``` -------------------------------- ### Define a Basic State Machine Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/api-machine.md Demonstrates a standard state machine setup with an initial state and a transition event. ```ruby class Vehicle state_machine :status, initial: :parked do event :ignite do transition parked: :idling end end end vehicle = Vehicle.new vehicle.status # => "parked" vehicle.ignite # => true vehicle.status # => "idling" ``` -------------------------------- ### Get available transitions Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/api-instance-methods.md Returns a list of Transition objects available from the current state. ```ruby def state_transitions ``` ```ruby vehicle = Vehicle.new vehicle.state_transitions.map { |t| "#{t.event}: #{t.from_name} -> #{t.to_name}" } # => ["ignite: parked -> idling"] ``` -------------------------------- ### Implement multiple state guard system Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/callbacks-guards.md A complete example demonstrating coordination across multiple state machines using aggregate state guards. ```ruby class StarshipBridge state_machine :shields, initial: :down do event :raise do transition down: :up end end state_machine :weapons, initial: :offline do event :arm do transition offline: :armed end end state_machine :warp_core, initial: :stable do event :overload do transition stable: :critical end end state_machine :alert_status, initial: :green do event :red_alert do # Red alert if ANY critical system needs attention transition green: :red, if_any_state: { warp_core: :critical, shields: :down } end event :battle_stations do # Battle stations only if ALL combat systems are ready transition green: :battle, if_all_states: { shields: :up, weapons: :armed } end event :stand_down do # Return to green if no critical conditions transition red: :green, unless_any_state: { warp_core: :critical, shields: :down } end end end bridge = StarshipBridge.new bridge.alert_status_name # => :green # Raise shields - not enough for battle bridge.raise_shields bridge.can_battle_stations? # => false # Arm weapons - now ready bridge.arm_weapons bridge.can_battle_stations? # => true bridge.battle_stations bridge.alert_status_name # => :battle # Overload warp core - triggers red alert bridge.overload_warp_core bridge.can_red_alert? # => true bridge.red_alert bridge.alert_status_name # => :red ``` -------------------------------- ### Setup TestHelper for Minitest and RSpec Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/test-helper.md Include the module in your test class or spec to enable state machine assertions. ```ruby # For Minitest require 'state_machines/test_helper' class VehicleTest < Minitest::Test include StateMachines::TestHelper def test_initial_state vehicle = Vehicle.new assert_sm_state(vehicle, :parked) end end # For RSpec require 'state_machines/test_helper' RSpec.describe Vehicle do include StateMachines::TestHelper it "starts in parked state" do vehicle = Vehicle.new assert_sm_state(vehicle, :parked) end end ``` -------------------------------- ### Execute successful parallel events Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/errors.md Example of firing multiple events that do not conflict. ```ruby # This works if defined properly vehicle.fire_events(:shift_down, :enable_alarm) # Different machines ``` -------------------------------- ### Define a State Machine Class Source: https://github.com/state-machines/state_machines/blob/master/README.md Example of a class using state_machine to manage states, transitions, and callbacks. Ensure super() is called in initialize to properly set up state machine attributes. ```ruby class Vehicle attr_accessor :seatbelt_on, :time_used, :auto_shop_busy, :parking_meter_number state_machine :state, initial: :parked do before_transition parked: any - :parked, do: :put_on_seatbelt after_transition on: :crash, do: :tow after_transition on: :repair, do: :fix after_transition any => :parked do |vehicle, transition| vehicle.seatbelt_on = false end after_failure on: :ignite, do: :log_start_failure around_transition do |vehicle, transition, block| start = Time.now block.call vehicle.time_used += Time.now - start end event :park do transition [:idling, :first_gear] => :parked end before_transition on: :park do |vehicle, transition| # If using Rails: # options = transition.args.extract_options! options = transition.args.last.is_a?(Hash) ? transition.args.pop : {} meter_number = options[:meter_number] unless meter_number.nil? vehicle.parking_meter_number = meter_number end end event :ignite do transition stalled: same, parked: :idling end event :idle do transition first_gear: :idling end event :shift_up do transition idling: :first_gear, first_gear: :second_gear, second_gear: :third_gear end event :shift_down do transition third_gear: :second_gear, second_gear: :first_gear end event :crash do transition all - [:parked, :stalled] => :stalled, if: ->(vehicle) {!vehicle.passed_inspection?} end event :repair do # The first transition that matches the state and passes its conditions # will be used transition stalled: :parked, unless: :auto_shop_busy transition stalled: same end state :parked do def speed 0 end end state :idling, :first_gear do def speed 10 end end state all - [:parked, :stalled, :idling] do def moving? true end end state :parked, :stalled, :idling do def moving? false end end end state_machine :alarm_state, initial: :active, namespace: :'alarm' do event :enable do transition all => :active end event :disable do transition all => :off end state :active, :value => 1 state :off, :value => 0 end def initialize @seatbelt_on = false @time_used = 0 @auto_shop_busy = true @parking_meter_number = nil super() # NOTE: This *must* be called, otherwise states won't get initialized end def put_on_seatbelt @seatbelt_on = true end def passed_inspection? false end def tow # tow the vehicle end def fix # get the vehicle fixed by a mechanic end def log_start_failure # log a failed attempt to start the vehicle end end ``` -------------------------------- ### Example failure output for state assertions Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/test-helper.md The output format when a state assertion fails. ```text Expected Vehicle#state to be parked, but was idling ``` -------------------------------- ### Define state machine with strings Source: https://github.com/state-machines/state_machines/blob/master/README.md Example of using string literals instead of symbols for state and event definitions. ```ruby class Vehicle state_machine initial: 'parked' do event 'ignite' do transition 'parked' => 'idling' end # ... end end ``` -------------------------------- ### Handle State Machine Configuration Errors Source: https://github.com/state-machines/state_machines/blob/master/README.md Examples of ArgumentErrors raised when referencing undefined state machines or invalid states within a transition. ```ruby # Referencing a non-existent state machine event :invalid, if_state: { nonexistent_machine: :some_state } # => ArgumentError: State machine 'nonexistent_machine' is not defined for StarshipBridge # Referencing a non-existent state event :another_invalid, if_state: { shields: :nonexistent_state } # => ArgumentError: State 'nonexistent_state' is not defined in state machine 'shields' ``` -------------------------------- ### Define an ActiveRecord state machine Source: https://github.com/state-machines/state_machines/blob/master/README.md Basic setup for a state machine within an ActiveRecord model. ```ruby class Vehicle < ActiveRecord::Base state_machine initial: :parked do event :ignite do transition parked: :idling end end end ``` -------------------------------- ### Filter transition paths by state Source: https://github.com/state-machines/state_machines/blob/master/README.md Find all possible transition paths between specific starting and ending states. ```ruby vehicle.state_paths(:from => :parked, :to => :first_gear) # => [[ # #, # # # ]] ``` -------------------------------- ### initial Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/configuration.md Configures the initial state for new instances using either a static symbol or a dynamic Proc. ```APIDOC ## initial ### Description Configures the initial state for new instances. The value can be a Symbol representing the state or a Proc that returns the state. ### Type Symbol or Proc (lambda) ### Proc Signature - Receives the object instance as a parameter. - Returns the initial state (symbol or value). - Evaluated once per object creation. ``` -------------------------------- ### Configure initial state with static and dynamic values Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/configuration.md Use a symbol for static initial states or a lambda for dynamic logic based on object attributes. ```ruby class Vehicle state_machine :state, initial: :parked do event :ignite do transition parked: :idling end end end vehicle = Vehicle.new vehicle.state # => "parked" ``` ```ruby class Vehicle attr_accessor :speed state_machine :state, initial: lambda {|vehicle| vehicle.speed == 0 ? :parked : :idling} do # ... end end vehicle = Vehicle.new vehicle.speed = 0 vehicle.state # => "parked" vehicle2 = Vehicle.new vehicle2.speed = 50 vehicle2.state # => "idling" ``` -------------------------------- ### human_event_name Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/api-machine.md Gets the human-readable name for an event. ```APIDOC ## human_event_name ### Description Gets the human-readable name for an event. ### Signature `self.human_event_name(event, klass = nil)` ### Parameters - **event** (Symbol, String) - Required - Event name - **klass** (Class) - Optional - Owner class (auto-detected if nil) ### Returns - **String** - The human-readable name. ``` -------------------------------- ### human_state_event_name Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/class-methods.md Gets the human-readable name for an event. ```APIDOC ## self.human_state_event_name(event, klass = nil) ### Description Gets the human-readable name for an event. ### Parameters - **event** (Symbol, String) - Required - Event name - **klass** (Class) - Optional - Owner class (auto-detected) ### Returns - **String** - The human-readable name. ### Example ```ruby Vehicle.human_state_event_name(:shift_down) # => "shift down" ``` ``` -------------------------------- ### human_state_name Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/class-methods.md Gets the human-readable name for a state. ```APIDOC ## self.human_state_name(state, klass = nil) ### Description Gets the human-readable name for a state. ### Parameters - **state** (Symbol, String) - Required - State name - **klass** (Class) - Optional - Owner class (auto-detected) ### Returns - **String** - The human-readable name. ### Example ```ruby Vehicle.human_state_name(:first_gear) # => "first gear" ``` ``` -------------------------------- ### Handle InvalidParallelTransition exception Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/errors.md Example of rescuing an InvalidParallelTransition when events conflict. ```ruby # Two events that can't run in parallel vehicle = Vehicle.new begin vehicle.fire_events!(:ignite, :shift_up) rescue StateMachines::InvalidParallelTransition => e puts e.message # => "Cannot run events in parallel: ignite, shift_up" puts e.events # => [:ignite, :shift_up] end ``` -------------------------------- ### Instance Methods Reference Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/README.md List of instance methods generated for a state machine named :state with states :parked and events :ignite. ```text state # Get state value state_name # Get state as symbol human_state_name # Get human-readable name parked? # Predicate for state state?(:parked) # Generic predicate ignite # Fire event ignite! # Fire event (strict) can_ignite? # Check if event possible ignite_transition # Get pending transition fire_state_event(:ignite) # Dynamic event firing state_events # Available events state_transitions # Available transitions state_paths # Path analysis ``` -------------------------------- ### Handle InvalidEvent exception Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/errors.md Example of rescuing an InvalidEvent when firing an undefined event. ```ruby vehicle = Vehicle.new begin vehicle.fire_state_event(:invalid) rescue StateMachines::InvalidEvent => e puts e.message # => ":invalid is an unknown state machine event" puts e.event # => :invalid end ``` -------------------------------- ### Get available events Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/api-instance-methods.md Returns a list of events that can be fired from the current state. ```ruby def state_events ``` ```ruby vehicle = Vehicle.new # In :parked state vehicle.state_events # => [:ignite] vehicle.ignite # Transition to :idling vehicle.state_events # => [:idle, :shift_up] ``` -------------------------------- ### Get human-readable state name Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/api-instance-methods.md Returns the human-readable version of the current state. ```ruby def human_state_name ``` ```ruby vehicle.state_name # => :first_gear vehicle.human_state_name # => "first gear" ``` -------------------------------- ### Get human-readable event name Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/class-methods.md Convert an event symbol or string into a human-readable format. ```ruby Vehicle.human_state_event_name(:shift_down) # => "shift down" Vehicle.human_state_event_name('shift_down') # => "shift down" ``` -------------------------------- ### Define a state machine with the macro Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/configuration.md Basic syntax for initializing a state machine with an attribute name and configuration options. ```ruby state_machine :attribute_name, option_name: option_value do # State and event definitions end ``` -------------------------------- ### initialize(owner_class, attribute = :state, options = {}, &block) Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/api-machine.md Creates a new state machine for the given class and attribute. The block is used to configure states, events, and transitions. ```APIDOC ## initialize(owner_class, attribute = :state, options = {}, &block) ### Description Creates a new state machine for the given class and attribute. The block provided is used to configure states, events, and transitions. ### Parameters - **owner_class** (Class) - Required - The class that owns this state machine - **attribute** (Symbol) - Optional - The name of the attribute storing the state value (default: :state) - **options** (Hash) - Optional - Configuration options for the machine - **block** (Proc) - Optional - DSL block for defining states, events, and transitions ### Options - **:initial** - Initial state as a symbol or lambda - **:action** - Instance method to invoke on transition - **:namespace** - Namespace for generated methods - **:initialize** - Automatically initialize attribute via #initialize hook (default: true) - **:integration** - Integration type (e.g., :active_model, :active_record) - **:async** - Enable asynchronous event firing (default: false) - **:plural** - Pluralized name for ORM scopes - **:use_transactions** - Use database transactions on events - **:messages** - Custom error messages for validation ``` -------------------------------- ### Instance Methods Cheat Sheet Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/quick-reference.md Reference for common instance methods used to interact with, query, and analyze state machine objects. ```ruby # State access vehicle.state # Get state value vehicle.state_name # Get state as symbol vehicle.human_state_name # Get human-readable name # State predicates vehicle.parked? # Check specific state vehicle.state?(:parked) # Generic state check # Events vehicle.ignite # Fire event (returns boolean) vehicle.ignite! # Fire event (raises on fail) vehicle.can_ignite? # Check if event possible vehicle.ignite_transition # Get pending transition # Generic methods vehicle.fire_state_event(:ignite) # Dynamic event firing vehicle.fire_events(:ignite, :enable_alarm) # Parallel events vehicle.state_events # Available events from current state vehicle.state_transitions # Available transitions # Analysis vehicle.state_paths # Possible paths from current state vehicle.state_paths(from: :parked, to: :first_gear) # Paths between states ``` -------------------------------- ### Handle InvalidTransition errors Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/types.md Example of rescuing an invalid transition to access machine and state metadata. ```ruby begin vehicle.park! rescue StateMachines::InvalidTransition => e puts "Cannot transition #{e.machine.name} via :#{e.event} from #{e.from_name.inspect}" end ``` -------------------------------- ### Define State Machine Transitions with Matchers Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/configuration.md Demonstrates the use of all, any, and same matchers to define complex transition logic within a state machine block. ```ruby state_machine :state do event :crash do # Transition all except parked/stalled to stalled transition all - [:parked, :stalled] => :stalled end event :repair do transition stalled: same # Stays in stalled end event :ignite do transition stalled: same, parked: :idling end end ``` -------------------------------- ### Get state as symbol Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/api-instance-methods.md Retrieves the current state as a symbol name rather than the stored value. ```ruby def state_name ``` ```ruby vehicle = Vehicle.new # state stored as "parked" vehicle.state_name # => :parked (symbol) vehicle.state # => "parked" (actual value) ``` -------------------------------- ### {machine_name}_transitions Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/api-instance-methods.md Returns a list of all Transition objects available from the current state. ```APIDOC ## {machine_name}_transitions ### Description Gets the list of Transition objects available from the current state. ### Returns Array of Transition ### Example ```ruby vehicle.state_transitions.map { |t| "#{t.event}: #{t.from_name} -> #{t.to_name}" } ``` ``` -------------------------------- ### Validate State Machine Guards Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/callbacks-guards.md Examples of guard validation errors when referencing nonexistent machines or states. ```ruby class Vehicle begin state_machine :status do event :go do # Error: nonexistent_machine doesn't exist transition parked: :moving, if_state: { nonexistent_machine: :ready } end end rescue ArgumentError => e # => "State machine 'nonexistent_machine' is not defined for Vehicle" end end class Vehicle begin state_machine :status do state_machine :engine do event :start do # Error: :invalid_state doesn't exist in engine machine transition off: :on, if_state: { engine: :invalid_state } end end end rescue ArgumentError => e # => "State 'invalid_state' is not defined in state machine 'engine'" end end ``` -------------------------------- ### Get human-readable name for namespaced machine Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/class-methods.md Retrieve the human-readable name for a state within a specific namespace. ```ruby class Vehicle state_machine :alarm_state, namespace: :'alarm' do # ... end end Vehicle.human_alarm_state_name(:active) # => "active" ``` -------------------------------- ### Implement around_transition in a state machine Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/callbacks-guards.md Demonstrates timing, logging, and conditional logic within around_transition. ```ruby class Vehicle state_machine :state, initial: :parked do # Time the transition around_transition do |vehicle, transition, block| start = Time.now block.call vehicle.transition_time = Time.now - start end # Log before and after around_transition do |vehicle, transition, block| puts "Before: #{transition.from_name} -> #{transition.to_name}" block.call puts "After: #{vehicle.state}" end # Conditional around_transition on: :ignite do |vehicle, transition, block| vehicle.engine_diagnostics do block.call end end event :ignite do transition parked: :idling end end end ``` -------------------------------- ### Get transition object Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/api-instance-methods.md Retrieves the Transition object for a potential event, or nil if no valid transition exists. ```ruby def ignite_transition ``` ```ruby vehicle = Vehicle.new transition = vehicle.ignite_transition transition.from_name # => :parked transition.to_name # => :idling transition.event # => :ignite ``` -------------------------------- ### Complete Class Method Usage for State Machines Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/class-methods.md Demonstrates defining multiple state machines within a class and utilizing various class-level helper methods for introspection and state management. ```ruby class Vehicle state_machine :state, initial: :parked do event :ignite do transition parked: :idling end event :park do transition idling: :parked end state :parked state :idling end state_machine :alarm_state, namespace: :'alarm', initial: :off do event :enable do transition off: :active end end end # Class method usage Vehicle.state_machine # => Machine instance Vehicle.state_machine(:state) # => Machine instance Vehicle.state_machine(:alarm_state) # => Machine instance Vehicle.state_machines # => {state: Machine, alarm_state: Machine} Vehicle.state_machines.keys # => [:state, :alarm_state] # Human names Vehicle.human_state_name(:parked) # => "parked" Vehicle.human_state_name(:idling) # => "idling" # State predicates Vehicle.parked? # => true Vehicle.idling? # => true Vehicle.invalid_state? # => false # Path analysis paths = Vehicle.state_paths paths.to_states # => [:parked, :idling] paths.events # => [:ignite, :park] # Namespaced methods Vehicle.human_alarm_state_name(:active) # => "active" Vehicle.alarm_active? # => true Vehicle.alarm_off? # => true ``` -------------------------------- ### Initialize a State Machine Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/api-machine.md Defines the constructor signature for creating a new state machine instance. ```ruby def initialize(owner_class, attribute = :state, options = {}, &block) ``` -------------------------------- ### Implement after_failure in a state machine Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/callbacks-guards.md Demonstrates handling transition failures using after_failure. ```ruby class Vehicle state_machine :state, initial: :parked do after_failure on: :ignite, do: :log_start_failure after_failure on: :park do |vehicle, transition| vehicle.errors.add(:state, "Cannot park from this state") end event :ignite do transition parked: :idling transition stalled: same end end def log_start_failure Rails.logger.warn("Failed to start engine") end end vehicle = Vehicle.new # In :parked vehicle.ignite # Succeeds # Later, in invalid state vehicle.state = 'invalid' vehicle.ignite # Fails, calls log_start_failure ``` -------------------------------- ### Create a new feature branch Source: https://github.com/state-machines/state_machines/blob/master/README.md Use this command to initialize a new feature branch in your local repository. ```bash git checkout -b my-new-feature ``` -------------------------------- ### Triggering StateMachines::IntegrationNotFound Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/errors.md Example of an error raised when an unsupported or non-existent integration is specified in a state machine definition. ```ruby class Vehicle state_machine :state, integration: :nonexistent do event :ignite do transition parked: :idling end end end # Raises: StateMachines::IntegrationNotFound # Message: ":nonexistent is an invalid integration. Valid integrations are: ..." ``` -------------------------------- ### Transition Callback Parameters Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/api-instance-methods.md Accessing transition metadata and objects within before and after transition hooks. ```ruby state_machine :state do before_transition do |object, transition| # object = instance of Vehicle # transition = Transition object transition.from_name # => :parked transition.to_name # => :idling transition.event # => :ignite transition.args # => [args passed to event method] end after_transition on: :park do |object, transition, result| # result = return value from action (if configured) end end ``` -------------------------------- ### Test multiple state machines on a single class Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/test-helper.md Demonstrates how to use StateMachines::TestHelper to verify states, transitions, and callbacks across multiple state machines defined on one class. ```ruby class Vehicle state_machine :status, initial: :docked do event :launch do transition docked: :flying end end state_machine :shields, initial: :down do event :raise do transition down: :up end end state_machine :weapons, initial: :disarmed do event :arm do transition disarmed: :armed end end end class StarfleetShipTest < Minitest::Test include StateMachines::TestHelper def test_multiple_machines ship = Vehicle.new # Test different machines assert_sm_state(ship, :docked, machine_name: :status) assert_sm_state(ship, :down, machine_name: :shields) assert_sm_state(ship, :disarmed, machine_name: :weapons) # Transitions on specific machines assert_sm_transition(ship, :launch, :flying, machine_name: :status) assert_sm_transition(ship, :raise, :up, machine_name: :shields) assert_sm_transition(ship, :arm, :armed, machine_name: :weapons) # Callbacks on specific machines assert_before_transition(Vehicle.state_machine(:shields), from: :down, to: :up, do: :power_up_shields) end end ``` -------------------------------- ### RSpec Style Event Trigger Expectation Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/test-helper.md Example of using an RSpec-style matcher for event triggering within a test suite. ```ruby RSpec.describe Vehicle do include StateMachines::TestHelper it "triggers crash when redlining" do vehicle = Vehicle.new vehicle.ignite expect_to_trigger_event(vehicle, :crash) do vehicle.redline end end end ``` -------------------------------- ### Class Methods Reference Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/README.md List of class methods generated for a state machine named :state with states :parked and events :ignite. ```text state_machine # Get machine state_machines # Get all machines human_state_name(:parked) # Human-readable state human_state_event_name(:ignite) # Human-readable event parked? # State predicate state_paths # Path analysis parked # Scope (ORM only) ``` -------------------------------- ### Iterate and Fetch Events Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/types.md Demonstrates iterating over machine events and fetching specific event branches. ```ruby machine.events.each { |event| puts event.name } machine.events.fetch(:ignite).branches ``` -------------------------------- ### Transition Path Analysis Source: https://github.com/state-machines/state_machines/blob/master/README.md Methods to analyze available transition paths for a specific object instance. ```APIDOC ## vehicle.state_paths(options = {}) ### Description Analyzes and returns available transition paths for the object instance. ### Parameters - **options** (Hash) - Optional - Filter paths by :from or :to states. ### Returns - **state_paths** (Array) - A collection of transition paths. ``` -------------------------------- ### Define verbose transitions and callbacks Source: https://github.com/state-machines/state_machines/blob/master/README.md Use explicit options like :from, :except_from, :to, and :except_to for fine-grained control over transition triggers. ```ruby class Vehicle state_machine initial: :parked do before_transition from: :parked, except_to: :parked, do: :put_on_seatbelt after_transition to: :parked do |vehicle, transition| vehicle.seatbelt = 'off' end event :ignite do transition from: :parked, to: :idling end end end ``` -------------------------------- ### state_paths Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/class-methods.md Analyzes possible transition paths for the class based on provided options. ```APIDOC ## state_paths ### Description Analyzes possible transition paths for the class. ### Signature `def self.state_paths(options = {})` ### Parameters - **options** (Hash) - Optional - Path analysis options - **:from** - Starting state(s) - **:to** - Ending state(s) ### Returns TransitionPaths object ### Example ```ruby Vehicle.state_paths(from: :parked, to: :third_gear) Vehicle.state_paths.to_states ``` ``` -------------------------------- ### Retrieve human-friendly names for states and events Source: https://github.com/state-machines/state_machines/blob/master/README.md Use these methods to get human-readable strings for states and events, supporting both symbol and string inputs. ```ruby Vehicle.human_state_name(:first_gear) # => "first gear" Vehicle.human_alarm_state_name(:active) # => "active" Vehicle.human_state_event_name(:shift_down) # => "shift down" Vehicle.human_alarm_state_event_name(:enable) # => "enable" # States / events can also be references by the string version of their name Vehicle.human_state_name('first_gear') # => "first gear" Vehicle.human_state_event_name('shift_down') # => "shift down" ``` -------------------------------- ### Define a state machine with events and callbacks Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/00-START-HERE.txt Use the state_machine DSL to define initial states, events, transitions, and lifecycle callbacks within a class. ```ruby class Vehicle state_machine :state, initial: :parked do event :ignite do transition parked: :idling end event :park do transition [:idling, :first_gear] => :parked end before_transition on: :ignite, do: :check_fuel after_transition any => :parked do |vehicle| vehicle.seatbelt_on = false end end end vehicle = Vehicle.new vehicle.state_name # => :parked vehicle.ignite # => true vehicle.state_name # => :idling vehicle.can_park? # => true ``` -------------------------------- ### Fire event method Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/api-instance-methods.md Fires the event and attempts the transition. Returns true if successful, false otherwise. ```ruby def ignite ``` ```ruby vehicle.ignite # => true (transition parked -> idling) vehicle.ignite # => false (already idling, transition blocked) ``` -------------------------------- ### Implement State Machine Callbacks Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/README.md Uses before and after transition hooks to trigger logic during state changes. ```ruby class Vehicle state_machine :state, initial: :parked do before_transition on: :ignite, do: :check_fuel after_transition on: :crash, do: :tow event :ignite do transition parked: :idling end end def check_fuel # Validation logic end end ``` -------------------------------- ### Handle transition rollback via action return values Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/configuration.md Demonstrates how returning false from an action method triggers a state rollback. ```ruby class Vehicle state_machine :state, action: :save, initial: :parked do event :ignite do transition parked: :idling end end attr_accessor :fail_save def save !fail_save # Returns true to allow transition end end vehicle = Vehicle.new vehicle.fail_save = true vehicle.ignite # => false (save returned false) vehicle.state # => "parked" (rolled back) vehicle.fail_save = false vehicle.ignite # => true (save returned true) vehicle.state # => "idling" (persisted) ``` -------------------------------- ### Namespaced State Machine Methods Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/api-instance-methods.md Demonstrates how method names are qualified when a namespace is defined for a state machine. ```ruby class Vehicle state_machine :alarm_state, namespace: :'alarm' do event :enable do transition all => :active end end end vehicle = Vehicle.new vehicle.alarm_state # => "active" vehicle.alarm_state_name # => :active vehicle.alarm_active? # => true vehicle.can_enable_alarm? # => true vehicle.enable_alarm # => true ``` -------------------------------- ### Define before_transition method Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/callbacks-guards.md The method signature for defining a before_transition callback. ```ruby def before_transition(options = {}, &block) ``` -------------------------------- ### Implement Conditional Transitions Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/quick-reference.md Control transition execution using if/unless conditions or state guards based on other machines. ```ruby state_machine :state do event :ignite do # Condition must be true transition parked: :idling, if: :seatbelt_on? # Condition must be false transition stalled: :idling, unless: :engine_broken? end event :park do # State guard: other machine must be in state transition idling: :parked, if_state: { engine: :off } # State guard: other machine must NOT be in state transition idling: :parked, unless_state: { alarm: :active } end end def seatbelt_on? # return true/false end ``` -------------------------------- ### Transition Callbacks Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/api-instance-methods.md Methods for defining hooks that execute before, after, or around state transitions. ```APIDOC ## Transition Callbacks ### before_transition / after_transition - **object**: The instance of the class containing the state machine. - **transition**: A Transition object containing `from_name`, `to_name`, `event`, and `args`. - **result**: The return value from the action (available in `after_transition`). ### around_transition - **object**: The instance of the class. - **transition**: The Transition object. - **block**: The block that must be called to execute the transition. ``` -------------------------------- ### Test State Machines with TestHelper Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/quick-reference.md Use the TestHelper module in Minitest to assert state values, transition capabilities, and callback definitions. ```ruby require 'state_machines/test_helper' class VehicleTest < Minitest::Test include StateMachines::TestHelper def test_states vehicle = Vehicle.new # State assertions assert_sm_state(vehicle, :parked) assert_sm_state(vehicle, :active, machine_name: :alarm_state) # Transition capability assert_sm_can_transition(vehicle, :ignite) assert_sm_cannot_transition(vehicle, :shift_up) # Actual transitions assert_sm_transition(vehicle, :ignite, :idling) end def test_callbacks # Test callback definitions assert_before_transition(Vehicle, on: :ignite, do: :check_fuel) assert_after_transition(Vehicle, on: :crash, do: :tow) end def test_event_triggers vehicle = Vehicle.new vehicle.ignite # Test that method triggers event assert_sm_triggers_event(vehicle, :crash) do vehicle.redline end end def test_machine_states machine = Vehicle.state_machine(:state) # Machine-level assertions assert_sm_states_list(machine, [:parked, :idling, :first_gear, :stalled]) assert_sm_initial_state(machine, :parked) end end ``` -------------------------------- ### Querying states with mixed input types Source: https://github.com/state-machines/state_machines/blob/master/README.md Shows how helper methods handle both symbols and strings when querying the current state. ```ruby class Vehicle state_machine initial: :parked do event :ignite do transition parked: :idling end end end v = Vehicle.new # => # v.state?('parked') # => true v.state?(:parked) # => true ``` -------------------------------- ### Event Firing Methods Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/README.md Methods available on instances to trigger state transitions. ```APIDOC ## {event_name} ### Description Attempts to fire the specified event. Returns true if successful, false otherwise. ## {event_name}! ### Description Attempts to fire the specified event. Raises an exception if the transition fails. ## can_{event_name}? ### Description Checks if the specified event can be fired from the current state. Returns a boolean. ``` -------------------------------- ### initialize Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/configuration.md Controls whether the state machine automatically initializes the state attribute upon object creation. ```APIDOC ## initialize ### Description Controls whether to auto-initialize the state attribute. When set to false, the state attribute remains nil until manually set. ### Default true ### Usage - Set to false when managing initialization manually, handling complex logic in custom #initialize methods, or deferring state setting. ``` -------------------------------- ### Callback Definition Testing Source: https://github.com/state-machines/state_machines/blob/master/README.md Verify that after_transition and before_transition callbacks are correctly defined on the class or machine instance. ```ruby # Test after_transition callbacks assert_after_transition(Vehicle, on: :crash, do: :tow) assert_after_transition(Vehicle, from: :stalled, to: :parked, do: :log_repair) # Test before_transition callbacks assert_before_transition(Vehicle, from: :parked, do: :put_on_seatbelt) assert_before_transition(Vehicle, on: :ignite, if: :seatbelt_on?) # Works with machine instances too machine = Vehicle.state_machine(:state) assert_after_transition(machine, on: :crash, do: :tow) ``` -------------------------------- ### Configure State Machine Options Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/quick-reference.md Defines various configuration settings for state machines, including attribute mapping, initial states, namespaces, and integration modes. ```ruby # Attribute name state_machine :status, attribute: :status_code # Initial state (static or dynamic) state_machine :state, initial: :parked state_machine :state, initial: lambda {|obj| obj.speed == 0 ? :parked : :idling} # Action on transition state_machine :state, action: :save # Namespace methods state_machine :alarm, namespace: :'alarm' # Integration type state_machine :state, integration: :active_record # Async mode state_machine :state, async: true # Don't auto-initialize state_machine :state, initialize: false # Custom messages state_machine :state, messages: { invalid: "must have a valid state" } # Use transactions (ActiveRecord) state_machine :state, use_transactions: true # Ignore method conflicts StateMachines::Machine.ignore_method_conflicts = true ``` -------------------------------- ### Correct usage of after_transition with state identifiers Source: https://github.com/state-machines/state_machines/wiki/FAQ-and-Gotchas Use the hash syntax to specify state transitions rather than the :on key, which refers to event names. ```ruby # Good: after_transition all => :paid, do: :process_payment # Bad (won't work): after_transition on: :paid, do: :process_payment ``` -------------------------------- ### Define Callback Types Source: https://github.com/state-machines/state_machines/blob/master/_autodocs/README.md List of available callback hooks for state transitions. ```ruby before_transition # Executes before transition (can halt) after_transition # Executes after transition (already committed) around_transition # Wraps transition (must yield to proceed) after_failure # Executes when transition fails ```