Sha256: 09004c3d82543c03d287edd7957b96638bbf3bedb602b15f3afe83f062bf03e1
Contents?: true
Size: 1.52 KB
Versions: 1
Compression:
Stored size: 1.52 KB
Contents
module Mountapi module Route # An api path # It is ordered by descending length class Path TOKEN = /\{\w*\}/ include Comparable def initialize(path) @path = path end def raw_value @path end def regexp @regexp ||= self.class.to_regexp(@path) end def match?(path) self.class.count_segment(path) == segment_count && !(regexp =~ path).nil? end def <=>(other) other.length <=> length end def length @length ||= @path.gsub(TOKEN, "").length end def segment_count @segment_count ||= self.class.count_segment(@path) end # Return params from url def get_params(url) matches = regexp.match(url) Hash[matches.names.zip(matches.captures)] end def to_url(version, base_url, params = {}) params.inject(base_url + "/#{version}" + @path) do |url, (param, value)| url.sub(/\{#{Regexp.quote(param)}\}/, value.to_s) end end def self.count_segment(path) path.split("/").count end # Take a template string /{}/ and transform to regexp def self.to_regexp(path, new_path = "") head, match, tail = path.partition(TOKEN) if match == "" Regexp.compile([new_path, head].join) else new_path << [Regexp.escape(head), %Q{(?<#{match.delete("{}")}>(\\w|\\.|\\-)+)}].join("") to_regexp(tail, new_path) end end end end end
Version data entries
1 entries across 1 versions & 1 rubygems
Version | Path |
---|---|
mountapi-0.11.1 | lib/mountapi/route/path.rb |