Class: Transitions::Event

Inherits:
Object
  • Object
show all
Defined in:
lib/transitions/event.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(machine, name, options = {}, &block) ⇒ Event

Returns a new instance of Event.



27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/transitions/event.rb', line 27

def initialize(machine, name, options = {}, &block)
  @machine, @name, @transitions = machine, name, []
  if machine
    machine.klass.send(:define_method, "#{name}!") do |*args|
      machine.fire_event(name, self, true, *args)
    end

    machine.klass.send(:define_method, name.to_s) do |*args|
      machine.fire_event(name, self, false, *args)
    end
  end
  update(options, &block)
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



25
26
27
# File 'lib/transitions/event.rb', line 25

def name
  @name
end

#successObject (readonly)

Returns the value of attribute success.



25
26
27
# File 'lib/transitions/event.rb', line 25

def success
  @success
end

Instance Method Details

#==(event) ⇒ Object



61
62
63
64
65
66
67
# File 'lib/transitions/event.rb', line 61

def ==(event)
  if event.is_a? Symbol
    name == event
  else
    name == event.name
  end
end

#fire(obj, to_state = nil, *args) ⇒ Object

Raises:



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/transitions/event.rb', line 41

def fire(obj, to_state = nil, *args)
  transitions = @transitions.select { |t| t.from == obj.current_state(@machine ? @machine.name : nil) }
  raise InvalidTransition if transitions.size == 0

  next_state = nil
  transitions.each do |transition|
    next if to_state && !Array(transition.to).include?(to_state)
    if transition.perform(obj)
      next_state = to_state || Array(transition.to).first
      transition.execute(obj, *args)
      break
    end
  end
  next_state
end

#transitions_from_state?(state) ⇒ Boolean

Returns:

  • (Boolean)


57
58
59
# File 'lib/transitions/event.rb', line 57

def transitions_from_state?(state)
  @transitions.any? { |t| t.from? state }
end

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



69
70
71
72
73
# File 'lib/transitions/event.rb', line 69

def update(options = {}, &block)
  @success = options[:success] if options.key?(:success)
  instance_eval(&block) if block
  self
end