The Rails session object supports
many hash methods.
Ruby 2.3 introduced dig method to Hash,
for safe hash traversal.
Rails 6 bringsdig
method to ActionDispatch::Request::Session similar to Hash#dig.
This is useful if we have a want to access data
or nested hashes in our session.
Before Rails 6
Lets take a look of this user attributes information,
for current user stored as session information:
We can access this individual piece of information by hash access like so:
While retrieving the value if any of the key is missing,
it throws a NoMethodError:
To handle this error, we need to add individual key presence checks.
This can get quite descriptive and repetitive.
With Rails 6
With Rails 6,
we can now make use of dig method instead
to access this information:
dig returns nil if any key is missing.
This takes care of handling any nil values
in nested hash accesses and returns nil.
This allows us for simpler, safer access,
of session objects.