Class: EnumRecords::Definer

Inherits:
Object
  • Object
show all
Defined in:
lib/enum_records.rb

Overview

use the Enumeration class capture enum names as methods or contants

Instance Method Summary collapse

Constructor Details

#initialize(model_class, &block) ⇒ Definer

Returns a new instance of Definer.



56
57
58
59
# File 'lib/enum_records.rb', line 56

def initialize model_class, &block
  @model_class = model_class
  EnumNameCapturer.new(self, &block)
end

Instance Method Details

#add_new_enum(method_sym, options) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/enum_records.rb', line 61

def add_new_enum(method_sym, options)
  # Check that the model's translation table exist if locales are passed so that in migration we will not have an exception
  return if @model_class._enums[:globalized] && !@model_class.connection.table_exists?(@model_class.translations_table_name)

  enum_name = method_sym.to_s
  @model_class._enums[:definitions][enum_name] = options

  # Reject options that aren't real data base fields.
  fields = options.reject { |k, v| !@model_class.columns_hash.keys.include?(k.to_s) }

  localized_fields = options[:locales] || {}
  
  # Create or find the record associated with the enum.
  if !localized_fields.blank? # In case locales hash is passed
    # Reject options that aren't real data base fields for localized fields.
    for locale in localized_fields.keys
      localized_fields[locale] = localized_fields[locale].reject { |k, v| !@model_class.columns_hash.keys.include?(k.to_s) }
    end
    if @model_class.enum(enum_name).nil? #enum hasn't been created yet
      record = find_or_create_enum_record(enum_name, fields)
      localized_fields.each_pair do |locale, l_fields|
        Globalize.with_locale locale do
          record.update_attributes(l_fields)
        end
      end
    end
  else # no localization needed => create or find the record associated with the enum.
    find_or_create_enum_record(enum_name, fields)
  end
end

#find_or_create_enum_record(enum_name, fields) ⇒ Object



92
93
94
# File 'lib/enum_records.rb', line 92

def find_or_create_enum_record(enum_name, fields)
  @model_class.send "find_or_create_by_#{@model_class._enums[:column_name]}", enum_name, fields
end