Class | DataMapper::Type |
In: |
lib/dm-core/type.rb
|
Parent: | Object |
Provides means of writing custom types for properties. Each type is based on a ruby primitive and handles its own serialization and materialization, and therefore is responsible for providing those methods.
To see complete list of supported types, see documentation for Property::PRIMITIVES. dm-types library provides less common types such as ip address, uuid, json, yaml, uri, slug, version, file path, bcrypt hash and so forth.
To define a new type, subclass DataMapper::Type, pick ruby primitive, and set the options for this type.
class LowerCase < DataMapper::Type primitive String auto_validation true length 255 end
Following this, you will be able to use LowerCase as a type for any given property. If special materialization and serialization is required, override the class methods
class LowerCase < DataMapper::Type primitive String auto_validation true length 255 def self.dump(value, property) return nil unless value value.to_s.downcase end def self.load(value) value end end
Properties of LowerCase type now will downcase it‘s values before it is persisted to the storage.
One more real world example from dm-types library is a JSON type that stores values serialized as JSON, and often useful for embedded values:
module DataMapper
module Types class Json < DataMapper::Type primitive String length 65535 lazy true def self.load(value, property) if value.nil? nil elsif value.kind_of?(String) ::JSON.load(value) else raise ArgumentError, '+value+ of a property of JSON type must be nil or a String' end end def self.dump(value, property) if value.nil? || value.kind_of?(String) value else ::JSON.dump(value) end end def self.typecast(value, property) if value.nil? || value.kind_of?(Array) || value.kind_of?(Hash) value else ::JSON.load(value.to_s) end end end # class Json JSON = Json end # module Types
end # module DataMapper
PROPERTY_OPTIONS | = | [ :accessor, :reader, :writer, :lazy, :default, :nullable, :key, :serial, :field, :size, :length, :format, :index, :unique_index, :auto_validation, :validates, :unique, :precision, :scale, :min, :max | Until cooperation of Property and Type does not change, each must have a separate list of options, because plugins (ex.: dm-validations) may want to extend one or the other, and expects no side effects |