Module: Hashie::Extensions::MethodReader

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

Overview

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.

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.

Examples:

class User < Hash
  include Hashie::Extensions::MethodReader
end

user = User.new
user['first_name'] = 'Michael'
user.first_name # => 'Michael'

user[:last_name] = 'Bleigh'
user.last_name # => 'Bleigh'    

user[:birthday] = nil
user.birthday # => nil

user.not_declared # => NoMethodError

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args) ⇒ Object


35
36
37
38
39
# File 'lib/hashie/extensions/method_access.rb', line 35

def method_missing(name, *args)
  return self[name.to_s] if key?(name.to_s)
  return self[name.to_sym] if key?(name.to_sym)
  super
end

Instance Method Details

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


30
31
32
33
# File 'lib/hashie/extensions/method_access.rb', line 30

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