Module: Yummi::Aligner

Defined in:
lib/yummi.rb

Overview

A module to align texts based on a reference width

Class Method Summary collapse

Class Method Details

.align(to, text, width) ⇒ Object

Aligns the text

Args

to

Defines the type of the alignment (must be a method defined in this module)

text

The text to align

width

The width of alignment, this will define how much the text will be moved.



92
93
94
# File 'lib/yummi.rb', line 92

def self.align to, text, width
  send to, text, width
end

.center(text, width) ⇒ Object

Aligns the text to the center



109
110
111
112
113
114
115
116
# File 'lib/yummi.rb', line 109

def self.center text, width
  text = text.to_s unless text.is_a? String
  return text if text.size >= width
  size = width - text.size
  left_size = size / 2
  right_size = size - left_size
  (' ' * left_size) << text << (' ' * right_size)
end

.justify(text, width) ⇒ Object

Aligns the text to both sides



119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
# File 'lib/yummi.rb', line 119

def self.justify text, width
  text = text.to_s unless text.is_a? String
  extra_spaces = width - text.size
  return text unless extra_spaces > 0
  words = text.split ' '
  # do not justify only one word
  return text if words.size == 1
  # do not justify few words
  return text if extra_spaces / (words.size - 1) > 2
  until extra_spaces == 0
    words.each_index do |i|
      break if i - 1 == words.size # do not add spaces in the last word
      words[i] << ' '
      extra_spaces -= 1
      break if extra_spaces == 0
    end
  end
  words.join ' '
end

.left(text, width) ⇒ Object

Aligns the text to the left



103
104
105
106
# File 'lib/yummi.rb', line 103

def self.left text, width
  text = text.to_s unless text.is_a? String
  text.ljust(width)
end

.right(text, width) ⇒ Object

Aligns the text to the right



97
98
99
100
# File 'lib/yummi.rb', line 97

def self.right text, width
  text = text.to_s unless text.is_a? String
  text.rjust(width)
end