|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +module Ruby |
| 4 | + module Enum |
| 5 | + ## |
| 6 | + # Adds a method to an enum class that allows for exhaustive matching on a value. |
| 7 | + # |
| 8 | + # @example |
| 9 | + # class Color |
| 10 | + # include Ruby::Enum |
| 11 | + # include Ruby::Enum::Case |
| 12 | + # |
| 13 | + # define :RED, :red |
| 14 | + # define :GREEN, :green |
| 15 | + # define :BLUE, :blue |
| 16 | + # define :YELLOW, :yellow |
| 17 | + # end |
| 18 | + # |
| 19 | + # Color.case(Color::RED, { |
| 20 | + # [Color::RED, Color::GREEN] => -> { "red or green" }, |
| 21 | + # Color::BLUE => -> { "blue" }, |
| 22 | + # Color::YELLOW => -> { "yellow" }, |
| 23 | + # }) |
| 24 | + # |
| 25 | + # Reserves the :else key for a default case: |
| 26 | + # Color.case(Color::RED, { |
| 27 | + # [Color::RED, Color::GREEN] => -> { "red or green" }, |
| 28 | + # else: -> { "blue or yellow" }, |
| 29 | + # }) |
| 30 | + module Case |
| 31 | + def self.included(klass) |
| 32 | + klass.extend(ClassMethods) |
| 33 | + end |
| 34 | + |
| 35 | + ## |
| 36 | + # @see Ruby::Enum::Case |
| 37 | + module ClassMethods |
| 38 | + class ValuesNotDefinedError < StandardError |
| 39 | + end |
| 40 | + |
| 41 | + class NotAllCasesHandledError < StandardError |
| 42 | + end |
| 43 | + |
| 44 | + def case(value, cases) |
| 45 | + validate_cases(cases) |
| 46 | + |
| 47 | + filtered_cases = cases.select do |values, _proc| |
| 48 | + values = [values] unless values.is_a?(Array) |
| 49 | + values.include?(value) |
| 50 | + end |
| 51 | + |
| 52 | + return call_proc(cases[:else], value) if filtered_cases.none? |
| 53 | + |
| 54 | + results = filtered_cases.map { |_values, proc| call_proc(proc, value) } |
| 55 | + |
| 56 | + # Return the first result if there is only one result |
| 57 | + results.size == 1 ? results.first : results |
| 58 | + end |
| 59 | + |
| 60 | + private |
| 61 | + |
| 62 | + def call_proc(proc, value) |
| 63 | + return if proc.nil? |
| 64 | + |
| 65 | + if proc.arity == 1 |
| 66 | + proc.call(value) |
| 67 | + else |
| 68 | + proc.call |
| 69 | + end |
| 70 | + end |
| 71 | + |
| 72 | + def validate_cases(cases) |
| 73 | + all_values = cases.keys.flatten - [:else] |
| 74 | + else_defined = cases.key?(:else) |
| 75 | + superfluous_values = all_values - values |
| 76 | + missing_values = values - all_values |
| 77 | + |
| 78 | + raise ValuesNotDefinedError, "Value(s) not defined: #{superfluous_values.join(', ')}" if superfluous_values.any? |
| 79 | + raise NotAllCasesHandledError, "Not all cases handled: #{missing_values.join(', ')}" if missing_values.any? && !else_defined |
| 80 | + end |
| 81 | + end |
| 82 | + end |
| 83 | + end |
| 84 | +end |
0 commit comments