From 15871a51ad17d45ffb8229d4f9562a0b63390043 Mon Sep 17 00:00:00 2001 From: Adrian Setyadi Date: Mon, 30 Sep 2019 06:42:41 +0700 Subject: Make stringify_keys use transform_keys --- lib/rack/core_ext/hash.rb | 19 +++++++++++++++++++ lib/rack/session/abstract/id.rb | 9 ++++----- 2 files changed, 23 insertions(+), 5 deletions(-) create mode 100644 lib/rack/core_ext/hash.rb diff --git a/lib/rack/core_ext/hash.rb b/lib/rack/core_ext/hash.rb new file mode 100644 index 00000000..f86a3611 --- /dev/null +++ b/lib/rack/core_ext/hash.rb @@ -0,0 +1,19 @@ +# frozen_string_literal: true + +# Hash has `transform_keys` since Ruby 2.5. +# For Ruby < 2.5, we need to add the following + +module Rack + module HashExtensions + refine Hash do + def transform_keys(&block) + hash = {} + each do |key, value| + hash[block.call(key)] = value + end + hash + end unless {}.respond_to?(:transform_keys) + end + end +end + diff --git a/lib/rack/session/abstract/id.rb b/lib/rack/session/abstract/id.rb index c9f9f458..69dafe78 100644 --- a/lib/rack/session/abstract/id.rb +++ b/lib/rack/session/abstract/id.rb @@ -9,6 +9,8 @@ require 'rack/request' require 'rack/response' require 'securerandom' +require_relative '../../core_ext/hash' + module Rack module Session @@ -17,6 +19,7 @@ module Rack # SessionHash is responsible to lazily load the session from store. class SessionHash + using ::Rack::HashExtensions include Enumerable attr_writer :id @@ -162,11 +165,7 @@ module Rack end def stringify_keys(other) - hash = {} - other.each do |key, value| - hash[key.to_s] = value - end - hash + other.transform_keys(&:to_s) end end -- cgit v1.2.3-24-ge0c7