Module: DataMapper::Is::StateMachine

Defined in:
lib/dm-is-state_machine/is/data/event.rb,
lib/dm-is-state_machine/is/data/state.rb,
lib/dm-is-state_machine/is/data/machine.rb,
lib/dm-is-state_machine/is/dsl/event_dsl.rb,
lib/dm-is-state_machine/is/dsl/state_dsl.rb,
lib/dm-is-state_machine/is/state_machine.rb

Defined Under Namespace

Modules: Data, EventDsl, InstanceMethods, StateDsl Classes: DuplicateStates, EventConfusion, InvalidContext, InvalidEvent, InvalidState, NoInitialState

Instance Method Summary collapse

Instance Method Details

#inherited(base) ⇒ Object



71
72
73
74
75
76
# File 'lib/dm-is-state_machine/is/state_machine.rb', line 71

def inherited(base)
  super
  base.class_eval do
    @is_state_machine = superclass.instance_variable_get(:@is_state_machine)
  end
end

#is_state_machine(options = {}, &block) ⇒ Object

Makes a column (‘state’ by default) act as a state machine. It will define the property if it does not exist.

Examples:

Usage
is :state_machine
is :state_machine, :initial => :internal
is :state_machine, :column => :availability
is :state_machine, :column => :availability, :initial => :external

Parameters:

  • options (Hash) (defaults to: {})

    a hash of options

  • :column<Symbol> (Hash)

    a customizable set of options



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/dm-is-state_machine/is/state_machine.rb', line 26

def is_state_machine(options = {}, &block)
  extend DataMapper::Is::StateMachine::EventDsl
  extend DataMapper::Is::StateMachine::StateDsl
  include DataMapper::Is::StateMachine::InstanceMethods

  # ===== Setup context =====
  options = { :column => :state, :initial => nil }.merge(options)
  column  = options[:column]
  initial = options[:initial].to_s
  unless properties.detect { |p| p.name == column }
    property column, String, :default => initial
  end
  machine = Data::Machine.new(column, initial)
  @is_state_machine = { :machine => machine }

  class_eval <<-RUBY, __FILE__, __LINE__ + 1
    def #{column}=(value)
      value = value.to_s if value.kind_of?(Symbol)
      attribute_set(#{column.inspect}, value)
    end
  RUBY

  # ===== Define callbacks =====
  # TODO: define callbacks
  # before :save do
  #   if self.new_record?
  #     # ...
  #   else
  #     # ...
  #   end
  # end

  before :destroy do
    # Do we need to do anything here?
  end

  # ===== Setup context =====
  push_state_machine_context(:is)

  yield if block_given?

  # ===== Teardown context =====
  pop_state_machine_context
end