Module: CoreExt::String::HeredocUnindent

Defined in:
lib/heredoc_unindent.rb

Overview

This module, which is automatically included in ::String, define in-place and out-of-place unindentation methods.

Instance Method Summary collapse

Instance Method Details

#heredoc_unindent(warn_first_not_min = true, args = {}) ⇒ ::String Also known as: unindent

Removes common margin from indented strings, such as the ones produced by indented heredocs. In other words, it strips out leading whitespace chars at the beggining of each line, but only as much as the line with the smallest margin.

Unless the optional argument warn_first_dif_min is set to false (or nil), a warning is produced when the margin of the first line differs from the minimum.

Examples:


if true
  s = <<-EOS
    How sad it is to be unable to unindent heredocs
  EOS
  t = <<-EOS.unindent
    How wonderful it is to be able to do it!
  EOS
end

s[0..12]  #=>  "      How sad"
t[0..12]  #=>  "How wonderful"

Parameters:

  • warn_first_not_min (Boolean) (defaults to: true)

    toggle warning if the margin of the first line differs from minimum margin

Returns:

  • (::String)

    unindented string



111
112
113
114
# File 'lib/heredoc_unindent.rb', line 111

def heredoc_unindent(warn_first_not_min=true, args={})
  args, warn_first_not_min = warn_first_not_min, true if warn_first_not_min.is_a? Hash
  unindent_base(false, warn_first_not_min, args)
end

#heredoc_unindent!(warn_first_not_min = true, args = {}) ⇒ ::String, NilClass Also known as: unindent!

Note:

Avoid attributing the return value of this method because it may be nil (see Example 2).

Same as #heredoc_unindent, but works in-place. Returns self, or nil if no changes were made

Examples:

1 Recommended


s = "   foo"  #=> "   foo"
s.unindent!   #=>  "foo"
s.unindent!   #=>  nil

2 Disencouraged


s = <<-EOS.unindent!
  the result would be as intended
if this line weren't unindented
EOS
s  #=>  nil

Parameters:

  • warn_first_dif_min (Boolean)

    toggle warning if the margin of the first line differs from minimum margin

Returns:

  • (::String, NilClass)

    unindented self, or nil if no changes were made



140
141
142
# File 'lib/heredoc_unindent.rb', line 140

def  heredoc_unindent!(warn_first_not_min=true, args={})
  unindent_base(true, warn_first_not_min, args)
end