Module: Hm::Dig
- Defined in:
- lib/hm/dig.rb
Constant Summary collapse
- DIGGABLE_CLASSES =
TODO: Struct/OpenStruct are also diggable in Ruby core, can be added for future implementation
[Hash, Array].freeze
- NotFound =
Object.new.freeze
Class Method Summary collapse
Class Method Details
.dig(what, key, *keys) ⇒ Object
8 9 10 11 12 13 14 15 16 17 18 19 20 |
# File 'lib/hm/dig.rb', line 8 def self.dig(what, key, *keys) # We want to return special value when key is not present, because # 1. "at some point in path, we have a value, and this value is `nil`", and # 2. "at some point in path, we don't have a value (key is absent)" # ...should be different in Algo.visit return NotFound unless key?(what, key) return what.dig(key, *keys) if what.respond_to?(:dig) ensure_diggable?(what) or fail TypeError, "#{value.class} is not diggable" value = what[key] keys.empty? ? value : dig(value, *keys) end |
.diggable?(what) ⇒ Boolean
31 32 33 |
# File 'lib/hm/dig.rb', line 31 def self.diggable?(what) DIGGABLE_CLASSES.include?(what.class) end |
.key?(what, key) ⇒ Boolean
22 23 24 25 26 27 28 29 |
# File 'lib/hm/dig.rb', line 22 def self.key?(what, key) case what when Array (0...what.size).cover?(key) when Hash what.key?(key) end end |