Class: MongoMapper::Key

Inherits:
Object show all
Defined in:
lib/mongomapper/key.rb

Constant Summary collapse

NativeTypes =

DateTime and Date are currently not supported by mongo’s bson so just use Time

[String, Float, Time, Integer, Boolean, Array, Hash]

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/mongomapper/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.delete(:default)
end

Instance Attribute Details

#default_valueObject

Returns the value of attribute default_value.



6
7
8
# File 'lib/mongomapper/key.rb', line 6

def default_value
  @default_value
end

#nameObject

Returns the value of attribute name.



6
7
8
# File 'lib/mongomapper/key.rb', line 6

def name
  @name
end

#optionsObject

Returns the value of attribute options.



6
7
8
# File 'lib/mongomapper/key.rb', line 6

def options
  @options
end

#typeObject

Returns the value of attribute type.



6
7
8
# File 'lib/mongomapper/key.rb', line 6

def type
  @type
end

Instance Method Details

#==(other) ⇒ Object



15
16
17
# File 'lib/mongomapper/key.rb', line 15

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

#embedded_document?Boolean

Returns:



27
28
29
# File 'lib/mongomapper/key.rb', line 27

def embedded_document?
  type.respond_to?(:embeddable?) && type.embeddable?
end

#get(value) ⇒ Object



31
32
33
34
35
36
37
38
39
40
# File 'lib/mongomapper/key.rb', line 31

def get(value)
  return default_value if value.nil? && !default_value.nil?
  if type == Array
    value || []
  elsif type == Hash
    HashWithIndifferentAccess.new(value || {})
  else
    value
  end
end

#native?Boolean

Returns:



23
24
25
# File 'lib/mongomapper/key.rb', line 23

def native?
  @native ||= NativeTypes.include?(type) || type.nil?
end

#set(value) ⇒ Object



19
20
21
# File 'lib/mongomapper/key.rb', line 19

def set(value)
  typecast(value)
end