DataMapper::Is::StateMachine

Public Instance Methods

inherited(base) click to toggle source
# 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) click to toggle source

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

@example [Usage]

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

@param options<Hash> a hash of options

@option :column<Symbol> the name of the custom column

# 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           def #{column}=(value)            value = value.to_s if value.kind_of?(Symbol)            attribute_set(#{column.inspect}, value)          end, __FILE__, __LINE__ + 1

  # ===== 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

Protected Instance Methods

pop_state_machine_context() click to toggle source
# File lib/dm-is-state_machine/is/state_machine.rb, line 89
def pop_state_machine_context
  @is_state_machine[:context].pop
end
push_state_machine_context(label) click to toggle source
# File lib/dm-is-state_machine/is/state_machine.rb, line 80
def push_state_machine_context(label)
  @is_state_machine ||= {}
  @is_state_machine[:context] ||= []
  @is_state_machine[:context] << label

  # Compacted, but barely readable for humans
  # ((@is_state_machine ||= {})[:context] ||= []) << label
end
state_machine_context?(label) click to toggle source
# File lib/dm-is-state_machine/is/state_machine.rb, line 93
def state_machine_context?(label)
  (i = @is_state_machine) && (c = i[:context]) &&
  c.respond_to?(:include?) && c.include?(label)
end

[Validate]

Generated with the Darkfish Rdoc Generator 2.