Skip to content

Instantly share code, notes, and snippets.

@fiftin
Last active December 3, 2015 08:30
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 fiftin/004b70ac0fc0a72738f8 to your computer and use it in GitHub Desktop.
Save fiftin/004b70ac0fc0a72738f8 to your computer and use it in GitHub Desktop.
Long word wrap with using Ruby on Rails
def long_word_wrap(str, options = {})
opts = { length: 10000, word_length: 10, shy_length: 4 }.merge(options)
ret = ''
offset = 0
str = truncate(str, length: opts[:length]) if str.length > opts[:length]
m = str.match(/[^\s\n\r]{#{opts[:word_length]},}/, offset)
while m
ret << h(str[offset..m.begin(0)-1]) if offset < m.begin(0)
s = m[0].scan(/[^\s\n\r]{1,#{opts[:shy_length]}}/)
ret << s.map{ |x| h(x) }.join('&shy;')
offset = m.end(0)
m = str.match(/[^\s\n\r]{#{opts[:word_length],}/, offset)
end
ret << h(str[offset..-1])
ret.html_safe
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment