Created
August 29, 2011 16:53
-
-
Save caomai/1178815 to your computer and use it in GitHub Desktop.
Extend String class with unindent method to tidy HEREDOC
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## Credit to SpiralOfHope for bugfix | |
### https://twitter.com/#!/spiralofhope | |
## Credit to Rene Sarsoo for original code | |
### http://stackoverflow.com/users/15982/rene-saarsoo | |
### http://stackoverflow.com/questions/3772864/how-do-i-remove-leading-whitespace-chars-from-ruby-heredoc/4465640#4465640 | |
class String | |
# Bug-fixed: If there is no indenting, this explodes. I changed \s+ to \s* | |
# Removes beginning-whitespace from each line of a string. | |
# But only as many whitespace as the first line of text has. | |
# | |
# Meant to be used with heredoc strings like so: | |
# | |
# text = <<-EOS.unindent | |
# This line has no indentation | |
# This line has 2 spaces of indentation | |
# This line is also not indented | |
# EOS | |
def unindent() | |
lines = Array.new | |
self.each_line { |ln| lines << ln } | |
first_line_ws = lines[0].match( /^\s*/ )[0] | |
rx = Regexp.new( '^\s{0,' + first_line_ws.length.to_s + '}' ) | |
lines.collect { |line| line.sub( rx, '' ) }.join | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment