Skip to content

Instantly share code, notes, and snippets.

@skyeagle
Created March 29, 2016 18: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 skyeagle/4a547b355d307db8b6268be40f0a1e65 to your computer and use it in GitHub Desktop.
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
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