Class: Transitions::StateTransition

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts) ⇒ StateTransition

Returns a new instance of StateTransition.



7
8
9
10
11
12
13
# File 'lib/transitions/state_transition.rb', line 7

def initialize(opts)
  @from = opts[:from]
  @to = opts[:to]
  @guard = opts[:guard]
  @on_transition = opts[:on_transition]
  @options = opts
end

Instance Attribute Details

#fromObject (readonly)

Returns the value of attribute from.



3
4
5
# File 'lib/transitions/state_transition.rb', line 3

def from
  @from
end

#toObject (readonly)

Returns the value of attribute to.



3
4
5
# File 'lib/transitions/state_transition.rb', line 3

def to
  @to
end

Instance Method Details

#==(other) ⇒ Object



63
64
65
# File 'lib/transitions/state_transition.rb', line 63

def ==(other)
  @from == other.from && @to == other.to
end

#executable?(obj, *args, **kwargs) ⇒ Bool

Parameters:

  • obj (Any)
    • the subject

  • args (Array<Symbol>)
    • any arguments passed into the transition method

    E.g. something like

    car.drive!(:fast, :now)
    

    with ‘car` being the subject and `drive` the transition method would result in `args` looking like this:

    [:fast, :now]
    

Returns:

  • (Bool)


26
27
28
# File 'lib/transitions/state_transition.rb', line 26

def executable?(obj, *args, **kwargs)
  [@guard].flatten.all? { |g| perform_guard(obj, g, *args, **kwargs) }
end

#execute(obj, *args, **kwargs) ⇒ void

This method returns an undefined value.

rubocop:disable Metrics/MethodLength

Parameters:

  • obj (Any)
    • the subject

  • args (Array<Symbol>)
    • any arguments passed into the transition method

    E.g. something like

    car.drive!(:fast, :now)
    

    with ‘car` being the subject and `drive` the transition method would result in `args` looking like this:

    [:fast, :now]
    


43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/transitions/state_transition.rb', line 43

def execute(obj, *args, **kwargs)
  case @on_transition
  when Symbol, String
    obj.send(@on_transition, *args, **kwargs)
  when Proc
    @on_transition.call(obj, *args, **kwargs)
  when Array
    @on_transition.each do |callback|
      # Yes, we're passing always the same parameters for each callback in here.
      # We should probably drop args altogether in case we get an array.
      obj.send(callback, *args, **kwargs)
    end
  else
    # TODO: We probably should check for this in the constructor and not that late.
    fail ArgumentError,
         "You can only pass a Symbol, a String, a Proc or an Array to 'on_transition'"\
         " - got #{@on_transition.class}." unless @on_transition.nil?
  end
end

#from?(value) ⇒ Boolean

Returns:

  • (Boolean)


67
68
69
# File 'lib/transitions/state_transition.rb', line 67

def from?(value)
  @from == value
end