Created
October 8, 2017 10:19
-
-
Save dux/356b7dca3ea916aeaeeeb22e4f9a1924 to your computer and use it in GitHub Desktop.
HashWithIndifferentAccess plain ruby object, no Rails needed
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
# access hash keys with strings or symbols | |
# h = HashWithIndifferentAccess.new a: 1 | |
# h[:a] -> 1 | |
# h['a'] -> 1 | |
class HashWithIndifferentAccess | |
def initialize data=nil | |
@data = {} | |
merge! data if data | |
end | |
def merge! data | |
data.each { |key, value| @data[convert_key(key)] = convert_value(value) } | |
end | |
alias_method :update, :merge! | |
def merge data | |
copy = self.class.new @data | |
copy.merge! data | |
copy | |
end | |
def [] key | |
@data[convert_key(key)] | |
end | |
def []= key, value | |
@data[convert_key(key)] = convert_value(value) | |
end | |
alias_method :store, :[]= | |
def key? name | |
@data.key? convert_key(name) | |
end | |
alias_method :include?, :key? | |
alias_method :has_key?, :key? | |
alias_method :member?, :key? | |
def to_json opts=nil | |
@data.to_json opts | |
end | |
def each; @data.each { |k,v| yield(k,v) }; end | |
def keys; @data.keys; end | |
def values; @data.keys; end | |
def to_hash; @data; end | |
private | |
def convert_key key | |
key.kind_of?(Symbol) ? key.to_s : key | |
end | |
def convert_value value | |
value.is_a?(Hash) ? self.class.new(value) : value.dup | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment