Class: Ahnnotate::Tables

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/ahnnotate/tables.rb

Instance Method Summary collapse

Constructor Details

#initialize(connection = ActiveRecord::Base.connection) ⇒ Tables

Returns a new instance of Tables.



5
6
7
8
# File 'lib/ahnnotate/tables.rb', line 5

def initialize(connection = ActiveRecord::Base.connection)
  @connection = connection
  @abilities = Abilities.new(connection)
end

Instance Method Details

#data_sources_method_nameObject



83
84
85
86
87
88
89
90
# File 'lib/ahnnotate/tables.rb', line 83

def data_sources_method_name
  @data_sources_method_name ||=
    if ActiveRecordVersion.five_and_up?
      :data_sources
    else
      :tables
    end
end

#eachObject



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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/ahnnotate/tables.rb', line 14

def each
  if !block_given?
    enum_for(:each)
  end

  @connection.public_send(data_sources_method_name).each do |table_name|
    begin
      original_stderr = $stderr
      $stderr = StringIO.new

      primary_key = ActiveRecord::Base.get_primary_key(table_name)

      columns = @connection.columns(table_name).map do |c|
        is_primary_key =
          if primary_key.is_a?(Array)
            primary_key.include?(c.name)
          else
            primary_key == c.name
          end

        Column.new(
          name: c.name,
          sql_type: c.sql_type,
          nullable: c.null,
          primary_key: is_primary_key,
          default: c.default
        )
      end

      indexes = @connection.indexes(table_name).map do |i|
        comment =
          if i.respond_to?(:comment)
            i.comment
          end

        Index.new(
          name: i.name,
          columns: i.columns,
          unique: i.unique,
          comment: comment
        )
      end

      foreign_keys =
        if @abilities.foreign_key?
          @connection.foreign_keys(table_name).map do |fk|
            ForeignKey.new(
              name: fk.name,
              from_column: fk.column,
              to_table: fk.to_table,
              to_column: fk.primary_key
            )
          end
        else
          []
        end

      yield Table.new(
        name: table_name,
        columns: columns,
        indexes: indexes,
        foreign_keys: foreign_keys,
      )
    ensure
      $stderr = original_stderr
    end
  end
end

#to_hObject



10
11
12
# File 'lib/ahnnotate/tables.rb', line 10

def to_h
  map { |table| [table.name, table] }.to_h
end