Class: Bp3::String::TableModelMap

Inherits:
MapperBase show all
Defined in:
lib/bp3/string/table_model_map.rb

Overview

TableModelMap provides for mappings between tables and model class names

Constant Summary collapse

CACHED_HASH_MUTEX =
Mutex.new

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from MapperBase

build_hash, #hash, hash, reset_cached_hash, #sti_subclass?, #subclassed?, testing?

Class Method Details

.cached_hashObject



12
13
14
15
16
17
18
19
20
21
# File 'lib/bp3/string/table_model_map.rb', line 12

def self.cached_hash
  return build_hash if testing?
  return @cached_hash if @cached_hash.present?

  CACHED_HASH_MUTEX.synchronize do
    return @cached_hash if @cached_hash.present?

    @cached_hash = build_hash
  end
end

Instance Method Details

#build_hashObject



23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/bp3/string/table_model_map.rb', line 23

def build_hash
  encoding = 'string'.encoding # TODO: not sure why encoding sometimes doesn't match
  hash = {}
  ActiveRecord::Base.descendants.each do |model|
    table_name = model.table_name
    next if table_name.blank?

    table_name = table_name.split('.').last # remove the schema
    model_name = determine_model_name(model).encode(encoding)
    hash[table_name] = model_name
    hash[table_name.singularize] = model_name
  end
  hash
end

#determine_model_name(model) ⇒ Object



38
39
40
41
42
43
# File 'lib/bp3/string/table_model_map.rb', line 38

def determine_model_name(model)
  return determine_model_name(model.superclass) if sti_subclass?(model)
  return determine_model_name(model.descendants.first) if subclassed?(model)

  model.name
end