Last active
August 29, 2015 13:56
-
-
Save samleb/9312296 to your computer and use it in GitHub Desktop.
“Replace Method With Method Object” to the rescue.
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
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 |
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
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