class ServiceWorker::Route::AssetResolver

Constants

DEFAULT_WILDCARD_NAME
INTERPOLATION_PATTERN
LEADING_SLASH_PATTERN
NAMED_SEGMENTS_PATTERN
PATH_INFO
WILDCARD_PATTERN

Attributes

asset_pattern[R]
path_pattern[R]

Public Class Methods

new(path_pattern, asset_pattern) click to toggle source
# File lib/serviceworker/route.rb, line 67
def initialize(path_pattern, asset_pattern)
  @path_pattern = path_pattern
  @asset_pattern = asset_pattern
end

Public Instance Methods

call(path) click to toggle source
# File lib/serviceworker/route.rb, line 72
def call(path)
  raise ArgumentError, "path is required" if path.to_s.strip.empty?

  captures = path_captures(regexp, path) or return nil

  interpolate_captures(asset_pattern, captures)
end

Private Instance Methods

compile_regexp(pattern) click to toggle source
# File lib/serviceworker/route.rb, line 86
def compile_regexp(pattern)
  Regexp.new("\\A#{compiled_source(pattern)}\\Z")
end
compiled_source(pattern) click to toggle source
# File lib/serviceworker/route.rb, line 90
def compiled_source(pattern)
  @wildcard_name = nil
  pattern_match = pattern.match(WILDCARD_PATTERN)
  if pattern_match
    @wildcard_name = if pattern_match[1].to_s.strip.empty?
                       DEFAULT_WILDCARD_NAME
                     else
                       pattern_match[1].to_sym
                     end
    pattern.gsub(WILDCARD_PATTERN, "(?:/(.*)|)")
  else
    p = if pattern.match(NAMED_SEGMENTS_PATTERN)
          pattern.gsub(NAMED_SEGMENTS_PATTERN, '/\1(?<\2>[^.$/]+)')
        else
          pattern
        end
    p + '(?:\.(?<format>.*))?'
  end
end
interpolate_captures(string, captures) click to toggle source
# File lib/serviceworker/route.rb, line 121
def interpolate_captures(string, captures)
  string.gsub(INTERPOLATION_PATTERN) do |match|
    if match == "%%"
      "%"
    else
      key = (Regexp.last_match(1) || Regexp.last_match(2)).to_sym
      value = captures.key?(key) ? Array(captures[key]).join("/") : key
      value = value.call(captures) if value.respond_to?(:call)
      Regexp.last_match(3) ? format("%#{Regexp.last_match(3)}", value) : value
    end
  end.gsub(LEADING_SLASH_PATTERN, "")
end
path_captures(regexp, path) click to toggle source
# File lib/serviceworker/route.rb, line 110
def path_captures(regexp, path)
  path_match = path.match(regexp) or return nil
  params = if @wildcard_name
             { @wildcard_name => path_match[1].to_s.split("/") }
           else
             Hash[path_match.names.map(&:to_sym).zip(path_match.captures)]
           end
  params.delete(:format) if params.key?(:format) && params[:format].nil?
  params
end
regexp() click to toggle source
# File lib/serviceworker/route.rb, line 82
def regexp
  @regexp ||= compile_regexp(path_pattern)
end