Created
June 6, 2014 03:32
-
-
Save avand/5006e58369b03aa9ddea to your computer and use it in GitHub Desktop.
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
require "test/unit" | |
class TruncateFromCenter | |
def self.truncate(string, length = 30, separator = "...") | |
return string if length > string.length | |
if string.length <= separator.length || length <= separator.length | |
return string[0...length] | |
end | |
middle = (length - separator.length) / 2.0 | |
separator_start = middle.ceil | |
separator_end = string.length - middle.floor | |
string[0...separator_start] + separator + string[separator_end..-1] | |
end | |
end | |
class TruncateTest < Test::Unit::TestCase | |
def test_truncate_from_center | |
assert_equal TruncateFromCenter.truncate("foo", 1), "f" | |
assert_equal TruncateFromCenter.truncate("foo", 3), "foo" | |
assert_equal TruncateFromCenter.truncate("foo", 5), "foo" | |
assert_equal TruncateFromCenter.truncate("foobar", 3), "foo" | |
assert_equal TruncateFromCenter.truncate("foobar", 4), "f..." | |
assert_equal TruncateFromCenter.truncate("foobar", 5), "f...r" | |
assert_equal TruncateFromCenter.truncate("foobarbaz", 6), "fo...z" | |
assert_equal TruncateFromCenter.truncate("foobarbaz", 7), "fo...az" | |
assert_equal TruncateFromCenter.truncate("foobar", 4, "-"), "fo-r" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment