Last active
December 11, 2015 04:08
-
-
Save JoelQ/4542501 to your computer and use it in GitHub Desktop.
Refactoring example for Replace Conditional with Polymorphism
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
require 'uri' | |
class MediaParser | |
def initialize(text) | |
@text = text | |
@links = URI.extract @text | |
end | |
def parse_links | |
@links.each do |link| | |
embedable_media = convert_to_media(link) | |
replace_url_with_html_embed link, embedable_media | |
end | |
@parsed_text | |
end | |
def convert_to_media(link) | |
image_embedder = ImageEmbedder.new link | |
youtube_embedder = YouTubeEmbedder.new link | |
hyperlink_embedder = HyperlinkEmbedder.new link | |
if image_embedder.can_process_url? | |
image_embedder.convert_to_media_markup | |
elsif youtube_embedder.can_process_url? | |
youtube_embedder.convert_to_media_markup | |
else | |
hyperlink_embedder.convert_to_media_markup | |
end | |
end | |
private | |
def replace_url_with_html_embed(link, html_snippet) | |
source = @parsed_text || @text | |
@parsed_text = source.gsub(link, html_snippet) | |
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
require 'uri' | |
class MediaParser | |
EMBEDDERS = [ImageEmbedder, YouTubeEmbedder, HyperlinkEmbedder] | |
def initialize(text) | |
@text = text | |
@links = URI.extract @text | |
end | |
def parse_links | |
@links.each do |link| | |
embedable_media = convert_to_media(link) | |
replace_url_with_html_embed link, embedable_media | |
end | |
@parsed_text | |
end | |
def convert_to_media(link) | |
EMBEDDERS.each do |embedder_class| | |
embedder = embedder_class.new(link) | |
if embedder.can_process_url? | |
return embedder.convert_to_media_markup | |
end | |
end | |
end | |
private | |
def replace_url_with_html_embed(link, html_snippet) | |
source = @parsed_text || @text | |
@parsed_text = source.gsub(link, html_snippet) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
As a suggestion, would the following implementation of
convert_media
method be more readable ?