Module: Renalware::ExplicitStateModel
- Extended by:
- ActiveSupport::Concern
- Included in:
- HD::Session, Letters::Letter
- Defined in:
- app/models/concerns/renalware/explicit_state_model.rb
Overview
Enables Explicit State Models with ActiveRecord in contrast to the State pattern or Finite State Machines (FSM). For more information: medium.com/@martinezdelariva/explicit-state-modeling-f6e534c33508#.ljvhnkz01
Example
class Letter < ActiveRecord
include ExplicitStateModel
# define the states you would like
has_states :draft, :approved
end
Calling the ‘has_states` macro will:
-
define scopes for each state; e.g. ‘Letter.draft`, `Letter.approved`
-
add a state attribute; e.g. ‘Letter::Draft.state # => “draft”`
Create subclasses representing those states, this uses ActiveRecord’s STI implementation.
class Letter::Draft < Letter
def approve!
becomes!(Approved)
end
end
class Letter::Approved < Letter
end
You are responsible for managing state transitions using ActiveRecord’s ‘becomes` class method:
Letter::Draft.create!
draft_letter = Letter.draft.first!
draft_letter.state # => "draft"
draft_letter.draft? # => true
approved_letter = draft_letter.approve!
approved_letter.save!
approved_letter.state # => "approved"
Defined Under Namespace
Modules: ClassMethods