Module: Hashie::Extensions::MethodQuery

Defined in:
lib/hashie/extensions/method_access.rb

Overview

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.

Examples:

class MyHash < Hash
  include Hashie::Extensions::MethodQuery
end

h = MyHash.new
h['abc'] = 123
h.abc? # => true
h['def'] = nil
h.def? # => false
h.hji? # => NoMethodError

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args) ⇒ Object



117
118
119
120
121
122
123
124
125
126
127
128
129
130
# File 'lib/hashie/extensions/method_access.rb', line 117

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

Instance Method Details

#respond_to_missing?(name, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


109
110
111
112
113
114
115
# File 'lib/hashie/extensions/method_access.rb', line 109

def respond_to_missing?(name, include_private = false)
  if query_method?(name) && indifferent_key?(key_from_query_method(name))
    true
  else
    super
  end
end