Code Monkey home page Code Monkey logo

micromachine's Introduction

MicroMachine

Minimal Finite State Machine.

Description

There are many finite state machine implementations for Ruby, and they all provide a nice DSL for declaring events, exceptions, callbacks, and all kinds of niceties in general.

But if all you want is a finite state machine, look no further: this has less than 50 lines of code and provides everything a finite state machine must have, and nothing more.

Usage

require 'micromachine'

machine = MicroMachine.new(:new) # Initial state.

# Define the possible transitions for each event.
machine.when(:confirm, :new => :confirmed)
machine.when(:ignore, :new => :ignored)
machine.when(:reset, :confirmed => :new, :ignored => :new)

machine.trigger(:confirm)  #=> true
machine.state              #=> :confirmed

machine.trigger(:ignore)   #=> false
machine.state              #=> :confirmed

machine.trigger(:reset)    #=> true
machine.state              #=> :new

machine.trigger(:ignore)   #=> true
machine.state              #=> :ignored

The when helper is syntactic sugar for assigning to the transitions_for hash. This code is equivalent:

machine.transitions_for[:confirm] = { :new => :confirmed }
machine.transitions_for[:ignore]  = { :new => :ignored }
machine.transitions_for[:reset]   = { :confirmed => :new, :ignored => :new }

You can also ask if an event will trigger a change in state. Following the example above:

machine.state              #=> :ignored

machine.trigger?(:ignore)  #=> false
machine.trigger?(:reset)   #=> true

# And the state is preserved, because you were only asking.
machine.state              #=> :ignored

If you want to force an Exception when trying to trigger a event from a non compatible state use the trigger! method:

machine.trigger?(:ignore)  #=> false
machine.trigger!(:ignore)  #=> MicroMachine::InvalidState raised

It can also have callbacks when entering some state:

machine.on(:confirmed) do
  puts "Confirmed"
end

Or callbacks on any transition:

machine.on(:any) do
  puts "Transitioned..."
end

Note that :any is a special key. Using it as a state when declaring transitions will give you unexpected results.

You can also pass any data as the second argument for trigger and trigger! which will be passed to every callback as the second argument too:

machine.on(:any) do |_status, payload|
  puts payload.inspect
end

machine.trigger(:cancel, from: :user)

Finally, you can list possible events or states:

# All possible events
machine.events #=> [:confirm, :ignore, :reset]

# All events triggerable from the current state
machine.triggerable_events #=> [:confirm, :ignore]

# All possible states
machine.states #=> [:new, :confirmed, :ignored]

Check the examples directory for more information.

Adding MicroMachine to your models

The most popular pattern among Ruby libraries that tackle this problem is to extend the model and transform it into a finite state machine. Instead of working as a mixin, MicroMachine's implementation is by composition: you instantiate a finite state machine (or many!) inside your model and you are in charge of querying and persisting the state. Here's an example of how to use it with an ActiveRecord model:

class Event < ActiveRecord::Base
  before_save :persist_confirmation

  def confirm!
    confirmation.trigger(:confirm)
  end

  def cancel!
    confirmation.trigger(:cancel)
  end

  def reset!
    confirmation.trigger(:reset)
  end

  def confirmation
    @confirmation ||= begin
      fsm = MicroMachine.new(confirmation_state || "pending")

      fsm.when(:confirm, "pending" => "confirmed")
      fsm.when(:cancel, "confirmed" => "cancelled")
      fsm.when(:reset, "confirmed" => "pending", "cancelled" => "pending")

      fsm
    end
  end

private

  def persist_confirmation
    self.confirmation_state = confirmation.state
  end
end

This example asumes you have a :confirmation_state attribute in your model. This may look like a very verbose implementation, but you gain a lot in flexibility.

An alternative approach, using callbacks:

class Event < ActiveRecord::Base
  def confirm!
    confirmation.trigger(:confirm)
  end

  def cancel!
    confirmation.trigger(:cancel)
  end

  def reset!
    confirmation.trigger(:reset)
  end

  def confirmation
    @confirmation ||= begin
      fsm = MicroMachine.new(confirmation_state || "pending")

      fsm.when(:confirm, "pending" => "confirmed")
      fsm.when(:cancel, "confirmed" => "cancelled")
      fsm.when(:reset, "confirmed" => "pending", "cancelled" => "pending")

      fsm.on(:any) { self.confirmation_state = confirmation.state }

      fsm
    end
  end
end

Now, on any transition the confirmation_state attribute in the model will be updated.

Installation

$ sudo gem install micromachine

License

Copyright (c) 2009 Michel Martens

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

micromachine's People

Contributors

burgestrand avatar envek avatar fguillen avatar foca avatar frodsan avatar jeg2 avatar jeremyf avatar nathanl avatar soveran avatar vangberg avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

