Strange Symphonies The best way to predict the future is to invent it

7Dec/090

Ruby on Rails Finite State Machine Plugin: Workflow

I've been using the acts_as_state_machine plugin for Ruby on Rails for ages, but I thought it was time I look for alternatives, to see if there has been any development in the Finite State Machine scene. I also started getting worried that even though acts_as_state_machine still works, development on it has pretty much been discontinued. Good or bad, you can't really say.

Lucky me. I found one, and a pretty great one.

Introducing Workflow, your alternate Finite State Machine for Ruby on Rails.

acts_as_state_machine vs Workflow

At its core acts_as_state_machine and Workflow function exactly the same way. Feature wise Workflow wins out as it makes it easier to manage the callbacks. Workflow is more up to date, and I personally prefer its syntax a lot better than acts_as_state_machine.

Workflow's syntax looks a lot more like a Domain Specific Language.

Installing Workflow

Installing Workflow as a Ruby on Rails Plugin

Workflow can be installed either via Ruby Gems or a Ruby on Rails plugin.

As a Ruby on Rails plugin, go to the root folder of your Rails application and execute:

./script/plugin install \
     git://github.com/geekq/workflow.git

Note: You may need Git installed

Installing Workflow via Ruby Gems

Likewise as a Ruby Gem, Workflow can be easily installed. As your root user execute:

gem install workflow

We will need to update your config/environments.rb, and in the Rails::Initializer.run block we will need to add in config.gem 'workflow'.

Your config/environments.rb may look like so:

Rails::Initializer.run do |config|
  ...
  config.gem 'workflow'
  ..
end

Using Workflow

Lets have a look at a sample code, featuring a Person.

class Person < ActiveRecord::Base
  include Workflow
  workflow do
    state :sleeping do
      event :shower, :transitions_to => :showering
      event :work, :transitions_to => :working
    end

    state :showering do
      event :sleep, :transitions_to => :sleeping
      event :work, :transitions_to => :working
      event :date, :transitions_to => :dating do |romantic_interest|
        successful = self.flirt(romantic_interest)
        halt unless successful
      end
    end

    state :working do
      event :shower, :transitions_to => :showering
    end

    state :dating do
      event :shower, :transitions_to => :showering
      event :sleep, :transitions_to => :showering
      event :work, :transitions_to => :showering
    end
  end
end

Note: Workflow makes the assumption that the state of your model is saved in a field called workflow_state.

In line 2 we have to specifically include include Workflow into our model. From there we begin describing the workflow by opening up a workflow block. Inside we define what states the model is going to contain, and what events can be fired to transition the model from one state to another.

The initial state of a model is the first state defined, in this case it is the sleeping state. States are defined in a state block as seen on lines 4, 9, 17, and 23. We have four states here: sleeping, working, showering, dating. Possible events a state may fire are contained within the state block as an event method. These events describe which state they would transition to if they were fired.

Methods are created every time you define a state or event. The method created when you define is a state tests wether or not the state is within a particular state, ie person.sleeping?. The methods created when you define an event is the event itself, ie person.sleep!.

There is also an additional method current_state, where you can investigate the current state of the object.

Given our example model above, these methods were created for our model:

  • sleeping?
  • showering?
  • working?
  • dating?
  • sleep!
  • work!
  • shower!
  • date!
  • current_state

Events

Events help you to transition from one state to another. So suppose your person is sleeping, and you want him to shower, well we'll just call shower!.

person.current_state # "sleeping"
person.shower!
person.current_state # "showering"

Note: When firing an event, Workflow calls ActiveRecord::Base.update_attribute. This means that only your record's state will be saved in the database, any other changes to the record are not. You still have to call ActiveRecord::Base.save. It also doesn't call any validations. Validations will be handled by your guards, which will be discussed later. Calling an event from a new unsaved record, will save the record into the database.

Event Arguments

You can even have your events accept arguments, this can be see on line 12, in the :date block.

    state :showering do
      event :sleep, :transitions_to => :sleeping
      event :work, :transitions_to => :working
      event :date, :transitions_to => :dating do |romantic_interest|
        successful = self.flirt(romantic_interest)
        halt unless successful
      end
    end

Note: The scope of the block is within the instance. Treat it as any other method. self refers to the instance itself. flirt is a method defined in the instance. You would have to define the flirt method yourself.

Lets have a look at an example:

person.current_state # showering

romantic_interest = Person.new
person.date! romantic_interest
person.current_state # dating

With events being able to accept arguments, this gives us a wider range of flexibility on handling and organizing the flow of your model. But they can get more powerful with callbacks.

Callbacks

