Created
May 25, 2015 06:32
-
-
Save stefansundin/ab871e91c9b46c465fb8 to your computer and use it in GitHub Desktop.
Ruby stringified hash.
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
# I have been annoyed that hash[:key] != hash["key"], which has caused problems more than once when converting things to Sidekiq jobs, etc. | |
# This is a major hack, and it is probably not really useful unless you can monkey patch the Hash class, which I didn't succeed with. | |
# I will have to look into how Rack does the params magic... | |
class StringHash < Hash | |
def []=(key, val) | |
super(key.to_s, val) | |
end | |
def [](key) | |
super(key.to_s) | |
end | |
def has_key?(key) | |
super(key.to_s) | |
end | |
def merge(other_hash) | |
new_hash = self.clone | |
other_hash.each do |k,v| | |
new_hash[k] = v | |
end | |
new_hash | |
end | |
def merge!(other_hash) | |
other_hash.each do |k,v| | |
self[k] = v | |
end | |
self | |
end | |
def values_at(*keys) | |
super(*keys.map(&:to_s)) | |
end | |
alias_method :include?, :has_key? | |
alias_method :key?, :has_key? | |
alias_method :member?, :has_key? | |
alias_method :store, :[]= | |
alias_method :update, :merge! | |
end |
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
h = StringHash.new | |
h[:test] = "arnold" | |
h["test"] == h[:test] # => true | |
h.any? { |k,v| k == :test } # => false | |
h.merge!({kossa: 'muu'}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment