Created
June 20, 2012 23:42
-
-
Save pmarreck/2962946 to your computer and use it in GitHub Desktop.
A monkeypatch to Rails' ActionView::Helpers::TextHelper (or that class provided by the rails_autolink gem) which causes it to chop up input data in case it's too long to handle
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
# encoding: utf-8 | |
# Patch for auto_link method to chop text up into lines first, | |
# speeding up its run time considerably and making it resilient to bad or overly gigantic input | |
if defined?(ActionView::Helpers::TextHelper) && ActionView::Helpers::TextHelper.instance_methods.include?(:auto_link) | |
module ActionView | |
module Helpers | |
module TextHelper | |
unless defined?(slow_auto_link) # we don't want to method chain it twice... | |
MAX_LINE_LENGTH = 500 # characters | |
alias_method :slow_auto_link, :auto_link | |
# Redefine auto_link to split its text by lines first | |
# and then run the original auto_link against those lines | |
def auto_link(text, *args, &block) | |
words = [] | |
text.split("\n").map! do |line| | |
# I'm worried about the line being too long still, catastrophic case of no line breaks | |
# so I am further splitting into groups of words on spaces. | |
# In the catastrophic case of no spaces either... Well then we're | |
# stuck as splitting randomly could chop up URL's, so I just return the original string. | |
if line.length > MAX_LINE_LENGTH | |
# Try to split into groups of 30 words if the line is too long. | |
# note: splitting on \s here instead of ' ' for a reason- the latter does not preserve runs of spaces | |
words_grouped = line.split(/\s/).each_slice(30).to_a.map!{|wg| wg.join(' ')} | |
words_grouped.map! do |words| | |
if words.length > MAX_LINE_LENGTH | |
words # just give up and choke out the original text | |
else | |
slow_auto_link(words, *args, &block) | |
end | |
end.join(' ') | |
else | |
slow_auto_link(line, *args, &block) | |
end | |
end.join("\n") | |
end # new auto_link | |
else | |
msg = "WARNING: Attempt to alias auto_link to slow_auto_link when slow_auto_link is already defined, in #{__FILE__}" | |
puts msg | |
Rails.logger.warn msg | |
end # redefining slow_auto_link check | |
end # TextHelper | |
end # Helpers | |
end # ActionView | |
else | |
raise "Can't monkeypatch ActionView::Helpers::TextHelper#auto_link unless the class exists first and the method is already defined, perhaps via the rails_autolink gem if this is Rails.version >= 3.1" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment