Module: Klenod::Runtime::AssetUrl

Defined in:
lib/klenod/runtime/asset_url.rb

Constant Summary collapse

DEFAULT_BASE =
"/assets/"
LEGACY_OUTPUT_PREFIX =
"/assets/"

Class Method Summary collapse

Class Method Details

.join(base, output_path) ⇒ Object



31
32
33
34
35
36
37
38
# File 'lib/klenod/runtime/asset_url.rb', line 31

def join(base, output_path)
  path = output_path.to_s
  unless path.start_with?("/") && !path.start_with?("//")
    raise ArgumentError, "asset output path must be root-relative: #{output_path.inspect}"
  end

  "#{normalize(base)}#{path.delete_prefix("/")}"
end

.legacy_join(base, output_path) ⇒ Object



40
41
42
# File 'lib/klenod/runtime/asset_url.rb', line 40

def legacy_join(base, output_path)
  join(base, output_path.delete_prefix(LEGACY_OUTPUT_PREFIX).prepend("/"))
end

.normalize(base) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/klenod/runtime/asset_url.rb', line 13

def normalize(base)
  value = base.to_s
  value = DEFAULT_BASE if value.empty?
  uri = URI.parse(value)

  if uri.scheme
    unless %w[http https].include?(uri.scheme) && uri.host && !uri.query && !uri.fragment
      raise ArgumentError, "asset base must be an absolute HTTP(S) URL without a query or fragment: #{base.inspect}"
    end
  elsif !value.start_with?("/") || uri.query || uri.fragment
    raise ArgumentError, "asset base must be an absolute path or HTTP(S) URL: #{base.inspect}"
  end

  value.end_with?("/") ? value : "#{value}/"
rescue URI::InvalidURIError
  raise ArgumentError, "asset base must be an absolute path or HTTP(S) URL: #{base.inspect}"
end

.origin(base) ⇒ Object



49
50
51
52
# File 'lib/klenod/runtime/asset_url.rb', line 49

def origin(base)
  uri = URI.parse(normalize(base))
  uri.origin if uri.is_a?(URI::HTTP)
end

.path_prefix(base) ⇒ Object



44
45
46
47
# File 'lib/klenod/runtime/asset_url.rb', line 44

def path_prefix(base)
  normalized = normalize(base)
  normalized if normalized.start_with?("/")
end