Created
March 29, 2016 18:32
-
-
Save skyeagle/4a547b355d307db8b6268be40f0a1e65 to your computer and use it in GitHub Desktop.
Smart truncate method. It doesn't break words. Add it to rails initializers
This file contains hidden or 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
module ActionView::Helpers::TextHelper | |
def truncate(text, *args) | |
return '' unless text | |
text.truncate(*args) | |
end | |
end | |
class String | |
def truncate(*args) | |
options = args.extract_options! | |
# support either old or Rails 2.2 calling convention: | |
unless args.empty? | |
options[:length] = args[0] || 30 | |
options[:omission] = args[1] || "..." | |
end | |
options.reverse_merge!(:length => 30, :omission => "...") | |
chars = self.mb_chars | |
omission = options[:omission].mb_chars | |
l = options[:length] - omission.length | |
if chars.length > options[:length] | |
result = chars[/\A.{#{l}}\p{Word}*\;?/mu][/.*[\p{Word}\;]/mu].to_s | |
result.replace result[0..l-1] if result.length > l && !result.match(/(\s|\n)/) | |
((options[:avoid_orphans] && result =~ /\A(.*?)\n+\W*\p{Word}*\W*\Z/mu) ? $1 : result) + omission | |
else | |
self | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment