File tree Expand file tree Collapse file tree 3 files changed +37
-0
lines changed
lib/action_dispatch/request Expand file tree Collapse file tree 3 files changed +37
-0
lines changed Original file line number Diff line number Diff line change
1
+ * Add ` session#fetch ` method
2
+
3
+ fetch behaves like [ Hash#fetch] ( http://www.ruby-doc.org/core-1.9.3/Hash.html#method-i-fetch ) .
4
+ It returns a value from the hash for the given key.
5
+ If the key can’t be found, there are several options:
6
+
7
+ * With no other arguments, it will raise an KeyError exception.
8
+ * If a default value is given, then that will be returned.
9
+ * If the optional code block is specified, then that will be run and its result returned.
10
+
11
+ * Damien Mathieu*
12
+
1
13
* Don't let strong parameters mutate the given hash via ` fetch `
2
14
3
15
Create a new instance if the given parameter is a ` Hash ` instead of
Original file line number Diff line number Diff line change @@ -127,6 +127,18 @@ def delete(key)
127
127
@delegate . delete key . to_s
128
128
end
129
129
130
+ def fetch ( key , default = nil )
131
+ if self . key? ( key )
132
+ self [ key ]
133
+ elsif default
134
+ self [ key ] = default
135
+ elsif block_given?
136
+ self [ key ] = yield ( key )
137
+ else
138
+ raise KeyError
139
+ end
140
+ end
141
+
130
142
def inspect
131
143
if loaded?
132
144
super
Original file line number Diff line number Diff line change @@ -61,6 +61,19 @@ def test_clear
61
61
assert_equal ( [ ] , s . values )
62
62
end
63
63
64
+ def test_fetch
65
+ session = Session . create ( store , { } , { } )
66
+ session [ 'one' ] = '1'
67
+
68
+ assert_equal '1' , session . fetch ( :one )
69
+ assert_equal '2' , session . fetch ( :two , '2' )
70
+ assert_equal 'three' , session . fetch ( :three ) { |el | el . to_s }
71
+
72
+ assert_raise KeyError do
73
+ session . fetch ( :four )
74
+ end
75
+ end
76
+
64
77
private
65
78
def store
66
79
Class . new {
You can’t perform that action at this time.
0 commit comments