Skip to content

Instantly share code, notes, and snippets.

@dux
Created October 8, 2017 10:19
Show Gist options
  • Save dux/356b7dca3ea916aeaeeeb22e4f9a1924 to your computer and use it in GitHub Desktop.
Save dux/356b7dca3ea916aeaeeeb22e4f9a1924 to your computer and use it in GitHub Desktop.
HashWithIndifferentAccess plain ruby object, no Rails needed
# 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