Class: CanvasLinkMigrator::LinkReplacer

Inherits:
Object
  • Object
show all
Defined in:
lib/canvas_link_migrator/link_replacer.rb

Constant Summary collapse

HTML_ESCAPES =
{ '"' => "&quot;", "<" => "&lt;", ">" => "&gt;" }.freeze
HTML_ESCAPE_RE =
Regexp.union(HTML_ESCAPES.keys).freeze

Class Method Summary collapse

Class Method Details

.escape_url_for_html(value) ⇒ Object



25
26
27
# File 'lib/canvas_link_migrator/link_replacer.rb', line 25

def self.escape_url_for_html(value)
  value.to_s.gsub(HTML_ESCAPE_RE, HTML_ESCAPES)
end

.recursively_sub_placeholders!(object, links) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/canvas_link_migrator/link_replacer.rb', line 57

def self.recursively_sub_placeholders!(object, links)
  subbed = false
  case object
  when Hash
    object.each_value { |o| subbed = true if recursively_sub_placeholders!(o, links) }
  when Array
    object.each { |o| subbed = true if recursively_sub_placeholders!(o, links) }
  when String
    subbed = sub_placeholders!(object, links)
  end
  subbed
end

.sub_placeholders!(html, links) ⇒ Object

returns false if no substitutions were made



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/canvas_link_migrator/link_replacer.rb', line 30

def self.sub_placeholders!(html, links)
  subbed = false
  media_links, other_links = links.partition { |l| l[:link_type] == :media_object }

  if media_links.any?
    by_placeholder = media_links.to_h { |l| [l[:placeholder], l] }
    if html.gsub!(Regexp.union(by_placeholder.keys)) { |m|
      link = by_placeholder[m]
      link[:replaced] = true
      link[:new_value] || link[:old_value]
    }
      subbed = true
    end
  end

  other_links.each do |link|
    new_value = link[:new_value] || link[:old_value]
    new_value = escape_url_for_html(new_value)
    if html.gsub!(link[:placeholder]) { new_value }
      link[:replaced] = true
      subbed = true
    end
  end

  subbed
end