Class: Palantir::Base
- Inherits:
-
Object
- Object
- Palantir::Base
- Defined in:
- lib/palantir/base.rb
Instance Attribute Summary collapse
-
#data ⇒ Object
Returns the value of attribute data.
-
#default ⇒ Object
Returns the value of attribute default.
Instance Method Summary collapse
-
#initialize(data, default = 0) ⇒ Base
constructor
Create a Palantir.
-
#size ⇒ Object
Return the @data size in the Palantir instance.
-
#sum(key, first_value = 0) ⇒ Object
Sum data of a specific key, if any, otherwise add the default_value.
-
#where(key, value) ⇒ Object
Filter data with a where clause given a pair <key, value>.
Constructor Details
#initialize(data, default = 0) ⇒ Base
Create a Palantir.
Example:
>> p = Palantir::Base.new([{key: 'key', value: 'value'}])
=> #<Palantir::Base:0x007fe1de9642f0 @data=[{:foo=>"bar"}], @default=0>
Arguments:
data: (Array)
default: (Integer)
15 16 17 18 |
# File 'lib/palantir/base.rb', line 15 def initialize(data, default = 0) @data = data @default = default end |
Instance Attribute Details
#data ⇒ Object
Returns the value of attribute data.
4 5 6 |
# File 'lib/palantir/base.rb', line 4 def data @data end |
#default ⇒ Object
Returns the value of attribute default.
4 5 6 |
# File 'lib/palantir/base.rb', line 4 def default @default end |
Instance Method Details
#size ⇒ Object
Return the @data size in the Palantir instance.
22 23 24 |
# File 'lib/palantir/base.rb', line 22 def size @data.count end |
#sum(key, first_value = 0) ⇒ Object
Sum data of a specific key, if any, otherwise add the default_value. This ends a chain of ‘where’.
Example:
>> palantir.where(:class, 'wizard').sum(:age)
Arguments:
key: (Symbol)
first_value: (Integer)
52 53 54 55 56 |
# File 'lib/palantir/base.rb', line 52 def sum(key, first_value = 0) @data.reduce(first_value) do |sum, element| sum += element.fetch(key){ @default } end end |
#where(key, value) ⇒ Object
Filter data with a where clause given a pair <key, value>. Chainable
Example:
>> palantir.where(:class, 'wizard').where(:name, 'Gandalf')
Arguments:
key: (Symbol)
value: (String, Integer, Decimal...)
35 36 37 38 39 40 |
# File 'lib/palantir/base.rb', line 35 def where(key, value) filtered_data = @data.select do |element| element.has_key?(key) && element.fetch(key) == value end self.class.new(filtered_data, @default) end |