Created
April 10, 2012 20:54
-
-
Save pmarreck/2354407 to your computer and use it in GitHub Desktop.
My Ruby string unindenter method
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
# encoding: utf-8 | |
module StringUtils | |
# Unindents a multiline string, | |
# even if the first line is not the one with the least whitespace. | |
# Best used with heredocs like this: <<-EOS.unindent ... | |
# Note that if there are lines that are just newlines that | |
# those will not break the next minimum indent length due to (?!\n) in the regex. | |
# This is to get around editors which auto strip trailing whitespace on lines. | |
# Otherwise any stripped whitespace on a blank line would kill the unindenting. | |
# Test coverage in string_utils_test.rb | |
def unindent | |
gsub(/^#{scan(/^(?!\n)\s*/).min_by{|l|l.length}}/u, "") | |
end | |
end | |
class String | |
include StringUtils | |
end | |
########################### string_utils_test.rb | |
# encoding: utf-8 | |
begin | |
require 'test_helper' | |
rescue LoadError | |
require File.expand_path(File.dirname(__FILE__) + '/../../test_helper') | |
end | |
class StringUtilsTest < ActiveSupport::TestCase | |
context "with a heredoc that includes foreign characters" do | |
setup do | |
end | |
should "not break extra indentation or encoding" do | |
sample = <<-EOS.unindent | |
This test | |
is sponsored by | |
Mötley Crüe | |
EOS | |
assert_equal " This test\n is sponsored by\nMötley Crüe\n\n", sample | |
end | |
should "be tolerant of editors that strip indented whitespace on a blank line and still unindent" do | |
sample = <<-EOS.unindent | |
This is the first line | |
This is the second line | |
This is the third line after a blank line | |
EOS | |
assert_equal "This is the first line\n This is the second line\n\n This is the third line after a blank line\n", sample | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment