Sha256: 9706a92c20d6e935b8aeefcfdd68a735824783be92535c06388102f7c76bccc3

Contents?: true

Size: 1.22 KB

Versions: 6

Compression:

Stored size: 1.22 KB

Contents

# encoding: utf-8

# =String
class String
  # ==justify pipe using table format
  def justify_table
    return self if self.empty?
    max_sizes = get_column_maxes
    return self if max_sizes.nil?
    justify_lines max_sizes
  end

  private

  def get_column_maxes
    max_sizes = []
    each_line do |line|
      return nil unless table? line
      columns = get_columuns(line)
      max_sizes = get_column_max(columns, max_sizes)
    end
    max_sizes
  end

  def justify_lines(max_sizes)
    ret = []
    each_line do |line|
      columns = get_columuns(line)
      line_ret = []
      columns.each_with_index do |column, cnt|
        line_ret << column.ljust(max_sizes[cnt])
      end
      ret << "|#{line_ret.join('|')}|"
    end
    ret.join("\n") + "\n"
  end

  def get_columuns(line)
    line.split('|')[1..-2]
  end

  def get_column_max(columns, max_sizes)
    columns.each_with_index do |column, index|
      current_size = column.size
      if max_sizes[index].nil?
        max_sizes << current_size
        next
      end
      max_sizes[index] = current_size if current_size > max_sizes[index]
    end
    max_sizes
  end

  def table?(text)
    text.count('|') > 0
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
tbpgr_utils-0.0.6 lib/open_classes/string.rb
tbpgr_utils-0.0.5 lib/open_classes/string.rb
tbpgr_utils-0.0.4 lib/open_classes/string.rb
tbpgr_utils-0.0.3 lib/open_classes/string.rb
tbpgr_utils-0.0.2 lib/open_classes/string.rb
tbpgr_utils-0.0.1 lib/open_classes/string.rb