Rails Workflow Gem - metaprogramming events in named_scopes?

I am using http://github.com/geekq/workflow to provide a state machine. I use ActiveRecord to save state, which means that I have the attribute "workflow_state" in the model. I think I want named_scope for every event in the destination machine, so I can find all objects in a specific state. For example, assuming a very simple state machine:

workflow do
  state :new do
    event :time_passes, :transitions_to => :old
  end
  state :old do
    event :death_arrives, :transitions_to => :dead
  end
  state :dead
end

I want the scope to be specified for each state. However, this is NOT DRY ... What I want in the end is something like:

named_scope :new, :conditions => ['workflow_state = ?', 'new']
named_scope :old, :conditions => ['workflow_state = ?', 'old']
named_scope :dead, :conditions => ['workflow_state = ?', 'dead']

But with a few lines that are independent of the current list of states.

, Model # workflow_spec.states.keys . , , - , . , . . irb, , , . , !

, , - :

  workflow_spec.states.keys.each do |state|
     named_scope state, :conditions => ['workflow_state = ?', state.to_s] 
  end
+5
2

-

workflow_spec.states.keys.each do |state|
   named_scope state, :conditions => ['workflow_state = ?', state] 
end
+3

. , :

class Order < ActiveRecord::Base
  include Workflow
  workflow do
    state :approved
    state :pending
    state :clear
  end
end

# returns all orders with `approved` state
Order.with_approved_state

# returns all orders with `pending` state
Order.with_pending_state

# returns all orders with `clear` state
Order.with_clear_state

: https://github.com/geekq/workflow

0

All Articles