Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

A very simple state machine plugin built on top of ActiveRecord::Enum

License

NotificationsYou must be signed in to change notification settings

amatsuda/stateful_enum

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

stateful_enum is a state machine gem built on top of ActiveRecord's built-in ActiveRecord::Enum.

Installation

Add this line to your Rails app's Gemfile:

gem'stateful_enum'

And bundle.

Motivation

You Ain't Gonna Need Abstraction

stateful_enum depends on ActiveRecord. If you prefer a "well-abstracted" state machine library that supports multiple datastores, or Plain Old Ruby Objects (who needs that feature?), I'm sorry but this gem is not for you.

I Hate Saving States in a VARCHAR Column

From a database design point of view, I prefer to save state data in an INTEGER column rather than saving the state name directly in a VARCHAR column.

❤️ ActiveRecord::Enum

ActiveRecord 4.1+ has a very simple and useful built-in Enum DSL that provides human-friendly API over integer values in DB.

Method Names Should be Verbs

AR::Enum automatically defines Ruby methods per each label. However, Enum labels are in most cases adjectives or past participle, which often creates weird method names.What we really want to define as methods are the transition events between states, and not the states themselves.

Usage

The stateful_enum gem extends AR::Enum definition to take a block with a similar DSL to thestate_machine gem.

Example:

classBug <ApplicationRecordenum:status,{unassigned:0,assigned:1,resolved:2,closed:3}doevent:assigndotransition:unassigned=>:assignedendevent:resolvedobeforedoself.resolved_at=Time.zone.nowendtransition[:unassigned,:assigned]=>:resolvedendevent:closedoafterdoNotifier.notify"Bug##{id} has been closed."endtransitionall -[:closed]=>:closedendendend

Defining the States

Just call the AR::Enum'senum method. The only difference from the originalenum method is that ourenum call takes a block.Please see the full API documentation ofAR::Enum for more information.

Defining the Events

You can declare events throughevent method inside of anenum block. Then stateful_enum defines the following methods per each event:

An instance method to fire the event

@bug.assign# does nothing and returns false if a valid transition for the current state is not defined

An instance method with! to fire the event

@bug.assign!# raises if a valid transition for the current state is not defined

A predicate method that returns if the event is fireable

@bug.can_assign?# returns if the `assign` event can be called on this bug or not

An instance method that returns the state name after an event

@bug.assign_transition#=> :assigned

Defining the Transitions

You can define state transitions throughtransition method inside of anevent block.

There are a few important details to note regarding this feature:

  • Thetransition method takes a Hash each key of which is state "from" transitions to the Hash value.
  • The "from" states and the "to" states should both be given in Symbols.
  • The "from" state can be multiple states, in which case the key can be given as an Array of states, as shown in the usage example.
  • The "from" state can beall that means all defined states.
  • The "from" state can be an exception of Array of states, in this case the key can be a subtraction ofall with the state to be excluded, as shown in the usage example.

:if and :unless Condition

Thetransition method takes an:if or:unless option as a Proc.

Example:

event:assigndotransition:unassigned=>:assigned,if:->{ !!assigned_to}end

Event Hooks

You can definebefore andafter event hooks inside of anevent block.

Inspecting All Defined Events And Current Possible Events

You can get the list of defined events from the model class:

Bug.stateful_enum.events#=> an Array of all defined StatefulEnum::Machine::Event objects

And you can get the list of possible event definitions from the model instance:

Bug.new(status::assigned).stateful_enum.possible_events#=> an Array of StatefulEnum::Machine::Event objects that are callable from the receiver object

Maybe what you really need for your app is the list of possible event "names":

Bug.new(status::assigned).stateful_enum.possible_event_names#=> [:resolve, :close]

You can get the list of next possible state names as well:

Bug.new(status::assigned).stateful_enum.possible_states#=> [:resolved, :closed]

These features would help some kind of metaprogramming over state transitions.

Generating State Machine Diagrams

stateful_enum includes a Rails generator that generates a state machine diagram.Note that you need to bundle the ruby-graphviz gem (and its dependencies) for the development env in order to run the generator.

% rails g stateful_enum:graph bug

You can specify relative or absolute output path via environment variableDEST_DIR.

% DEST_DIR=doc rails g stateful_enum:graph bug

TODO

  • Better Error handling

Support Rails Versions

  • Rails 4.1.x, 4.2.x, 5.0, 5.1, 5.2, 6.0, 6.1, 7.0, 7.1, 7.2, 8.0, and 8.1 (edge)

Contributing

Pull requests are welcome on GitHub athttps://github.com/amatsuda/stateful_enum.

License

The gem is available as open source under the terms of theMIT License.

About

A very simple state machine plugin built on top of ActiveRecord::Enum

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors13


[8]ページ先頭

©2009-2025 Movatter.jp