Module: BranchableCDNAssets::Middleman::Helpers

Defined in:
lib/branchable_cdn_assets/middleman/helpers.rb

Instance Method Summary collapse

Instance Method Details

#cdn_asset_url(path, cdn = nil) ⇒ String Also known as: cdn_asset_path

return the correct path to an asset depending on what environment you’re in and the state of the cdn

Parameters:

  • path (String)

Returns:

  • (String)

    path to asset

Raises:



11
12
13
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
53
54
55
# File 'lib/branchable_cdn_assets/middleman/helpers.rb', line 11

def cdn_asset_url path, cdn=nil

  # remove trailing characters after extension
  # http://rubular.com/r/l0JR3ZuqI2
  ext_trail = path.match(/(?:\.\w+)?([\#\?\&]\S+)/).to_a
  ext_trail = ext_trail[1] || ''

  real_path = path.sub(ext_trail, '')

  # check for file in sitemap on each extension
  sitemap_candidates = []
  if !build?
    extensions[:cdn_assets].each do |k, inst|
      next if cdn && inst.id != cdn

      resource = sitemap.find_resource_by_path( File.join( "assets/cdn", inst.id, real_path ) )
      sitemap_candidates.push ["/", resource.destination_path, ext_trail].join('') if resource
    end
  end

  # check for the file in the file_managers
  file_manager_candidates = []
  extensions[:cdn_assets].each do |k, inst|
    next if cdn && inst.id != cdn

    location = build? ? :remote : :all;
    file     = inst.file_manager.find(real_path, location)

    file_manager_candidates.push [file, ext_trail].join('') if file && file != :local
  end

  candidates = file_manager_candidates + sitemap_candidates
  unless candidates.empty?
    if candidates.length == 1
      return candidates.first
    elsif cdn # file found local & on remote
      return candidates.first
    else
      raise MultipleCDNError, "asset at '#{real_path}' found on multiple cdns. please pass a cdn id"
    end
  end

  # not found at any location
  raise FileNotFoundError, "missing asset at '#{real_path}'"
end