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
- #get(*queries, nil_value: nil, raise_when_nil: nil) ⇒ Object
- #get_all(*queries, nil_value: nil) ⇒ Object
-
#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
#get(*queries, nil_value: nil, raise_when_nil: nil) ⇒ Object
25 26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/queryable_hash/wrapper.rb', line 25 def get(*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 = get_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 |
#get_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 get_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 |
#to_hash ⇒ Object
38 39 40 |
# File 'lib/queryable_hash/wrapper.rb', line 38 def to_hash @original_hash end |