Class: QueryableHash::Wrapper

Inherits:
SimpleDelegator
  • Object
show all
Defined in:
lib/queryable_hash/wrapper.rb

Instance Method Summary collapse

Constructor Details

#initialize(hash) ⇒ Wrapper

Returns a new instance of Wrapper.



6
7
8
9
# File 'lib/queryable_hash/wrapper.rb', line 6

def initialize(hash)
  @original_hash = hash
  super hash
end

Instance Method Details

#find_all(*queries, nil_value: nil) ⇒ Object



11
12
13
14
15
16
17
18
19
20
# File 'lib/queryable_hash/wrapper.rb', line 11

def find_all(*queries, nil_value: nil)
  queries.reduce([]) do |memo, query|
    context = self
    query.split(".").each do |name|
      break if context.nil?
      context = context[name.to_sym] || context[name]
    end
    memo << (context || nil_value)
  end
end

#find_first(*queries, nil_value: nil, raise_when_nil: false) ⇒ Object Also known as: find

Raises:



22
23
24
25
26
27
28
29
30
# File 'lib/queryable_hash/wrapper.rb', line 22

def find_first(*queries, nil_value: nil, raise_when_nil: false)
  first = find_all(*queries, nil_value: nil_value).find do |result|
    result != nil_value
  end
  first ||= nil_value

  raise NotFoundError if raise_when_nil && first == nil_value
  first
end

#to_hashObject



34
35
36
# File 'lib/queryable_hash/wrapper.rb', line 34

def to_hash
  @original_hash
end