class TableTransformer::Data

Attributes

keys[R]
original[R]

Public Class Methods

new(original:, keys: []) click to toggle source
# File lib/table_transformer.rb, line 10
def initialize(original:, keys: [])
  @original = if original.class.method_defined?(:keys)
                [] << original
              else
                [] + original
              end
  @keys = if keys.blank?
            @original[0].keys
          else
            keys
          end
end

Public Instance Methods

column_width() click to toggle source
# File lib/table_transformer.rb, line 69
def column_width
  @column_width ||= {}.tap do |width|
    keys.each do |k|
      width[k] = max_size[k] < width(k) ? width(k) : max_size[k]
      width[k] += 2
    end
    break width
  end
end
line_generator() click to toggle source
# File lib/table_transformer.rb, line 63
def line_generator
  @line_generator ||= LineGenerator.new(
    column_width: column_width
  )
end
max_size() click to toggle source
# File lib/table_transformer.rb, line 79
def max_size
  @max_size ||= {}.tap do |size|
    keys.each do |k|
      max_data = string_data.max_by { |data| width(data[k]) }
      size[k] = width(max_data[k])
    end
    break size
  end
end
output() click to toggle source
# File lib/table_transformer.rb, line 23
def output
  puts output_data
end
output_data() click to toggle source
# File lib/table_transformer.rb, line 27
def output_data
  @output_data ||=
    if string_data.present?
      output_data_given_data
    else
      "Empty set\n\n"
    end
end
output_data_given_data() click to toggle source
# File lib/table_transformer.rb, line 36
def output_data_given_data
  [].tap do |arr|
    arr << line_generator.delimiter_line
    arr << line_generator.header_line
    arr << line_generator.delimiter_line
    string_data.each do |data|
      arr << line_generator.data_line(data)
    end
    arr << line_generator.delimiter_line
    arr << "#{string_data.size} rows in set\n\n"
  end
end
string_data() click to toggle source
# File lib/table_transformer.rb, line 49
def string_data
  @string_data ||= [].tap do |arr|
    original.each do |data|
      transformed_data = {}.tap do |t_data|
        keys.each do |k|
          t_data[k] = data[k].to_s
        end
        break t_data
      end
      arr << transformed_data if transformed_data.present?
    end
  end
end