Class: MongoMapper::Key

Inherits:
Object
  • 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, Ref]

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, type, options = {}) ⇒ Key

Returns a new instance of Key.



11
12
13
14
15
# File 'lib/mongomapper/key.rb', line 11

def initialize(name, type, options={})
  @name, @type = name.to_s, type
  self.options = options.symbolize_keys
  self.default_value = options.delete(:default)
end

Instance Attribute Details

#default_valueObject

Returns the value of attribute default_value.



9
10
11
# File 'lib/mongomapper/key.rb', line 9

def default_value
  @default_value
end

#nameObject

Returns the value of attribute name.



9
10
11
# File 'lib/mongomapper/key.rb', line 9

def name
  @name
end

#optionsObject

Returns the value of attribute options.



9
10
11
# File 'lib/mongomapper/key.rb', line 9

def options
  @options
end

#typeObject

Returns the value of attribute type.



9
10
11
# File 'lib/mongomapper/key.rb', line 9

def type
  @type
end

Instance Method Details

#==(other) ⇒ Object



17
18
19
# File 'lib/mongomapper/key.rb', line 17

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

#embedded_document?Boolean

Returns:



29
30
31
# File 'lib/mongomapper/key.rb', line 29

def embedded_document?
  type.ancestors.include?(EmbeddedDocument) && !type.ancestors.include?(Document)
end

#get(value) ⇒ Object



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

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:



25
26
27
# File 'lib/mongomapper/key.rb', line 25

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

#set(value) ⇒ Object



21
22
23
# File 'lib/mongomapper/key.rb', line 21

def set(value)
  typecast(value)
end