Sha256: c33fd84c07eaeea91905d96a2a84df91bd1ab5dd8bbcd5c3bccc57ed3855ffe2

Contents?: true

Size: 1.9 KB

Versions: 1

Compression:

Stored size: 1.9 KB

Contents

module ActiveEnum
  module ActsAsEnum

    module MacroMethods

      def acts_as_enum(options={})
        extend ClassMethods
        class_attribute :active_enum_options
        self.active_enum_options = options.reverse_merge(:name_column => 'name')
        scope :enum_values, proc { select("#{primary_key}, #{active_enum_options[:name_column]}").
                                   where(active_enum_options[:conditions]).
                                   order("#{primary_key} #{active_enum_options[:order]}") }
      end

    end

    module ClassMethods

      def ids
        enum_values.map { |v| v.id }
      end

      def names
        enum_values.map { |v| v.send(active_enum_options[:name_column]) }
      end

      def to_select
        enum_values.map { |v| [v.send(active_enum_options[:name_column]), v.id] }
      end

      def [](index)
        row = get_value(index)
        return if row.nil?
        index.is_a?(Integer) ? row.send(active_enum_options[:name_column]) : row.id
      end

      # Access any meta data defined for a given id or name. Returns a hash.
      def meta(index)
        row = lookup_relation(index).unscope(:select).first
        row&.attributes.except(primary_key.to_s, active_enum_options[:name_column].to_s)
      end

      # Enables use as a delimiter in inclusion validation
      def include?(value)
        !self[value].nil?
      end

      private

      def get_value(index)
        lookup_relation(index).first || begin
          raise(ActiveEnum::NotFound, "#{self} value for '#{index}' was not found") if ActiveEnum.raise_on_not_found
        end
      end
      
      def lookup_relation(index)
        if index.is_a?(Integer)
          enum_values.where(id: index)
        else
          enum_values.where("#{active_enum_options[:name_column]} like lower(?)", index.to_s)
        end
      end
    end

  end
end

ActiveRecord::Base.extend ActiveEnum::ActsAsEnum::MacroMethods

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
active_enum-1.0.0.rc2 lib/active_enum/acts_as_enum.rb