module ActiveRecord::HumanizedEnum

Constants

ENUM_HUMANIZABLE_CONFLICT_MESSAGE

Public Instance Methods

detect_humanized_enum_conflict!(enum_name, method_name, klass_method = false) click to toggle source
# File lib/active_record/humanized_enum.rb, line 41
def detect_humanized_enum_conflict!(enum_name, method_name, klass_method = false)
  if klass_method && dangerous_class_method?(method_name)
    raise ArgumentError, ENUM_HUMANIZABLE_CONFLICT_MESSAGE % {
      enum: enum_name,
      klass: self.name,
      type: 'class',
      method: method_name,
      source: 'Active Record'
    }
  elsif !klass_method && dangerous_attribute_method?(method_name)
    raise ArgumentError, ENUM_HUMANIZABLE_CONFLICT_MESSAGE % {
      enum: enum_name,
      klass: self.name,
      type: 'instance',
      method: method_name,
      source: 'Active Record'
    }
  elsif klass_method && respond_to?(method_name)
    raise ArgumentError, ENUM_HUMANIZABLE_CONFLICT_MESSAGE % {
      enum: enum_name,
      klass: self.name,
      type: 'class',
      method: method_name,
      source: 'another humanized enum'
    }
  elsif !klass_method && method_defined?(method_name)
    raise ArgumentError, ENUM_HUMANIZABLE_CONFLICT_MESSAGE % {
      enum: enum_name,
      klass: self.name,
      type: 'instance',
      method: method_name,
      source: 'another humanized enum'
    }
  end
end
enum(definitions) click to toggle source
Calls superclass method
# File lib/active_record/humanized_enum.rb, line 14
def enum(definitions)
  super(definitions)
  humanized_enum(*definitions.keys)
end
humanized_enum(*enums) click to toggle source
# File lib/active_record/humanized_enum.rb, line 19
def humanized_enum(*enums)
  klass = self
  enums.each do |enum|
    enum = enum.to_s
    method_name = "humanized_#{enum}"

    # def self.humanized_status(status) ... end
    detect_humanized_enum_conflict! enum, method_name, true
    klass.singleton_class.send :define_method, method_name do |enum_value|
      I18n.t enum_value.to_sym, scope: [:activerecord, :attributes, klass.model_name.i18n_key, enum.pluralize.to_sym], default: enum_value.to_s.humanize if enum_value.present?
    end

    # def humanized_status ... end
    detect_humanized_enum_conflict! enum, method_name
    define_method method_name do
      klass.send method_name.to_sym, send(enum.to_sym)
    end
  end
end