Class: MongoMapper::Plugins::Keys::Key

Inherits:
Object
  • Object
show all
Defined in:
lib/mongo_mapper/plugins/keys/key.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ Key

Returns a new instance of Key.



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

def initialize(*args)
  options = args.extract_options!
  @name, @type = args.shift.to_s, args.shift
  self.options = (options || {}).symbolize_keys
  self.default_value = self.options[:default]
end

Instance Attribute Details

#default_valueObject

Returns the value of attribute default_value.



6
7
8
# File 'lib/mongo_mapper/plugins/keys/key.rb', line 6

def default_value
  @default_value
end

#nameObject

Returns the value of attribute name.



6
7
8
# File 'lib/mongo_mapper/plugins/keys/key.rb', line 6

def name
  @name
end

#optionsObject

Returns the value of attribute options.



6
7
8
# File 'lib/mongo_mapper/plugins/keys/key.rb', line 6

def options
  @options
end

#typeObject

Returns the value of attribute type.



6
7
8
# File 'lib/mongo_mapper/plugins/keys/key.rb', line 6

def type
  @type
end

Instance Method Details

#==(other) ⇒ Object



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

def ==(other)
  @name == other.name && @type == other.type
end

#can_default_id?Boolean

Returns:



24
25
26
# File 'lib/mongo_mapper/plugins/keys/key.rb', line 24

def can_default_id?
  type && [ObjectId, BSON::ObjectId, String].include?(type)
end

#embeddable?Boolean

Returns:



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

def embeddable?
  return false unless type.respond_to?(:embeddable?)
  type.embeddable?
end

#get(value) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/mongo_mapper/plugins/keys/key.rb', line 32

def get(value)
  if value.nil? && !default_value.nil?
    if default_value.respond_to?(:call)
      return default_value.call
    else
      # Using Marshal is easiest way to get a copy of mutable objects
      # without getting an error on immutable objects
      return Marshal.load(Marshal.dump(default_value))
    end
  end

  if options[:typecast].present?
    type.from_mongo(value).map! { |v| typecast_class.from_mongo(v) }
  else
    type.from_mongo(value)
  end
end

#number?Boolean

Returns:



28
29
30
# File 'lib/mongo_mapper/plugins/keys/key.rb', line 28

def number?
  [Integer, Float].include?(type)
end

#set(value) ⇒ Object



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

def set(value)
  type.to_mongo(value).tap do |values|
    if options[:typecast].present?
      values.map! { |v| typecast_class.to_mongo(v) }
    end
  end
end