# frozen_string_literal: true # Requirements # ======================================================================= # Stdlib # ----------------------------------------------------------------------- # Deps # ----------------------------------------------------------------------- # Project / Package # ----------------------------------------------------------------------- # Refinements # ======================================================================= require 'nrser/refinements/types' using NRSER::Types # Definitions # ======================================================================= # class Locd::CLI::Table # Unicode superscript number to use as references for columns with # descriptions. # # @return [Array] # SUPERSCRIPT_NUMBERS = [ "\u2070", "\u00B9", "\u00B2", "\u00B3", "\u2070", "\u2074", "\u2075", "\u2076", "\u2077", "\u2078", "\u2079", ].freeze NULL = '␀' # Mixins # ============================================================================ include Enumerable # Classes # ============================================================================ # A column in a table. # class Column attr_reader :name, :getter, :desc def initialize name, desc: nil, &getter @name = name @getter = getter @desc = desc end end # class Column # @todo Document build method. # # @param [type] arg_name # @todo Add name param description. # # @return [return_type] # @todo Document return value. # def self.build &block new.tap &block end # .build def initialize @columns = [] @rows = [] end def each &block @rows.each &block end def each_index &block @rows.each_index &block end def column *args, &getter @columns << Column.new( *args, &getter ) end alias_method :col, :column def rows entries = nil unless entries.nil? @rows = entries.to_a end @rows end def to_a header: true, col_desc_refs: true [].tap do |array| if header desc_ref_index = 0 array << @columns.map { |column| if column.desc && col_desc_refs desc_ref_index += 1 "#{ column.name }#{ SUPERSCRIPT_NUMBERS[desc_ref_index] }" else column.name end } end @rows.each do |row| values = if NRSER.array_like? row row.to_a else @columns.map do |column| column.getter.call( row ) end end array << values.map { |value| if value.nil? NULL else value.to_s end } end end end # #to_a def footer NULL + " Null\n" + @columns.select { |col| col.desc }.each_with_index.map { |col, index| "#{ SUPERSCRIPT_NUMBERS[index + 1] } #{ col.desc }" }.join( "\n" ) end end # class Locd::CLI::Table