Class: Verse::Alignment

Inherits:
Object
  • Object
show all
Defined in:
lib/verse/alignment.rb

Overview

A class responsible for text alignment

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(text, options = {}) ⇒ Alignment

Initialize an Alignment



13
14
15
16
17
# File 'lib/verse/alignment.rb', line 13

def initialize(text, options = {})
  @text      = text
  @fill      = options.fetch(:fill) { SPACE }
  @direction = options.fetch(:direction) { :left }
end

Instance Attribute Details

#directionObject (readonly)

Returns the value of attribute direction.



8
9
10
# File 'lib/verse/alignment.rb', line 8

def direction
  @direction
end

#fillObject (readonly)

Returns the value of attribute fill.



6
7
8
# File 'lib/verse/alignment.rb', line 6

def fill
  @fill
end

Class Method Details

.align(text, width, direction, options) ⇒ Object

Align a text to a given direction with the width

See Also:



51
52
53
# File 'lib/verse/alignment.rb', line 51

def self.align(text, width, direction, options)
  new(text, options).align(width, direction, options)
end

Instance Method Details

#align(width, direction = :left, options = {}) ⇒ Object

Aligns text within the width.

If the text is greater than the width then unmodified string is returned.

Examples:

alignment = Verse::Alignment.new "the madness of men"

alignment.align(22, :left)
# => "the madness of men      "

alignment.align(22, :center)
# => "   the madness of men   "

alignment.align(22, :right)
# => "      the madness of men"


73
74
75
76
77
78
79
# File 'lib/verse/alignment.rb', line 73

def align(width, direction = :left, options = {})
  return text unless width

  filler = options.fetch(:fill) { fill }
  method = convert_to_method(direction)
  process_lines { |line| send(method, line, width, filler) }
end

#center(width, options = {}) ⇒ String

Centers text within the width

Returns:

  • (String)


33
34
35
# File 'lib/verse/alignment.rb', line 33

def center(width, options = {})
  align(width, :center, options)
end

#left(width, options = {}) ⇒ String

Aligns text to the left

Returns:

  • (String)


24
25
26
# File 'lib/verse/alignment.rb', line 24

def left(width, options = {})
  align(width, :left, options)
end

#right(width, options = {}) ⇒ String

Aligns text to the right

Returns:

  • (String)


42
43
44
# File 'lib/verse/alignment.rb', line 42

def right(width, options = {})
  align(width, :right, options)
end