Last active
July 19, 2017 18:17
-
-
Save mattantonelli/b19d44627eca66f6d7516756c2cc302c to your computer and use it in GitHub Desktop.
A sexy version of Hash that strips whitespace from string keys. #StripperHash
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
class Hash | |
def strip | |
StripperHash.new(self) | |
end | |
end | |
class StripperHash < Hash | |
def initialize(constructor = {}) | |
if constructor.respond_to?(:to_hash) | |
super | |
merge!(constructor) | |
else | |
super(constructor) | |
end | |
end | |
def []=(key, value) | |
super(key.strip, value) | |
end | |
alias_method :store, :[]= | |
def merge(other_hash) | |
super(strip(other_hash)) | |
end | |
alias_method :update, :merge | |
def merge!(other_hash) | |
super(strip(other_hash)) | |
end | |
def replace(other_hash) | |
super(strip(other_hash)) | |
end | |
private | |
def strip(hash) | |
stripped_hash = hash.dup | |
hash.each_key do |key| | |
if key.is_a?(String) && (stripped_key = key.strip) && key != stripped_key | |
stripped_hash[stripped_key] = stripped_hash.delete(key) | |
end | |
end | |
stripped_hash | |
end | |
end |
Author
mattantonelli
commented
Apr 19, 2017
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment