Skip to content

Instantly share code, notes, and snippets.

@localhostdotdev
Created April 20, 2019 18:31
Show Gist options
  • Select an option

  • Save localhostdotdev/3c978fe76511a5b9223fa725829e93b8 to your computer and use it in GitHub Desktop.

Select an option

Save localhostdotdev/3c978fe76511a5b9223fa725829e93b8 to your computer and use it in GitHub Desktop.
Hash based SimpleHash (instead of HashWithIndifferentAccess)
class SimpleHash < Hash
def method_missing(method_name, *args, &block)
if keys.map(&:to_s).include?(method_name.to_s)
if args.empty? && block.nil?
send(:simple_fetch, method_name)
else
raise "can't pass arguments and/or blocks"
end
else
super
end
end
def respond_to_missing?(method_name, include_private = false)
keys.map(&:to_s).include?(method_name.to_s) || super
end
def methods
super + keys
end
def simple_fetch(key)
convert(fetch(key.to_sym) { fetch(key.to_s) })
end
private
def convert(value)
if value.is_a?(Hash)
SimpleHash[value].freeze
elsif value.is_a?(Array)
value.map { |value| convert(value) }
else
value
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment