33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
# File 'lib/ree_lib/packages/ree_string/package/ree_string/functions/truncate_bytes.rb', line 33
def call(str, truncate_at, **opts)
str = str.dup
omission = opts[:omission] || DEFAULT_OMISSION
case
when str.bytesize <= truncate_at
str
when omission.bytesize > truncate_at
raise ArgumentError, "Omission #{omission.inspect} is #{omission.bytesize}, larger than the truncation length of #{truncate_at} bytes"
when omission.bytesize == truncate_at
omission.dup
else
String.new.tap do |cut|
cut_at = truncate_at - omission.bytesize
str.each_grapheme_cluster do |grapheme|
if cut.bytesize + grapheme.bytesize <= cut_at
cut << grapheme
else
break
end
end
cut << omission
end
end
end
|