Module: CarrierWave::Cloudflare::URL

Defined in:
lib/carrierwave/cloudflare/url.rb,
lib/carrierwave/cloudflare/url/query_string.rb

Defined Under Namespace

Classes: QueryString

Constant Summary collapse

ALLOWED_OPTIONS =
%w[width height dpr fit gravity quality format onerror metadata].freeze

Class Method Summary collapse

Class Method Details

.append_options!(uri, options) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/carrierwave/cloudflare/url.rb', line 53

def append_options!(uri, options)
  if should_modify_path?
    query = options.map { |k, v| "#{k}=#{v}" }.join(",")

    segment = "/cdn-cgi/image/#{query}"
    uri.path = segment + uri.path
  else
    uri.query = QueryString.new(uri.query).tap do |params|
      # the format is "width-500.height.200", only safe symbols are used
      param_with_options = options.map { |k, v| "#{k}-#{v}" }.join(".")

      params["cdn-cgi"] = param_with_options
    end.to_query
  end
end

.extract(url) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/carrierwave/cloudflare/url.rb', line 16

def extract(url)
  uri = URI.parse(url)
  options = {}

  if should_modify_path?
    if %r{/cdn-cgi/image/([^/]+)(/.*)} =~ uri.path
      formatted = $LAST_MATCH_INFO[1]
      original_path = $LAST_MATCH_INFO[2]

      options = parse_options(formatted)
      uri.path = original_path
    end
  else
    query = QueryString.new(uri.query)

    if query.key?("cdn-cgi")
      options = parse_options(query["cdn-cgi"], separator: ".", assigner: "-")
    end
  end

  [uri, options]
end

.parse_options(str, separator: ",", assigner: "=") ⇒ Object

converts strings “w=foo,h=bar” into hashes



84
85
86
87
# File 'lib/carrierwave/cloudflare/url.rb', line 84

def parse_options(str, separator: ",", assigner: "=")
  kv = str.split(separator).map { |s| s.strip.split(assigner) }
  Hash[kv]
end

.sanitized_options(options) ⇒ Object



69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/carrierwave/cloudflare/url.rb', line 69

def sanitized_options(options)
  ordered = options.map do |k, v|
    idx = ALLOWED_OPTIONS.index(k)
    [idx, [k, v]]
  end

  filtered = ordered.select { |i,| i }.sort

  filtered.map do |_, (k, v)|
    v = v.join("x") if v.is_a?(Array)
    [k, v]
  end
end

.should_modify_path?Boolean

Returns:

  • (Boolean)


12
13
14
# File 'lib/carrierwave/cloudflare/url.rb', line 12

def should_modify_path?
  ::CarrierWave::Cloudflare.cloudflare_transform
end

.transform(url, **options) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/carrierwave/cloudflare/url.rb', line 39

def transform(url, **options)
  uri, existing_opts = extract(url)
  options = existing_opts.merge(options.transform_keys(&:to_s))

  pairs = sanitized_options(options)

  if pairs.empty?
    url
  else
    append_options!(uri, pairs)
    uri.to_s
  end
end