-
-
Notifications
You must be signed in to change notification settings - Fork 52
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
(cherry picked from commit c7ec35291dc89b68351a059eec8fd66669ecf1e9)
- Loading branch information
Showing
4 changed files
with
85 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
# frozen_string_literal: true | ||
|
||
module Anyway | ||
module Ext | ||
# Add #deep_freeze to hashes and arrays | ||
module DeepFreeze | ||
refine ::Hash do | ||
def deep_freeze | ||
freeze | ||
each_value do |value| | ||
value.deep_freeze if value.is_a?(::Hash) || value.is_a?(::Array) | ||
end | ||
end | ||
end | ||
|
||
refine ::Array do | ||
def deep_freeze | ||
freeze | ||
each do |value| | ||
value.deep_freeze if value.is_a?(::Hash) || value.is_a?(::Array) | ||
end | ||
end | ||
end | ||
end | ||
end | ||
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
# frozen_string_literal: true | ||
|
||
require 'spec_helper' | ||
require 'anyway/ext/deep_freeze' | ||
|
||
describe Anyway::Ext::DeepFreeze do | ||
using Anyway::Ext::DeepFreeze | ||
|
||
it "freezes nested arrays and hashes", :aggregate_failures do | ||
source = { | ||
a: 1, | ||
b: 'hello', | ||
c: { | ||
id: 1, | ||
list: [1, 2, { name: 'John' }] | ||
}, | ||
d: [{ id: 1 }, { id: 2 }] | ||
} | ||
|
||
dup = source.deep_freeze | ||
|
||
expect(dup).to be_frozen | ||
expect(dup[:c]).to be_frozen | ||
expect(dup[:d]).to be_frozen | ||
|
||
expect(dup[:c][:list]).to be_frozen | ||
expect(dup[:c][:list].last).to be_frozen | ||
|
||
expect(dup[:d].first).to be_frozen | ||
expect(dup[:d].last).to be_frozen | ||
end | ||
end |