Class: Super::Useful::Enum::Case
- Inherits:
-
Object
- Object
- Super::Useful::Enum::Case
- Defined in:
- lib/super/useful/enum.rb
Instance Method Summary collapse
-
#initialize(choices, chosen) ⇒ Case
constructor
A new instance of Case.
- #result ⇒ Object
- #when(*keys, &block) ⇒ Object
Constructor Details
#initialize(choices, chosen) ⇒ Case
Returns a new instance of Case.
15 16 17 18 19 20 21 22 23 24 |
# File 'lib/super/useful/enum.rb', line 15 def initialize(choices, chosen) if !choices.key?(chosen) raise Error::Enum::ImpossibleValue, "`#{chosen}` isn't in: #{choices.keys.map(&:inspect).join(", ")}" end @choices = choices @chosen = chosen @whens = {} end |
Instance Method Details
#result ⇒ Object
42 43 44 45 46 47 48 49 |
# File 'lib/super/useful/enum.rb', line 42 def result if @choices.size != @whens.size missing_keys = @choices.keys - @whens.keys raise Error::Enum::UndefinedCase, "Unset cases: #{missing_keys.join(", ")}" end @whens[@chosen].call(@value) end |
#when(*keys, &block) ⇒ Object
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
# File 'lib/super/useful/enum.rb', line 26 def when(*keys, &block) if !block raise Error::ArgumentError, "must receive block" end keys.each do |key| if !@choices.key?(key) raise Error::Enum::ImpossibleValue, "`#{key.inspect}` is not a possibility" end @whens[key] = block end self end |