Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 11 additions & 7 deletions lib/core_ext/stringify_keys.rb
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
class Hash
# Stolen from ActiveSupport
def transform_keys
return enum_for(:transform_keys) { size } unless block_given?
result = {}
each_key do |key|
result[yield(key)] = self[key]
# Only define transform_keys when the native method is unavailable (Ruby < 2.5).
# Defining it unconditionally clobbers the native version, which also accepts a
# mapping hash, so downstream `transform_keys(a: :b)` calls raise ArgumentError.
unless method_defined?(:transform_keys)
def transform_keys
return enum_for(:transform_keys) { size } unless block_given?
result = {}
each_key do |key|
result[yield(key)] = self[key]
end
result
end
result
end

# Returns a new hash with all keys converted to strings.
Expand Down
9 changes: 9 additions & 0 deletions test/json_logic_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,15 @@ def test_filter_with_non_array
)
end

def test_transform_keys_mapping_hash_preserved
skip "native transform_keys mapping form requires Ruby >= 3.0" if RUBY_VERSION < "3.0"
assert_equal({ b: 1 }, { a: 1 }.transform_keys(a: :b))
end

def test_stringify_keys_still_works
assert_equal({ "a" => 1, "b" => 2 }, { a: 1, b: 2 }.stringify_keys)
end

def test_uses_data
assert_equal ["x", "y"], JSONLogic.uses_data(
{
Expand Down