Created
October 18, 2014 18:36
-
-
Save mahemoff/03a64ead9e34c5b48aa9 to your computer and use it in GitHub Desktop.
This file contains 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
# A rought attempt at balancing text. Injects normal spaces (thus allowing a newline) after too many characters; otherwise | |
# adds a non-breaking space. | |
# | |
# It works in reverse because we'd rather have longer text on top than on bottom. | |
def some_non_breaking_spacing(s) | |
words = s.split(/\s+/).reverse | |
first_word = words.shift | |
html_tokens = [first_word] | |
chars_since_normal_space = first_word.length | |
max_line_length = [10,first_word.length].max # allow longer than ideal if bottom line is already over that | |
words.each_with_object('') { |word, string| | |
if chars_since_normal_space + word.length > max_line_length | |
html_tokens << ' ' | |
chars_since_normal_space = word.length | |
else | |
html_tokens << ' ' | |
chars_since_normal_space += word.length+1 | |
end | |
html_tokens << word | |
} | |
html_tokens.reverse.join.safe | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment