-
-
Save jnstq/7d8c2cbb7b7fb095bfe624a2ac9fa44f to your computer and use it in GitHub Desktop.
This file contains hidden or 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
module DeepCompact | |
def self.blank?(o) | |
o.nil? || (o.respond_to?(:empty?) && o.empty?) | |
end | |
module Array | |
def deep_compact | |
map.with_object(self.class.new) { |e, o| | |
o << (e.respond_to?(:deep_compact) ? e.deep_compact : e) | |
}.select { |value| !DeepCompact.blank?(value) } | |
end | |
end | |
module Hash | |
def deep_compact | |
map.with_object(self.class.new) { |(k, v), o| | |
o[k] = v.respond_to?(:deep_compact) ? v.deep_compact : v | |
}.select { |_, v| !DeepCompact.blank?(v) } | |
end | |
end | |
end | |
class Array | |
include DeepCompact::Array | |
end | |
class Hash | |
include DeepCompact::Hash | |
end | |
{a: {b: nil}}.deep_compact # => {} | |
{a: {b: {c: 1, d: nil}}}.deep_compact # => {:a=>{:b=>{:c=>1}}} | |
{a: {b: {c: 1, d: [{e: []}]}}}.deep_compact # => {:a=>{:b=>{:c=>1}}} | |
{a: {b: {c: 1, d: [{e: []}, {f: ""}, 1, nil, {}]}}}.deep_compact # => {:a=>{:b=>{:c=>1, :d=>[1]}}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment