Class: CouchbaseStructures::Stack

Inherits:
Object
  • Object
show all
Includes:
CouchbaseDocStore
Defined in:
lib/couchbase_structures/stack.rb

Instance Method Summary collapse

Constructor Details

#initialize(key) ⇒ Stack

Returns a new instance of Stack.



7
8
9
10
11
12
13
14
# File 'lib/couchbase_structures/stack.rb', line 7

def initialize(key)
  @user_key = key
  @key = "#{@user_key}::stack"
  @top_index_key = "#{@key}::top"
  initialize_document(@top_index_key, 0)
  initialize_document(@key, { :type => "stack", :class => "CouchbaseStructures::Stack", :user_key => @user_key } )
  self
end

Instance Method Details

#deleteObject



44
45
46
47
48
49
50
51
52
# File 'lib/couchbase_structures/stack.rb', line 44

def delete
  top_index = get_document(@top_index_key)
  
  top_index.downto(1) do |i|
    delete_document("#{@key}::#{i}")
  end
  delete_document(@top_index_key)
  delete_document(@key)
end

#inspect(html = false) ⇒ Object



16
17
18
19
20
21
22
# File 'lib/couchbase_structures/stack.rb', line 16

def inspect(html = false)
  if html
    "<strong>key</strong> = #{@key}    <br /><strong>top_index</strong> = #{get_document(@top_index_key).to_s}    <br /><strong>items</strong> = #{self.to_a(true)}"
  else
    "key = #{@key}\ntop_index = #{get_document(@top_index_key).to_s}\nitems = #{self.to_a}"
  end
end

#popObject



30
31
32
33
34
35
36
37
38
# File 'lib/couchbase_structures/stack.rb', line 30

def pop()
  old_top_index = get_document(@top_index_key)
  return nil if @top_index_key == 0 # if the stack has returned to zero items
  decrease_atomic_count(@top_index_key)

  doc = get_document("#{@key}::#{old_top_index}")
  delete_document("#{@key}::#{old_top_index}")
  doc
end

#push(value) ⇒ Object



24
25
26
27
28
# File 'lib/couchbase_structures/stack.rb', line 24

def push(value)
  new_top_index = increase_atomic_count(@top_index_key)
  create_document("#{@key}::#{new_top_index}", value)
  self
end

#sizeObject



40
41
42
# File 'lib/couchbase_structures/stack.rb', line 40

def size
  get_document(@top_index_key)
end

#to_a(html = false) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/couchbase_structures/stack.rb', line 54

def to_a(html=false)
  a = []
  top_index = get_document(@top_index_key)

  # delete all queued documents, including those that were before the current head (those aren't deleted as of now)
  top_index.downto(1) do |i|
    a << get_document("#{@key}::#{i}")
  end
  
  if html
    str = "["
    a.each do |item|
      str += "<br />&nbsp;&nbsp;&nbsp;&nbsp;" + item.inspect
    end
    str += "<br />]"
    return str
  else
    return a
  end
end