Module: Redis::Relations::HasOne

Defined in:
lib/redis/relations/has_one.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/redis/relations/has_one.rb', line 32

def self.included(base)
  base.class_eval do
    add_relation :has_one
    
    class << self
      def has_one(relation_name, options = {})
        has_one_relations[relation_name] = options.reverse_merge({ :relation => relation_name })
        
        define_method relation_name do
          get_has_one_reference(relation_name)
        end
        
        define_method "#{relation_name}=" do |a|
          set_has_one_reference(relation_name, a)
        end
      end
    end
  end
end

Instance Method Details

#get_has_one_reference(relation_name) ⇒ Object



10
11
12
13
14
15
16
17
# File 'lib/redis/relations/has_one.rb', line 10

def get_has_one_reference(relation_name)
  if has_one_references.key?(relation_name)
    has_one_references[relation_name]
  else
    result = self.class.find(connection.hget(has_one_relation_id(relation_name), id))
    has_one_references[relation_name] = result
  end
end

#has_one_referencesObject



2
3
4
# File 'lib/redis/relations/has_one.rb', line 2

def has_one_references
  @has_one_references ||= {}
end

#has_one_relation_id(name) ⇒ Object



19
20
21
# File 'lib/redis/relations/has_one.rb', line 19

def has_one_relation_id(name)
  File.join("references", has_one_relations[name][:relation].to_s)
end

#save_has_one_referencesObject



23
24
25
26
27
28
29
30
# File 'lib/redis/relations/has_one.rb', line 23

def save_has_one_references
  has_one_references.each do |relation_name, reference|
    if reference
      connection.hset(has_one_relation_id(relation_name), id, reference.id)
      connection.hset(has_one_relation_id(relation_name), reference.id, id)
    end
  end
end

#set_has_one_reference(relation_name, value) ⇒ Object



6
7
8
# File 'lib/redis/relations/has_one.rb', line 6

def set_has_one_reference(relation_name, value)
  has_one_references[relation_name] = value
end