Class: Berg::Key

Inherits:
Object
  • Object
show all
Includes:
Base
Defined in:
lib/berg/key.rb

Constant Summary

Constants included from Base

Base::ARRAY_ID

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Base

#add

Constructor Details

#initialize(&block) ⇒ Key

Returns a new instance of Key.



5
6
7
# File 'lib/berg/key.rb', line 5

def initialize(&block)
  @block = block
end

Class Method Details

.locate(object, &block) ⇒ Object



9
10
11
# File 'lib/berg/key.rb', line 9

def self.locate(object, &block)
  new(&block).locate(object)
end

Instance Method Details

#locate(object, trace = "") ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/berg/key.rb', line 13

def locate(object, trace = "")
  case object
  when Array
    object.each_with_index do |rest, index|
      if (result = locate(rest, add(trace, "[#{index}]"))).found?
        return result
      end
    end
  when Hash
    object.each_pair do |key, value|
      if (result = locate(value, add(trace, key))).found?
        return result
      end
    end
  when TrueClass, FalseClass, NilClass, Fixnum, String
    return @block.call(object) ? Found.new(trace) : NotFound.new
  when Found, NotFound
    return object
  else
    raise "Type #{object.class} not supported"
  end

  return NotFound.new
end