A state also includes two callbacks. One for entering the state, and one for exiting the state.

Like the event blocks, the callback blocks also accept arguments.

You can define a state's callback like so:

state :sleeping do
  event :shower, :transitions_to => :showering
  event :work, :transitions_to => :working

  on_entry do |prior_state, triggering_event, *event_args|
    # code
  end

  on_exit do |new_state, triggering_event, *event_args|
    # code
  end
end
  • The on_entry callback is called when a person enters the sleeping state.
  • The on_exit callback is called when a person exits the sleeping state.

You can also define your callbacks outside of the state block and in your model itself as methods:

state :sleeping do
  event :shower, :transitions_to => :showering
  event :work, :transitions_to => :working
end

def on_sleeping_entry(prior_state, triggering_event, *event_args)
  # code
end

def on_sleeping_exit(new_state, triggering_event, *event_args)
  # code
end

Note: Notice the naming convention of the method name? To use this method, the callback is called on_ + state name + _entry, and on_ + state name + _entry.

The arguments for the block and method are optional. Therefore for clarity, you may just enter:

state :sleeping do
  event :shower, :transitions_to => :showering
  event :work, :transitions_to => :working

  on_entry do
    # code
  end

def on_sleeping_exit(new_state, triggering_event, *event_args)
  # code
end

Global Callback

This gets tedious if you want to monitor the transitions of every state change. Don't worry, Workflow can handle that.

Workflow comes with an on_transition callback which is placed inside the workflow block:

workflow do
  on_transition do |from, to, triggering_event, *event_args|
    puts "from #{from} to #{to} via #{triggering_event}"
  end
end

Callback Order

With all these callbacks, it gets a bit confusing. Here are Workflow's callbacks in context of ActiveRecord's callbacks:

  • Workflow's in event
  • Workflow's on_transition
  • Workflow's on_exit
  • ActiveRecord::Base.before_save
  • ActiveRecord::Base.save
  • ActiveRecord::Base.after_save
  • Workflow's on_entry

Guarding States: halt!

Using Workflow your model's validations do not work when an event is fired. In fact, only the model's workflow_state is saved when an event is fired, and not any other data.

In Workflow we can setup a guard, or a halt. This will prevent the transition from ever occurring, and provide us with the safety of having our models validated.

Guards can only be used inside the event block itself. For example:

    state :showering do
      event :date, :transitions_to => :dating do |romantic_interest|
        successful = self.flirt(romantic_interest)
        halt unless successful
      end
    end

Assuming that the flirting with the romantic interest was unsuccessful, the person would still be in the the showering state. All thanks to the halt on line 15.

This would run as follows:

person.current_state # showering

romantic_interest = Person.new
person.date! romantic_interest
person.current_state # showering

Instead of just a halt, you can make it more destructive by calling halt! (with an exclamation mark) instead, which will throw the Workflow::TransitionHalted Exception instead.

Conclusion

As you can see Workflow is quite feature rich, and provides more flexibility than acts_as_state_machine. I would recommend using this over acts_as_state_machine any day. So why don't you experiment with it, and have some fun?

19Nov/070

autotest-ting your Rails Application with Visual and Audio Feedback using Growl and mpg321

autotest is a commandline tool that comes packaged together with ZenTest. Designed to continually test your Rails application, autotest makes a slight notch easier by removing the need to repeatedly call the rake task to run your application's various tests.

Note: autotest is not limited to the default Ruby Test::Unit::TestCase. It will even work out of the box with RSpec.

Installing autotest

autotest is actually in the ZenTest gem.

sudo gem install -y ZenTest

Go to your application root directory and run autotest and watch it go!

autotest

Dead simple right? But still slightly irritating having to switch back to the terminal to see the results of test. So lets spruce it up a little, lets make it notify us of the results.

Visual Feedback with Growl

Growl is a notification that is over layed on top of your desktop, so that other applications are able to notify/inform you of anything, generally updates. For example Adium uses it to notify you of people logging in or out.

Note: Growl is a Mac OS X application. For other platforms you'll have to look at integration with their notification apps, for example knotify, or gnome-notification.

Combined together with Growl, you will continuously be notified of the current status of your test suite through a nice non disruptive interface. Thus helping to ensure the integrity of your code base.

Installing Growl

Download Growl and install it. But don't eject the Disc Image yet. We have to install the growlnotify command as well. This has to be done via the command line, so pull up your Terminal again.

We need to find out where Growl has been mounted to.

mount | grep -i growl

Possible Result:

/dev/disk2s2 on /Volumes/Growl 1.1.2 (local, nodev, nosuid, read-only, mounted by aizat)

