Class: Oj::EasyHash

Inherits:
Hash
  • Object
show all
Defined in:
lib/oj/easy_hash.rb

Overview

A Hash subclass that normalizes the hash keys to allow lookup by the key.to_s or key.to_sym. It also supports looking up hash values by methods that match the keys.

Instance Method Summary collapse

Constructor Details

#initializeEasyHash

Initializes the instance to an empty Hash.



10
11
# File 'lib/oj/easy_hash.rb', line 10

def initialize()
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(m, *args, &block) ⇒ Boolean

Handles requests for Hash values. Others cause an Exception to be raised.

Parameters:

  • m (Symbol|String)

    method symbol

Returns:

  • (Boolean)

    the value of the specified instance variable.

Raises:

  • (ArgumentError)

    if an argument is given. Zero arguments expected.

  • (NoMethodError)

    if the instance variable is not defined.



35
36
37
38
39
40
41
# File 'lib/oj/easy_hash.rb', line 35

def method_missing(m, *args, &block)
  raise ArgumentError.new("wrong number of arguments (#{args.size} for 0 with #{m}) to method #{m}") unless args.nil? or args.empty?
  return fetch(m, nil) if has_key?(m)
  return fetch(m.to_s, nil) if has_key?(m.to_s)
  return fetch(m.to_sym, nil) if has_key?(m.to_sym)
  raise NoMethodError.new("undefined method #{m}", m)
end

Instance Method Details

#[](key) ⇒ Object



24
25
26
27
28
# File 'lib/oj/easy_hash.rb', line 24

def [](key)
  return fetch(key, nil) if has_key?(key)
  return fetch(key.to_s, nil) if has_key?(key.to_s)
  fetch(key.to_sym, nil)
end

#respond_to?(m) ⇒ Boolean

Replaces the Object.respond_to?() method.

Parameters:

  • m (Symbol)

    method symbol

Returns:

  • (Boolean)

    true for any method that matches an instance variable reader, otherwise false.



17
18
19
20
21
22
# File 'lib/oj/easy_hash.rb', line 17

def respond_to?(m)
  return true if super
  return true if has_key?(key)
  return true if has_key?(key.to_s)
  has_key?(key.to_sym)
end