Skip to content

Instantly share code, notes, and snippets.

@JoelQ
Last active December 11, 2015 03:58
Show Gist options
  • Save JoelQ/4541522 to your computer and use it in GitHub Desktop.
Save JoelQ/4541522 to your computer and use it in GitHub Desktop.
Example refactoring for Extract Method
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)
url_components = URI.split(link)
host = url_components[2]
path = url_components[5]
query = url_components[7]
if path.end_with? 'png', 'gif', 'jpeg'
"<img src=\"#{link}\" />"
elsif host.include?("youtube") && query && query.include?('v=')
video_id = query[2..-1]
"<iframe width=\"560\" height=\"315\" src=\"http://www.youtube.com/embed/#{video_id}\" frameborder=\"0\" allowfullscreen></iframe>"
elsif host.include? "youtu.be"
video_id = path.gsub('/', '')
"<iframe width=\"560\" height=\"315\" src=\"http://www.youtube.com/embed/#{video_id}\" frameborder=\"0\" allowfullscreen></iframe>"
else
"<a href=\"#{link}\">#{link}</a>"
end
end
def replace_url_with_html_embed(link, html_snippet)
source = @parsed_text || @text
@parsed_text = source.gsub(link, html_snippet)
end
end
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)
url_components = URI.split(link)
path = url_components[5]
query = url_components[7]
if url_is_an_image? link
"<img src=\"#{link}\" />"
elsif url_is_a_youtube_regular? link
video_id = query[2..-1]
"<iframe width=\"560\" height=\"315\" src=\"http://www.youtube.com/embed/#{video_id}\" frameborder=\"0\" allowfullscreen></iframe>"
elsif url_is_a_youtube_short? link
video_id = path.gsub('/', '')
"<iframe width=\"560\" height=\"315\" src=\"http://www.youtube.com/embed/#{video_id}\" frameborder=\"0\" allowfullscreen></iframe>"
else
"<a href=\"#{link}\">#{link}</a>"
end
end
private
def url_is_an_image?(url)
path = URI.split(url)[5]
path.end_with? 'png', 'gif', 'jpeg'
end
def url_is_a_youtube_regular?(url)
host = URI.split(url)[2]
query = URI.split(url)[7]
host.include?("youtube") && query && query.include?('v=')
end
def url_is_a_youtube_short?(url)
host = URI.split(url)[2]
host.include? "youtu.be"
end
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