lib/mongo_mapper/plugins/keys/key.rb in mongo_mapper-0.15.0 vs lib/mongo_mapper/plugins/keys/key.rb in mongo_mapper-0.15.1
- old
+ new
@@ -1,14 +1,15 @@
# encoding: UTF-8
module MongoMapper
module Plugins
module Keys
class Key
- attr_accessor :name, :type, :options, :default, :ivar, :abbr, :accessors
-
+ RESERVED_KEYS = %w( id class object_id attributes )
ID_STR = '_id'
+ attr_accessor :name, :type, :options, :default, :ivar, :abbr, :accessors
+
def initialize(*args)
options_from_args = args.extract_options!
@name, @type = args.shift.to_s, args.shift
self.options = (options_from_args || {}).symbolize_keys
@dynamic = !!options[:__dynamic]
@@ -58,16 +59,21 @@
def get(value)
# Special Case: Generate default _id on access
value = default_value if @is_id and !value
+ value = type.from_mongo(value)
+
if @typecast
- klass = typecast_class # Don't make this lookup on every call
- type.from_mongo(value).map { |v| klass.from_mongo(v) }
- else
- type.from_mongo(value)
+ klass = typecast_class # Don't make this lookup on every call
+ # typecast assumes array-ish object.
+ value = value.map { |v| klass.from_mongo(v) }
+ # recast it in the original type
+ value = type.from_mongo(value)
end
+
+ value
end
def set(value)
# Avoid tap here so we don't have to create a block binding.
values = type.to_mongo(value)
@@ -91,11 +97,10 @@
def valid_ruby_name?
!!@name.match(/\A[a-z_][a-z0-9_]*\z/i)
end
- RESERVED_KEYS = %w( id class object_id )
def reserved_name?
RESERVED_KEYS.include?(@name)
end
def read_accessor?
@@ -122,10 +127,10 @@
@typecast_class ||= options[:typecast].constantize
end
def validate_key_name!
if reserved_name?
- raise MongoMapper::InvalidKey.new("`#{@name}` is a reserved key name (did you mean to use _id?)")
+ raise MongoMapper::InvalidKey.new("`#{@name}` is a reserved key name")
elsif !valid_ruby_name?
raise MongoMapper::InvalidKey.new("`#{@name}` is not a valid key name. Keys must match [a-z][a-z0-9_]*")
end
end
end