Module: Simple::SQL::Helpers::Printer

Extended by:
Printer
Included in:
Printer
Defined in:
lib/simple/sql/helpers/printer.rb

Overview

private

Instance Method Summary collapse

Instance Method Details

#load_table_printObject



50
51
52
53
54
55
# File 'lib/simple/sql/helpers/printer.rb', line 50

def load_table_print
  require "table_print"
  @table_print = true
rescue LoadError
  @table_print = false
end

#lp(records) ⇒ Object



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
# File 'lib/simple/sql/helpers/printer.rb', line 15

def lp(records)
  return if records.empty?

  keys = records.first.keys
  return if keys.empty?

  rows = []
  rows << keys

  records.each do |rec|
    rows << rec.values_at(*keys).map(&:to_s)
  end

  max_lengths = rows.inject([0] * keys.count) do |ary, row|
    ary.zip(row.map(&:length)).map(&:max)
  end

  rows.each_with_index do |row, idx|
    parts = row.zip(max_lengths).map do |value, max_length|
      " %-#{max_length}s " % value
    end

    STDERR.puts parts.join("|")

    if idx == 0
      STDERR.puts parts.join("|").gsub(/[^|]/, "-")
    end
  end
end


7
8
9
10
11
12
13
# File 'lib/simple/sql/helpers/printer.rb', line 7

def print(records)
  if table_print?
    tp records
  else
    lp records
  end
end

#table_print?Boolean

Returns:

  • (Boolean)


45
46
47
48
# File 'lib/simple/sql/helpers/printer.rb', line 45

def table_print?
  load_table_print unless instance_variable_defined? :@table_print
  @table_print
end