From here you can see it has been mounted on /Volumes/Growl 1.1.2. Now go back to your Terminal, and we'll install growlnotify.

cd "/Volumes/Growl 1.1.2/"
cd Extras/growlnotify
sudo ./install.sh

By default growlnotify is installed into /usr/local/bin, your applications may not be able to see that this exists. So let's find out.

Execute:

which growlnotify

Desired Result:

/usr/local/bin/growlnotify

Possible Result:

no growlnotify in /opt/local/bin /opt/local/sbin /usr/local/bin /bin /sbin /usr/bin /usr/sbin

We want the desired result, so what do you do if you don't get it?

echo "export PATH=/usr/local/bin:$PATH" &gt;&gt; ~/.bashrc

Now growlnotify is accessible by all new Terminal sessions.

Let's give it a shot, and test out Growl!

growlnotify -m "Hey <a href="http://en.wikipedia.org/wiki/Tony_the_Tiger">Tony</a>, isn't this just grrrrrrreat?

Integrating Growl with autotest

We need to create a .autotest (yes with the period) file in your home directory.

touch ~/.autotest
open ~/.autotest

Now stuff this in there!

module Autotest::Growl

  def self.growl title, msg, img, pri=0, sticky=""
    system "growlnotify -n autotest --image #{img.inspect} -p #{pri} -m #{msg.inspect} #{title} #{sticky}"
  end

  Autotest.add_hook :ran_command do |at|
    results = [at.results].flatten.join("\n")
    output = results.slice(/(\d+)\s+examples?,\s*(\d+)\s+failures?(,\s*(\d+)\s+not implemented)?/)
    if output
      if $~[2].to_i > 0
        growl "Test Results", "#{output}", File.join(ENV['HOME'], %w[Library Application\ Support autotest rails_fail.png]), 2
      else
        growl "Test Results", "#{output}", File.join(ENV['HOME'], %w[Library Application\ Support autotest rails_ok.png])
      end
    end
  end

end

Note: Adapted from Wincent Knowledge Base. I also took the personal liability to move files to the ~/Library/Application Support/ directory as I thought it would be more appropriate. Your choice, just change as desired.

Now for the final touch, the elusive images!

mkdir -p ~/Library/Application\ Support/autotest
cd ~/Library/Application\ Support/autotest
curl -O http://blog.internautdesign.com/files/rails_fail.png
curl -O http://blog.internautdesign.com/files/rails_ok.png

Note: If you want, you can even change the images to whatever you want yourself, just change lines 12 and 14 to point to the image location.

autotest-ing

Now go to the root directory of your Rails application, and simply execute:

autotest

and you should soon be notified of the results of your test.

Note: You can further customize Growl in the System Preferences!

Audio Feedback

Visual feedback is cool, but it would be even more awesome if it had audio feedback to accompany it.

Note: This method is cross platform.

This was first described on FozWorks (read on how to Install)

As I aggregated my autotest images into the ~/Library/Application Support/autotest directory, I thought I'd dump the sound files in there as well. Just pay attention when you have to modify your ~/.autotest to accommodate the different path.

The only disappointment with the default sounds they provide is that, they are a little bit soft, and is often drowned out by my music player. But no worries, you can decide to use your own effects, or if your like me, increase the gain with Audacity.

In the mean time, anyone have some interesting replacement sound effects?

11May/070

Using RubyGems package in Ubuntu Feisty Fawn apt-get Repository

After receiving a comment on my post about installing Rails on Ubuntu Feisty Fawn via RubyGems, I found, to my surprise, there exists a rubygems package in the Ubuntu Feisty Fawn universe repository. Though it is a bit outdated at 0.9.0, while the latest is 0.9.2.

So the commenter ran into a problem trying to use the repository installed rubygems and when executing in the terminal rails [image16x16:terminal], they would get a command not found error.

In actual fact, the rails program does exist but in another path ( /var/lib/gems/1.8/bin [image16x16:file] ).

There are two solutions to this. If you want to use the rubygems package from the repository, go with solution 1. Personally, I would go with solution 2.

Select your poison.

Solution 1: Modify your PATH environment variable

Open up ~/.bashrc [image16x16:file] (This is in your home directory). Append the following:
[block:file]

export PATH=$PATH:/var/lib/gems/1.8/bin

[/block]

Now either source your .bashrc (source ~/.bashrc [image16x16:terminal]) or restart your terminal. But it should work fine after this.

Solution 2: Remove the rubygems package and install via source

[block:terminal]

sudo apt-get remove rubygems

[/block]

Then continue with my guide on installing Rails on Ubuntu Feisty Fawn via RubyGems.