Skip to content

Instantly share code, notes, and snippets.

@ClayShentrup
Forked from garybernhardt/wrap.rb
Created June 26, 2012 05:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ClayShentrup/2993424 to your computer and use it in GitHub Desktop.
Save ClayShentrup/2993424 to your computer and use it in GitHub Desktop.
Probably a really bad implementation of word wrapping
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
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