Class: Kase::Switcher
- Inherits:
-
Object
- Object
- Kase::Switcher
- Defined in:
- lib/kase/switcher.rb
Defined Under Namespace
Modules: DSL
Instance Attribute Summary collapse
-
#result ⇒ Object
readonly
Returns the value of attribute result.
-
#values ⇒ Object
readonly
Returns the value of attribute values.
Instance Method Summary collapse
-
#initialize(*values) ⇒ Switcher
constructor
A new instance of Switcher.
- #match?(*pattern) ⇒ Boolean
- #matched? ⇒ Boolean
- #on(*pattern) ⇒ Object
- #switch(&block) ⇒ Object
- #validate! ⇒ Object
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
#result ⇒ Object (readonly)
Returns the value of attribute result.
14 15 16 |
# File 'lib/kase/switcher.rb', line 14 def result @result end |
#values ⇒ Object (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
20 21 22 |
# File 'lib/kase/switcher.rb', line 20 def match?(*pattern) values[0...pattern.size] == pattern end |
#matched? ⇒ 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
31 32 33 34 |
# File 'lib/kase/switcher.rb', line 31 def validate! raise NoMatchError.new(values) unless matched? true end |