class HashWithQuickAccess
Attributes
hash[R]
Public Class Methods
add_convenience_method_to_hash!()
click to toggle source
# File lib/hash_with_quick_access.rb, line 2 def self.add_convenience_method_to_hash! Hash.send(:include, ConvenienceMethod) end
new(hash)
click to toggle source
# File lib/hash_with_quick_access.rb, line 6 def initialize(hash) @hash = hash end
Public Instance Methods
[](key)
click to toggle source
# File lib/hash_with_quick_access.rb, line 34 def [](key) send(key) end
keys()
click to toggle source
# File lib/hash_with_quick_access.rb, line 30 def keys hash.keys.map(&:to_sym) end
method_missing(key, *args, &block)
click to toggle source
# File lib/hash_with_quick_access.rb, line 10 def method_missing(key, *args, &block) value = if key?(key) fetch_possibly_decorated_value(key) elsif hash.respond_to?(key) delegate_and_decorate(key, *args, &block) else fail KeyError, "key :#{key} was not found" end if !hash.respond_to?(key) define_singleton_method(key) { value } end value end
respond_to?(method_name, include_private = false)
click to toggle source
Calls superclass method
# File lib/hash_with_quick_access.rb, line 26 def respond_to?(method_name, include_private = false) key?(method_name) || super end
Private Instance Methods
all_keys()
click to toggle source
# File lib/hash_with_quick_access.rb, line 76 def all_keys hash.keys.flat_map do |key| [key, key.to_sym] end end
decorate(obj)
click to toggle source
# File lib/hash_with_quick_access.rb, line 64 def decorate(obj) if obj.is_a?(Array) obj.map { |o| HashWithQuickAccess.new(o) } elsif obj.is_a?(Hash) HashWithQuickAccess.new(obj) end end
delegate_and_decorate(method_name, *args, &block)
click to toggle source
# File lib/hash_with_quick_access.rb, line 42 def delegate_and_decorate(method_name, *args, &block) obj = hash.send(method_name, *args, &block) possibly_decorate(obj) end
fetch_possibly_decorated_value(key)
click to toggle source
# File lib/hash_with_quick_access.rb, line 47 def fetch_possibly_decorated_value(key) obj = hash.fetch(key) { hash.fetch(key.to_s) } possibly_decorate(obj) end
key?(key)
click to toggle source
# File lib/hash_with_quick_access.rb, line 72 def key?(key) all_keys.include?(key) end
possibly_decorate(obj)
click to toggle source
# File lib/hash_with_quick_access.rb, line 52 def possibly_decorate(obj) if should_be_decorated(obj) decorate(obj) else obj end end
should_be_decorated(obj)
click to toggle source
# File lib/hash_with_quick_access.rb, line 60 def should_be_decorated(obj) (obj.is_a?(Array) && obj[0].is_a?(Hash)) || obj.is_a?(Hash) end