Module: Garcon::Extensions::MethodQuery

Defined in:
lib/garcon/core_ext/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 Garcon::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



129
130
131
132
133
134
135
136
137
# File 'lib/garcon/core_ext/method_access.rb', line 129

def method_missing(name, *args)
  if args.empty? && name.to_s =~ /(.*)\?$/ &&
    (key?(Regexp.last_match[1]) ||
     key?(Regexp.last_match[1].to_sym))
    return self[Regexp.last_match[1]] ||
           self[Regexp.last_match[1].to_sym]
  end
  super
end

Instance Method Details

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

Returns:



121
122
123
124
125
126
127
# File 'lib/garcon/core_ext/method_access.rb', line 121

def respond_to?(name, include_private = false)
  if name.to_s =~ /(.*)\?$/ && (key?(Regexp.last_match[1]) ||
                                key?(Regexp.last_match[1].to_sym))
    return true
  end
  super
end