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

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

Instance Method Summary collapse

Instance Method Details

#from_mongo(value) ⇒ Object



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

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

#inherited(descendant) ⇒ Object



9
10
11
12
# File 'lib/mongo_mapper/plugins/keys.rb', line 9

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

#key(*args) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
# File 'lib/mongo_mapper/plugins/keys.rb', line 18

def key(*args)
  key = Key.new(*args)
  keys[key.name] = key

  create_accessors_for(key)
  create_key_in_descendants(*args)
  create_indexes_for(key)
  create_validations_for(key)

  key
end

#keysObject



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

def keys
  @keys ||= defined?(HashWithIndifferentAccess) ? HashWithIndifferentAccess.new : ActiveSupport::HashWithIndifferentAccess.new
end

#load(attrs) ⇒ Object

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



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

def load(attrs)
  begin
    klass = attrs['_type'].present? ? attrs['_type'].constantize : self
    klass.new(attrs, true)
  rescue NameError
    new(attrs, true)
  end
end

#object_id_key?(name) ⇒ Boolean

Returns:



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

def object_id_key?(name)
  key = keys[name.to_s]
  key && key.type == ObjectId
end

#to_mongo(instance) ⇒ Object



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

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

#using_object_id?Boolean

Returns:



30
31
32
# File 'lib/mongo_mapper/plugins/keys.rb', line 30

def using_object_id?
  object_id_key?(:_id)
end