Sha256: 6d305aed92a4961ebe0da9bb4324b29d6390b43f9709f9fc9057831507170fd7

Contents?: true

Size: 1.16 KB

Versions: 1

Compression:

Stored size: 1.16 KB

Contents

module SwifterEnum
  class Base
    class << self
      attr_accessor :values

      def set_values(input)
        case input
        when Hash
          @values = input.freeze
        when Array
          validate_array_elements!(input)
          @values = input.map { |item| [item.to_sym, item.to_s] }.to_h.freeze
        else
          raise ArgumentError, "Input must be a Hash or an Array of symbols or strings"
        end
      end

      private

      def validate_array_elements!(array)
        unless array.all? { |item| item.is_a?(Symbol) || item.is_a?(String) }
          raise ArgumentError, "Array elements must all be symbols or strings"
        end
      end
    end

    attr_reader :value

    def initialize(value)
      @value = value&.to_sym
    end

    def ==(other)
      if other.is_a?(Symbol) || other.is_a?(String)
        value.to_s == other.to_s
      else
        other.instance_of?(self.class) && value == other.value
      end
    end

    def t
      I18n.t("swifter_enum.#{self.class.name.demodulize.underscore}.#{@value}")
    end

    def to_s
      @value
    end

    def self.all
      values.keys.map { |value| new(value) }
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
swifter_enum-0.9.3 lib/swifter_enum/base.rb