Sha256: 8e9e1e489d35b7c3ea3b9b05492039282bf0a3a393984f4cd2253ff9f1c2a427

Contents?: true

Size: 1.06 KB

Versions: 4

Compression:

Stored size: 1.06 KB

Contents

module RailsAttrEnum

  ## Enum representation
  module Enum
    def self.included(base)
      base.extend ClassMethods
    end

    module ClassMethods
      def init_enum(attr_name)
        return if @init
        @attr_name = attr_name
        @entries = []
        @init = true
      end

      def add(entry)
        const_name = entry[:key].to_s.upcase
        const_set(const_name, entry[:value])
        const_set("#{const_name}_LABEL", entry[:label])
        @entries << entry
      end

      def label_value_pairs
        labels.zip values
      end

      def get_label(value)
        get_from_entries(:label, value)
      end

      def get_key(value)
        get_from_entries(:key, value)
      end

      def attr_name; @attr_name end
      def keys;   mapped(:key) end
      def values; mapped(:value) end
      def labels; mapped(:label) end

      private

      def get_from_entries(key, value)
        @entries.find { |hash| hash[:value] == value }.try(:[], key)
      end

      def mapped(key)
        @entries.map { |hash| hash[key] }
      end
    end
  end

end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
rails_attr_enum-0.0.5 lib/rails_attr_enum/enum.rb
rails_attr_enum-0.0.4 lib/rails_attr_enum/enum.rb
rails_attr_enum-0.0.3 lib/rails_attr_enum/enum.rb
rails_attr_enum-0.0.2 lib/rails_attr_enum/enum.rb