Class: String

Inherits:
Object show all
Defined in:
lib/ceedling/plugin.rb

Instance Method Summary collapse

Instance Method Details

#left_margin(margin = 0) ⇒ Object

reformat a multiline string to have given number of whitespace columns; helpful for formatting heredocs



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/ceedling/plugin.rb', line 5

def left_margin(margin=0)
  non_whitespace_column = 0
  new_lines = []
  
  # find first line with non-whitespace and count left columns of whitespace
  self.each_line do |line|
    if (line =~ /^\s*\S/)
      non_whitespace_column = $&.length - 1
      break
    end
  end
  
  # iterate through each line, chopping off leftmost whitespace columns and add back the desired whitespace margin
  self.each_line do |line|
    columns = []
    margin.times{columns << ' '}
    # handle special case of line being narrower than width to be lopped off
    if (non_whitespace_column < line.length)
      new_lines << "#{columns.join}#{line[non_whitespace_column..-1]}"
    else
      new_lines << "\n"
    end
  end
  
  return new_lines.join
end