Class: Doze::URITemplate
- Inherits:
-
Object
show all
- Defined in:
- lib/doze/uri_template.rb
Overview
Implements a subset of URI template spec. This is somewhat optimised for fast matching and generation of URI strings, although probably a fair bit of mileage still to be gotten out of it.
Defined Under Namespace
Classes: Composite, QuadHexBytesVariable, String, Variable, WithPrefix
Class Method Summary
collapse
Instance Method Summary
collapse
Class Method Details
.compile(string, var_regexps = {}) ⇒ Object
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
# File 'lib/doze/uri_template.rb', line 5
def self.compile(string, var_regexps={})
is_varexp = true
parts = string.split(/\{(.*?)\}/).map do |bit|
if (is_varexp = !is_varexp)
case bit
when /^\/(.*).quadhexbytes\*$/
QuadHexBytesVariable.new($1.to_sym)
else
var = bit.to_sym
Variable.new(var, var_regexps[var] || Variable::DEFAULT_REGEXP)
end
else
String.new(bit)
end
end
template = parts.length > 1 ? Composite.new(parts) : parts.first
template.compile_expand!
template
end
|
Instance Method Details
#anchored_regexp ⇒ Object
31
32
33
|
# File 'lib/doze/uri_template.rb', line 31
def anchored_regexp
@anchored_regexp ||= Regexp.new("^#{regexp_fragment}$")
end
|
#compile_expand! ⇒ Object
Compile a ruby string substitution expression for the ‘expand’ method to make filling out these templates blazing fast. This was actually a bottleneck in some simple cache lookups by list of URIs
27
28
29
|
# File 'lib/doze/uri_template.rb', line 27
def compile_expand!
instance_eval "def expand(vars); \"#{expand_code_fragment}\"; end", __FILE__, __LINE__
end
|
#inspect ⇒ Object
46
47
48
|
# File 'lib/doze/uri_template.rb', line 46
def inspect
"#<#{self.class} #{to_s}>"
end
|
#match(uri) ⇒ Object
50
51
52
53
54
55
56
57
|
# File 'lib/doze/uri_template.rb', line 50
def match(uri)
match = anchored_regexp.match(uri) or return
result = {}; captures = match.captures
variables.each_with_index do |var, index|
result[var.name] = var.translate_captured_string(captures[index])
end
result
end
|
#match_with_trailing(uri) ⇒ Object
59
60
61
62
63
64
65
66
67
68
|
# File 'lib/doze/uri_template.rb', line 59
def match_with_trailing(uri)
match = start_anchored_regexp.match(uri) or return
result = {}; captures = match.captures
variables.each_with_index do |var, index|
result[var.name] = var.translate_captured_string(captures[index])
end
trailing = match.post_match
trailing = nil if trailing.empty?
[result, match.to_s, trailing]
end
|
#parts ⇒ Object
39
|
# File 'lib/doze/uri_template.rb', line 39
def parts; @parts ||= [self]; end
|
#start_anchored_regexp ⇒ Object
35
36
37
|
# File 'lib/doze/uri_template.rb', line 35
def start_anchored_regexp
@start_anchored_regexp ||= Regexp.new("^#{regexp_fragment}")
end
|
#with_prefix(prefix) ⇒ Object
217
218
219
|
# File 'lib/doze/uri_template.rb', line 217
def with_prefix(prefix)
WithPrefix.new(self, prefix)
end
|