aptinio / text-table

A feature-rich, easy-to-use plain text table formatter.
MIT License
96 stars 14 forks source link

No aligns with ANSI characters (for colors) #6

Open alexandre-mbm opened 10 years ago

Larusso commented 9 years ago

The problem is, that ljust, rjust and center calculate the length of the string value with the hidden escaped ANSI characters. I use this in my code. I apply the color after the alignment:

require 'colorize'

module Text
    class Table
        class Cell
            def initialize(options = {}) #:nodoc:
                @value        = options[:value].to_s
                @row          = options[:row]
                @align        = options[:align  ] || :left
                @colspan      = options[:colspan] || 1
                @color        = options[:color] || :default
                @background   = options[:background] || :default
                @effect       = options[:effect] || :default
            end

            def set_color(string)
                string.colorize color: @color, background: @background, mode: @effect
            end

            def to_s #:nodoc:
                ([' ' * table.horizontal_padding]*2).join case align
                when :left
                    set_color(value.ljust cell_width)
                when :right
                    set_color(value.rjust cell_width)
                when :center
                    set_color(value.center cell_width)
                end
            end
        end
    end
end 

https://gist.github.com/ce7df9a788e945e83cae.git I thinking about if it is worth to either integrate into text-table or create a separate gem that extents text-table and integrates this.

aptinio commented 9 years ago

I'd like people to be able to do this using text-table but I haven't decided on the best way to do it. One of the things I've been thinking of is allowing a post_processor proc to be passed in like so:

highlight = ->(cell) { cell.content.colorize :yellow }
table.rows << [{ value: 'reminder', post_processor: highlight }]

In this example, Cell#content still needs to be implemented.

I was also planning of rewriting everything except the specs. That's why I haven't gotten to resolving this issue. But that remains a plan. Pull requests are welcome though :-)

mattheworiordan commented 7 years ago

Thanks @Larusso I am using your patch, works well, although it's a bit hacky! Hopefully @aptinio will find a better solution. Sorry @aptinio not enough of an issue for me to do a PR at this stage.