Skip to content

Commit

Permalink
rename String#outdent to String#unindent and improve
Browse files Browse the repository at this point in the history
  • Loading branch information
trans committed May 29, 2010
1 parent 4e0f626 commit 3317ec1
Show file tree
Hide file tree
Showing 3 changed files with 87 additions and 4 deletions.
42 changes: 42 additions & 0 deletions lemon/core/string/test_unindent.rb
@@ -0,0 +1,42 @@
Covers 'facets/string/unindent'

Case String do

Concern "Single-line indentation"

Unit :unindent => "removes space indentation" do
"\s\sabc".unindent.assert == "abc"
end

Unit :unindent => "removes_tab_indentation" do
"\tabc".unindent.assert == "abc"
end

Unit :unindent => "removes space and tab indentation" do
"\t\sabc".unindent.assert == "abc"
end

Concern "Multi-line indentation"

Unit :unindent => "removes indentation" do
"\tabc\n\tabc".unindent.assert == "abc\nabc"
end

Unit :unindent => "keeps relative indentation" do
"\tabc\n\t\tabc".unindent.assert == "abc\n\tabc"
end

Unit :unindent => "ignores blank lines for indent calculation" do
"\n\tabc\n\n\t\tabc\n".unindent.assert == "\nabc\n\n\tabc\n"
end

Concern "Inplace method"

Unit :unindent! => "modifies string in place" do
str = "\s\sabc"
str.unindent!
str.assert == "abc"
end

end

48 changes: 44 additions & 4 deletions lib/core/facets/string/indent.rb
Expand Up @@ -13,12 +13,52 @@ def indent(n, c=' ')
end
end

# Outdent just indents a negative number of spaces.
# Equivalent to String#indent, but modifies the receiver in place.

def indent!(n, c=' ')
replace(indent(n,c))
end

# Remove excessive indentation. Useful for multi-line strings embeded in
# already indented code.
#
# puts <<-END.unindent
# ohaie
# wurld
# END
#
# # outputs:
# ohaie
# wurld
#
# # instead of:
# ohaie
# wurld
#
# CREDIT: Noah Gibbs, mynyml

def unindent(size=nil)
if size
indent(-size)
else
char = ' '
self.scan(/^[\ \t]*\S/) do |m|
if size.nil? || m.size < size
size = m.size
char = m[0...-1]
end
end
size -= 1
indent(-size, char)
end
end

# Equivalent to String#unindent, but modifies the receiver in place.
#
# CREDIT: Noah Gibbs
# CREDIT: mynyml

def outdent(n)
indent(-n)
def unindent!
self.replace(self.unindent)
end

end
Expand Down
1 change: 1 addition & 0 deletions lib/core/facets/string/unindent.rb
@@ -0,0 +1 @@
require 'facets/string/indent'

0 comments on commit 3317ec1

Please sign in to comment.