Module: MongoMapper::Plugins::Keys::ClassMethods

Defined in:
lib/mongo_mapper/plugins/keys.rb

Instance Method Summary collapse

Instance Method Details

#from_mongo(value) ⇒ Object



55
56
57
58
# File 'lib/mongo_mapper/plugins/keys.rb', line 55

def from_mongo(value)
  return nil if value.nil?
  value.is_a?(self) ? value : load(value)
end

#inherited(descendant) ⇒ Object



15
16
17
18
# File 'lib/mongo_mapper/plugins/keys.rb', line 15

def inherited(descendant)
  descendant.instance_variable_set(:@keys, keys.dup)
  super
end

#key(*args) ⇒ Object



24
25
26
27
28
29
30
31
32
# File 'lib/mongo_mapper/plugins/keys.rb', line 24

def key(*args)
  Key.new(*args).tap do |key|
    keys[key.name] = key
    create_accessors_for(key)
    create_key_in_descendants(*args)
    create_indexes_for(key)
    create_validations_for(key)
  end
end

#key?(key) ⇒ Boolean

Returns:



34
35
36
# File 'lib/mongo_mapper/plugins/keys.rb', line 34

def key?(key)
  keys.keys.include?(key.to_s)
end

#keysObject



20
21
22
# File 'lib/mongo_mapper/plugins/keys.rb', line 20

def keys
  @keys ||= {}
end

#load(attrs) ⇒ Object

load is overridden in identity map to ensure same objects are loaded



61
62
63
64
65
66
67
68
# File 'lib/mongo_mapper/plugins/keys.rb', line 61

def load(attrs)
  return nil if attrs.nil?
  begin
    attrs['_type'].present? ? attrs['_type'].constantize : self
  rescue NameError
    self
  end.allocate.initialize_from_database(attrs)
end

#object_id_key?(name) ⇒ Boolean

Returns:



46
47
48
# File 'lib/mongo_mapper/plugins/keys.rb', line 46

def object_id_key?(name)
  object_id_keys.include?(name.to_sym)
end

#object_id_keysObject



42
43
44
# File 'lib/mongo_mapper/plugins/keys.rb', line 42

def object_id_keys
  keys.keys.select { |key| keys[key].type == ObjectId }.map { |k| k.to_sym }
end

#to_mongo(instance) ⇒ Object



50
51
52
53
# File 'lib/mongo_mapper/plugins/keys.rb', line 50

def to_mongo(instance)
  return nil if instance.nil?
  instance.to_mongo
end

#using_object_id?Boolean

Returns:



38
39
40
# File 'lib/mongo_mapper/plugins/keys.rb', line 38

def using_object_id?
  object_id_key?(:_id)
end