Sha256: 3519c85c1758a3f5d553f5adfc0771b95c2789153f169c36c9eb75ae0834aab0

Contents?: true

Size: 811 Bytes

Versions: 11

Compression:

Stored size: 811 Bytes

Contents

module NxtSupport
  class Enum
    def initialize(*keys)
      @store = ActiveSupport::HashWithIndifferentAccess.new

      keys.each do |key|
        normalized_key = normalized_key(key)
        store[normalized_key] = NxtSupport::Enum::Value.new(key)
        define_getter(normalized_key)
      end

      freeze
    end

    def self.[](*keys)
      new(*keys)
    end

    def [](key)
      store[key] || (raise KeyError, "No value for key '#{key}' in #{store}")
    end

    def to_h
      store
    end

    delegate_missing_to :to_h

    private

    attr_reader :store

    def normalized_key(key)
      key.to_s.downcase.underscore.gsub(/\s+/, '_')
    end

    def define_getter(normalized_key)
      define_singleton_method normalized_key do
        store[normalized_key]
      end
    end
  end
end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
nxt_support-0.6.0 lib/nxt_support/util/enum.rb
nxt_support-0.5.0 lib/nxt_support/util/enum.rb
nxt_support-0.4.3 lib/nxt_support/util/enum.rb
nxt_support-0.4.2 lib/nxt_support/util/enum.rb
nxt_support-0.4.1 lib/nxt_support/util/enum.rb
nxt_support-0.4.0 lib/nxt_support/util/enum.rb
nxt_support-0.3.0 lib/nxt_support/util/enum.rb
nxt_support-0.2.1 lib/nxt_support/util/enum.rb
nxt_support-0.2.0 lib/nxt_support/util/enum.rb
nxt_support-0.1.16 lib/nxt_support/util/enum.rb
nxt_support-0.1.15 lib/nxt_support/util/enum.rb