Module: Garcon::Extensions::MethodReader

Defined in:
lib/garcon/core_ext/method_access.rb

Overview

Note:

That while nil keys will be returned as nil, undefined keys will raise NoMethodErrors. Also note that #respond_to? has been patched to appropriately recognize key methods.

MethodReader allows you to access keys of the hash via method calls. This gives you an OStruct like way to access your hash’s keys. It will recognize keys either as strings or symbols.

Examples:

class StashCache < Hash
  include Garcon::Extensions::MethodReader
end

cash = StashCache.new
cash['box'] = 'full'
cash.box # => 'full'

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/garcon/core_ext/method_access.rb', line 46

def method_missing(name, *args)
  if key?(name)
    self[name]
  else
    sname = name.to_s
    if key?(sname)
      self[sname]
    elsif sname[-1] == '?'
      kname = sname[0..-2]
      key?(kname) || key?(kname.to_sym)
    else
      super
    end
  end
end

Instance Method Details

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

Returns:



41
42
43
44
# File 'lib/garcon/core_ext/method_access.rb', line 41

def respond_to?(name, include_private = false)
  return true if key?(name.to_s) || key?(name.to_sym)
  super
end