Skip to content

Instantly share code, notes, and snippets.

@pbyrne
Last active December 15, 2015 11:58
Show Gist options
  • Save pbyrne/5256449 to your computer and use it in GitHub Desktop.
Save pbyrne/5256449 to your computer and use it in GitHub Desktop.
Sample implementation of the SslUrlReplacer that we discussed at the whiteboard.
# Search and replace page elements in the CMS for old SSL URLs and replace with
# a new domain.
#
# Example:
#
# CMS::SslUrlReplacer.new(Site.first, "foo.bar.com", "foobar.example.com").perform
class CMS::SslUrlReplacer
# Public: Initialize a new SslUrlReplacer
#
# site - An instance of Site
# old_domain - A String with the old domain to search for
# new_domain - A Stiing with the new domain to replace with
def initialize(site, old_domain, new_domain)
self.site = site
self.old_domain = old_domain
self.new_domain = new_domain
end
def perform
perform_on(TextBlockElement) do |element|
element.update_attribute(:content, replace(element.content, "https://#{old_domain}", "https://#{new_domain}"))
end
perform_on(DisplayCodeElement) do |element|
element.update_attribute(:content, replace(element.content, "https://#{old_domain}", "https://#{new_domain}"))
end
# and so on for the simple case
perform_on(LinkElement) do |element|
# only perform the update for HTTPS link elements
if element.protocol == "https" # or whatever the logic is/should be
element.update_attribute(:domain, replace(element.domain, old_domain, new_domain))
end
end
perform_on(USMapElement) do |element|
hash = element.link_info
hash[:url] = replace(hash.url, "https://#{old_domain}", "https://#{new_domain}")
element.update_attribute(:link_info, hash)
end
perform_on(ElementWithTwoAttributes) do |element|
element.first_attribute = replace(element.first_attribute, old_domain, new_domain)
element.second_attribute = replace(element.second_attribute, old_domain, new_domain)
element.save(false)
end
end
# Perform the given block on each matching element of klass
#
# klass - An ActiveRecord class to work with
# &block - The block to perform the update for this class
#
# Example:
#
# perform_on(DisplayCodeElement) do |element|
# element.update_attribute(:content, replace(element.content, "https://#{old_domain}", "https://#{new_domain}"))
# end
def perform_on(klass)
find_for_site(klass).find_each do |element|
yield element
end
end
def find_for_site(klass)
klass.all_the_arel.where(:site_id => site.id)
end
def replace(string, search, replace)
string.gsub(search, replace)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment