Class: PlatformosCheck::JsonHelper
- Inherits:
-
Object
- Object
- PlatformosCheck::JsonHelper
- Defined in:
- lib/platformos_check/json_helper.rb
Class Method Summary collapse
-
.delete(hash, path) ⇒ Object
Deeply delete a key from a hash.
-
.json_corrector(json, path, value) ⇒ Object
Deeply add key/values inside a hash.
-
.set(hash, path, value) ⇒ Object
Deeply sets a value in a hash.
Class Method Details
.delete(hash, path) ⇒ Object
Deeply delete a key from a hash
20 21 22 23 24 25 26 27 |
# File 'lib/platformos_check/json_helper.rb', line 20 def self.delete(hash, path) path = path.split('.') if path.is_a?(String) path.each_with_index.reduce(hash) do |pointer, (token, index)| break pointer.delete(token) if index == path.size - 1 pointer[token] end end |
.json_corrector(json, path, value) ⇒ Object
Deeply add key/values inside a hash.
Handles arrays by adding the key/value to all hashes inside the array.
Specially handles objects that have the “id” key like this:
e.g.
json = {
"deep" => [
{ "id" => "hi" },
{ "id" => "oh" },
],
} assert_equal(
{
"deep" => [
{ "id" => "hi", "ho" => "ho" },
{ "id" => "oh" },
],
},
JsonHelper.json_corrector(json, "deep.hi.ho", "ho")
)
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
# File 'lib/platformos_check/json_helper.rb', line 52 def self.json_corrector(json, path, value) return json unless json.is_a?(Hash) path = path.split('.') if path.is_a?(String) path.each_with_index.reduce(json) do |pointer, (token, index)| case pointer when Array pointer.each do |item| json_corrector(item, path.drop(1), value) end when Hash break pointer[token] = value if index == path.size - 1 pointer[token] = {} unless pointer.key?(token) || pointer.key?("id") pointer[token].nil? && pointer["id"] == token ? pointer : pointer[token] end end json end |
.set(hash, path, value) ⇒ Object
Deeply sets a value in a hash. Accepts both arrays and strings for path.
6 7 8 9 10 11 12 13 14 15 16 17 |
# File 'lib/platformos_check/json_helper.rb', line 6 def self.set(hash, path, value) path = path.split('.') if path.is_a?(String) path.each_with_index.reduce(hash) do |pointer, (token, index)| if index == path.size - 1 pointer[token] = value elsif !pointer.key?(token) || !pointer[token].is_a?(Hash) pointer[token] = {} end pointer[token] end hash end |