Class: TTY::Table::Operation::Alignment

Inherits:
Object
  • Object
show all
Includes:
Coercion
Defined in:
lib/tty/table/operation/alignment.rb

Overview

A class representing an alignment of cell data.

Constant Summary collapse

LEFT =
:left.freeze
RIGHT =
:right.freeze
CENTER =
:center.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Coercion

#coerce_to

Constructor Details

#initialize(type = nil) ⇒ self

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Initialize an Alignment

Raises:

  • (TypeError)

    raise if the alignment is not supported type



30
31
32
33
# File 'lib/tty/table/operation/alignment.rb', line 30

def initialize(type=nil)
  @type = coerce_to((type || LEFT), Symbol, :to_sym)
  assert_valid_type
end

Instance Attribute Details

#typeObject (readonly)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Hold the type of alignment



20
21
22
# File 'lib/tty/table/operation/alignment.rb', line 20

def type
  @type
end

Instance Method Details

#assert_valid_typeundefined

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Assert the type is valid

Returns:

  • (undefined)

Raises:

  • (TypeError)

    raise if the alignment is not supported type



43
44
45
46
47
# File 'lib/tty/table/operation/alignment.rb', line 43

def assert_valid_type
  unless supported.include? type
    raise TypeError, "Alignment must be one of: #{supported.join(' ')}"
  end
end

#format(field, column_width, space = '') ⇒ String

Format field with a given alignment

Parameters:

  • field (Object)
  • column_width (Integer)
  • space (String) (defaults to: '')

Returns:

  • (String)

    aligned



70
71
72
73
74
75
76
77
78
79
# File 'lib/tty/table/operation/alignment.rb', line 70

def format(field, column_width, space='')
  case type
  when :left
    "%-#{column_width}s#{space}" % field.to_s
  when :right
    "%#{column_width}s#{space}" % field.to_s
  when :center
    center_align field, column_width, space
  end
end

#supportedArray

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

List supported alignment types

Returns:

  • (Array)

    valid alignments



55
56
57
# File 'lib/tty/table/operation/alignment.rb', line 55

def supported
  [LEFT, RIGHT, CENTER]
end