Sha256: 74531bf04de61af7907f566a249eabaf1ce43f9a82543c01ef7652d074e34cb2

Contents?: true

Size: 1.58 KB

Versions: 1

Compression:

Stored size: 1.58 KB

Contents

module ActiveRecord
  class Enum
    extend ActiveRecord::Enumerations::OptionsHelper
    
    attr_reader :id, :name, :extra_columns
    class_inheritable_accessor :label_method
    
    def initialize attrs = {}
      @id = attrs.delete(:id).to_i
      @name = attrs.delete(:name).to_s
      @extra_columns = attrs.reject { |k, _| [:enum_class, :on_style_not_matched].include?(k) }
    end
    
    def self.create_from value, values, options
      required_attrs = case value
      when String, Symbol
        { :name => value }
      else
        value
      end
      required_attrs[:id] ||= values.index(value) + 1
      new options.merge(required_attrs)
    end
    
    def == other
      return id == other.id if other.is_a?(Enum)
      [id.to_s, name].include?(other.to_s)
    end
    
    def to_s
      try_labelize(self, :desc) || try_labelize(name, :titleize)
    end
    
    def to_sym
      name.to_sym
    end
    
    def self.enumeration *config, &block
      add_option config, :class_name => self
      define_enums_getter ActiveRecord::Enumerations::Factory.make_enums(*config, &block)
    end
    
    def self.[] name_or_id
      all.detect { |enum| enum == name_or_id }
    end
    
    def self.find_all_by_id ids
      all.select { |enum| ids.include? enum.id }
    end
    
    private
    def self.define_enums_getter enums
      cattr_accessor :all
      self.all = enums
    end
    
    def try_labelize object, default_method
      object.respond_to?(label_method) && object.send(label_method) or object.respond_to?(default_method) && object.send(default_method)
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
ar-enums-0.3.4 lib/enum.rb