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



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

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.



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

def direction
  @direction
end

#fillObject (readonly)

Returns the value of attribute fill.



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

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:



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

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"


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

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)


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

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

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

Aligns text to the left

Returns:

  • (String)


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

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

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

Aligns text to the right

Returns:

  • (String)


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

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