Skip to content

Commit

Permalink
Fix: in Rails 3 HashWithIndifferentAccess doesn't convert nested Hashes.
Browse files Browse the repository at this point in the history
  • Loading branch information
dblock committed Apr 14, 2017
1 parent fb4b60f commit 0ae3608
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 10 deletions.
1 change: 1 addition & 0 deletions lib/grape.rb
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ module Extensions

autoload :DeepMergeableHash
autoload :DeepSymbolizeHash
autoload :DeepHashWithIndifferentAccess
autoload :Hash

module ActiveSupport
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,22 @@ module Grape
module Extensions
module ActiveSupport
module HashWithIndifferentAccess
extend ::ActiveSupport::Concern
module ParamBuilder
extend ::ActiveSupport::Concern

included do
namespace_inheritable(:build_params_with, Grape::Extensions::ActiveSupport::HashWithIndifferentAccess::ParamBuilder)
end
included do
namespace_inheritable(:build_params_with, Grape::Extensions::ActiveSupport::HashWithIndifferentAccess::ParamBuilder)
end

def params_builder
Grape::Extensions::ActiveSupport::HashWithIndifferentAccess::ParamBuilder
end
def params_builder
Grape::Extensions::ActiveSupport::HashWithIndifferentAccess::ParamBuilder
end

module ParamBuilder
def build_params
params = ::ActiveSupport::HashWithIndifferentAccess[rack_params]
params.deep_merge!(grape_routing_args) if env[Grape::Env::GRAPE_ROUTING_ARGS]
params
# TODO: remove, in Rails 4 or later ::ActiveSupport::HashWithIndifferentAccess converts nested Hashes into indifferent access ones
DeepHashWithIndifferentAccess.deep_hash_with_indifferent_access(params)
end
end
end
Expand Down
18 changes: 18 additions & 0 deletions lib/grape/extensions/deep_hash_with_indifferent_access.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
module Grape
module Extensions
module DeepHashWithIndifferentAccess
def self.deep_hash_with_indifferent_access(object)
case object
when ::Hash
object.inject(::ActiveSupport::HashWithIndifferentAccess.new) do |new_hash, (key, value)|
new_hash.merge!(key => deep_hash_with_indifferent_access(value))
end
when ::Array
object.map { |element| deep_hash_with_indifferent_access(element) }
else
object
end
end
end
end
end
10 changes: 9 additions & 1 deletion lib/grape/extensions/deep_symbolize_hash.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,15 @@ def self.deep_symbolize_keys_in(object)
end

def self.symbolize_key(key)
key.respond_to?(:to_sym) ? key.to_sym : key
if key.is_a?(Symbol)
key
elsif key.is_a?(String)
key.to_sym
elsif key.respond_to?(:to_sym)
key.to_sym
else
key
end
end
end
end
Expand Down

0 comments on commit 0ae3608

Please sign in to comment.