Class: Oj::EasyHash
- Inherits:
-
Hash
- Object
- Hash
- Oj::EasyHash
- 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
- #[](key) ⇒ Object
-
#method_missing(m, *args, &block) ⇒ Boolean
Handles requests for Hash values.
-
#respond_to?(m, include_all = false) ⇒ Boolean
Replaces the Object.respond_to?() method.
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.
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/oj/easy_hash.rb', line 33 def method_missing(m, *args, &block) if m.to_s.end_with?('=') raise ArgumentError.new("wrong number of arguments (#{args.size} for 1 with #{m}) to method #{m}") if args.nil? or 1 != args.length m = m[0..-2] return store(m.to_s, args[0]) if has_key?(m.to_s) return store(m.to_sym, args[0]) if has_key?(m.to_sym) return store(m, args[0]) else 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) end raise NoMethodError.new("undefined method #{m}", m) end |
Instance Method Details
#[](key) ⇒ Object
21 22 23 24 25 26 |
# File 'lib/oj/easy_hash.rb', line 21 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, include_all = false) ⇒ Boolean
Replaces the Object.respond_to?() method.
13 14 15 16 17 18 19 |
# File 'lib/oj/easy_hash.rb', line 13 def respond_to?(m, include_all = false) return true if super return true if has_key?(m) return true if has_key?(m.to_s) has_key?(m.to_sym) end |