Class: BelongsTo

Inherits:
Relation show all
Defined in:
lib/redisant/relations.rb

Instance Attribute Summary

Attributes inherited from Relation

#name, #object

Instance Method Summary collapse

Methods inherited from Relation

#object_class

Constructor Details

#initialize(name, object) ⇒ BelongsTo

Returns a new instance of BelongsTo.



17
18
19
20
# File 'lib/redisant/relations.rb', line 17

def initialize name, object
  super name, object
  @reverse_name = Inflector.pluralize @object.class.name.downcase
end

Instance Method Details

#destroyObject



22
23
24
# File 'lib/redisant/relations.rb', line 22

def destroy
  set_owner nil, true
end

#ownerObject



37
38
39
# File 'lib/redisant/relations.rb', line 37

def owner
  @owner ||= @class.find(owner_id) if owner_id
end

#owner_idObject

query



33
34
35
# File 'lib/redisant/relations.rb', line 33

def owner_id
  @owner_id ||= $redis.get redis_key
end

#redis_keyObject

keys



27
28
29
30
# File 'lib/redisant/relations.rb', line 27

def redis_key
  raise Redisant::InvalidArgument.new('Cannot make key without id') unless @object && @object.id
  "#{@object.class_name}:#{@object.id}:belongs_to:#{@name}"
end

#set_owner(item, reprocitate = true) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/redisant/relations.rb', line 41

def set_owner item, reprocitate=true
  if owner
    if owner.respond_to? @reverse_name
      owner.send(@reverse_name).remove @object, false if reprocitate
    end
  end
  if item
    raise Redisant::InvalidArgument.new('Wrong object type') unless item.class_name == @name
    raise Redisant::InvalidArgument.new('Missing id') unless item.id
    $redis.set redis_key, item.id
    @owner = item
    @owner_id = item.id
    if owner.respond_to? @reverse_name
      owner.send(@reverse_name).add @object, false if reprocitate
    end
  else
    $redis.del redis_key
    @owner_id = nil
    @owner = nil
  end
end