Sha256: 04dd6fd339bb5b463387237315e0ca21e6e54a292779896f00b7ca6caed872e0

Contents?: true

Size: 1.74 KB

Versions: 2

Compression:

Stored size: 1.74 KB

Contents

$KCODE = 'u'
require 'jcode'

class CucumberTableFormatter
  attr_accessor :lines
  attr_reader :whitespace
  attr_reader :columns
  
  class Column
    attr_accessor :values
    
    def initialize
      @values = []
    end

    def formatted_values
      @formatted_values ||= values.map do |value|
        value_length = value.jlength # Required for ruby 1.8 utf-8 issues
        " " + " " * (longest_value - value_length) + value + " "
      end
    end
    
    private
    
    def longest_value
      @longest_value ||= values.sort_by {|v| v.length }.reverse.first.length
    end
  end
  
  def initialize(table)
    # Convert string by splitting by newlines if string given. If array, this can be skipped
    table = table.split("\n") if table.kind_of?(String)
    # Remove all empty lines and put all others into lines instance variable, cleaned up from newline chars
    # TODO: Leave lines without a pipe character as they are so whole feature-files can be processed
    self.lines = table.reject { |l| l.strip.chomp.length == 0 }.map(&:chomp)
    # Get the whitespace 
    @whitespace = self.lines.first.split("|")[0].length
    read_columns!
  end
  
  def formatted
    (0...lines.length).to_a.map { |i| " "*whitespace + "|" + formatted_line(i) + "|" }.join("\n")
  end
  
  def formatted_line(index)
    columns.map do |c|
      c.formatted_values[index]
    end.join("|")
  end
  
  private
  
  #
  # Process the lines
  #
  def read_columns!
    @columns ||= []
    lines.each do |line|
      line.strip.chomp.split("|").reject {|l| l.length == 0}.each_with_index do |value, column_index|
        # Initialize column when needed
        @columns[column_index] ||= Column.new
        @columns[column_index].values << value.strip.chomp
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
colszowka-cucumber_table_formatter-0.2.1 lib/cucumber_table_formatter.rb
colszowka-cucumber_table_formatter-0.2.2 lib/cucumber_table_formatter.rb