Created
May 11, 2020 08:51
-
-
Save lebalz/6cb876543e254521922376b56bdaea8c to your computer and use it in GitHub Desktop.
methods to create a markdown-formatted table from 2d-arrays, hashes or csv data
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'json' | |
def to_md_row(row, max_field_sizes) | |
md = row.zip(max_field_sizes).map do |field, sz| | |
"#{field.to_s.ljust(sz, ' ')}" | |
end.join(' | ') | |
"| #{md} |" | |
end | |
def table_def_row(max_field_sizes) | |
table_def = max_field_sizes.map { |sz| ":#{'-' * (sz + 1)}"}.join('|') | |
"|#{table_def}|" | |
end | |
# @param name [String] table name | |
# @param fields [Array<Array<String>>] mxn 2d array to be converted to table. | |
# First row is used as the header | |
def to_table(fields, name = nil) | |
table = name ? ["**#{name}**"] : [] | |
m = fields.size | |
return table[0] unless m > 0 | |
n = fields[0].size | |
return table[0] unless n > 0 | |
max_field_sizes = n.times.map{ |col| fields.map { |row| row[col].to_s.length }.max } | |
table << to_md_row(fields.first, max_field_sizes) | |
table << table_def_row(max_field_sizes) | |
fields[1..-1].each do |row| | |
table << to_md_row(row, max_field_sizes) | |
end | |
table.join("\n") | |
end | |
# @param json_string [String] String containing all results, e.g. | |
# [ | |
# { | |
# "id": 1, | |
# "name": "Meier", | |
# "vorname": "Lena", | |
# "adresse": "Heideweg 1", | |
# "plz": 3000, | |
# "gebdatum": "1996-02-16", | |
# "lehrfirma": "Ascom", | |
# "klassen_id": 1 | |
# }, | |
# { | |
# "id": 2, | |
# "name": "Zangger", | |
# "vorname": "Eva", | |
# "adresse": "Ahornweg 34", | |
# "plz": 4002, | |
# "gebdatum": "1998-08-23", | |
# "lehrfirma": "Swisscom", | |
# "klassen_id": 1 | |
# }, | |
# ... | |
# ] | |
def to_table_from_json(name, json_string) | |
begin | |
data = JSON.parse(json_string) | |
rescue StandardError => e | |
return to_table(name, []) | |
end | |
return to_table(name, []) unless fields.size > 0 | |
arr_data = [] | |
arr_data << data[0].keys | |
arr_data.push(*data.map(&:values)) | |
return to_table(name, arr_data) | |
end | |
def to_table_from_csv(name, csv_string) | |
begin | |
data = JSON.parse(json_string) | |
rescue StandardError => e | |
return to_table(name, []) | |
end | |
return to_table(name, []) unless fields.size > 0 | |
arr_data = [] | |
arr_data << data[0].keys | |
arr_data.push(*data.map(&:values)) | |
return to_table(name, arr_data) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment