mustermann 0.1.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/README.md +472 -321
- data/bench/capturing.rb +4 -4
- data/bench/regexp.rb +21 -0
- data/lib/mustermann/ast/boundaries.rb +44 -0
- data/lib/mustermann/ast/compiler.rb +13 -7
- data/lib/mustermann/ast/expander.rb +45 -14
- data/lib/mustermann/ast/node.rb +69 -6
- data/lib/mustermann/ast/param_scanner.rb +20 -0
- data/lib/mustermann/ast/parser.rb +140 -22
- data/lib/mustermann/ast/pattern.rb +68 -21
- data/lib/mustermann/ast/template_generator.rb +28 -0
- data/lib/mustermann/ast/transformer.rb +32 -24
- data/lib/mustermann/ast/translator.rb +24 -10
- data/lib/mustermann/ast/validation.rb +10 -6
- data/lib/mustermann/caster.rb +116 -0
- data/lib/mustermann/composite.rb +101 -0
- data/lib/mustermann/expander.rb +204 -0
- data/lib/mustermann/identity.rb +56 -0
- data/lib/mustermann/mapper.rb +94 -0
- data/lib/mustermann/pattern.rb +193 -13
- data/lib/mustermann/pattern_cache.rb +49 -0
- data/lib/mustermann/regexp.rb +1 -0
- data/lib/mustermann/regexp_based.rb +19 -2
- data/lib/mustermann/regular.rb +29 -0
- data/lib/mustermann/router/rack.rb +47 -0
- data/lib/mustermann/router/simple.rb +142 -0
- data/lib/mustermann/router.rb +9 -0
- data/lib/mustermann/simple_match.rb +5 -0
- data/lib/mustermann/sinatra.rb +22 -5
- data/lib/mustermann/to_pattern.rb +50 -0
- data/lib/mustermann/version.rb +1 -1
- data/lib/mustermann.rb +102 -19
- data/mustermann.gemspec +2 -12
- data/spec/ast_spec.rb +14 -0
- data/spec/composite_spec.rb +147 -0
- data/spec/expander_spec.rb +120 -0
- data/spec/identity_spec.rb +44 -0
- data/spec/mapper_spec.rb +83 -0
- data/spec/mustermann_spec.rb +50 -11
- data/spec/pattern_spec.rb +34 -7
- data/spec/regexp_based_spec.rb +1 -1
- data/spec/regular_spec.rb +61 -0
- data/spec/router/rack_spec.rb +39 -0
- data/spec/router/simple_spec.rb +32 -0
- data/spec/simple_match_spec.rb +1 -1
- data/spec/sinatra_spec.rb +197 -9
- data/spec/to_pattern_spec.rb +69 -0
- metadata +44 -146
- data/.gitignore +0 -18
- data/.rspec +0 -2
- data/.travis.yml +0 -7
- data/.yardopts +0 -1
- data/Gemfile +0 -2
- data/LICENSE +0 -22
- data/Rakefile +0 -6
- data/internals.md +0 -64
- data/lib/mustermann/ast/tree_renderer.rb +0 -29
- data/lib/mustermann/rails.rb +0 -17
- data/lib/mustermann/shell.rb +0 -22
- data/lib/mustermann/simple.rb +0 -35
- data/lib/mustermann/template.rb +0 -47
- data/spec/rails_spec.rb +0 -521
- data/spec/shell_spec.rb +0 -108
- data/spec/simple_spec.rb +0 -236
- data/spec/support/coverage.rb +0 -18
- data/spec/support/env.rb +0 -6
- data/spec/support/expand_matcher.rb +0 -27
- data/spec/support/match_matcher.rb +0 -39
- data/spec/support/pattern.rb +0 -28
- data/spec/support.rb +0 -5
- data/spec/template_spec.rb +0 -814
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
require 'mustermann/ast/expander'
|
|
2
|
+
require 'mustermann/caster'
|
|
3
|
+
require 'mustermann'
|
|
4
|
+
|
|
5
|
+
module Mustermann
|
|
6
|
+
# Allows fine-grained control over pattern expansion.
|
|
7
|
+
#
|
|
8
|
+
# @example
|
|
9
|
+
# expander = Mustermann::Expander.new(additional_values: :append)
|
|
10
|
+
# expander << "/users/:user_id"
|
|
11
|
+
# expander << "/pages/:page_id"
|
|
12
|
+
#
|
|
13
|
+
# expander.expand(page_id: 58, format: :html5) # => "/pages/58?format=html5"
|
|
14
|
+
class Expander
|
|
15
|
+
attr_reader :patterns, :additional_values, :caster
|
|
16
|
+
|
|
17
|
+
# @param [Array<#to_str, Mustermann::Pattern>] patterns list of patterns to expand, see {#add}.
|
|
18
|
+
# @param [Symbol] additional_values behavior when encountering additional values, see {#expand}.
|
|
19
|
+
# @param [Hash] options used when creating/expanding patterns, see {Mustermann.new}.
|
|
20
|
+
def initialize(*patterns, additional_values: :raise, **options)
|
|
21
|
+
unless additional_values == :raise or additional_values == :ignore or additional_values == :append
|
|
22
|
+
raise ArgumentError, "Illegal value %p for additional_values" % additional_values
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
@patterns = []
|
|
26
|
+
@api_expander = AST::Expander.new
|
|
27
|
+
@additional_values = additional_values
|
|
28
|
+
@options = options
|
|
29
|
+
@caster = Caster.new(Caster::Nil)
|
|
30
|
+
add(*patterns)
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
# Add patterns to expand.
|
|
34
|
+
#
|
|
35
|
+
# @example
|
|
36
|
+
# expander = Mustermann::Expander.new
|
|
37
|
+
# expander.add("/:a.jpg", "/:b.png")
|
|
38
|
+
# expander.expand(a: "pony") # => "/pony.jpg"
|
|
39
|
+
#
|
|
40
|
+
# @param [Array<#to_str, Mustermann::Pattern>] patterns list of to add for expansion, Strings will be compiled to patterns.
|
|
41
|
+
# @return [Mustermann::Expander] the expander
|
|
42
|
+
def add(*patterns)
|
|
43
|
+
patterns.each do |pattern|
|
|
44
|
+
pattern = Mustermann.new(pattern, **@options)
|
|
45
|
+
raise NotImplementedError, "expanding not supported for #{pattern.class}" unless pattern.respond_to? :to_ast
|
|
46
|
+
@api_expander.add(pattern.to_ast)
|
|
47
|
+
@patterns << pattern
|
|
48
|
+
end
|
|
49
|
+
self
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
alias_method :<<, :add
|
|
53
|
+
|
|
54
|
+
# Register a block as simple hash transformation that runs before expanding the pattern.
|
|
55
|
+
# @return [Mustermann::Expander] the expander
|
|
56
|
+
#
|
|
57
|
+
# @overload cast
|
|
58
|
+
# Register a block as simple hash transformation that runs before expanding the pattern for all entries.
|
|
59
|
+
#
|
|
60
|
+
# @example casting everything that implements to_param to param
|
|
61
|
+
# expander.cast { |o| o.to_param if o.respond_to? :to_param }
|
|
62
|
+
#
|
|
63
|
+
# @yield every key/value pair
|
|
64
|
+
# @yieldparam key [Symbol] omitted if block takes less than 2
|
|
65
|
+
# @yieldparam value [Object] omitted if block takes no arguments
|
|
66
|
+
# @yieldreturn [Hash{Symbol: Object}] will replace key/value pair with returned hash
|
|
67
|
+
# @yieldreturn [nil, false] will keep key/value pair in hash
|
|
68
|
+
# @yieldreturn [Object] will replace value with returned object
|
|
69
|
+
#
|
|
70
|
+
# @overload cast(*type_matchers)
|
|
71
|
+
# Register a block as simple hash transformation that runs before expanding the pattern for certain entries.
|
|
72
|
+
#
|
|
73
|
+
# @example convert user to user_id
|
|
74
|
+
# expander = Mustermann::Expander.new('/users/:user_id')
|
|
75
|
+
# expand.cast(:user) { |user| { user_id: user.id } }
|
|
76
|
+
#
|
|
77
|
+
# expand.expand(user: User.current) # => "/users/42"
|
|
78
|
+
#
|
|
79
|
+
# @example convert user, page, image to user_id, page_id, image_id
|
|
80
|
+
# expander = Mustermann::Expander.new('/users/:user_id', '/pages/:page_id', '/:image_id.jpg')
|
|
81
|
+
# expand.cast(:user, :page, :image) { |key, value| { "#{key}_id".to_sym => value.id } }
|
|
82
|
+
#
|
|
83
|
+
# expand.expand(user: User.current) # => "/users/42"
|
|
84
|
+
#
|
|
85
|
+
# @example casting to multiple key/value pairs
|
|
86
|
+
# expander = Mustermann::Expander.new('/users/:user_id/:image_id.:format')
|
|
87
|
+
# expander.cast(:image) { |i| { user_id: i.owner.id, image_id: i.id, format: i.format } }
|
|
88
|
+
#
|
|
89
|
+
# expander.expander(image: User.current.avatar) # => "/users/42/avatar.jpg"
|
|
90
|
+
#
|
|
91
|
+
# @example casting all ActiveRecord objects to param
|
|
92
|
+
# expander.cast(ActiveRecord::Base, &:to_param)
|
|
93
|
+
#
|
|
94
|
+
# @param [Array<Symbol, Regexp, #===>] type_matchers
|
|
95
|
+
# To identify key/value pairs to match against.
|
|
96
|
+
# Regexps and Symbols match against key, everything else matches against value.
|
|
97
|
+
#
|
|
98
|
+
# @yield every key/value pair
|
|
99
|
+
# @yieldparam key [Symbol] omitted if block takes less than 2
|
|
100
|
+
# @yieldparam value [Object] omitted if block takes no arguments
|
|
101
|
+
# @yieldreturn [Hash{Symbol: Object}] will replace key/value pair with returned hash
|
|
102
|
+
# @yieldreturn [nil, false] will keep key/value pair in hash
|
|
103
|
+
# @yieldreturn [Object] will replace value with returned object
|
|
104
|
+
#
|
|
105
|
+
# @overload cast(*cast_objects)
|
|
106
|
+
#
|
|
107
|
+
# @param [Array<#cast>] cast_objects
|
|
108
|
+
# Before expanding, will call #cast on these objects for each key/value pair.
|
|
109
|
+
# Return value will be treated same as block return values described above.
|
|
110
|
+
def cast(*types, &block)
|
|
111
|
+
caster.register(*types, &block)
|
|
112
|
+
self
|
|
113
|
+
end
|
|
114
|
+
|
|
115
|
+
# @example Expanding a pattern
|
|
116
|
+
# pattern = Mustermann::Expander.new('/:name', '/:name.:ext')
|
|
117
|
+
# pattern.expand(name: 'hello') # => "/hello"
|
|
118
|
+
# pattern.expand(name: 'hello', ext: 'png') # => "/hello.png"
|
|
119
|
+
#
|
|
120
|
+
# @example Handling additional values
|
|
121
|
+
# pattern = Mustermann::Expander.new('/:name', '/:name.:ext')
|
|
122
|
+
# pattern.expand(:ignore, name: 'hello', ext: 'png', scale: '2x') # => "/hello.png"
|
|
123
|
+
# pattern.expand(:append, name: 'hello', ext: 'png', scale: '2x') # => "/hello.png?scale=2x"
|
|
124
|
+
# pattern.expand(:raise, name: 'hello', ext: 'png', scale: '2x') # raises Mustermann::ExpandError
|
|
125
|
+
#
|
|
126
|
+
# @example Setting additional values behavior for the expander object
|
|
127
|
+
# pattern = Mustermann::Expander.new('/:name', '/:name.:ext', additional_values: :append)
|
|
128
|
+
# pattern.expand(name: 'hello', ext: 'png', scale: '2x') # => "/hello.png?scale=2x"
|
|
129
|
+
#
|
|
130
|
+
# @param [Symbol] behavior
|
|
131
|
+
# What to do with additional key/value pairs not present in the values hash.
|
|
132
|
+
# Possible options: :raise, :ignore, :append.
|
|
133
|
+
#
|
|
134
|
+
# @param [Hash{Symbol: #to_s, Array<#to_s>}] values
|
|
135
|
+
# Values to use for expansion.
|
|
136
|
+
#
|
|
137
|
+
# @return [String] expanded string
|
|
138
|
+
# @raise [NotImplementedError] raised if expand is not supported.
|
|
139
|
+
# @raise [Mustermann::ExpandError] raised if a value is missing or unknown
|
|
140
|
+
def expand(behavior = nil, values = {})
|
|
141
|
+
behavior, values = nil, behavior if behavior.is_a? Hash
|
|
142
|
+
values = map_values(values)
|
|
143
|
+
|
|
144
|
+
case behavior || additional_values
|
|
145
|
+
when :raise then @api_expander.expand(values)
|
|
146
|
+
when :ignore then with_rest(values) { |uri, rest| uri }
|
|
147
|
+
when :append then with_rest(values) { |uri, rest| append(uri, rest) }
|
|
148
|
+
else raise ArgumentError, "unknown behavior %p" % behavior
|
|
149
|
+
end
|
|
150
|
+
end
|
|
151
|
+
|
|
152
|
+
# @see Object#==
|
|
153
|
+
def ==(other)
|
|
154
|
+
return false unless other.class == self.class
|
|
155
|
+
other.patterns == patterns and other.additional_values == additional_values
|
|
156
|
+
end
|
|
157
|
+
|
|
158
|
+
# @see Object#eql?
|
|
159
|
+
def eql?(other)
|
|
160
|
+
return false unless other.class == self.class
|
|
161
|
+
other.patterns.eql? patterns and other.additional_values.eql? additional_values
|
|
162
|
+
end
|
|
163
|
+
|
|
164
|
+
# @see Object#hash
|
|
165
|
+
def hash
|
|
166
|
+
patterns.hash + additional_values.hash
|
|
167
|
+
end
|
|
168
|
+
|
|
169
|
+
def expandable?(values)
|
|
170
|
+
return false unless values
|
|
171
|
+
expandable, _ = split_values(map_values(values))
|
|
172
|
+
@api_expander.expandable? expandable
|
|
173
|
+
end
|
|
174
|
+
|
|
175
|
+
def with_rest(values)
|
|
176
|
+
expandable, non_expandable = split_values(values)
|
|
177
|
+
yield expand(:raise, slice(values, expandable)), slice(values, non_expandable)
|
|
178
|
+
end
|
|
179
|
+
|
|
180
|
+
def split_values(values)
|
|
181
|
+
expandable = @api_expander.expandable_keys(values.keys)
|
|
182
|
+
non_expandable = values.keys - expandable
|
|
183
|
+
[expandable, non_expandable]
|
|
184
|
+
end
|
|
185
|
+
|
|
186
|
+
def slice(hash, keys)
|
|
187
|
+
Hash[keys.map { |k| [k, hash[k]] }]
|
|
188
|
+
end
|
|
189
|
+
|
|
190
|
+
def append(uri, values)
|
|
191
|
+
return uri unless values and values.any?
|
|
192
|
+
entries = values.map { |pair| pair.map { |e| @api_expander.escape(e, also_escape: /[\/\?#\&\=%]/) }.join(?=) }
|
|
193
|
+
"#{ uri }#{ uri[??]??&:?? }#{ entries.join(?&) }"
|
|
194
|
+
end
|
|
195
|
+
|
|
196
|
+
def map_values(values)
|
|
197
|
+
values = values.dup
|
|
198
|
+
@api_expander.keys.each { |key| values[key] ||= values.delete(key.to_s) if values.include? key.to_s }
|
|
199
|
+
caster.cast(values)
|
|
200
|
+
end
|
|
201
|
+
|
|
202
|
+
private :with_rest, :slice, :append, :caster, :map_values, :split_values
|
|
203
|
+
end
|
|
204
|
+
end
|
data/lib/mustermann/identity.rb
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
+
require 'mustermann'
|
|
1
2
|
require 'mustermann/pattern'
|
|
3
|
+
require 'mustermann/ast/node'
|
|
2
4
|
|
|
3
5
|
module Mustermann
|
|
4
6
|
# Matches strings that are identical to the pattern.
|
|
@@ -9,11 +11,65 @@ module Mustermann
|
|
|
9
11
|
# @see Mustermann::Pattern
|
|
10
12
|
# @see file:README.md#identity Syntax description in the README
|
|
11
13
|
class Identity < Pattern
|
|
14
|
+
register :identity
|
|
15
|
+
|
|
12
16
|
# @param (see Mustermann::Pattern#===)
|
|
13
17
|
# @return (see Mustermann::Pattern#===)
|
|
14
18
|
# @see (see Mustermann::Pattern#===)
|
|
15
19
|
def ===(string)
|
|
16
20
|
unescape(string) == @string
|
|
17
21
|
end
|
|
22
|
+
|
|
23
|
+
# @param (see Mustermann::Pattern#peek_size)
|
|
24
|
+
# @return (see Mustermann::Pattern#peek_size)
|
|
25
|
+
# @see (see Mustermann::Pattern#peek_size)
|
|
26
|
+
def peek_size(string)
|
|
27
|
+
return unless unescape(string).start_with? @string
|
|
28
|
+
return @string.size if string.start_with? @string # optimization
|
|
29
|
+
@string.each_char.with_index.inject(0) do |count, (char, index)|
|
|
30
|
+
char_size = 1
|
|
31
|
+
escaped = @@uri.escape(char, /./)
|
|
32
|
+
char_size = escaped.size if string[index, escaped.size].downcase == escaped.downcase
|
|
33
|
+
count + char_size
|
|
34
|
+
end
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
# URI templates support generating templates (the logic is quite complex, though).
|
|
38
|
+
#
|
|
39
|
+
# @example (see Mustermann::Pattern#to_templates)
|
|
40
|
+
# @param (see Mustermann::Pattern#to_templates)
|
|
41
|
+
# @return (see Mustermann::Pattern#to_templates)
|
|
42
|
+
# @see Mustermann::Pattern#to_templates
|
|
43
|
+
def to_templates
|
|
44
|
+
[@@uri.escape(to_s)]
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
# Generates an AST so it's compatible with {Mustermann::AST::Pattern}.
|
|
48
|
+
# Not used internally by {Mustermann::Identity}.
|
|
49
|
+
# @!visibility private
|
|
50
|
+
def to_ast
|
|
51
|
+
payload = @string.each_char.with_index.map { |c, i| AST::Node[c == ?/ ? :separator : :char].new(c, start: i, stop: i+1) }
|
|
52
|
+
AST::Node[:root].new(payload, pattern: @string, start: 0, stop: @string.length)
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
# Identity patterns support expanding.
|
|
56
|
+
#
|
|
57
|
+
# This implementation does not use {Mustermann::Expander} internally to save memory and
|
|
58
|
+
# compilation time.
|
|
59
|
+
#
|
|
60
|
+
# @example (see Mustermann::Pattern#expand)
|
|
61
|
+
# @param (see Mustermann::Pattern#expand)
|
|
62
|
+
# @return (see Mustermann::Pattern#expand)
|
|
63
|
+
# @raise (see Mustermann::Pattern#expand)
|
|
64
|
+
# @see Mustermann::Pattern#expand
|
|
65
|
+
# @see Mustermann::Expander
|
|
66
|
+
def expand(behavior = nil, values = {})
|
|
67
|
+
return to_s if values.empty? or behavior == :ignore
|
|
68
|
+
raise ExpandError, "cannot expand with keys %p" % values.keys.sort if behavior == :raise
|
|
69
|
+
raise ArgumentError, "unknown behavior %p" % behavior if behavior != :append
|
|
70
|
+
params = values.map { |key, value| @@uri.escape(key.to_s) + "=" + @@uri.escape(value.to_s, /[^\w]/) }
|
|
71
|
+
separator = @string.include?(??) ? ?& : ??
|
|
72
|
+
@string + separator + params.join(?&)
|
|
73
|
+
end
|
|
18
74
|
end
|
|
19
75
|
end
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
require 'mustermann'
|
|
2
|
+
require 'mustermann/expander'
|
|
3
|
+
|
|
4
|
+
module Mustermann
|
|
5
|
+
# A mapper allows mapping one string to another based on pattern parsing and expanding.
|
|
6
|
+
#
|
|
7
|
+
# @example
|
|
8
|
+
# require 'mustermann/mapper'
|
|
9
|
+
# mapper = Mustermann::Mapper.new("/:foo" => "/:foo.html")
|
|
10
|
+
# mapper['/example'] # => "/example.html"
|
|
11
|
+
class Mapper
|
|
12
|
+
# Creates a new mapper.
|
|
13
|
+
#
|
|
14
|
+
# @overload initialize(**options)
|
|
15
|
+
# @param options [Hash] options The options hash
|
|
16
|
+
# @yield block for generating mappings as a hash
|
|
17
|
+
# @yieldreturn [Hash] see {#update}
|
|
18
|
+
#
|
|
19
|
+
# @example
|
|
20
|
+
# require 'mustermann/mapper'
|
|
21
|
+
# Mustermann::Mapper.new(type: :rails) {{
|
|
22
|
+
# "/:foo" => ["/:foo.html", "/:foo.:format"]
|
|
23
|
+
# }}
|
|
24
|
+
#
|
|
25
|
+
# @overload initialize(**options)
|
|
26
|
+
# @param options [Hash] options The options hash
|
|
27
|
+
# @yield block for generating mappings as a hash
|
|
28
|
+
# @yieldparam mapper [Mustermann::Mapper] the mapper instance
|
|
29
|
+
#
|
|
30
|
+
# @example
|
|
31
|
+
# require 'mustermann/mapper'
|
|
32
|
+
# Mustermann::Mapper.new(type: :rails) do |mapper|
|
|
33
|
+
# mapper["/:foo"] = ["/:foo.html", "/:foo.:format"]
|
|
34
|
+
# end
|
|
35
|
+
#
|
|
36
|
+
# @overload initialize(map = {}, **options)
|
|
37
|
+
# @param map [Hash] see {#update}
|
|
38
|
+
# @param [Hash] options The options hash
|
|
39
|
+
#
|
|
40
|
+
# @example map before options
|
|
41
|
+
# require 'mustermann/mapper'
|
|
42
|
+
# Mustermann::Mapper.new("/:foo" => "/:foo.html", type: :rails)
|
|
43
|
+
#
|
|
44
|
+
# @example map after options
|
|
45
|
+
# require 'mustermann/mapper'
|
|
46
|
+
# Mustermann::Mapper.new(type: :rails, "/:foo" => "/:foo.html")
|
|
47
|
+
def initialize(map = {}, additional_values: :ignore, **options, &block)
|
|
48
|
+
@map = []
|
|
49
|
+
@options = options
|
|
50
|
+
@additional_values = additional_values
|
|
51
|
+
block.arity == 0 ? update(yield) : yield(self) if block
|
|
52
|
+
update(map) if map
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
# Add multiple mappings.
|
|
56
|
+
#
|
|
57
|
+
# @param map [Hash{String, Pattern: String, Pattern, Arry<String, Pattern>, Expander}] the mapping
|
|
58
|
+
def update(map)
|
|
59
|
+
map.to_h.each_pair do |input, output|
|
|
60
|
+
input = Mustermann.new(input, **@options)
|
|
61
|
+
output = Expander.new(*output, additional_values: @additional_values, **@options) unless output.is_a? Expander
|
|
62
|
+
@map << [input, output]
|
|
63
|
+
end
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
# @return [Hash{Patttern: Expander}] Hash version of the mapper.
|
|
67
|
+
def to_h
|
|
68
|
+
Hash[@map]
|
|
69
|
+
end
|
|
70
|
+
|
|
71
|
+
# Convert a string according to mappings. You can pass in additional params.
|
|
72
|
+
#
|
|
73
|
+
# @example mapping with and without additional parameters
|
|
74
|
+
# mapper = Mustermann::Mapper.new("/:example" => "(/:prefix)?/:example.html")
|
|
75
|
+
#
|
|
76
|
+
def convert(input, values = {})
|
|
77
|
+
@map.inject(input) do |current, (pattern, expander)|
|
|
78
|
+
params = pattern.params(current)
|
|
79
|
+
params &&= Hash[values.merge(params).map { |k,v| [k.to_s, v] }]
|
|
80
|
+
expander.expandable?(params) ? expander.expand(params) : current
|
|
81
|
+
end
|
|
82
|
+
end
|
|
83
|
+
|
|
84
|
+
# Add a single mapping.
|
|
85
|
+
#
|
|
86
|
+
# @param key [String, Pattern] format of the input string
|
|
87
|
+
# @param value [String, Pattern, Arry<String, Pattern>, Expander] format of the output string
|
|
88
|
+
def []=(key, value)
|
|
89
|
+
update key => value
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
alias_method :[], :convert
|
|
93
|
+
end
|
|
94
|
+
end
|
data/lib/mustermann/pattern.rb
CHANGED
|
@@ -1,11 +1,15 @@
|
|
|
1
1
|
require 'mustermann/error'
|
|
2
2
|
require 'mustermann/simple_match'
|
|
3
|
+
require 'tool/equality_map'
|
|
3
4
|
require 'uri'
|
|
4
5
|
|
|
5
6
|
module Mustermann
|
|
6
7
|
# Superclass for all pattern implementations.
|
|
7
8
|
# @abstract
|
|
8
9
|
class Pattern
|
|
10
|
+
include Mustermann
|
|
11
|
+
@@uri ||= URI::Parser.new
|
|
12
|
+
|
|
9
13
|
# List of supported options.
|
|
10
14
|
#
|
|
11
15
|
# @overload supported_options
|
|
@@ -23,9 +27,16 @@ module Mustermann
|
|
|
23
27
|
options
|
|
24
28
|
end
|
|
25
29
|
|
|
30
|
+
# Registers the pattern with Mustermann.
|
|
31
|
+
# @see Mustermann.register
|
|
32
|
+
# @!visibility private
|
|
33
|
+
def self.register(*names)
|
|
34
|
+
names.each { |name| Mustermann.register(name, self) }
|
|
35
|
+
end
|
|
36
|
+
|
|
26
37
|
# @param [Symbol] option The option to check.
|
|
27
38
|
# @return [Boolean] Whether or not option is supported.
|
|
28
|
-
def self.supported?(option)
|
|
39
|
+
def self.supported?(option, **options)
|
|
29
40
|
supported_options.include? option
|
|
30
41
|
end
|
|
31
42
|
|
|
@@ -37,11 +48,12 @@ module Mustermann
|
|
|
37
48
|
# @see #initialize
|
|
38
49
|
def self.new(string, ignore_unknown_options: false, **options)
|
|
39
50
|
unless ignore_unknown_options
|
|
40
|
-
unsupported = options.keys.detect { |key| not supported?(key) }
|
|
51
|
+
unsupported = options.keys.detect { |key| not supported?(key, **options) }
|
|
41
52
|
raise ArgumentError, "unsupported option %p for %p" % [unsupported, self] if unsupported
|
|
42
53
|
end
|
|
43
54
|
|
|
44
|
-
|
|
55
|
+
@map ||= Tool::EqualityMap.new
|
|
56
|
+
@map.fetch(string, options) { super(string, options) }
|
|
45
57
|
end
|
|
46
58
|
|
|
47
59
|
supported_options :uri_decode, :ignore_unknown_options
|
|
@@ -54,7 +66,7 @@ module Mustermann
|
|
|
54
66
|
# @see Mustermann.new
|
|
55
67
|
def initialize(string, uri_decode: true, **options)
|
|
56
68
|
@uri_decode = uri_decode
|
|
57
|
-
@string = string.dup
|
|
69
|
+
@string = string.to_s.dup
|
|
58
70
|
end
|
|
59
71
|
|
|
60
72
|
# @return [String] the string representation of the pattern
|
|
@@ -86,13 +98,73 @@ module Mustermann
|
|
|
86
98
|
raise NotImplementedError, 'subclass responsibility'
|
|
87
99
|
end
|
|
88
100
|
|
|
89
|
-
#
|
|
101
|
+
# Tries to match the pattern against the beginning of the string (as opposed to the full string).
|
|
102
|
+
# Will return the count of the matching characters if it matches.
|
|
103
|
+
#
|
|
104
|
+
# @example
|
|
105
|
+
# pattern = Mustermann.new('/:name')
|
|
106
|
+
# pattern.size("/Frank/Sinatra") # => 6
|
|
107
|
+
#
|
|
108
|
+
# @param [String] string The string to match against
|
|
109
|
+
# @return [Integer, nil] the number of characters that match
|
|
110
|
+
def peek_size(string)
|
|
111
|
+
# this is a very naive, unperformant implementation
|
|
112
|
+
string.size.downto(0).detect { |s| self === string[0, s] }
|
|
113
|
+
end
|
|
114
|
+
|
|
115
|
+
# Tries to match the pattern against the beginning of the string (as opposed to the full string).
|
|
116
|
+
# Will return the substring if it matches.
|
|
117
|
+
#
|
|
118
|
+
# @example
|
|
119
|
+
# pattern = Mustermann.new('/:name')
|
|
120
|
+
# pattern.peek("/Frank/Sinatra") # => "/Frank"
|
|
121
|
+
#
|
|
122
|
+
# @param [String] string The string to match against
|
|
123
|
+
# @return [String, nil] matched subsctring
|
|
124
|
+
def peek(string)
|
|
125
|
+
size = peek_size(string)
|
|
126
|
+
string[0, size] if size
|
|
127
|
+
end
|
|
128
|
+
|
|
129
|
+
# Tries to match the pattern against the beginning of the string (as opposed to the full string).
|
|
130
|
+
# Will return a MatchData or similar instance for the matched substring.
|
|
131
|
+
#
|
|
132
|
+
# @example
|
|
133
|
+
# pattern = Mustermann.new('/:name')
|
|
134
|
+
# pattern.peek("/Frank/Sinatra") # => #<MatchData "/Frank" name:"Frank">
|
|
135
|
+
#
|
|
136
|
+
# @param [String] string The string to match against
|
|
137
|
+
# @return [MatchData, Mustermann::SimpleMatch, nil] MatchData or similar object if the pattern matches.
|
|
138
|
+
# @see #peek_params
|
|
139
|
+
def peek_match(string)
|
|
140
|
+
matched = peek(string)
|
|
141
|
+
match(matched) if matched
|
|
142
|
+
end
|
|
143
|
+
|
|
144
|
+
# Tries to match the pattern against the beginning of the string (as opposed to the full string).
|
|
145
|
+
# Will return a two element Array with the params parsed from the substring as first entry and the length of
|
|
146
|
+
# the substring as second.
|
|
147
|
+
#
|
|
148
|
+
# @example
|
|
149
|
+
# pattern = Mustermann.new('/:name')
|
|
150
|
+
# params, _ = pattern.peek_params("/Frank/Sinatra")
|
|
151
|
+
#
|
|
152
|
+
# puts "Hello, #{params['name']}!" # Hello, Frank!
|
|
153
|
+
#
|
|
154
|
+
# @param [String] string The string to match against
|
|
155
|
+
# @return [Array<Hash, Integer>, nil] Array with params hash and length of substing if matched, nil otherwise
|
|
156
|
+
def peek_params(string)
|
|
157
|
+
match = peek_match(string)
|
|
158
|
+
[params(captures: match), match.to_s.size] if match
|
|
159
|
+
end
|
|
160
|
+
|
|
161
|
+
# @return [Hash{String: Array<Integer>}] capture names mapped to capture index.
|
|
90
162
|
# @see http://ruby-doc.org/core-2.0/Regexp.html#method-i-named_captures Regexp#named_captures
|
|
91
163
|
def named_captures
|
|
92
164
|
{}
|
|
93
165
|
end
|
|
94
166
|
|
|
95
|
-
# @return [
|
|
167
|
+
# @return [Array<String>] capture names.
|
|
96
168
|
# @see http://ruby-doc.org/core-2.0/Regexp.html#method-i-names Regexp#names
|
|
97
169
|
def names
|
|
98
170
|
[]
|
|
@@ -125,19 +197,122 @@ module Mustermann
|
|
|
125
197
|
# warn "does not support expanding"
|
|
126
198
|
# end
|
|
127
199
|
#
|
|
128
|
-
#
|
|
200
|
+
# Expanding is supported by almost all patterns (notable execptions are {Mustermann::Shell},
|
|
201
|
+
# {Mustermann::Regular} and {Mustermann::Simple}).
|
|
202
|
+
#
|
|
203
|
+
# Union {Mustermann::Composite} patterns (with the | operator) support expanding if all
|
|
204
|
+
# patterns they are composed of also support it.
|
|
205
|
+
#
|
|
206
|
+
# @param (see Mustermann::Expander#expand)
|
|
129
207
|
# @return [String] expanded string
|
|
130
208
|
# @raise [NotImplementedError] raised if expand is not supported.
|
|
131
|
-
# @raise [
|
|
132
|
-
|
|
209
|
+
# @raise [Mustermann::ExpandError] raised if a value is missing or unknown
|
|
210
|
+
# @see Mustermann::Expander
|
|
211
|
+
def expand(behavior = nil, values = {})
|
|
133
212
|
raise NotImplementedError, "expanding not supported by #{self.class}"
|
|
134
213
|
end
|
|
135
214
|
|
|
215
|
+
# @note This method is only implemented by certain subclasses.
|
|
216
|
+
#
|
|
217
|
+
# Generates a list of URI template strings representing the pattern.
|
|
218
|
+
#
|
|
219
|
+
# Note that this transformation is lossy and the strings matching these
|
|
220
|
+
# templates might not match the pattern (and vice versa).
|
|
221
|
+
#
|
|
222
|
+
# This comes in quite handy since URI templates are not made for pattern matching.
|
|
223
|
+
# That way you can easily use a more precise template syntax and have it automatically
|
|
224
|
+
# generate hypermedia links for you.
|
|
225
|
+
#
|
|
226
|
+
# @example generating templates
|
|
227
|
+
# Mustermann.new("/:name").to_templates # => ["/{name}"]
|
|
228
|
+
# Mustermann.new("/:foo(@:bar)?/*baz").to_templates # => ["/{foo}@{bar}/{+baz}", "/{foo}/{+baz}"]
|
|
229
|
+
# Mustermann.new("/{name}", type: :template).to_templates # => ["/{name}"]
|
|
230
|
+
#
|
|
231
|
+
# @example generating templates from composite patterns
|
|
232
|
+
# pattern = Mustermann.new('/:name')
|
|
233
|
+
# pattern |= Mustermann.new('/{name}', type: :template)
|
|
234
|
+
# pattern |= Mustermann.new('/example/*nested')
|
|
235
|
+
# pattern.to_templates # => ["/{name}", "/example/{+nested}"]
|
|
236
|
+
#
|
|
237
|
+
# Template generation is supported by almost all patterns (notable execptions are
|
|
238
|
+
# {Mustermann::Shell}, {Mustermann::Regular} and {Mustermann::Simple}).
|
|
239
|
+
# Union {Mustermann::Composite} patterns (with the | operator) support template generation
|
|
240
|
+
# if all patterns they are composed of also support it.
|
|
241
|
+
#
|
|
242
|
+
# @example Checking if a pattern supports expanding
|
|
243
|
+
# if pattern.respond_to? :to_templates
|
|
244
|
+
# pattern.to_templates
|
|
245
|
+
# else
|
|
246
|
+
# warn "does not support template generation"
|
|
247
|
+
# end
|
|
248
|
+
#
|
|
249
|
+
# @return [Array<String>] list of URI templates
|
|
250
|
+
def to_templates
|
|
251
|
+
raise NotImplementedError, "template generation not supported by #{self.class}"
|
|
252
|
+
end
|
|
253
|
+
|
|
254
|
+
# @overload |(other)
|
|
255
|
+
# Creates a pattern that matches any string matching either one of the patterns.
|
|
256
|
+
# If a string is supplied, it is treated as an identity pattern.
|
|
257
|
+
#
|
|
258
|
+
# @example
|
|
259
|
+
# pattern = Mustermann.new('/foo/:name') | Mustermann.new('/:first/:second')
|
|
260
|
+
# pattern === '/foo/bar' # => true
|
|
261
|
+
# pattern === '/fox/bar' # => true
|
|
262
|
+
# pattern === '/foo' # => false
|
|
263
|
+
#
|
|
264
|
+
# @overload &(other)
|
|
265
|
+
# Creates a pattern that matches any string matching both of the patterns.
|
|
266
|
+
# If a string is supplied, it is treated as an identity pattern.
|
|
267
|
+
#
|
|
268
|
+
# @example
|
|
269
|
+
# pattern = Mustermann.new('/foo/:name') & Mustermann.new('/:first/:second')
|
|
270
|
+
# pattern === '/foo/bar' # => true
|
|
271
|
+
# pattern === '/fox/bar' # => false
|
|
272
|
+
# pattern === '/foo' # => false
|
|
273
|
+
#
|
|
274
|
+
# @overload ^(other)
|
|
275
|
+
# Creates a pattern that matches any string matching exactly one of the patterns.
|
|
276
|
+
# If a string is supplied, it is treated as an identity pattern.
|
|
277
|
+
#
|
|
278
|
+
# @example
|
|
279
|
+
# pattern = Mustermann.new('/foo/:name') ^ Mustermann.new('/:first/:second')
|
|
280
|
+
# pattern === '/foo/bar' # => false
|
|
281
|
+
# pattern === '/fox/bar' # => true
|
|
282
|
+
# pattern === '/foo' # => false
|
|
283
|
+
#
|
|
284
|
+
# @param [Mustermann::Pattern, String] other the other pattern
|
|
285
|
+
# @return [Mustermann::Pattern] a composite pattern
|
|
286
|
+
def |(other)
|
|
287
|
+
Mustermann.new(self, other, operator: __callee__, type: :identity)
|
|
288
|
+
end
|
|
289
|
+
|
|
290
|
+
alias_method :&, :|
|
|
291
|
+
alias_method :^, :|
|
|
292
|
+
|
|
293
|
+
# @example
|
|
294
|
+
# pattern = Mustermann.new('/:a/:b')
|
|
295
|
+
# strings = ["foo/bar", "/foo/bar", "/foo/bar/"]
|
|
296
|
+
# strings.detect(&pattern) # => "/foo/bar"
|
|
297
|
+
#
|
|
298
|
+
# @return [Proc] proc wrapping {#===}
|
|
299
|
+
def to_proc
|
|
300
|
+
@to_proc ||= method(:===).to_proc
|
|
301
|
+
end
|
|
302
|
+
|
|
136
303
|
# @!visibility private
|
|
137
304
|
# @return [Boolean]
|
|
138
305
|
# @see Object#respond_to?
|
|
139
306
|
def respond_to?(method, *args)
|
|
140
|
-
|
|
307
|
+
return super unless %i[expand to_templates].include? method
|
|
308
|
+
respond_to_special?(method)
|
|
309
|
+
end
|
|
310
|
+
|
|
311
|
+
# @!visibility private
|
|
312
|
+
# @return [Boolean]
|
|
313
|
+
# @see #respond_to?
|
|
314
|
+
def respond_to_special?(method)
|
|
315
|
+
method(method).owner != Mustermann::Pattern
|
|
141
316
|
end
|
|
142
317
|
|
|
143
318
|
# @!visibility private
|
|
@@ -145,6 +320,12 @@ module Mustermann
|
|
|
145
320
|
"#<%p:%p>" % [self.class, @string]
|
|
146
321
|
end
|
|
147
322
|
|
|
323
|
+
# @!visibility private
|
|
324
|
+
def simple_inspect
|
|
325
|
+
type = self.class.name[/[^:]+$/].downcase
|
|
326
|
+
"%s:%p" % [type, @string]
|
|
327
|
+
end
|
|
328
|
+
|
|
148
329
|
# @!visibility private
|
|
149
330
|
def map_param(key, value)
|
|
150
331
|
unescape(value, true)
|
|
@@ -153,8 +334,7 @@ module Mustermann
|
|
|
153
334
|
# @!visibility private
|
|
154
335
|
def unescape(string, decode = @uri_decode)
|
|
155
336
|
return string unless decode and string
|
|
156
|
-
|
|
157
|
-
@uri.unescape(string)
|
|
337
|
+
@@uri.unescape(string)
|
|
158
338
|
end
|
|
159
339
|
|
|
160
340
|
# @!visibility private
|
|
@@ -165,7 +345,7 @@ module Mustermann
|
|
|
165
345
|
ALWAYS_ARRAY.include? key
|
|
166
346
|
end
|
|
167
347
|
|
|
168
|
-
private :unescape, :map_param
|
|
348
|
+
private :unescape, :map_param, :respond_to_special?
|
|
169
349
|
private_constant :ALWAYS_ARRAY
|
|
170
350
|
end
|
|
171
351
|
end
|