Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@mahemoff
Created October 18, 2014 18:36
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 mahemoff/03a64ead9e34c5b48aa9 to your computer and use it in GitHub Desktop.
Save mahemoff/03a64ead9e34c5b48aa9 to your computer and use it in GitHub Desktop.
# 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 << '&nbsp;'
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