Skip to content

Instantly share code, notes, and snippets.

@edelpero
Last active August 29, 2015 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edelpero/37d41f1ddb866b439660 to your computer and use it in GitHub Desktop.
Save edelpero/37d41f1ddb866b439660 to your computer and use it in GitHub Desktop.
How to Remove Empty Elements and Empty Strings from a Hash and it's Child Elements

How to Remove Empty Elements and Empty Strings from a Hash and it's Child Elements

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment