/
uri.rb
2497 lines (2333 loc) · 80.9 KB
/
uri.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding:utf-8
#--
# Addressable, Copyright (c) 2006-2008 Bob Aman
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
$:.unshift(File.expand_path(File.join(File.dirname(__FILE__), '/..')))
$:.uniq!
require "addressable/version"
require "addressable/idna"
module Addressable
##
# This is an implementation of a URI parser based on
# <a href="http://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>,
# <a href="http://www.ietf.org/rfc/rfc3987.txt">RFC 3987</a>.
class URI
##
# Raised if something other than a uri is supplied.
class InvalidURIError < StandardError
end
##
# Raised if an invalid method option is supplied.
class InvalidOptionError < StandardError
end
##
# Raised if an invalid template value is supplied.
class InvalidTemplateValueError < StandardError
end
##
# Raised if an invalid template operator is used in a pattern.
class InvalidTemplateOperatorError < StandardError
end
##
# Raised if an invalid template operator is used in a pattern.
class TemplateOperatorAbortedError < StandardError
end
##
# Container for the character classes specified in
# <a href="http://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>.
module CharacterClasses
ALPHA = "a-zA-Z"
DIGIT = "0-9"
GEN_DELIMS = "\\:\\/\\?\\#\\[\\]\\@"
SUB_DELIMS = "\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\="
RESERVED = GEN_DELIMS + SUB_DELIMS
UNRESERVED = ALPHA + DIGIT + "\\-\\.\\_\\~"
PCHAR = UNRESERVED + SUB_DELIMS + "\\:\\@"
SCHEME = ALPHA + DIGIT + "\\-\\+\\."
AUTHORITY = PCHAR
PATH = PCHAR + "\\/"
QUERY = PCHAR + "\\/\\?"
FRAGMENT = PCHAR + "\\/\\?"
end
##
# Returns a URI object based on the parsed string.
#
# @param [String, Addressable::URI, #to_str] uri
# The URI string to parse. No parsing is performed if the object is
# already an <tt>Addressable::URI</tt>.
#
# @return [Addressable::URI] The parsed URI.
def self.parse(uri)
# If we were given nil, return nil.
return nil unless uri
# If a URI object is passed, just return itself.
return uri if uri.kind_of?(self)
# If a URI object of the Ruby standard library variety is passed,
# convert it to a string, then parse the string.
# We do the check this way because we don't want to accidentally
# cause a missing constant exception to be thrown.
if uri.class.name =~ /^URI\b/
uri = uri.to_s
end
if !uri.respond_to?(:to_str)
raise TypeError, "Can't convert #{uri.class} into String."
end
# Otherwise, convert to a String
uri = uri.to_str
# This Regexp supplied as an example in RFC 3986, and it works great.
uri_regex =
/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/
scan = uri.scan(uri_regex)
fragments = scan[0]
scheme = fragments[1]
authority = fragments[3]
path = fragments[4]
query = fragments[6]
fragment = fragments[8]
user = nil
password = nil
host = nil
port = nil
if authority != nil
# The Regexp above doesn't split apart the authority.
userinfo = authority[/^([^\[\]]*)@/, 1]
if userinfo != nil
user = userinfo.strip[/^([^:]*):?/, 1]
password = userinfo.strip[/:(.*)$/, 1]
end
host = authority.gsub(/^([^\[\]]*)@/, "").gsub(/:([^:@\[\]]*?)$/, "")
port = authority[/:([^:@\[\]]*?)$/, 1]
end
if port == ""
port = nil
end
return Addressable::URI.new(
:scheme => scheme,
:user => user,
:password => password,
:host => host,
:port => port,
:path => path,
:query => query,
:fragment => fragment
)
end
##
# Converts an input to a URI. The input does not have to be a valid
# URI — the method will use heuristics to guess what URI was intended.
# This is not standards-compliant, merely user-friendly.
#
# @param [String, Addressable::URI, #to_str] uri
# The URI string to parse. No parsing is performed if the object is
# already an <tt>Addressable::URI</tt>.
# @param [Hash] hints
# A <tt>Hash</tt> of hints to the heuristic parser. Defaults to
# <tt>{:scheme => "http"}</tt>.
#
# @return [Addressable::URI] The parsed URI.
def self.heuristic_parse(uri, hints={})
# If we were given nil, return nil.
return nil unless uri
# If a URI object is passed, just return itself.
return uri if uri.kind_of?(self)
if !uri.respond_to?(:to_str)
raise TypeError, "Can't convert #{uri.class} into String."
end
# Otherwise, convert to a String
uri = uri.to_str.dup
hints = {
:scheme => "http"
}.merge(hints)
case uri
when /^http:\/+/
uri.gsub!(/^http:\/+/, "http://")
when /^feed:\/+http:\/+/
uri.gsub!(/^feed:\/+http:\/+/, "feed:http://")
when /^feed:\/+/
uri.gsub!(/^feed:\/+/, "feed://")
when /^file:\/+/
uri.gsub!(/^file:\/+/, "file:///")
end
parsed = self.parse(uri)
if parsed.scheme =~ /^[^\/?#\.]+\.[^\/?#]+$/
parsed = self.parse(hints[:scheme] + "://" + uri)
end
if parsed.path.include?(".")
new_host = parsed.path[/^([^\/]+\.[^\/]*)/, 1]
if new_host
new_path = parsed.path.gsub(
Regexp.new("^" + Regexp.escape(new_host)), "")
parsed.host = new_host
parsed.path = new_path
parsed.scheme = hints[:scheme] unless parsed.scheme
end
end
return parsed
end
##
# Converts a path to a file scheme URI. If the path supplied is
# relative, it will be returned as a relative URI. If the path supplied
# is actually a non-file URI, it will parse the URI as if it had been
# parsed with <tt>Addressable::URI.parse</tt>. Handles all of the
# various Microsoft-specific formats for specifying paths.
#
# @param [String, Addressable::URI, #to_str] path
# Typically a <tt>String</tt> path to a file or directory, but
# will return a sensible return value if an absolute URI is supplied
# instead.
#
# @return [Addressable::URI]
# The parsed file scheme URI or the original URI if some other URI
# scheme was provided.
#
# @example
# base = Addressable::URI.convert_path("/absolute/path/")
# uri = Addressable::URI.convert_path("relative/path")
# (base + uri).to_s
# #=> "file:///absolute/path/relative/path"
#
# Addressable::URI.convert_path(
# "c:\\windows\\My Documents 100%20\\foo.txt"
# ).to_s
# #=> "file:///c:/windows/My%20Documents%20100%20/foo.txt"
#
# Addressable::URI.convert_path("http://example.com/").to_s
# #=> "http://example.com/"
def self.convert_path(path)
# If we were given nil, return nil.
return nil unless path
# If a URI object is passed, just return itself.
return path if path.kind_of?(self)
if !path.respond_to?(:to_str)
raise TypeError, "Can't convert #{path.class} into String."
end
# Otherwise, convert to a String
path = path.to_str.strip
path.gsub!(/^file:\/?\/?/, "") if path =~ /^file:\/?\/?/
path = "/" + path if path =~ /^([a-zA-Z])(\||:)/
uri = self.parse(path)
if uri.scheme == nil
# Adjust windows-style uris
uri.path.gsub!(/^\/?([a-zA-Z])\|(\\|\/)/, "/\\1:/")
uri.path.gsub!(/\\/, "/")
if File.exists?(uri.path) &&
File.stat(uri.path).directory?
uri.path.gsub!(/\/$/, "")
uri.path = uri.path + '/'
end
# If the path is absolute, set the scheme and host.
if uri.path =~ /^\//
uri.scheme = "file"
uri.host = ""
end
uri.normalize!
end
return uri
end
##
# Expands a URI template into a full URI.
#
# @param [String, #to_str] pattern The URI template pattern.
# @param [Hash] mapping The mapping that corresponds to the pattern.
# @param [#validate, #transform] processor
# An optional processor object may be supplied. The object should
# respond to either the <tt>validate</tt> or <tt>transform</tt> messages
# or both. Both the <tt>validate</tt> and <tt>transform</tt> methods
# should take two parameters: <tt>name</tt> and <tt>value</tt>. The
# <tt>validate</tt> method should return <tt>true</tt> or
# <tt>false</tt>; <tt>true</tt> if the value of the variable is valid,
# <tt>false</tt> otherwise. An <tt>InvalidTemplateValueError</tt>
# exception will be raised if the value is invalid. The
# <tt>transform</tt> method should return the transformed variable
# value as a <tt>String</tt>. If a <tt>transform</tt> method is used,
# the value will not be percent encoded automatically. Unicode
# normalization will be performed both before and after sending the
# value to the transform method.
#
# @return [Addressable::URI] The expanded URI template.
#
# @example
# class ExampleProcessor
# def self.validate(name, value)
# return !!(value =~ /^[\w ]+$/) if name == "query"
# return true
# end
#
# def self.transform(name, value)
# return value.gsub(/ /, "+") if name == "query"
# return value
# end
# end
#
# Addressable::URI.expand_template(
# "http://example.com/search/{query}/",
# {"query" => "an example search query"},
# ExampleProcessor
# ).to_s
# #=> "http://example.com/search/an+example+search+query/"
#
# Addressable::URI.expand_template(
# "http://example.com/search/{-list|+|query}/",
# {"query" => "an example search query".split(" ")}
# ).to_s
# #=> "http://example.com/search/an+example+search+query/"
#
# Addressable::URI.expand_template(
# "http://example.com/search/{query}/",
# {"query" => "bogus!"},
# ExampleProcessor
# ).to_s
# #=> Addressable::URI::InvalidTemplateValueError
def self.expand_template(pattern, mapping, processor=nil)
# FIXME: MUST REFACTOR!!!
result = pattern.dup
reserved = Addressable::URI::CharacterClasses::RESERVED
unreserved = Addressable::URI::CharacterClasses::UNRESERVED
anything = reserved + unreserved
operator_expansion =
/\{-([a-zA-Z]+)\|([#{anything}]+)\|([#{anything}]+)\}/
variable_expansion = /\{([#{anything}]+?)(=([#{anything}]+))?\}/
transformed_mapping = mapping.inject({}) do |accu, pair|
name, value = pair
unless value.respond_to?(:to_ary) || value.respond_to?(:to_str)
raise TypeError,
"Can't convert #{value.class} into String or Array."
end
value =
value.respond_to?(:to_ary) ? value.to_ary : value.to_str
# Handle unicode normalization
if value.kind_of?(Array)
value.map! { |val| Addressable::IDNA.unicode_normalize_kc(val) }
else
value = Addressable::IDNA.unicode_normalize_kc(value)
end
if processor == nil || !processor.respond_to?(:transform)
# Handle percent escaping
if value.kind_of?(Array)
transformed_value = value.map do |val|
self.encode_component(
val, Addressable::URI::CharacterClasses::UNRESERVED)
end
else
transformed_value = self.encode_component(
value, Addressable::URI::CharacterClasses::UNRESERVED)
end
end
# Process, if we've got a processor
if processor != nil
if processor.respond_to?(:validate)
if !processor.validate(name, value)
display_value = value.kind_of?(Array) ? value.inspect : value
raise InvalidTemplateValueError,
"#{name}=#{display_value} is an invalid template value."
end
end
if processor.respond_to?(:transform)
transformed_value = processor.transform(name, value)
if transformed_value.kind_of?(Array)
transformed_value.map! do |val|
Addressable::IDNA.unicode_normalize_kc(val)
end
else
transformed_value =
Addressable::IDNA.unicode_normalize_kc(transformed_value)
end
end
end
accu[name] = transformed_value
accu
end
result.gsub!(
/#{operator_expansion}|#{variable_expansion}/
) do |capture|
if capture =~ operator_expansion
operator, argument, variables, default_mapping =
parse_template_expansion(capture, transformed_mapping)
expand_method = "expand_#{operator}_operator"
if ([expand_method, expand_method.to_sym] & private_methods).empty?
raise InvalidTemplateOperatorError,
"Invalid template operator: #{operator}"
else
send(expand_method.to_sym, argument, variables, default_mapping)
end
else
varname, _, vardefault = capture.scan(/^\{(.+?)(=(.*))?\}$/)[0]
transformed_mapping[varname] || vardefault
end
end
return Addressable::URI.parse(result)
end
##
# Expands a URI Template opt operator.
#
# @param [String] argument The argument to the operator.
# @param [Array] variables The variables the operator is working on.
# @param [Hash] mapping The mapping of variables to values.
#
# @return [String] The expanded result.
def self.expand_opt_operator(argument, variables, mapping)
if (variables.any? do |variable|
mapping[variable] != [] &&
mapping[variable]
end)
argument
else
""
end
end
class <<self; private :expand_opt_operator; end
##
# Expands a URI Template neg operator.
#
# @param [String] argument The argument to the operator.
# @param [Array] variables The variables the operator is working on.
# @param [Hash] mapping The mapping of variables to values.
#
# @return [String] The expanded result.
def self.expand_neg_operator(argument, variables, mapping)
if (variables.any? do |variable|
mapping[variable] != [] &&
mapping[variable]
end)
""
else
argument
end
end
class <<self; private :expand_neg_operator; end
##
# Expands a URI Template prefix operator.
#
# @param [String] argument The argument to the operator.
# @param [Array] variables The variables the operator is working on.
# @param [Hash] mapping The mapping of variables to values.
#
# @return [String] The expanded result.
def self.expand_prefix_operator(argument, variables, mapping)
if variables.size != 1
raise InvalidTemplateOperatorError,
"Template operator 'prefix' takes exactly one variable."
end
value = mapping[variables.first]
if value.kind_of?(Array)
(value.map { |list_value| argument + list_value }).join("")
elsif value
argument + value.to_s
end
end
class <<self; private :expand_prefix_operator; end
##
# Expands a URI Template suffix operator.
#
# @param [String] argument The argument to the operator.
# @param [Array] variables The variables the operator is working on.
# @param [Hash] mapping The mapping of variables to values.
#
# @return [String] The expanded result.
def self.expand_suffix_operator(argument, variables, mapping)
if variables.size != 1
raise InvalidTemplateOperatorError,
"Template operator 'suffix' takes exactly one variable."
end
value = mapping[variables.first]
if value.kind_of?(Array)
(value.map { |list_value| list_value + argument }).join("")
elsif value
value.to_s + argument
end
end
class <<self; private :expand_suffix_operator; end
##
# Expands a URI Template join operator.
#
# @param [String] argument The argument to the operator.
# @param [Array] variables The variables the operator is working on.
# @param [Hash] mapping The mapping of variables to values.
#
# @return [String] The expanded result.
def self.expand_join_operator(argument, variables, mapping)
variable_values = variables.inject([]) do |accu, variable|
if !mapping[variable].kind_of?(Array)
if mapping[variable]
accu << variable + "=" + (mapping[variable])
end
else
raise InvalidTemplateOperatorError,
"Template operator 'join' does not accept Array values."
end
accu
end
variable_values.join(argument)
end
class <<self; private :expand_join_operator; end
##
# Expands a URI Template list operator.
#
# @param [String] argument The argument to the operator.
# @param [Array] variables The variables the operator is working on.
# @param [Hash] mapping The mapping of variables to values.
#
# @return [String] The expanded result.
def self.expand_list_operator(argument, variables, mapping)
if variables.size != 1
raise InvalidTemplateOperatorError,
"Template operator 'list' takes exactly one variable."
end
values = mapping[variables.first]
values.join(argument) if values
end
class <<self; private :expand_list_operator; end
##
# Parses a URI template expansion <tt>String</tt>.
#
# @param [String] expansion The operator <tt>String</tt>.
# @param [Hash] mapping The mapping to merge defaults into.
#
# @return [Array]
# A tuple of the operator, argument, variables, and mapping.
def self.parse_template_expansion(capture, mapping)
operator, argument, variables = capture[1...-1].split("|")
operator.gsub!(/^\-/, "")
variables = variables.split(",")
mapping = (variables.inject({}) do |accu, var|
varname, _, vardefault = var.scan(/^(.+?)(=(.*))?$/)[0]
accu[varname] = vardefault
accu
end).merge(mapping)
variables = variables.map { |var| var.gsub(/=.*$/, "") }
return operator, argument, variables, mapping
end
class <<self; private :parse_template_expansion; end
##
# Extracts a mapping from the URI using a URI Template pattern.
#
# @param [String] pattern
# A URI template pattern.
# @param [#restore, #match] processor
# A template processor object may optionally be supplied.
# The object should respond to either the <tt>restore</tt> or
# <tt>match</tt> messages or both. The <tt>restore</tt> method should
# take two parameters: [String] name and [String] value. The
# <tt>restore</tt> method should reverse any transformations that have
# been performed on the value to ensure a valid URI. The
# <tt>match</tt> method should take a single parameter: [String] name.
# The <tt>match</tt> method should return a <tt>String</tt> containing
# a regular expression capture group for matching on that particular
# variable. The default value is ".*?". The <tt>match</tt> method has
# no effect on multivariate operator expansions.
# @return [Hash, NilClass]
# The <tt>Hash</tt> mapping that was extracted from the URI, or
# <tt>nil</tt> if the URI didn't match the template.
#
# @example
# class ExampleProcessor
# def self.restore(name, value)
# return value.gsub(/\+/, " ") if name == "query"
# return value
# end
#
# def self.match(name)
# return ".*?" if name == "first"
# return ".*"
# end
# end
#
# uri = Addressable::URI.parse(
# "http://example.com/search/an+example+search+query/"
# )
# uri.extract_mapping(
# "http://example.com/search/{query}/",
# ExampleProcessor
# )
# #=> {"query" => "an example search query"}
#
# uri = Addressable::URI.parse("http://example.com/a/b/c/")
# uri.extract_mapping(
# "http://example.com/{first}/{second}/",
# ExampleProcessor
# )
# #=> {"first" => "a", "second" => "b/c"}
#
# uri = Addressable::URI.parse("http://example.com/a/b/c/")
# uri.extract_mapping(
# "http://example.com/{first}/{-list|/|second}/"
# )
# #=> {"first" => "a", "second" => ["b", "c"]}
def extract_mapping(pattern, processor=nil)
reserved = Addressable::URI::CharacterClasses::RESERVED
unreserved = Addressable::URI::CharacterClasses::UNRESERVED
anything = reserved + unreserved
operator_expansion =
/\{-([a-zA-Z]+)\|([#{anything}]+)\|([#{anything}]+)\}/
variable_expansion = /\{([#{anything}]+?)(=([#{anything}]+))?\}/
# First, we need to process the pattern, and extract the values.
expansions, expansion_regexp =
parse_template_pattern(pattern, processor)
unparsed_values = self.to_s.scan(expansion_regexp).flatten
mapping = {}
if self.to_s == pattern
return mapping
elsif expansions.size > 0 && expansions.size == unparsed_values.size
expansions.each_with_index do |expansion, index|
unparsed_value = unparsed_values[index]
if expansion =~ operator_expansion
operator, argument, variables =
parse_template_expansion(expansion)
extract_method = "extract_#{operator}_operator"
if ([extract_method, extract_method.to_sym] &
private_methods).empty?
raise InvalidTemplateOperatorError,
"Invalid template operator: #{operator}"
else
begin
send(
extract_method.to_sym, unparsed_value, processor,
argument, variables, mapping
)
rescue TemplateOperatorAbortedError
return nil
end
end
else
name = expansion[variable_expansion, 1]
value = unparsed_value
if processor != nil && processor.respond_to?(:restore)
value = processor.restore(name, value)
end
mapping[name] = value
end
end
return mapping
else
return nil
end
end
##
# Generates the <tt>Regexp</tt> that parses a template pattern.
#
# @param [String] pattern The URI template pattern.
# @param [#match] processor The template processor to use.
#
# @return [Regexp]
# A regular expression which may be used to parse a template pattern.
def parse_template_pattern(pattern, processor)
reserved = Addressable::URI::CharacterClasses::RESERVED
unreserved = Addressable::URI::CharacterClasses::UNRESERVED
anything = reserved + unreserved
operator_expansion =
/\{-[a-zA-Z]+\|[#{anything}]+\|[#{anything}]+\}/
variable_expansion = /\{([#{anything}]+?)(=([#{anything}]+))?\}/
# Escape the pattern. The two gsubs restore the escaped curly braces
# back to their original form. Basically, escape everything that isn't
# within an expansion.
escaped_pattern = Regexp.escape(
pattern
).gsub(/\\\{(.*?)\\\}/) do |escaped|
escaped.gsub(/\\(.)/, "\\1")
end
expansions = []
# Create a regular expression that captures the values of the
# variables in the URI.
regexp_string = escaped_pattern.gsub(
/#{operator_expansion}|#{variable_expansion}/
) do |expansion|
expansions << expansion
if expansion =~ operator_expansion
capture_group = "(.*)"
if processor != nil && processor.respond_to?(:match)
# We can only lookup the match values for single variable
# operator expansions. Besides, ".*" is usually the only
# reasonable value for multivariate operators anyways.
operator, _, names, _ =
parse_template_expansion(expansion)
if ["prefix", "suffix", "list"].include?(operator)
capture_group = "(#{processor.match(names.first)})"
end
end
capture_group
else
capture_group = "(.*?)"
if processor != nil && processor.respond_to?(:match)
name = expansion[/\{([^\}=]+)(=[^\}]+)?\}/, 1]
capture_group = "(#{processor.match(name)})"
end
capture_group
end
end
# Ensure that the regular expression matches the whole URI.
regexp_string = "^#{regexp_string}$"
return expansions, Regexp.new(regexp_string)
end
private :parse_template_pattern
##
# Parses a URI template expansion <tt>String</tt>.
#
# @param [String] expansion The operator <tt>String</tt>.
#
# @return [Array]
# A tuple of the operator, argument, variables.
def parse_template_expansion(capture)
operator, argument, variables = capture[1...-1].split("|")
operator.gsub!(/^\-/, "")
variables = variables.split(",").map { |var| var.gsub(/=.*$/, "") }
return operator, argument, variables
end
private :parse_template_expansion
##
# Extracts a URI Template opt operator.
#
# @param [String] value The unparsed value to extract from.
# @param [#restore] processor The processor object.
# @param [String] argument The argument to the operator.
# @param [Array] variables The variables the operator is working on.
# @param [Hash] mapping The mapping of variables to values.
#
# @return [String] The extracted result.
def extract_opt_operator(
value, processor, argument, variables, mapping)
if value != "" && value != argument
raise TemplateOperatorAbortedError,
"Value for template operator 'neg' was unexpected."
end
end
private :extract_opt_operator
##
# Extracts a URI Template neg operator.
#
# @param [String] value The unparsed value to extract from.
# @param [#restore] processor The processor object.
# @param [String] argument The argument to the operator.
# @param [Array] variables The variables the operator is working on.
# @param [Hash] mapping The mapping of variables to values.
#
# @return [String] The extracted result.
def extract_neg_operator(
value, processor, argument, variables, mapping)
if value != "" && value != argument
raise TemplateOperatorAbortedError,
"Value for template operator 'neg' was unexpected."
end
end
private :extract_neg_operator
##
# Extracts a URI Template prefix operator.
#
# @param [String] value The unparsed value to extract from.
# @param [#restore] processor The processor object.
# @param [String] argument The argument to the operator.
# @param [Array] variables The variables the operator is working on.
# @param [Hash] mapping The mapping of variables to values.
#
# @return [String] The extracted result.
def extract_prefix_operator(
value, processor, argument, variables, mapping)
if variables.size != 1
raise InvalidTemplateOperatorError,
"Template operator 'suffix' takes exactly one variable."
end
if value[0...argument.size] != argument
raise TemplateOperatorAbortedError,
"Value for template operator 'prefix' missing expected prefix."
end
values = value.split(argument)
# Compensate for the crappy result from split.
if value[-argument.size..-1] == argument
values << ""
end
if values[0] == ""
values.shift
end
if processor && processor.respond_to?(:restore)
values.map! { |value| processor.restore(variables.first, value) }
end
mapping[variables.first] = values
end
private :extract_prefix_operator
##
# Extracts a URI Template suffix operator.
#
# @param [String] value The unparsed value to extract from.
# @param [#restore] processor The processor object.
# @param [String] argument The argument to the operator.
# @param [Array] variables The variables the operator is working on.
# @param [Hash] mapping The mapping of variables to values.
#
# @return [String] The extracted result.
def extract_suffix_operator(
value, processor, argument, variables, mapping)
if variables.size != 1
raise InvalidTemplateOperatorError,
"Template operator 'suffix' takes exactly one variable."
end
if value[-argument.size..-1] != argument
raise TemplateOperatorAbortedError,
"Value for template operator 'suffix' missing expected suffix."
end
values = value.split(argument)
# Compensate for the crappy result from split.
if value[-argument.size..-1] == argument
values << ""
end
if values[-1] == ""
values.pop
end
if processor && processor.respond_to?(:restore)
values.map! { |value| processor.restore(variables.first, value) }
end
mapping[variables.first] = values
end
private :extract_suffix_operator
##
# Extracts a URI Template join operator.
#
# @param [String] value The unparsed value to extract from.
# @param [#restore] processor The processor object.
# @param [String] argument The argument to the operator.
# @param [Array] variables The variables the operator is working on.
# @param [Hash] mapping The mapping of variables to values.
#
# @return [String] The extracted result.
def extract_join_operator(value, processor, argument, variables, mapping)
unparsed_values = value.split(argument)
parsed_variables = []
for unparsed_value in unparsed_values
name = unparsed_value[/^(.+?)=(.+)$/, 1]
parsed_variables << name
parsed_value = unparsed_value[/^(.+?)=(.+)$/, 2]
if processor && processor.respond_to?(:restore)
parsed_value = processor.restore(name, parsed_value)
end
mapping[name] = parsed_value
end
if (parsed_variables & variables) != parsed_variables
raise TemplateOperatorAbortedError,
"Template operator 'join' variable mismatch: " +
"#{parsed_variables.inspect}, #{variables.inspect}"
end
end
private :extract_join_operator
##
# Extracts a URI Template list operator.
#
# @param [String] value The unparsed value to extract from.
# @param [#restore] processor The processor object.
# @param [String] argument The argument to the operator.
# @param [Array] variables The variables the operator is working on.
# @param [Hash] mapping The mapping of variables to values.
#
# @return [String] The extracted result.
def extract_list_operator(value, processor, argument, variables, mapping)
if variables.size != 1
raise InvalidTemplateOperatorError,
"Template operator 'list' takes exactly one variable."
end
values = value.split(argument)
if processor && processor.respond_to?(:restore)
values.map! { |value| processor.restore(variables.first, value) }
end
mapping[variables.first] = values
end
private :extract_list_operator
##
# Joins several URIs together.
#
# @param [String, Addressable::URI, #to_str] *uris
# The URIs to join.
#
# @return [Addressable::URI] The joined URI.
#
# @example
# base = "http://example.com/"
# uri = Addressable::URI.parse("relative/path")
# Addressable::URI.join(base, uri)
# #=> #<Addressable::URI:0xcab390 URI:http://example.com/relative/path>
def self.join(*uris)
uri_objects = uris.collect do |uri|
if !uri.respond_to?(:to_str)
raise TypeError, "Can't convert #{uri.class} into String."
end
uri.kind_of?(self) ? uri : self.parse(uri.to_str)
end
result = uri_objects.shift.dup
for uri in uri_objects
result.join!(uri)
end
return result
end
##
# Percent encodes a URI component.
#
# @param [String, #to_str] component The URI component to encode.
#
# @param [String, Regexp] character_class
# The characters which are not percent encoded. If a <tt>String</tt>
# is passed, the <tt>String</tt> must be formatted as a regular
# expression character class. (Do not include the surrounding square
# brackets.) For example, <tt>"b-zB-Z0-9"</tt> would cause everything
# but the letters 'b' through 'z' and the numbers '0' through '9' to be
# percent encoded. If a <tt>Regexp</tt> is passed, the value
# <tt>/[^b-zB-Z0-9]/</tt> would have the same effect.
# A set of useful <tt>String</tt> values may be found in the
# <tt>Addressable::URI::CharacterClasses</tt> module. The default value
# is the reserved plus unreserved character classes specified in
# <a href="http://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>.
#
# @return [String] The encoded component.
#
# @example
# Addressable::URI.encode_component("simple/example", "b-zB-Z0-9")
# => "simple%2Fex%61mple"
# Addressable::URI.encode_component("simple/example", /[^b-zB-Z0-9]/)
# => "simple%2Fex%61mple"
# Addressable::URI.encode_component(
# "simple/example", Addressable::URI::CharacterClasses::UNRESERVED
# )
# => "simple%2Fexample"
def self.encode_component(component, character_class=
CharacterClasses::RESERVED + CharacterClasses::UNRESERVED)
return nil if component.nil?
if !component.respond_to?(:to_str)
raise TypeError, "Can't convert #{component.class} into String."
end
component = component.to_str
if ![String, Regexp].include?(character_class.class)
raise TypeError,
"Expected String or Regexp, got #{character_class.inspect}"
end
if character_class.kind_of?(String)
character_class = /[^#{character_class}]/
end
return component.gsub(character_class) do |sequence|
(sequence.unpack('C*').map { |c| "%" + ("%02x" % c).upcase }).join("")
end
end
class << self
alias_method :encode_component, :encode_component
end
##
# Unencodes any percent encoded characters within a URI component.
# This method may be used for unencoding either components or full URIs,
# however, it is recommended to use the <tt>unencode_component</tt> alias
# when unencoding components.
#
# @param [String, Addressable::URI, #to_str] uri
# The URI or component to unencode.
#
# @param [Class] returning
# The type of object to return. This value may only be set to
# <tt>String</tt> or <tt>Addressable::URI</tt>. All other values
# are invalid. Defaults to <tt>String</tt>.
#
# @return [String, Addressable::URI]
# The unencoded component or URI. The return type is determined by
# the <tt>returning</tt> parameter.
def self.unencode(uri, returning=String)