提交 d684778a 编写于 作者: F Francesco Rodríguez 提交者: Jeremy Daer

Use String#truncate_bytes inside Multibyte::Chars#limit

上级 5943a556
......@@ -122,7 +122,7 @@ def reverse
#
# 'こんにちは'.mb_chars.limit(7).to_s # => "こん"
def limit(limit)
slice(0...translate_offset(limit))
truncate_bytes(limit, omission: nil)
end
# Capitalizes the first letter of every word, when possible.
......@@ -208,18 +208,6 @@ def as_json(options = nil) #:nodoc:
private
def translate_offset(byte_offset)
return nil if byte_offset.nil?
return 0 if @wrapped_string == ""
begin
@wrapped_string.byteslice(0...byte_offset).unpack("U*").length
rescue ArgumentError
byte_offset -= 1
retry
end
end
def chars(string)
self.class.new(string)
end
......
......@@ -785,21 +785,3 @@ def string_from_classes(classes)
end.pack("U*")
end
end
class MultibyteInternalsTest < ActiveSupport::TestCase
include MultibyteTestHelpers
test "Chars translates a character offset to a byte offset" do
example = chars("Puisque c'était son erreur, il m'a aidé")
[
[0, 0],
[3, 3],
[12, 11],
[14, 13],
[41, 39]
].each do |byte_offset, character_offset|
assert_equal character_offset, example.send(:translate_offset, byte_offset),
"Expected byte offset #{byte_offset} to translate to #{character_offset}"
end
end
end
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册