Class: Mountapi::Route::Path

Inherits:
Object
  • Object
show all
Includes:
Comparable
Defined in:
lib/mountapi/route/path.rb

Overview

An api path It is ordered by descending length

Constant Summary collapse

TOKEN =
/\{\w*\}/

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path) ⇒ Path

Returns a new instance of Path.



9
10
11
# File 'lib/mountapi/route/path.rb', line 9

def initialize(path)
  @path = path
end

Class Method Details

.count_segment(path) ⇒ Object



50
51
52
# File 'lib/mountapi/route/path.rb', line 50

def self.count_segment(path)
  path.split("/").count
end

.to_regexp(path, new_path = "") ⇒ Object

Take a template string /{}/ and transform to regexp



55
56
57
58
59
60
61
62
63
# File 'lib/mountapi/route/path.rb', line 55

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

Instance Method Details

#<=>(other) ⇒ Object



26
27
28
# File 'lib/mountapi/route/path.rb', line 26

def <=>(other)
  other.length <=> length
end

#get_params(url) ⇒ Object

Return params from url



39
40
41
42
# File 'lib/mountapi/route/path.rb', line 39

def get_params(url)
  matches = regexp.match(url)
  Hash[matches.names.zip(matches.captures)]
end

#lengthObject



30
31
32
# File 'lib/mountapi/route/path.rb', line 30

def length
  @length ||= @path.gsub(TOKEN, "").length
end

#match?(path) ⇒ Boolean

Returns:

  • (Boolean)


21
22
23
24
# File 'lib/mountapi/route/path.rb', line 21

def match?(path)
  self.class.count_segment(path) == segment_count &&
    !(regexp =~ path).nil?
end

#raw_valueObject



13
14
15
# File 'lib/mountapi/route/path.rb', line 13

def raw_value
  @path
end

#regexpObject



17
18
19
# File 'lib/mountapi/route/path.rb', line 17

def regexp
  @regexp ||= self.class.to_regexp(@path)
end

#segment_countObject



34
35
36
# File 'lib/mountapi/route/path.rb', line 34

def segment_count
  @segment_count ||= self.class.count_segment(@path)
end

#to_url(version, base_url, params = {}) ⇒ Object



44
45
46
47
48
# File 'lib/mountapi/route/path.rb', line 44

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