Class: RelaxDB::HasOneProxy

Inherits:
Object
  • Object
show all
Defined in:
lib/relaxdb/has_one_proxy.rb

Instance Method Summary collapse

Constructor Details

#initialize(client, relationship) ⇒ HasOneProxy

Returns a new instance of HasOneProxy.



5
6
7
8
9
10
11
12
# File 'lib/relaxdb/has_one_proxy.rb', line 5

def initialize(client, relationship)
  @client = client
  @relationship = relationship
  @target_class = @relationship.to_s.camel_case      
  @relationship_as_viewed_by_target = client.class.name.snake_case
  
  @target = nil
end

Instance Method Details

#load_targetObject



35
36
37
38
39
40
41
# File 'lib/relaxdb/has_one_proxy.rb', line 35

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

#targetObject



14
15
16
17
# File 'lib/relaxdb/has_one_proxy.rb', line 14

def target
  return @target if @target    
  @target = load_target
end

#target=(new_target) ⇒ Object

All database changes performed by this method would ideally be done in a transaction



20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/relaxdb/has_one_proxy.rb', line 20

def target=(new_target)
  # Nullify any existing relationship on assignment
  old_target = target
  if old_target
    old_target.send("#{@relationship_as_viewed_by_target}=".to_sym, nil)
    old_target.save
  end

  @target = new_target
  unless @target.nil?
    @target.send("#{@relationship_as_viewed_by_target}=".to_sym, @client)
    @target.save
  end
end