Last active
December 3, 2015 08:30
-
-
Save fiftin/004b70ac0fc0a72738f8 to your computer and use it in GitHub Desktop.
Long word wrap with using Ruby on Rails
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
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('­') | |
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