Module: Torque::PostgreSQL::SchemaCache::Inheritance

Included in:
Torque::PostgreSQL::SchemaCache
Defined in:
lib/torque/postgresql/schema_cache/inheritance.rb

Instance Method Summary collapse

Instance Method Details

#lookup_model(table_name, scoped_class = '', source_to_model:) ⇒ Object

Try to find a model based on a given table

Raises:



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/torque/postgresql/schema_cache/inheritance.rb', line 9

def lookup_model(table_name, scoped_class = '', source_to_model:)
  scoped_class = scoped_class.name if scoped_class.is_a?(Class)
  return source_to_model[table_name] if source_to_model.key?(table_name)

  # Get all the possible scopes
  scopes = scoped_class.scan(/(?:::)?[A-Z][a-z]+/)
  scopes.unshift('Object::')

  # Check if the table name comes with a schema
  if table_name.include?('.')
    schema, table_name = table_name.split('.')
    scopes.insert(1, schema.camelize) if schema != 'public'
  end

  # Consider the maximum namespaced possible model name
  max_name = table_name.tr('_', '/').camelize.split(/(::)/)
  max_name[-1] = max_name[-1].singularize

  # Test all the possible names against all the possible scopes
  until scopes.size == 0
    scope = scopes.join.chomp('::').safe_constantize
    model = find_model(max_name, table_name, scope) unless scope.nil?
    return source_to_model[table_name] = model unless model.nil?
    scopes.pop
  end

  # If this part is reach, no model name was found
  raise LookupError.new(<<~MSG.squish)
    Unable to find a valid model that is associated with the
    '#{table_name}' table. Please, check if they correctly inherit from
    ActiveRecord::Base
  MSG
end