Class: Kase::Switcher

Inherits:
Object
  • Object
show all
Defined in:
lib/kase/switcher.rb

Defined Under Namespace

Modules: DSL

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*values) ⇒ Switcher

Returns a new instance of Switcher.



5
6
7
8
9
10
11
# File 'lib/kase/switcher.rb', line 5

def initialize(*values)
  if values.size == 1 && values.first.is_a?(Array)
    values = values.first
  end
  @values = values
  @matched = false
end

Instance Attribute Details

#resultObject (readonly)

Returns the value of attribute result.



14
15
16
# File 'lib/kase/switcher.rb', line 14

def result
  @result
end

#valuesObject (readonly)

Returns the value of attribute values.



13
14
15
# File 'lib/kase/switcher.rb', line 13

def values
  @values
end

Instance Method Details

#match?(*pattern) ⇒ Boolean

Returns:

  • (Boolean)


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

def match?(*pattern)
  values[0...pattern.size] == pattern
end

#matched?Boolean

Returns:

  • (Boolean)


16
17
18
# File 'lib/kase/switcher.rb', line 16

def matched?
  !!@matched
end

#on(*pattern) ⇒ Object



24
25
26
27
28
29
# File 'lib/kase/switcher.rb', line 24

def on(*pattern)
  return if matched?
  return unless match?(*pattern)
  @matched = true
  @result = yield(*values[pattern.size..-1])
end

#switch(&block) ⇒ Object



36
37
38
39
40
# File 'lib/kase/switcher.rb', line 36

def switch(&block)
  DSL.call(self, &block)
  validate!
  result
end

#validate!Object

Raises:



31
32
33
34
# File 'lib/kase/switcher.rb', line 31

def validate!
  raise NoMatchError.new(values) unless matched?
  true
end