Skip to content

Instantly share code, notes, and snippets.

@samleb
Last active August 29, 2015 13:56
Show Gist options
  • Save samleb/9312296 to your computer and use it in GitHub Desktop.
Save samleb/9312296 to your computer and use it in GitHub Desktop.
“Replace Method With Method Object” to the rescue.
module Partners::DailymotionHelper
def dailymotion_sanitize_film_summary(summary)
summary.gsub!(/\r\n/, "\n")
summary.gsub!(%r{(\n\s*)?<br[^>]*>(\s*\n)?}i, "\n")
summary.gsub!(%r{</p[^>*]>}i, "</p>\n\n")
summary = strip_tags(summary)
summary.gsub!(/\u0003/, '')
summary.gsub!(/\n\n+/, "\n\n")
summary.strip!
summary
end
end
module Partners::DailymotionHelper
def dailymotion_sanitize_film_summary(summary)
DailymotionSanitizer.sanitize!(summary)
end
class DailymotionSanitizer
NEWLINE = "\n".freeze
DOUBLE_NEWLINE = "\n\n".freeze
EMPTY_STRING = ''.freeze
include ActionView::Helpers::SanitizeHelper
def self.sanitize!(string)
new(string).sanitize!
end
def initialize(string)
@string = string
end
def sanitize!
normalize_newlines
replace_br_tags_by_newlines
insert_double_newlines_after_p_tags
remove_control_characters
strip_html_tags
limit_to_two_following_newlines
@string.strip!
@string
end
protected
def normalize_newlines
# The following reads better but is approx 10 times slower...
# @string.encode!(Encoding::UTF_8, universal_newline: true)
@string.gsub!(/\r\n?/, NEWLINE)
end
def replace_br_tags_with_newlines
@string.gsub!(%r{
\s*
<br[^>]*>
\s*
}ix, NEWLINE)
end
def insert_double_newlines_after_p_tags
@string.gsub!(%r{</p[^>*]>}i, "</p>#{DOUBLE_NEWLINE}")
end
def remove_control_characters
# All control characters except \n
@string.gsub!(/[[:cntrl:]&&[^\n]]/, EMPTY_STRING)
end
def strip_html_tags
@string = strip_tags(@string)
end
def limit_to_two_following_newlines
@string.gsub!(/\n\n+/, DOUBLE_NEWLINE)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment