Class: YeetDba::Column

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(db_column:, table_name:, tables:) ⇒ Column

Returns a new instance of Column.



5
6
7
8
9
# File 'lib/yeet_dba/column.rb', line 5

def initialize(db_column:, table_name:, tables:)
  @db_column = db_column
  @table_name = table_name
  @tables = tables
end

Instance Attribute Details

#db_columnObject

Returns the value of attribute db_column.



3
4
5
# File 'lib/yeet_dba/column.rb', line 3

def db_column
  @db_column
end

#table_nameObject

Returns the value of attribute table_name.



3
4
5
# File 'lib/yeet_dba/column.rb', line 3

def table_name
  @table_name
end

#tablesObject

Returns the value of attribute tables.



3
4
5
# File 'lib/yeet_dba/column.rb', line 3

def tables
  @tables
end

Instance Method Details

#associationObject



35
36
37
# File 'lib/yeet_dba/column.rb', line 35

def association
  model && model.reflections[association_name]
end

#association_klassObject



15
16
17
# File 'lib/yeet_dba/column.rb', line 15

def association_klass
  association&.klass
end

#association_nameObject



27
28
29
# File 'lib/yeet_dba/column.rb', line 27

def association_name
  db_column.name.gsub(/_id\z/, '')
end

#association_table_nameObject



19
20
21
22
23
24
25
# File 'lib/yeet_dba/column.rb', line 19

def association_table_name
  if association_klass&.ancestors&.include?(ActiveRecord::Base)
    association_klass&.table_name
  else
    tables.detect { |table| table == guessed_table_name }
  end
end

#foreign_key_exists?Boolean

Returns:

  • (Boolean)


43
44
45
# File 'lib/yeet_dba/column.rb', line 43

def foreign_key_exists?
  ActiveRecord::Migration.foreign_key_exists?(table_name, column: db_column.name)
end

#guessed_table_nameObject



47
48
49
# File 'lib/yeet_dba/column.rb', line 47

def guessed_table_name
  @guessed_table_name ||= association_name.pluralize
end

#is_association?Boolean

Returns:

  • (Boolean)


11
12
13
# File 'lib/yeet_dba/column.rb', line 11

def is_association?
  db_column.name =~ /_id\z/
end

#modelObject



31
32
33
# File 'lib/yeet_dba/column.rb', line 31

def model
  ActiveRecord::Base.descendants.detect { |c| c.table_name == table_name }
end

#polymorphic_association?Boolean

Returns:

  • (Boolean)


39
40
41
# File 'lib/yeet_dba/column.rb', line 39

def polymorphic_association?
  association && association.options[:polymorphic]
end