This class will:
- Convert all keys of the given hash into symbols.
- Remove nil elements, empty strings, empty hashes and empty arrays, from the hash itself and it's child elements.
class HashSanitizer
def self.clean_blank_attributes(attributes)
return attributes.reduce({}) do |memo, (key, value)|
memo.tap do |m|
val = remove_blank_attributes(value)
if valid_attribute_for_hash?(val)
m[key.to_sym] = val
end
end
end if attributes.is_a?(Hash)
return attributes.reduce([]) do |memo, value|
val = remove_blank_attributes(value)
memo << val if attribute_not_empty_hash_or_array?(val)
memo.compact
end if attributes.is_a?(Array)
return attributes if attribute_not_nil_or_empty_string?(attributes)
end
private
def self.valid_attribute_for_hash?(attribute)
attribute_not_empty_hash_or_array?(attribute) && attribute_not_nil_or_empty_string?(attribute)
end
def self.attribute_not_empty_hash_or_array?(attribute)
valid_type = attribute.is_a?(Hash) || attribute.is_a?(Array)
!(valid_type && attribute.empty?)
end
def self.attribute_not_nil_or_empty_string?(attribute)
!(attribute.nil? || attribute.to_s.strip.empty?)
end
end