Module: Motor::ActiveRecordUtils::Types

Defined in:
lib/motor/active_record_utils/types.rb

Constant Summary collapse

MUTEX =
Mutex.new
DEFAULT_TYPE =
'string'
UNIFIED_TYPES =
{
  'smallint' => 'integer',
  'int' => 'integer',
  'int4' => 'integer',
  'int8' => 'integer',
  'int16' => 'integer',
  'bigint' => 'integer',
  'numeric' => 'float',
  'decimal' => 'float',
  'float4' => 'float',
  'bpchar' => 'string',
  'float8' => 'float',
  'float16' => 'float',
  'text' => 'string',
  'citext' => 'string',
  'jsonb' => 'json',
  'bool' => 'boolean',
  'timestamp' => 'datetime',
  'timestamptz' => 'datetime'
}.freeze

Class Method Summary collapse

Class Method Details

.allObject


32
33
34
35
36
# File 'lib/motor/active_record_utils/types.rb', line 32

def all
  @all || MUTEX.synchronize do
    @all ||= build_types_hash
  end
end

.build_types_hashObject


51
52
53
54
55
56
57
58
59
60
61
# File 'lib/motor/active_record_utils/types.rb', line 51

def build_types_hash
  connection_class = defined?(::ResourceRecord) ? ::ResourceRecord : ActiveRecord::Base

  type_map = connection_class.connection.send(:type_map)

  type_map.instance_variable_get('@mapping').map do |name, type|
    next unless name.is_a?(String)

    [type.call.class.to_s, name]
  end.compact.to_h
end

.find_class_for_name(name) ⇒ Object


38
39
40
# File 'lib/motor/active_record_utils/types.rb', line 38

def find_class_for_name(name)
  all.invert[name.to_s]
end

.find_name_for_type(type) ⇒ Object


42
43
44
45
46
47
48
49
# File 'lib/motor/active_record_utils/types.rb', line 42

def find_name_for_type(type)
  name   = all[type.subtype.class.to_s] if type.respond_to?(:subtype)
  name ||= all[type.class.to_s]

  return UNIFIED_TYPES.fetch(name, name) if name

  nil
end