Module: MongoMapper::EmbeddedDocument::ClassMethods

Defined in:
lib/mongomapper/embedded_document.rb

Instance Method Summary collapse

Instance Method Details

#add_to_subclasses(name, type, options) ⇒ Object



72
73
74
75
76
77
78
# File 'lib/mongomapper/embedded_document.rb', line 72

def add_to_subclasses(name, type, options)
  return if subclasses.blank?
  
  subclasses.each do |subclass|
    subclass.key name, type, options
  end
end

#create_accessors_for(key) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/mongomapper/embedded_document.rb', line 54

def create_accessors_for(key)
  define_method(key.name) do
    read_attribute(key.name)
  end
  
  define_method("#{key.name}_before_typecast") do
    read_attribute_before_typecast(key.name)
  end
  
  define_method("#{key.name}=") do |value|
    write_attribute(key.name, value)
  end
  
  define_method("#{key.name}?") do
    read_attribute(key.name).present?
  end
end

#embeddable?Boolean

Returns:



90
91
92
# File 'lib/mongomapper/embedded_document.rb', line 90

def embeddable?
  !self.ancestors.include?(Document)
end

#ensure_index(name_or_array, options = {}) ⇒ Object



80
81
82
83
84
85
86
87
88
# File 'lib/mongomapper/embedded_document.rb', line 80

def ensure_index(name_or_array, options={})
  keys_to_index = if name_or_array.is_a?(Array)
    name_or_array.map { |pair| [pair[0], pair[1]] }
  else
    name_or_array
  end
  
  collection.create_index(keys_to_index, options.delete(:unique))
end

#inherited(subclass) ⇒ Object



22
23
24
25
26
27
28
# File 'lib/mongomapper/embedded_document.rb', line 22

def inherited(subclass)
  unless subclass.embeddable?
    subclass.collection(self.collection.name)
  end
  
  (@subclasses ||= []) << subclass
end

#key(name, type, options = {}) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
# File 'lib/mongomapper/embedded_document.rb', line 42

def key(name, type, options={})        
  key = Key.new(name, type, options)
  keys[key.name] = key
  
  create_accessors_for(key)
  add_to_subclasses(name, type, options)
  apply_validations_for(key)
  create_indexes_for(key)
  
  key
end

#keysObject



34
35
36
37
38
39
40
# File 'lib/mongomapper/embedded_document.rb', line 34

def keys
  @keys ||= if parent = parent_model
    parent.keys.dup
  else
    HashWithIndifferentAccess.new
  end
end

#parent_modelObject



94
95
96
97
98
# File 'lib/mongomapper/embedded_document.rb', line 94

def parent_model
  if parent = ancestors[1]
    parent if parent.ancestors.include?(EmbeddedDocument)
  end
end

#subclassesObject



30
31
32
# File 'lib/mongomapper/embedded_document.rb', line 30

def subclasses
  @subclasses
end