Method: Kernel#print_tables

Defined in:
lib/crudboy/ext/kernel.rb


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
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
# File 'lib/crudboy/ext/kernel.rb', line 11

def print_tables(format = :md)
  require 'terminal-table'

  tables = ActiveRecord::Base.connection.tables.map do |table_name|
    {
      table: table_name,
      table_comment: ActiveRecord::Base.connection.table_comment(table_name) || '',
      columns: ::ActiveRecord::Base.connection.columns(table_name)
    }
  end

  outputs = tables.map do |table|
    table_name = table[:table]
    table_comment = table[:table_comment]
    case format
    when :md
      "# #{table_name} #{table_comment}\n\n" +
        Terminal::Table.new { |t|
        t.headings = ['PK', 'Name', 'SQL Type', 'Limit', 'Precision', 'Scale', 'Default', 'Nullable', 'Comment']
        t.rows = table[:columns].map { |column|
          pk = if [::ActiveRecord::Base.connection.primary_key(table_name)].flatten.include?(column)
                 'Y'
               else
                 ''
               end
          [pk, "`#{column.name}`", column.sql_type, column..limit || '', column..precision || '',
           column..scale || '', column.default || '', column.null, column.comment || '']
        }
        t.style = {
          border_top: false,
          border_bottom: false,
          border_i: '|'
        }
      }.to_s.lines.map { |l| '  ' + l }.join
    when :org
      "* #{table_name} #{table_comment}\n\n" +
        Terminal::Table.new { |t|
        t.headings = ['PK', 'Name', 'SQL Type', 'Limit', 'Precision', 'Scale', 'Default', 'Nullable', 'Comment']
        t.rows = table[:columns].map { |column|
          pk = if [::ActiveRecord::Base.connection.primary_key(table_name)].flatten.include?(column)
                 'Y'
               else
                 ''
               end
          [pk, "=#{column.name}=", column.sql_type, column..limit || '', column..precision || '',
           column..scale || '', column.default || '', column.null, column.comment || '']
        }
        t.style = {
          border_top: false,
          border_bottom: false,
        }
      }.to_s.lines.map { |l| '  ' + l.gsub(/^\+|\+$/, '|') }.join
    when :sql
      "-- Table: #{table_name}\n\n" + ActiveRecord::Base.connection.exec_query("show create table `#{table_name}`").rows.last.last + ';'
    end
  end

  outputs.each { |out| puts out; puts }
end