Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

add the fetch method to sessions

  • Loading branch information...
commit 84c9f4164bbd5f3d2697949bdd2cdbd15ce6091e 1 parent df2226e
Damien Mathieu dmathieu authored
12 actionpack/CHANGELOG.md
View
@@ -1,3 +1,15 @@
+* Add `session#fetch` method
+
+ fetch behaves like [Hash#fetch](http://www.ruby-doc.org/core-1.9.3/Hash.html#method-i-fetch).
+ It returns a value from the hash for the given key.
+ If the key can’t be found, there are several options:
+
+ * With no other arguments, it will raise an KeyError exception.
+ * If a default value is given, then that will be returned.
+ * If the optional code block is specified, then that will be run and its result returned.
+
+ *Damien Mathieu*
+
* Don't let strong parameters mutate the given hash via `fetch`
Create a new instance if the given parameter is a `Hash` instead of
12 actionpack/lib/action_dispatch/request/session.rb
View
@@ -127,6 +127,18 @@ def delete(key)
@delegate.delete key.to_s
end
+ def fetch(key, default=nil)
+ if self.key?(key)
+ self[key]
+ elsif default
+ self[key] = default
+ elsif block_given?
+ self[key] = yield(key)
+ else
+ raise KeyError
+ end
+ end
+
def inspect
if loaded?
super
13 actionpack/test/dispatch/request/session_test.rb
View
@@ -61,6 +61,19 @@ def test_clear
assert_equal([], s.values)
end
+ def test_fetch
+ session = Session.create(store, {}, {})
+ session['one'] = '1'
+
+ assert_equal '1', session.fetch(:one)
+ assert_equal '2', session.fetch(:two, '2')
+ assert_equal 'three', session.fetch(:three) {|el| el.to_s }
+
+ assert_raise KeyError do
+ session.fetch(:four)
+ end
+ end
+
private
def store
Class.new {
Please sign in to comment.
Something went wrong with that request. Please try again.