Module: Diversion::Encode

Includes:
Base64, Json, Signing
Included in:
Client
Defined in:
lib/diversion/encode.rb,
lib/diversion/encode/json.rb,
lib/diversion/encode/params.rb

Defined Under Namespace

Modules: Json, Params

Constant Summary collapse

ENCODERS =
[ Params, Json ]

Constants included from Signing

Signing::MAX_SIGN_LENGTH

Instance Method Summary collapse

Methods included from Json

get_url

Methods included from Signing

sign_data

Instance Method Details

#encode(html, global_attrs = {}, opts = {}) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/diversion/encode.rb', line 14

def encode(html, global_attrs = {}, opts = {})
  opts = options.merge(opts)
  validate_configuration!

  raise Error::UriMissingError if opts[:encode_uris].count == 0
  doc = Nokogiri::HTML.fragment(html)
  doc.search('a').each do |link|
    # ignore any non web uris
    next unless link[:href].start_with?(*opts[:encode_uris].collect{|uri| "#{uri}:"})

    # data attributes
    attrs = {}

    # gather data- attributes from all links
    link.attributes.each do |attr|
      name = attr[0]
      value = attr[1].value
      if name.start_with?('data-') 
        data_name = name[5..-1]
        attrs[data_name] = value
        # remove current attribute from the document
        link.remove_attribute(name)
      end
    end

    # set the url
    attrs["url"] = link[:href]

    # merge in any global attributes
    attrs = attrs.merge(global_attrs)

    # get url for required type
    url = opts[:url_encoding].get_url(attrs, opts)
    url = doc_escape(url)
    link["href"] = url
  end
  # work around Nokogiri escaping of & and replace with intended ampersands
  doc_unescape(doc.to_html)
end