diff options
author | Guillermo Iguaran <guilleiguaran@gmail.com> | 2013-10-29 12:59:40 -0700 |
---|---|---|
committer | Guillermo Iguaran <guilleiguaran@gmail.com> | 2013-10-29 12:59:40 -0700 |
commit | a5e2800221b29eb5b2a3f3b831e6bc8ce4e7d534 (patch) | |
tree | 446f7c51aab281ed8f6e2b8d6b5e2c191376236e | |
parent | 671af0716de6b8991b15e2d2cb56ed6c555cb343 (diff) | |
parent | 84c9f4164bbd5f3d2697949bdd2cdbd15ce6091e (diff) | |
download | rails-a5e2800221b29eb5b2a3f3b831e6bc8ce4e7d534.tar.gz rails-a5e2800221b29eb5b2a3f3b831e6bc8ce4e7d534.tar.bz2 rails-a5e2800221b29eb5b2a3f3b831e6bc8ce4e7d534.zip |
Merge pull request #12692 from dmathieu/session_fetch
Add session#fetch
-rw-r--r-- | actionpack/CHANGELOG.md | 12 | ||||
-rw-r--r-- | actionpack/lib/action_dispatch/request/session.rb | 12 | ||||
-rw-r--r-- | actionpack/test/dispatch/request/session_test.rb | 13 |
3 files changed, 37 insertions, 0 deletions
diff --git a/actionpack/CHANGELOG.md b/actionpack/CHANGELOG.md index f5527450c7..b8ba48f8f9 100644 --- a/actionpack/CHANGELOG.md +++ b/actionpack/CHANGELOG.md @@ -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 diff --git a/actionpack/lib/action_dispatch/request/session.rb b/actionpack/lib/action_dispatch/request/session.rb index 7bc812fd22..6d911a75f1 100644 --- a/actionpack/lib/action_dispatch/request/session.rb +++ b/actionpack/lib/action_dispatch/request/session.rb @@ -127,6 +127,18 @@ module ActionDispatch @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 diff --git a/actionpack/test/dispatch/request/session_test.rb b/actionpack/test/dispatch/request/session_test.rb index 1517f96fdc..2fed480396 100644 --- a/actionpack/test/dispatch/request/session_test.rb +++ b/actionpack/test/dispatch/request/session_test.rb @@ -61,6 +61,19 @@ module ActionDispatch 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 { |