Module: Redis::Relations::HasMany

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

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



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

def self.included(base)
  base.class_eval do
    add_relation :has_many
    
    class << self
      def has_many(relation_name, options = {})
        has_many_relations[relation_name] = options.reverse_merge({ :relation => relation_name })
      
        define_method relation_name do
          get_has_many_reference(relation_name)
        end
        
        define_method "#{relation_name}=" do |array|
          target = get_has_many_reference(relation_name)
          target.clear
          target.concat array
        end
      end
    end
  end
end

Instance Method Details

#get_has_many_reference(relation_name) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/redis/relations/has_many.rb', line 6

def get_has_many_reference(relation_name)
  if has_many_references.key?(relation_name)
    has_many_references[relation_name]
  else
    result = connection.hget(has_many_relation_id(relation_name), id)
    if result
      result = serializer.load(result)
      if result.respond_to?(:collect)
        result = result.collect { |r| self.class.find(r) }
      else
        result = [find(result)]
      end
    else
      result = []
    end
    has_many_references[relation_name] = result
  end
end

#has_many_referencesObject



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

def has_many_references
  @has_many_references ||= {}
end

#has_many_relation_id(name) ⇒ Object



35
36
37
# File 'lib/redis/relations/has_many.rb', line 35

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

#save_has_many_referencesObject



25
26
27
28
29
30
31
32
33
# File 'lib/redis/relations/has_many.rb', line 25

def save_has_many_references
  has_many_references.each do |relation_name, array|
    array = array.collect { |a| a.id }
    connection.hset(has_many_relation_id(relation_name), id, serializer.dump(array))
    array.each do |aid|
      connection.hset(has_many_relation_id(relation_name), aid, id)
    end
  end
end