diff options
author | Rafael França <rafaelmfranca@gmail.com> | 2018-04-04 17:34:57 -0400 |
---|---|---|
committer | GitHub <noreply@github.com> | 2018-04-04 17:34:57 -0400 |
commit | 8d62ff00805a222baa76cfe1fe7b16c985a1893e (patch) | |
tree | 36c5eaf70423247ea4d9aa86d56e43edced90641 | |
parent | 7252c2133f6f44085c64b1876cf41902e6a73847 (diff) | |
parent | 398267b14220c6659d6b1f8fdebf36ce7f8d58c9 (diff) | |
download | rails-8d62ff00805a222baa76cfe1fe7b16c985a1893e.tar.gz rails-8d62ff00805a222baa76cfe1fe7b16c985a1893e.tar.bz2 rails-8d62ff00805a222baa76cfe1fe7b16c985a1893e.zip |
Merge pull request #32446 from sinsoku/add_dig_to_session
Add #dig to ActionDispatch::Request::Session
-rw-r--r-- | actionpack/lib/action_dispatch/request/session.rb | 8 | ||||
-rw-r--r-- | actionpack/test/dispatch/request/session_test.rb | 12 |
2 files changed, 20 insertions, 0 deletions
diff --git a/actionpack/lib/action_dispatch/request/session.rb b/actionpack/lib/action_dispatch/request/session.rb index 000847e193..2ff651fc31 100644 --- a/actionpack/lib/action_dispatch/request/session.rb +++ b/actionpack/lib/action_dispatch/request/session.rb @@ -93,6 +93,14 @@ module ActionDispatch @delegate[key.to_s] end + # Returns the nested value specified by the sequence of key, returning + # nil if any intermediate step is nil. + def dig(*keys) + load_for_read! + keys = keys.map.with_index { |key, i| i.zero? ? key.to_s : key } + @delegate.dig(*keys) + end + # Returns true if the session has the given key or false. def has_key?(key) load_for_read! diff --git a/actionpack/test/dispatch/request/session_test.rb b/actionpack/test/dispatch/request/session_test.rb index bf5a74e694..74da2fe7d3 100644 --- a/actionpack/test/dispatch/request/session_test.rb +++ b/actionpack/test/dispatch/request/session_test.rb @@ -118,6 +118,18 @@ module ActionDispatch end end + def test_dig + session = Session.create(store, req, {}) + session["one"] = { "two" => "3" } + + assert_equal "3", session.dig("one", "two") + assert_equal "3", session.dig(:one, "two") + + assert_nil session.dig("three", "two") + assert_nil session.dig("one", "three") + assert_nil session.dig("one", :two) + end + private def store Class.new { |