This repository was archived by the owner on Sep 30, 2018. It is now read-only.
File tree 2 files changed +31
-2
lines changed
2 files changed +31
-2
lines changed Original file line number Diff line number Diff line change @@ -44,12 +44,15 @@ class Route
44
44
# Regexp for matching named splats in path
45
45
SPLAT = /\\ \* (\w +)/
46
46
47
+ OPTIONAL = /\\ \( (.*?)\\ \) /
48
+
47
49
attr_reader :regexp , :named
48
50
49
51
def initialize ( pattern , &handler )
50
52
@named , @handler = [ ] , handler
51
53
52
54
pattern = Regexp . escape pattern
55
+ pattern = pattern . gsub OPTIONAL , "(?:$1)?"
53
56
54
57
pattern . gsub ( NAMED ) { |m | @named << m [ 1 ..-1 ] }
55
58
pattern . gsub ( SPLAT ) { |m | @named << m [ 2 ..-1 ] }
Original file line number Diff line number Diff line change 57
57
subject . new ( '/:first/:second' ) { |params |
58
58
params . should eq ( { 'first' => 'woosh' , 'second' => 'kapow' } )
59
59
} . match ( '/woosh/kapow' )
60
- end
60
+ end
61
+
62
+ describe "optional segment" do
63
+ it "can match simple optional segments" do
64
+ route = subject . new ( '/foo(/bar)' )
65
+
66
+ expect ( route . match ( '/foo' ) ) . to eq ( true )
67
+ expect ( route . match ( '/foo/bar' ) ) . to eq ( true )
68
+ expect ( route . match ( '/foo/baz' ) ) . to_not eq ( true )
69
+ end
70
+
71
+ it "can match a named part inside an optional part" do
72
+ route = subject . new ( '/foo(/:bar)' )
73
+ expect ( route . named ) . to eq ( [ 'bar' ] )
74
+ end
75
+
76
+ it "returns set named part to nil when optional part not given" do
77
+ subject . new ( '/foo(/:bar)' ) { |params |
78
+ params . should eq ( { 'bar' => nil } )
79
+ } . match ( '/foo' )
80
+ end
81
+
82
+ it "returns correct value for named param inside optional part" do
83
+ subject . new ( '/foo(/:bar)' ) { |params |
84
+ params . should eq ( { 'bar' => '42' } )
85
+ } . match ( '/foo/42' )
86
+ end
87
+ end
61
88
end
62
89
end
63
-
You can’t perform that action at this time.
0 commit comments