Class: QueryableHash::Wrapper
- Inherits:
-
SimpleDelegator
- Object
- SimpleDelegator
- QueryableHash::Wrapper
- Defined in:
- lib/queryable_hash/wrapper.rb
Instance Attribute Summary collapse
-
#nil_value ⇒ Object
readonly
Returns the value of attribute nil_value.
-
#raise_when_nil ⇒ Object
readonly
Returns the value of attribute raise_when_nil.
Instance Method Summary collapse
- #find_all(*queries, nil_value: nil) ⇒ Object
- #find_first(*queries, nil_value: nil, raise_when_nil: nil) ⇒ Object (also: #find)
-
#initialize(hash, nil_value: nil, raise_when_nil: false) ⇒ Wrapper
constructor
A new instance of Wrapper.
- #to_hash ⇒ Object
Constructor Details
#initialize(hash, nil_value: nil, raise_when_nil: false) ⇒ Wrapper
Returns a new instance of Wrapper.
7 8 9 10 11 12 |
# File 'lib/queryable_hash/wrapper.rb', line 7 def initialize(hash, nil_value: nil, raise_when_nil: false) @original_hash = hash @nil_value = nil_value @raise_when_nil = raise_when_nil super hash end |
Instance Attribute Details
#nil_value ⇒ Object (readonly)
Returns the value of attribute nil_value.
5 6 7 |
# File 'lib/queryable_hash/wrapper.rb', line 5 def nil_value @nil_value end |
#raise_when_nil ⇒ Object (readonly)
Returns the value of attribute raise_when_nil.
5 6 7 |
# File 'lib/queryable_hash/wrapper.rb', line 5 def raise_when_nil @raise_when_nil end |
Instance Method Details
#find_all(*queries, nil_value: nil) ⇒ Object
14 15 16 17 18 19 20 21 22 23 |
# File 'lib/queryable_hash/wrapper.rb', line 14 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: nil) ⇒ Object Also known as: find
25 26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/queryable_hash/wrapper.rb', line 25 def find_first(*queries, nil_value: nil, raise_when_nil: nil) nil_value = @nil_value if nil_value.nil? raise_when_nil = @raise_when_nil if raise_when_nil.nil? first = find_all(*queries, nil_value: nil_value).find do |result| result != nil_value end first ||= nil_value raise NotFoundError.new("#{queries.join(", ")} not found") if raise_when_nil && first == nil_value first end |
#to_hash ⇒ Object
40 41 42 |
# File 'lib/queryable_hash/wrapper.rb', line 40 def to_hash @original_hash end |