module Hashie::Extensions::MethodQuery
MethodQuery gives you the ability to check for the truthiness of a key via method calls. Note that it will return false if the key is set to a non-truthful value, not if the key isn't set at all. Use key? for checking if a key has been set.
MethodQuery will check against both string and symbol names of the method for existing keys. It also patches respond_to to appropriately detect the query methods.
@example
class MyHash < Hash include Hashie::Extensions::MethodQuery end h = MyHash.new h['abc'] = 123 h.abc? # => true h['def'] = nil h.def? # => false expect { h.hji? }.to raise_error(NoMethodError)
Public Instance Methods
method_missing(name, *args)
click to toggle source
@example Query the truthiness of values
hash = { active: true, disabled: nil }.extend(Hashie::Extensions::MethodQuery) hash.active? # => true hash.disabled? # => false
Calls superclass method
# File lib/hashie/extensions/method_access.rb, line 146 def method_missing(name, *args) return super unless args.empty? if query_method?(name) key = key_from_query_method(name) if indifferent_key?(key) !!(self[key] || self[key.to_sym]) else super end else super end end
respond_to_missing?(name, include_private = false)
click to toggle source
@example Advertise queries for present keys, including nil values
hash = { name: nil }.extend(Hashie::Extensions::MethodQuery) hash.respond_to?(:name?) # => true hash.respond_to?(:missing?) # => false
Calls superclass method
# File lib/hashie/extensions/method_access.rb, line 134 def respond_to_missing?(name, include_private = false) if query_method?(name) && indifferent_key?(key_from_query_method(name)) true else super end end
Private Instance Methods
indifferent_key?(name)
click to toggle source
# File lib/hashie/extensions/method_access.rb, line 163 def indifferent_key?(name) name = name.to_s key?(name) || key?(name.to_sym) end
key_from_query_method(query_method)
click to toggle source
# File lib/hashie/extensions/method_access.rb, line 168 def key_from_query_method(query_method) query_method.to_s[0..-2] end
query_method?(name)
click to toggle source
# File lib/hashie/extensions/method_access.rb, line 172 def query_method?(name) name.to_s.end_with?('?') end