Skip to content

Instantly share code, notes, and snippets.

@avand
Created June 6, 2014 03:32
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 avand/5006e58369b03aa9ddea to your computer and use it in GitHub Desktop.
Save avand/5006e58369b03aa9ddea to your computer and use it in GitHub Desktop.
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