Class: Candy::CandyArray

Inherits:
Object
  • Object
show all
Includes:
Crunch, Embeddable
Defined in:
lib/candy/array.rb

Overview

An array-like object that saves itself to a parent Candy::Piece object. MongoDB’s atomic array operators are used extensively to perform concurrency-friendly updates of individual array elements without rewriting the whole array.

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Embeddable

#candy_adopt

Methods included from Crunch

#findAndModify, included

Constructor Details

#initialize(*args, &block) ⇒ CandyArray

Sets the initial array state.



21
22
23
# File 'lib/candy/array.rb', line 21

def initialize(*args, &block)
  @__candy = args
end

Class Method Details

.embed(*args, &block) ⇒ Object

Included for purposes of ‘embeddable’ compatibility, but does nothing except pass its parameters to the new object. Since you can’t save an array on its own anyway, there’s no need to flag it as “don’t save.”



16
17
18
# File 'lib/candy/array.rb', line 16

def self.embed(*args, &block)
  self.new(*args, &block)
end

Instance Method Details

#<<(val) ⇒ Object Also known as: push

Appends a value to our array.



40
41
42
43
44
# File 'lib/candy/array.rb', line 40

def <<(val)
  property = candy_coat(@__candy_parent_key, val)
  @__candy_parent.operate :push, @__candy_parent_key => property
  self.candy << property
end

#==(val) ⇒ Object

Array equality.



63
64
65
# File 'lib/candy/array.rb', line 63

def ==(val)
  self.to_ary == val
end

#[](index) ⇒ Object

Retrieves the value from our internal array.



35
36
37
# File 'lib/candy/array.rb', line 35

def [](index)
  candy[index]
end

#[]=(index, val) ⇒ Object

Set a value at a specified index in our array. Note that this operation _does not_ confirm that the array in Mongo still matches our current state. If concurrent updates have happened, you might end up overwriting something other than what you thought.



28
29
30
31
32
# File 'lib/candy/array.rb', line 28

def []=(index, val)
  property = candy_coat(@__candy_parent_key, val)
  @__candy_parent.set embedded(index => property)
  self.candy[index] = property
end

#candyObject Also known as: to_candy, to_ary

Returns the array of memoized values.



56
57
58
# File 'lib/candy/array.rb', line 56

def candy
  @__candy ||= []
end

#lengthObject Also known as: size

Array length.



68
69
70
# File 'lib/candy/array.rb', line 68

def length
  self.to_ary.length
end

#shift(n = 1) ⇒ Object

Pops the front off the MongoDB array and returns it, then resyncs the array. (Thus supporting real-time concurrency for queue-like behavior.)



49
50
51
52
53
# File 'lib/candy/array.rb', line 49

def shift(n=1)
  doc = @__candy_parent.findAndModify({"_id" => @__candy_parent.id}, {'$pop' => {@__candy_parent_key => -1}})
  @__candy = doc['value'][@__candy_parent_key.to_s]
  @__candy.shift
end