-
-
Save ClayShentrup/2993424 to your computer and use it in GitHub Desktop.
Probably a really bad implementation of word wrapping
This file contains hidden or 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
class Wrap < Struct.new(:string, :max_length) | |
def self.wrap(s, max_length) | |
raise ArgumentError.new("Maximum wrap length can't be 0") if max_length == 0 | |
new(s, max_length).wrap | |
end | |
def wrap | |
return [""] if blank? | |
string.scan(regexp) | |
end | |
private | |
def blank? | |
!string.match /\S/ | |
end | |
def regexp | |
Regexp.new(matchers.join('|')) | |
end | |
def matchers | |
[beginning_of_line, without_whitespace, with_whitespace] | |
end | |
def beginning_of_line | |
"^.{0,#{max_length - 1}}\\S(?=\\b)" | |
end | |
def without_whitespace | |
"\\S{#{max_length}}" | |
end | |
def with_whitespace | |
"\\S.{0,#{max_length - 2}}\\S(?=\\b)" | |
end | |
end |
This file contains hidden or 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
require_relative "../wrap" | |
describe Wrap do | |
it "wraps at word boundaries" do | |
Wrap.wrap("foo bar", 3).should == ["foo", "bar"] | |
Wrap.wrap("foo bar", 4).should == ["foo", "bar"] | |
Wrap.wrap("foo bar baz", 9).should == ["foo bar", "baz"] | |
end | |
it "errors when the wrap width is 0" do | |
expect { Wrap.wrap("foo", 0) }.to raise_error(ArgumentError) | |
end | |
it "doesn't wrap when it's not needed" do | |
Wrap.wrap("foo", 3).should == ["foo"] | |
Wrap.wrap("foo", 4).should == ["foo"] | |
Wrap.wrap("", 1).should == [""] | |
Wrap.wrap("", 2).should == [""] | |
Wrap.wrap(" ", 1).should == [""] | |
Wrap.wrap(" ", 2).should == [""] | |
Wrap.wrap("foo bar", 7).should == ["foo bar"] | |
end | |
it "doesn't left-strip lines" do | |
Wrap.wrap(" foo", 4).should == [" foo"] | |
Wrap.wrap(" foo bar", 4).should == [" foo", "bar"] | |
end | |
it "breaks words if necessary" do | |
Wrap.wrap("foobar", 3).should == ["foo", "bar"] | |
Wrap.wrap("foobar", 2).should == ["fo", "ob", "ar"] | |
Wrap.wrap("foobar ", 3).should == ["foo", "bar"] | |
Wrap.wrap(" foo", 3).should == ["foo"] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment