class Crowbar::Client::Formatter::Nested

Formatter to properly print out keys and values in different formats

Public Instance Methods

empty?() click to toggle source
# File lib/crowbar/client/formatter/nested.rb, line 27
def empty?
  options[:values].blank?
end

Protected Instance Methods

process_hash(values, path = "", type = :table) click to toggle source
# File lib/crowbar/client/formatter/nested.rb, line 98
def process_hash(values, path = "", type = :table)
  [].tap do |result|
    values.map do |key, value|
      new_path = [path.to_s.dup, key].reject(&:empty?).join(".")

      case
      when value.is_a?(::Hash)
        result.concat process_hash(
          value,
          new_path,
          type
        )
      when value.is_a?(::Array)
        case type
        when :table
          result.push [
            new_path,
            value.join("\n")
          ]
        when :plain
          value.each_with_index do |row, index|
            result.push [
              [new_path, index].join("."),
              row
            ]
          end
        end
      else
        result.push [
          new_path,
          value
        ]
      end
    end
  end
end
process_json() click to toggle source
# File lib/crowbar/client/formatter/nested.rb, line 88
def process_json
  if options[:values].is_a?(::Hash) || options[:values].is_a?(::Array)
    JSON.pretty_generate(
      options[:values]
    )
  else
    options[:values]
  end
end
process_plain() click to toggle source
# File lib/crowbar/client/formatter/nested.rb, line 59
def process_plain
  case
  when options[:values].is_a?(::Hash)
    values = process_hash(
      options[:values],
      options[:path],
      :plain
    )
  when options[:values].is_a?(::Array)
    values = [].tap do |result|
      options[:values].each_with_index do |row, index|
        result.push [
          [options[:path], index].join("."),
          row
        ]
      end
    end
  else
    values = [[
      options[:path],
      options[:values]
    ]]
  end

  values.map do |value|
    value.join(" ")
  end.join("\n")
end
process_table() click to toggle source
# File lib/crowbar/client/formatter/nested.rb, line 33
def process_table
  case
  when options[:values].is_a?(::Hash)
    values = process_hash(
      options[:values],
      options[:path],
      :table
    )
  when options[:values].is_a?(::Array)
    values = [[
      options[:path],
      options[:values].join("\n")
    ]]
  else
    values = [[
      options[:path],
      options[:values]
    ]]
  end

  Terminal::Table.new(
    headings: options[:headings],
    rows: values
  )
end