Module: CoreExtensions::String::Box

Defined in:
lib/core_extensions/string/box.rb

Instance Method Summary collapse

Instance Method Details

#boxed(width = 40, opts = {}) ⇒ Object

Raises:

  • (ArgumentError.new)


17
18
19
20
21
22
23
24
25
26
# File 'lib/core_extensions/string/box.rb', line 17

def boxed(width=40, opts={})
  justify = opts.fetch(:justify, :center)
  raise ArgumentError.new, "Width must be >= 5" unless width >= 5
  raise ArgumentError.new, ":justify must be :ljust, :rjust, or :center" unless %i(ljust rjust center).include? justify
  arr = self.split("\n").map do |l|
    "| #{l.send(justify, width - 4)} |"
  end
  header_line =  "+#{'-' * (width - 2)}+"
  [header_line, *arr, header_line].join("\n")
end

#space_at(width, opts = {}) ⇒ Object



4
5
6
7
8
9
# File 'lib/core_extensions/string/box.rb', line 4

def space_at(width, opts={})
  separator = opts.fetch(:on, / /)
  self.split(separator).map do |word|
    word.scan(/.{1,#{width}}/m)
  end.flatten.join(' ')
end

#wrap(width) ⇒ Object



11
12
13
14
15
# File 'lib/core_extensions/string/box.rb', line 11

def wrap(width)
  self.split("\n").map! do |line|
    line.length > width ? line.gsub(/(.{1,#{width}})(\s+|$)/, "\\1\n").strip : line.strip
  end.join("\n")
end