micromachine's Issues

Using micromachine

Not really used to IRC, so felt like i could ask here; sorry if it does not fit. Plus I'm pretty ne to fsm,
I found this gem very understandable, and somehow not bloated compared to other solutions, so 'id like to go further using it

I have a simple use case; let's say sending a specific mail when a state change for one to another.

So in a controller's action, and compared to the example you provide :

@model = Model.find(params[:id])
@model.confirm!
@model.save # to have the new sate effectively saved

In the model I have this :

...
fsm.on(:confirmed) do
  ... sending some mail ...
end
...

If for some reason the model does not save, the mail is still sent (the fsm.on event occurs right when you call confirm! on it). Is it possible able to fire the vent only if the model is valid to save ?

To keep a simple syntax, only calling .confirm! on the model (not overriding with .save to effectively having the state changed in the db), to validate and save the new state. Is that something possible ?

Again, I know it is not stack overflow; hope I'm clear and that it's okay to ask this kind of thing

Best.

Sharing some love

This is by far one of the cleanest code I've ever encountered.
You deserve my LOVE.
❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️

Add `#triggerable_events` method?

MicroMachine exposes an events method, which lists all events that may be possible at any time. But only a subset of those can be triggered from a given state.

In an application it's sometimes useful to present that subset to users. For instance, if a post is in "draft" status, display buttons to trigger :publish or :archive, but not to :unpublish.

I'm using this code to find triggerable events:

sm.transitions_for.keys.select { |event| sm.trigger?(event) }

Might this be worth adding to MicroMachine itself?

Test suite fails to run on ruby 2.1.2

If i run rake or rake test i get:

Warning: you should require 'minitest/autorun' instead.
Warning: or add 'gem "minitest"' before 'require "minitest/autorun"'

and the suite stops with the error

MiniTest::Unit::TestCase is now Minitest::Test. From /Users/xxx/.rbenv/versions/2.1.2/lib/ruby/2.1.0/test/unit/testcase.rb:8:in `<module:Unit>'
/Users/xxx/.rbenv/versions/2.1.2/lib/ruby/2.1.0/test/unit.rb:676:in `<class:Runner>': undefined method `_run_suite' for class `Test::Unit::Runner' (NameError)

I'm on OS X Yosemite (v 10.10) with
ruby 2.1.2p95 (2014-05-08 revision 45877) [x86_64-darwin13.0]
installed with rbenv

In order to have the test suite working i had to:

rbenv local 1.9.3-p547
gem install contest
rake

Side note: I've tried to use dep install to get contest installed but it failed with:

gem install contest:0.1.3
ERROR:  Could not find a valid gem 'contest:0.1.3' (>= 0) in any repository

Bang methods in the README example

It seems to me that bang methods in a state machine model suggests that the change in state will be saved. I think it's better not to use ! in the example code. What do you think?

Trigerring Event Automatically

Hello,

I love the simplicity of this library, thank you for creating it!

I am looking for a FSM framework and micormachine is a close match. However, we want to automate some part of our workflow. In order to do that, the object needs to know its available next states it can transition into, all its available events (to transition into the next state) and possibly the previous state.

Here is a code example to better describe this feature:

(irb): machine.state
=> :confirmed
# This is what I'd need
(irb): machine.next_events
=> [:reset]
(irb): machine.next_states
=> [:new]
(irb): machine.previous_states
=> [:new]

I understand this tool is very simple and you might want to keep it simple. I figured I need to build this functionality and others might take advantage of it.

What do you think?

Change to callback parameters in 1.2 is backwards-incompatible

This is probably a very rare case, but the change in fc9635c is not compatible with the previous version and could result in failures.

The code below demonstrates:

require 'micromachine'

class CallbackBug
  def initialize
    @fsm = MicroMachine.new(:new).tap do |fsm|
      fsm.when(:first,  new: :first_stage)
      fsm.when(:second, first_stage: :second_stage)

      fsm.on(:first_stage, &method(:first_stage))
      fsm.on(:second_stage, &method(:second_stage))

      fsm.on(:any) do |event|
        puts "Event #{event} => #{@fsm.state}"
      end
    end
  end

  def run
    @fsm.trigger!(:first)
    @fsm.trigger!(:second)
  end

  private

  def first_stage(event)
    p event
  end

  def second_stage
  end
end

CallbackBug.new.run

The output of this is:

:first
Event first => first_stage
ArgumentError: wrong number of arguments (1 for 0)
from (pry):28:in `second_stage'

:any transition state

it would be useful if one could do

machine.when(:event,:any => :state)

it is especially useful for events like :reset, for example a connection is dropped and everything must begin anew.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.