Class: Columnist::Column

Inherits:
Object
  • Object
show all
Includes:
OptionsValidator
Defined in:
lib/columnist/column.rb

Constant Summary collapse

VALID_OPTIONS =
[:width, :padding, :align, :color, :bold, :underline, :reversed]

Instance Method Summary collapse

Methods included from OptionsValidator

#validate_options

Constructor Details

#initialize(text = nil, options = {}) ⇒ Column

Returns a new instance of Column.

Raises:

  • (ArgumentError)


10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/columnist/column.rb', line 10

def initialize(text = nil, options = {})
    self.validate_options(options, *VALID_OPTIONS)
    self.text_without_colors = text.to_s.gsub(/(.)\[\d{1,3};\d{1,3};\d{1,3}m/, '')
    self.text                = text.to_s
    self.width               = options[:width] || 10
    self.align               = options[:align] || 'left'
    self.padding             = options[:padding] || 0
    self.color               = options[:color] || nil
    self.bold                = options[:bold] || false
    self.underline           = options[:underline] || false
    self.reversed            = options[:reversed] || false
    raise ArgumentError unless self.width > 0
    raise ArgumentError unless self.padding.to_s.match(/^\d+$/)
end

Instance Method Details

#required_widthObject



29
30
31
# File 'lib/columnist/column.rb', line 29

def required_width
    self.text_without_colors.to_s.size + 2 * self.padding
end

#screen_rowsObject



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/columnist/column.rb', line 33

def screen_rows
    if self.text_without_colors.nil? || self.text_without_colors.empty?
        [' ' * self.width]
    else
        x = self.text.scan(/.{1,#{self.size}}/).map { |s| to_cell(s) }
        if x.length > 1
            actual_length = 0
            x.each do |z|
                z                    = z.gsub(/\A(.)\[\d{1,3};\d{1,3};\d{1,3}m/, '').gsub(/\s+(.)\[\d{1,3};\d{1,3};\d{1,3}m\z/, '')
                characters_to_ignore = 0
                matches_to_ignore    = z.scan(/\[\d{1,3};\d{1,3};\d{1,3}m/)
                matches_to_ignore.each do |match|
                    characters_to_ignore += match.length + 1
                end
                actual_length += z.length - characters_to_ignore
            end
            if actual_length < self.size
                y = []
                x.each do |z|
                    y << z.gsub(/\A(.)\[\d{1,3};\d{1,3};\d{1,3}m/, '').gsub(/\s+(.)\[\d{1,3};\d{1,3};\d{1,3}m\z/, '')
                end
                y = ["#{y.join}#{' ' * (self.size - actual_length)}"]
                return y
            end
            return [x[0]]
        else
            return x
        end
    end
end

#sizeObject



25
26
27
# File 'lib/columnist/column.rb', line 25

def size
    self.width - 2 * self.padding
end