Module: ND::Enum

Extended by:
ActiveSupport::Concern, Configuration
Included in:
ActiveRecord::Base
Defined in:
lib/nd/enum/version.rb,
lib/nd/enum.rb

Defined Under Namespace

Modules: Base, Configuration, I18n Classes: Error, MissingTranslationError

Constant Summary collapse

VERSION =
'0.2.0'

Constants included from Configuration

Configuration::DEFAULT_CONFIGURATION

Class Method Summary collapse

Methods included from Configuration

configuration, configure

Class Method Details

.define_db_enum(options, enum_module) ⇒ Object



77
78
79
80
81
82
83
84
# File 'lib/nd/enum.rb', line 77

def define_db_enum(options, enum_module)
  enum_options = options[:db].is_a?(Hash) ? options[:db] : {}

  enum_options[:_prefix] = enum_options.delete(:prefix) if enum_options.key?(:prefix)
  enum_options[:_suffix] = enum_options.delete(:suffix) if enum_options.key?(:suffix)

  options[:model].enum(options[:attribute] => enum_module.to_h, **enum_options)
end

.define_module(options) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/nd/enum.rb', line 50

def define_module(options)
  Module.new do
    include ND::Enum::Base

    # Public methods

    define_singleton_method(:all) { options[:values] }

    # Private methods

    define_singleton_method(:options) { options }
    options.each_key do |name|
      define_singleton_method(name) { options[name] }
    end

    [:options, *options.keys].each do |method_name|
      singleton_class.class_eval { private method_name.to_sym }
    end

    # Constants

    options[:values].map do |value|
      const_set(value.to_s.upcase, value.to_s)
    end
  end
end

.set_options(caller_binding, caller_class, caller_class_name) ⇒ Object



39
40
41
42
43
44
45
46
47
48
# File 'lib/nd/enum.rb', line 39

def set_options(caller_binding, caller_class, caller_class_name)
  options = caller_class.method(:nd_enum).parameters.each_with_object({}) do |(_, name), options|
    options[name.to_sym] = caller_binding.local_variable_get(name)
  end
  options[:attribute], options[:values] = options.delete(:configuration).to_a.first
  options[:model] = caller_class
  options[:model_name] = caller_class_name

  options
end