Class: ActiveRecordMysqlRepl::Database::Associations

Inherits:
Object
  • Object
show all
Defined in:
lib/active_record_mysql_repl/database/association.rb

Defined Under Namespace

Classes: AnalyzedTable

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(associations) ⇒ Associations



20
21
22
# File 'lib/active_record_mysql_repl/database/association.rb', line 20

def initialize(associations)
  @associations = associations.map { |key, association| [key, Association.new(association)] }.to_h
end

Class Method Details

.analyze(tables, association_settings = {}) ⇒ Object

Analyze the relationship between tables based on the information of *_id columns For example, if users.company_id exists, users belongs_to companies and companies has_many users



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/active_record_mysql_repl/database/association.rb', line 30

def self.analyze(tables, association_settings = {})
  analyzed_tables = tables.map { |table| [table, AnalyzedTable.new(table)] }.to_h

  analyzed_tables.each do |table_name, table|
    association_setting = association_settings[table_name]
    columns = ActiveRecord::Base.connection.columns(table_name)
    columns.each do |column|
      next if association_setting.present? && association_settings.ignore_columns(table_name).include?(column.name)

      associatable = column.name.gsub(/_id$/, "") if column.name.end_with?("_id")
      next if associatable.blank? || associatable == "class" # reserved word

      if analyzed_tables.key?(associatable.pluralize)
        table.belongs_to << associatable.singularize if associatable
        analyzed_tables[associatable.pluralize].has_many << table_name.pluralize
      else
        associatable_table_name = associatable.split("_").last
        table.belongs_to << if analyzed_tables.key?(associatable_table_name.pluralize)
          {name: associatable, class_name: associatable_table_name.classify, foreign_key: :id}
        else
          {name: associatable, class_name: table_name.singularize.classify, foreign_key: :id}
        end
      end
    end

    next if association_setting.blank?

    # merge yaml settings
    [:has_many, :belongs_to].each do |type|
      ass = association_setting.fetch(type.to_s, []).map(&:symbolize_keys)
      table.send(type).concat(ass) unless ass.blank?
    end
  end

  analyzed_tables.values
end

.load(path) ⇒ Object



16
17
18
# File 'lib/active_record_mysql_repl/database/association.rb', line 16

def self.load(path)
  new(YAML.load_file(path, aliases: true))
end

Instance Method Details

#[](key) ⇒ Object



24
25
26
# File 'lib/active_record_mysql_repl/database/association.rb', line 24

def [](key)
  @associations[key]
end