Class: Class

Inherits:
Object show all
Defined in:
lib/is_a_collection.rb

Instance Method Summary collapse

Instance Method Details

#is_a_collection(id_method = :id, opts = {}) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/is_a_collection.rb', line 11

def is_a_collection(id_method=:id, opts={})
  id_method = id_method.to_sym
  indices = [opts[:index], opts[:indices]].flatten.compact
  
  include IsACollection::InstanceMethods
  extend IsACollection::ClassMethods
  
  define_method :add_to_collection do
    primary_key = __send__(id_method)
    raise IsACollection::DuplicateKeyError if self.class.__collection[primary_key]
    self.class.__collection[primary_key] = self
    
    indices.each do |index|
      self.class.__indices[index][__send__ index].add(self)
    end
  end
  
  define_method :remove_from_collection do
    self.class.__collection.delete(__send__ id_method)
    
    indices.each do |index|
      self.class.__indices[index][__send__ index].delete(self)
    end
  end
  
  indices.each do |index|
    meta_def :"find_by_#{index}" do |genre|
      __indices[index][genre]
    end
  end
  
end