Flow

Flow is a simple workflow engine mixin for controllers that makes generating simple or complex user flows as easy as it should be, rather than the painful process it usually is with MVC. Also, it makes your controllers incredibly skinny, by moving the flow logic out of the controller into a Flow::Context model.

Usage:

Say you want to create a multi-page flow for new user signup. Assuming you keep the logic for creating users in your User model, where it belongs, this is all the code you would need:

class NewUserFlowContext < Flow::Context
  state :start do
    if params[:already_a_member]
      transition(:login)
    else
      transition(:signup)
    end
  end

  state :login

  state :signup do
    if User.name_taken?(params[:username])
      flash[:error] = 'Username already taken. Please choose another.'
      transition(:signup)
    else
      u = User.create(params)
      data[:user_id] = u.id
      transition(:confirm)
    end
  end 
end

class NewUserController
  include Flow
  flow :new_user
end

Then you just create a template for each state in app/views/new_user. Flow also provides two helper functions to make template creation really easy:

<%= flow_link_to "I already have an account", :already_a_member => true %>

<% flow_form_tag do -%>
  <%= text_field_tag :name %>
  <%= text_field_tag :email_address %>
  <%= password_field_tag :password %>
  <%= submit_tag %>
<% end %>

These are just like link_to and form_tag, but they submit to the :next action, which is a special action for transitioning between states. They also add the parameters necessary to maintain context.

Internals:

When you call the flow class macro in a controller, it creates an action for each state defined in the specified flow context. It also creates an action called :next for transitioning between states. The template helper functions (flow_link_to, and flow_form_tag) submit a POST to this action. All transition logic is performed within next and then the user is redirected using a GET to the correct state action. This means users can safely use their browser back button to return to previous steps and use the forward button if they change their mind.

Flow::Context is an ActiveRecord model. This allows flows to be easily persisted between steps.

Install:

sudo gem install flow

You also need to create a migration to make the flow_contexts table. See examples/sample_migration.rb

License:

Copyright © 2009 Justin Balthrop, Geni.com; Published under The MIT License, see License.txt