Skip to content

Commit a5e2800

Browse files
committed
Merge pull request rails#12692 from dmathieu/session_fetch
Add session#fetch
2 parents 671af07 + 84c9f41 commit a5e2800

File tree

3 files changed

+37
-0
lines changed

3 files changed

+37
-0
lines changed

actionpack/CHANGELOG.md

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,15 @@
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+
113
* Don't let strong parameters mutate the given hash via `fetch`
214

315
Create a new instance if the given parameter is a `Hash` instead of

actionpack/lib/action_dispatch/request/session.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,18 @@ def delete(key)
127127
@delegate.delete key.to_s
128128
end
129129

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+
130142
def inspect
131143
if loaded?
132144
super

actionpack/test/dispatch/request/session_test.rb

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,19 @@ def test_clear
6161
assert_equal([], s.values)
6262
end
6363

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+
6477
private
6578
def store
6679
Class.new {

0 commit comments

Comments
 (0)