state_machine

https://github.com/pluginaweek/state_machine

Ruby

Adds support for creating state machines for attributes on any Ruby class

StateMachine::Machine#define_helper

Defines a new helper method in an instance or class scope with the given
name.  If the method is already defined in the scope, then this will not
override it.

If passing in a block, there are two side effects to be aware of
1. The method cannot be chained, meaning that the block cannot call +super+
2. If the method is already defined in an ancestor, then it will not get
   overridden and a warning will be output.

Example:

  # Instance helper
  machine.define_helper(:instance, :state_name) do |machine, object|
    machine.states.match(object).name
  end
  
  # Class helper
  machine.define_helper(:class, :state_machine_name) do |machine, klass|
    "State"
  end

You can also define helpers using string evaluation like so:

  # Instance helper
  machine.define_helper :instance, <<-end_eval, __FILE__, __LINE__ + 1
    def state_name
      self.class.state_machine(:state).states.match(self).name
    end
  end_eval
  
  # Class helper
  machine.define_helper :class, <<-end_eval, __FILE__, __LINE__ + 1
    def state_machine_name
      "State"
    end
  end_eval

Source | Google | Stack overflow

Edit

git clone [email protected]:pluginaweek/state_machine.git

cd state_machine

open lib/state_machine/machine.rb

Contribute

# Make a new branch

git checkout -b -your-name--update-docs-StateMachine--Machine-define_helper-for-pr


# Commit to git

git add lib/state_machine/machine.rbgit commit -m "better docs for StateMachine::Machine#define_helper"


# Open pull request

gem install hub # on a mac you can `brew install hub`

hub fork

git push <your name> -your-name--update-docs-StateMachine--Machine-define_helper-for-pr

hub pull-request


# Celebrate!