Class: Mountapi::Route::Path
- Inherits:
-
Object
- Object
- Mountapi::Route::Path
- 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
- .count_segment(path) ⇒ Object
-
.to_regexp(path, new_path = "") ⇒ Object
Take a template string /{}/ and transform to regexp.
Instance Method Summary collapse
- #<=>(other) ⇒ Object
-
#get_params(url) ⇒ Object
Return params from url.
-
#initialize(path) ⇒ Path
constructor
A new instance of Path.
- #length ⇒ Object
- #match?(path) ⇒ Boolean
- #raw_value ⇒ Object
- #regexp ⇒ Object
- #segment_count ⇒ Object
- #to_url(version, base_url, params = {}) ⇒ Object
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 |
#length ⇒ Object
30 31 32 |
# File 'lib/mountapi/route/path.rb', line 30 def length @length ||= @path.gsub(TOKEN, "").length end |
#match?(path) ⇒ 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_value ⇒ Object
13 14 15 |
# File 'lib/mountapi/route/path.rb', line 13 def raw_value @path end |
#regexp ⇒ Object
17 18 19 |
# File 'lib/mountapi/route/path.rb', line 17 def regexp @regexp ||= self.class.to_regexp(@path) end |
#segment_count ⇒ Object
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 |