module Hashie::Extensions::MethodReader
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.
@example
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 expect { user.not_declared }.to raise_error(NoMethodError)
Public Instance Methods
method_missing(name, *args)
click to toggle source
@example Read both symbol and string keys
hash = { name: 'Ada', 'age' => 42 }.extend(Hashie::Extensions::MethodReader) hash.name # => 'Ada' hash.age # => 42
Calls superclass method
# File lib/hashie/extensions/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
respond_to_missing?(name, include_private = false)
click to toggle source
@example Advertise readers for existing keys
hash = { name: 'Ada' }.extend(Hashie::Extensions::MethodReader) hash.respond_to?(:name) # => true hash.respond_to?(:missing) # => false
Calls superclass method
# File lib/hashie/extensions/method_access.rb, line 36 def respond_to_missing?(name, include_private = false) return true if key?(name.to_s) || key?(name.to_sym) super end