Class: Homerun::Instruction

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/homerun.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeInstruction

Returns a new instance of Instruction.



13
14
15
16
17
18
# File 'lib/homerun.rb', line 13

def initialize
  super

  @steps = []
  @ctx = { _pass: true }
end

Instance Attribute Details

#ctxObject (readonly)

Returns the value of attribute ctx.



11
12
13
# File 'lib/homerun.rb', line 11

def ctx
  @ctx
end

#stepsObject (readonly)

Returns the value of attribute steps.



11
12
13
# File 'lib/homerun.rb', line 11

def steps
  @steps
end

Class Method Details

.call(_ctx) ⇒ Object



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
70
71
# File 'lib/homerun.rb', line 36

def self.call(_ctx)
  instance.set_ctx(_ctx)

  cur = 0

  while cur < instance.steps.count do
    step = instance.steps[cur]

    pos = ->(_name) {
      instance.steps.index(instance.steps.find { |x| x[:name] == _name })
    }

    if step[:item].call(instance.ctx)
      if step[:success]
        cur = pos.call(step[:success])
        next
      else
        cur += 1
      end
    else
      if step[:failure]
        cur = pos.call(step[:failure])
        next
      else
        instance.set_pass(false)
        cur = instance.steps.count
      end
    end
  end

  if block_given?
    yield(instance.ctx) if instance.ctx[:_pass]
  end

  instance.ctx
end

.step(item, failure: nil, success: nil, name: nil) ⇒ Object



32
33
34
# File 'lib/homerun.rb', line 32

def self.step(item, failure: nil, success: nil, name: nil)
  instance.add_step({ item: item, failure: failure, success: success, name: name })
end

Instance Method Details

#add_step(step) ⇒ Object



20
21
22
# File 'lib/homerun.rb', line 20

def add_step(step)
  @steps << step
end

#set_ctx(_ctx) ⇒ Object



24
25
26
# File 'lib/homerun.rb', line 24

def set_ctx(_ctx)
  @ctx = { **ctx, **_ctx }
end

#set_pass(val) ⇒ Object



28
29
30
# File 'lib/homerun.rb', line 28

def set_pass(val)
  @ctx[:_pass] = val
end