Class: RelaxDB::HasManyProxy

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/relaxdb/has_many_proxy.rb

Instance Method Summary collapse

Constructor Details

#initialize(client, relationship, opts) ⇒ HasManyProxy

Returns a new instance of HasManyProxy.



7
8
9
10
11
12
13
14
15
16
# File 'lib/relaxdb/has_many_proxy.rb', line 7

def initialize(client, relationship, opts)
  @client = client 
  @relationship = relationship
  @opts = opts

  @target_class = opts[:class] 
  @relationship_as_viewed_by_target = (opts[:known_as] || client.class.name.snake_case).to_s

  @children = load_children
end

Instance Method Details

#<<(obj) ⇒ Object



18
19
20
21
22
23
24
25
26
# File 'lib/relaxdb/has_many_proxy.rb', line 18

def <<(obj)
  return false unless obj.validates?
  return false if @children.include?(obj)
  
  obj.send("#{@relationship_as_viewed_by_target}=".to_sym, @client)
  obj.save
  @children << obj
  self
end

#[](*args) ⇒ Object



55
56
57
# File 'lib/relaxdb/has_many_proxy.rb', line 55

def [](*args)
  @children[*args]
end


40
41
42
43
44
45
# File 'lib/relaxdb/has_many_proxy.rb', line 40

def break_back_link(obj)
  if obj
    obj.send("#{@relationship_as_viewed_by_target}=".to_sym, nil)
    obj.save
  end
end

#clearObject



28
29
30
31
32
33
# File 'lib/relaxdb/has_many_proxy.rb', line 28

def clear
  @children.each do |c|
    break_back_link c
  end
  @children.clear
end

#delete(obj) ⇒ Object



35
36
37
38
# File 'lib/relaxdb/has_many_proxy.rb', line 35

def delete(obj)
  obj = @children.delete(obj)
  break_back_link(obj) if obj
end

#each(&blk) ⇒ Object



59
60
61
# File 'lib/relaxdb/has_many_proxy.rb', line 59

def each(&blk)
  @children.each(&blk)
end

#empty?Boolean

Returns:

  • (Boolean)


47
48
49
# File 'lib/relaxdb/has_many_proxy.rb', line 47

def empty?
  @children.empty?
end

#inspectObject



75
76
77
# File 'lib/relaxdb/has_many_proxy.rb', line 75

def inspect
  @children.inspect
end

#load_childrenObject



67
68
69
70
71
72
73
# File 'lib/relaxdb/has_many_proxy.rb', line 67

def load_children
  view_path = "_view/#{@client.class}/#{@relationship}?key=\"#{@client._id}\""
  design_doc = @client.class
  view_name = @relationship
  map_function = ViewCreator.has_n(@target_class, @relationship_as_viewed_by_target)
  @children = RelaxDB.retrieve(view_path, design_doc, view_name, map_function)
end

#reloadObject



63
64
65
# File 'lib/relaxdb/has_many_proxy.rb', line 63

def reload
  @children = load_children
end

#sizeObject



51
52
53
# File 'lib/relaxdb/has_many_proxy.rb', line 51

def size
  @children.size
end