Module: DNote::String

Included in:
String
Defined in:
lib/dnote/core_ext.rb

Overview

Extensions for String class. These methods are taken directly from Ruby Facets.

Instance Method Summary collapse

Instance Method Details

#indent(n) ⇒ Object

Indent left or right by n spaces. (This used to be called #tab and aliased as #indent.)

CREDIT: Gavin Sinclair
CREDIT: Trans


65
66
67
68
69
70
71
# File 'lib/dnote/core_ext.rb', line 65

def indent(n)
  if n >= 0
    gsub(/^/, ' ' * n)
  else
    gsub(/^ {0,#{-n}}/, "")
  end
end

#margin(n = 0) ⇒ Object

Provides a margin controlled string.

 x = %Q{
       | This
       |   is
       |     margin controlled!
       }.margin

 NOTE: This may still need a bit of tweaking.

CREDIT: Trans


33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/dnote/core_ext.rb', line 33

def margin(n=0)
  #d = /\A.*\n\s*(.)/.match( self )[1]
  #d = /\A\s*(.)/.match( self)[1] unless d
  d = ((/\A.*\n\s*(.)/.match(self)) ||
      (/\A\s*(.)/.match(self)))[1]
  return '' unless d
  if n == 0
    gsub(/\n\s*\Z/,'').gsub(/^\s*[#{d}]/, '')
  else
    gsub(/\n\s*\Z/,'').gsub(/^\s*[#{d}]/, ' ' * n)
  end
end

#tabset(n) ⇒ Object



75
76
77
78
79
80
81
82
83
# File 'lib/dnote/core_ext.rb', line 75

def tabset(n) 
  i = lines.map do |line|
    line.strip.empty? ? nil : line.index(/\S/)
  end
  x = i.compact.min
  t = n - x.to_i
  t = 0 if t < 0
  indent(t)
end

#tabto(n) ⇒ Object

Preserves relative tabbing. The first non-empty line ends up with n spaces before nonspace.

CREDIT: Gavin Sinclair


51
52
53
54
55
56
57
# File 'lib/dnote/core_ext.rb', line 51

def tabto(n)
  if self =~ /^( *)\S/
    indent(n - $1.length)
  else
    self
  end
end