Class: DataMapper::Property
- Includes:
- Assertions, Subject
- Defined in:
- lib/dm-core/property.rb,
lib/dm-core/property/date.rb,
lib/dm-core/property/text.rb,
lib/dm-core/property/time.rb,
lib/dm-core/property/class.rb,
lib/dm-core/property/float.rb,
lib/dm-core/property/binary.rb,
lib/dm-core/property/lookup.rb,
lib/dm-core/property/object.rb,
lib/dm-core/property/serial.rb,
lib/dm-core/property/string.rb,
lib/dm-core/property/boolean.rb,
lib/dm-core/property/decimal.rb,
lib/dm-core/property/integer.rb,
lib/dm-core/property/numeric.rb,
lib/dm-core/property/date_time.rb,
lib/dm-core/property/discriminator.rb,
lib/dm-core/property/typecast/time.rb,
lib/dm-core/property/typecast/numeric.rb
Overview
Properties
Properties for a model are not derived from a database structure, but instead explicitly declared inside your model class definitions. These properties then map (or, if using automigrate, generate) fields in your repository/database.
If you are coming to DataMapper from another ORM framework, such as ActiveRecord, this may be a fundamental difference in thinking to you. However, there are several advantages to defining your properties in your models:
-
information about your model is centralized in one place: rather than having to dig out migrations, xml or other configuration files.
-
use of mixins can be applied to model properties: better code reuse
-
having information centralized in your models, encourages you and the developers on your team to take a model-centric view of development.
-
it provides the ability to use Ruby’s access control functions.
-
and, because DataMapper only cares about properties explicitly defined
in
your models, DataMapper plays well with legacy databases, and shares
databases easily with other applications.
Declaring Properties
Inside your class, you call the property method for each property you want to add. The only two required arguments are the name and type, everything else is optional.
class Post
include DataMapper::Resource
property :title, String, :required => true # Cannot be null
property :publish, Boolean, :default => false # Default value for new records is false
end
By default, DataMapper supports the following primitive (Ruby) types also called core types:
-
Boolean
-
String (default length is 50)
-
Text (limit of 65k characters by default)
-
Float
-
Integer
-
BigDecimal
-
DateTime
-
Date
-
Time
-
Object (marshalled out during serialization)
-
Class (datastore primitive is the same as String. Used for Inheritance)
Other types are known as custom types.
For more information about available Types, see DataMapper::Type
Limiting Access
Property access control is uses the same terminology Ruby does. Properties are public by default, but can also be declared private or protected as needed (via the :accessor option).
class Post
include DataMapper::Resource
property :title, String, :accessor => :private # Both reader and writer are private
property :body, Text, :accessor => :protected # Both reader and writer are protected
end
Access control is also analogous to Ruby attribute readers and writers, and can be declared using :reader and :writer, in addition to :accessor.
class Post
include DataMapper::Resource
property :title, String, :writer => :private # Only writer is private
property :tags, String, :reader => :protected # Only reader is protected
end
Overriding Accessors
The reader/writer for any property can be overridden in the same manner that Ruby attr readers/writers can be. After the property is defined, just add your custom reader or writer:
class Post
include DataMapper::Resource
property :title, String
def title=(new_title)
raise ArgumentError if new_title != 'Luke is Awesome'
@title = new_title
end
end
Lazy Loading
By default, some properties are not loaded when an object is fetched in DataMapper. These lazily loaded properties are fetched on demand when their accessor is called for the first time (as it is often unnecessary to instantiate -every- property -every- time an object is loaded). For instance, DataMapper::Property::Text fields are lazy loading by default, although you can over-ride this behavior if you wish:
Example:
class Post
include DataMapper::Resource
property :title, String # Loads normally
property :body, Text # Is lazily loaded by default
end
If you want to over-ride the lazy loading on any field you can set it to a context or false to disable it with the :lazy option. Contexts allow multipule lazy properties to be loaded at one time. If you set :lazy to true, it is placed in the :default context
class Post
include DataMapper::Resource
property :title, String # Loads normally
property :body, Text, :lazy => false # The default is now over-ridden
property :comment, String, :lazy => [ :detailed ] # Loads in the :detailed context
property :author, String, :lazy => [ :summary, :detailed ] # Loads in :summary & :detailed context
end
Delaying the request for lazy-loaded attributes even applies to objects accessed through associations. In a sense, DataMapper anticipates that you will likely be iterating over objects in associations and rolls all of the load commands for lazy-loaded properties into one request from the database.
Example:
Widget.get(1).components
# loads when the post object is pulled from database, by default
Widget.get(1).components.first.body
# loads the values for the body property on all objects in the
# association, rather than just this one.
Widget.get(1).components.first.comment
# loads both comment and author for all objects in the association
# since they are both in the :detailed context
Keys
Properties can be declared as primary or natural keys on a table. You should a property as the primary key of the table:
Examples:
property :id, Serial # auto-incrementing key
property :legacy_pk, String, :key => true # 'natural' key
This is roughly equivalent to ActiveRecord’s set_primary_key
, though non-integer data types may be used, thus DataMapper supports natural keys. When a property is declared as a natural key, accessing the object using the indexer syntax Class[key]
remains valid.
User.get(1)
# when :id is the primary key on the users table
User.get('bill')
# when :name is the primary (natural) key on the users table
Indices
You can add indices for your properties by using the :index
option. If you use true
as the option value, the index will be automatically named. If you want to name the index yourself, use a symbol as the value.
property :last_name, String, :index => true
property :first_name, String, :index => :name
You can create multi-column composite indices by using the same symbol in all the columns belonging to the index. The columns will appear in the index in the order they are declared.
property :last_name, String, :index => :name
property :first_name, String, :index => :name
# => index on (last_name, first_name)
If you want to make the indices unique, use :unique_index
instead of :index
Inferred Validations
If you require the dm-validations plugin, auto-validations will automatically be mixed-in in to your model classes: validation rules that are inferred when properties are declared with specific column restrictions.
class Post
include DataMapper::Resource
property :title, String, :length => 250
# => infers 'validates_length :title,
:minimum => 0, :maximum => 250'
property :title, String, :required => true
# => infers 'validates_present :title
property :email, String, :format => :email_address
# => infers 'validates_format :email, :with => :email_address
property :title, String, :length => 255, :required => true
# => infers both 'validates_length' as well as
# 'validates_present'
# better: property :title, String, :length => 1..255
end
This functionality is available with the dm-validations gem, part of the dm-more bundle. For more information about validations, check the documentation for dm-validations.
Default Values
To set a default for a property, use the :default
key. The property will be set to the value associated with that key the first time it is accessed, or when the resource is saved if it hasn’t been set with another value already. This value can be a static value, such as ‘hello’ but it can also be a proc that will be evaluated when the property is read before its value has been set. The property is set to the return of the proc. The proc is passed two values, the resource the property is being set for and the property itself.
property :display_name, String, :default => { |resource, property| resource.login }
Word of warning. Don’t try to read the value of the property you’re setting the default for in the proc. An infinite loop will ensue.
Embedded Values
As an alternative to extraneous has_one relationships, consider using an EmbeddedValue.
Property options reference
:accessor if false, neither reader nor writer methods are
created for this property
:reader if false, reader method is not created for this property
:writer if false, writer method is not created for this property
:lazy if true, property value is only loaded when on first read
if false, property value is always loaded
if a symbol, property value is loaded with other properties
in the same group
:default default value of this property
:allow_nil if true, property may have a nil value on save
:key name of the key associated with this property.
:serial if true, field value is auto incrementing
:field field in the data-store which the property corresponds to
:length string field length
:format format for autovalidation. Use with dm-validations plugin.
:index if true, index is created for the property. If a Symbol, index
is named after Symbol value instead of being based on property name.
:unique_index true specifies that index on this property should be unique
:auto_validation if true, automatic validation is performed on the property
:validates validation context. Use together with dm-validations.
:unique if true, property column is unique. Properties of type Serial
are unique by default.
:precision Indicates the number of significant digits. Usually only makes sense
for float type properties. Must be >= scale option value. Default is 10.
:scale The number of significant digits to the right of the decimal point.
Only makes sense for float type properties. Must be > 0.
Default is nil for Float type and 10 for BigDecimal
All other keys you pass to +property+ method are stored and available
as options[:extra_keys].
Misc. Notes
-
Properties declared as strings will default to a length of 50, rather than 255 (typical max varchar column size). To overload the default, pass
:length => 255
or:length => 0..255
. Since DataMapper does not introspect for properties, this means that legacy database tables may need theirString
columns defined with a:length
so that DM does not apply an un-needed length validation, or allow overflow. -
You may declare a Property with the data-type of
Class
. see SingleTableInheritance for more on how to useClass
columns.
Direct Known Subclasses
Defined Under Namespace
Modules: Lookup, PassThroughLoadDump, Typecast Classes: Binary, Boolean, Class, Date, DateTime, Decimal, Discriminator, Float, Integer, Numeric, Object, Serial, String, Text, Time
Constant Summary collapse
- PRIMITIVES =
[ TrueClass, ::String, ::Float, ::Integer, ::BigDecimal, ::DateTime, ::Date, ::Time, ::Class ].to_set.freeze
- OPTIONS =
[ :accessor, :reader, :writer, :lazy, :default, :key, :field, :index, :unique_index, :unique, :allow_nil, :allow_blank, :required ]
- VISIBILITY_OPTIONS =
Possible :visibility option values
[ :public, :protected, :private ].to_set.freeze
Instance Attribute Summary collapse
-
#allow_blank ⇒ Object
readonly
Returns the value of attribute allow_blank.
-
#allow_nil ⇒ Object
readonly
Returns the value of attribute allow_nil.
-
#default ⇒ Object
readonly
Returns the value of attribute default.
-
#instance_variable_name ⇒ Object
readonly
Returns the value of attribute instance_variable_name.
-
#model ⇒ Object
readonly
Returns the value of attribute model.
-
#name ⇒ Object
readonly
Returns the value of attribute name.
-
#options ⇒ Object
readonly
Returns the value of attribute options.
-
#primitive ⇒ Object
readonly
Returns the value of attribute primitive.
-
#reader_visibility ⇒ Object
readonly
Returns the value of attribute reader_visibility.
-
#repository_name ⇒ Object
readonly
Returns the value of attribute repository_name.
-
#required ⇒ Object
readonly
Returns the value of attribute required.
-
#type ⇒ Object
readonly
Returns the value of attribute type.
-
#writer_visibility ⇒ Object
readonly
Returns the value of attribute writer_visibility.
Class Method Summary collapse
- .accept_options(*args) ⇒ Object
- .accepted_options ⇒ Object
- .descendants ⇒ Object
- .determine_class(type) ⇒ Object
- .find_class(name) ⇒ Object
- .inherited(descendant) ⇒ Object private
- .nullable(*args) ⇒ Object private
-
.options ⇒ Hash
Gives all the options set on this type.
Instance Method Summary collapse
-
#allow_blank? ⇒ Boolean
Returns whether or not the property can be a blank value.
-
#allow_nil? ⇒ Boolean
Returns whether or not the property can accept ‘nil’ as it’s value.
-
#bind ⇒ Object
A hook to allow types to extend or modify property it’s bound to.
-
#custom? ⇒ Boolean
Returns whether or not the property is custom (not provided by dm-core).
-
#field(repository_name = Undefined) ⇒ String
Supplies the field in the data-store which the property corresponds to.
-
#get(resource) ⇒ Object
private
Standardized reader method for the property.
-
#get!(resource) ⇒ Object
private
Fetch the ivar value in the resource.
-
#hash ⇒ Integer
Returns the hash of the property name.
-
#index ⇒ Boolean, ...
Returns index name if property has index.
-
#inspect ⇒ String
Returns a concise string representation of the property instance.
-
#key? ⇒ Boolean
Returns whether or not the property is a key or a part of a key.
-
#lazy? ⇒ Boolean
Returns whether or not the property is to be lazy-loaded.
-
#lazy_load(resource) ⇒ Object
private
Loads lazy columns when get or set is called.
- #lazy_load_properties ⇒ Object private
-
#loaded?(resource) ⇒ Boolean
private
Check if the attribute corresponding to the property is loaded.
-
#primitive?(value) ⇒ Boolean
Test a value to see if it matches the primitive type.
- #properties ⇒ Object private
-
#required? ⇒ Boolean
Returns whether or not the property must be non-nil and non-blank.
-
#serial? ⇒ Boolean
Returns whether or not the property is “serial” (auto-incrementing).
-
#set(resource, value) ⇒ Object
private
Provides a standardized setter method for the property.
-
#set!(resource, value) ⇒ Object
private
Set the ivar value in the resource.
- #typecast(value) ⇒ Object
-
#unique? ⇒ Boolean
Returns true if property is unique.
-
#unique_index ⇒ Boolean, ...
Returns true if property has unique index.
-
#valid?(value, negated = false) ⇒ Boolean
Test the value to see if it is a valid value for this Property.
Methods included from Chainable
Methods included from Deprecate
Methods included from Equalizer
Methods included from Subject
Methods included from Assertions
Instance Attribute Details
#allow_blank ⇒ Object (readonly)
Returns the value of attribute allow_blank.
352 353 354 |
# File 'lib/dm-core/property.rb', line 352 def allow_blank @allow_blank end |
#allow_nil ⇒ Object (readonly)
Returns the value of attribute allow_nil.
352 353 354 |
# File 'lib/dm-core/property.rb', line 352 def allow_nil @allow_nil end |
#default ⇒ Object (readonly)
Returns the value of attribute default.
352 353 354 |
# File 'lib/dm-core/property.rb', line 352 def default @default end |
#instance_variable_name ⇒ Object (readonly)
Returns the value of attribute instance_variable_name.
352 353 354 |
# File 'lib/dm-core/property.rb', line 352 def instance_variable_name @instance_variable_name end |
#model ⇒ Object (readonly)
Returns the value of attribute model.
352 353 354 |
# File 'lib/dm-core/property.rb', line 352 def model @model end |
#name ⇒ Object (readonly)
Returns the value of attribute name.
352 353 354 |
# File 'lib/dm-core/property.rb', line 352 def name @name end |
#options ⇒ Object (readonly)
Returns the value of attribute options.
352 353 354 |
# File 'lib/dm-core/property.rb', line 352 def @options end |
#primitive ⇒ Object (readonly)
Returns the value of attribute primitive.
352 353 354 |
# File 'lib/dm-core/property.rb', line 352 def primitive @primitive end |
#reader_visibility ⇒ Object (readonly)
Returns the value of attribute reader_visibility.
352 353 354 |
# File 'lib/dm-core/property.rb', line 352 def reader_visibility @reader_visibility end |
#repository_name ⇒ Object (readonly)
Returns the value of attribute repository_name.
352 353 354 |
# File 'lib/dm-core/property.rb', line 352 def repository_name @repository_name end |
#required ⇒ Object (readonly)
Returns the value of attribute required.
352 353 354 |
# File 'lib/dm-core/property.rb', line 352 def required @required end |
#type ⇒ Object (readonly)
Returns the value of attribute type.
352 353 354 |
# File 'lib/dm-core/property.rb', line 352 def type @type end |
#writer_visibility ⇒ Object (readonly)
Returns the value of attribute writer_visibility.
352 353 354 |
# File 'lib/dm-core/property.rb', line 352 def writer_visibility @writer_visibility end |
Class Method Details
.accept_options(*args) ⇒ Object
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 |
# File 'lib/dm-core/property.rb', line 412 def (*args) .concat(args) # create methods for each new option args.each do |property_option| class_eval <<-RUBY, __FILE__, __LINE__ + 1 def self.#{property_option}(value = Undefined) # def self.unique(value = Undefined) return @#{property_option} if value.equal?(Undefined) # return @unique if value.equal?(Undefined) descendants.each do |descendant| # descendants.each do |descendant| descendant.#{property_option}(value) # descendant.unique(value) end # end @#{property_option} = value # @unique = value end # end RUBY end descendants.each { |descendant| descendant..concat(args) } end |
.accepted_options ⇒ Object
407 408 409 |
# File 'lib/dm-core/property.rb', line 407 def @accepted_options ||= [] end |
.descendants ⇒ Object
391 392 393 |
# File 'lib/dm-core/property.rb', line 391 def descendants @descendants ||= DescendantSet.new end |
.determine_class(type) ⇒ Object
362 363 364 365 366 367 368 369 370 371 372 373 374 375 |
# File 'lib/dm-core/property.rb', line 362 def determine_class(type) if type < DataMapper::Property::Object return type end name = DataMapper::Inflector.demodulize(type.name) klass = find_class(name) if !klass && type < DataMapper::Type klass = find_class(type.primitive.name) end klass end |
.find_class(name) ⇒ Object
378 379 380 381 382 383 384 385 386 387 388 |
# File 'lib/dm-core/property.rb', line 378 def find_class(name) klass = descendants.detect do |descendant| DataMapper::Inflector.demodulize(descendant.name) == name end if !klass && const_defined?(name) klass = const_get(name) end klass end |
.inherited(descendant) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
396 397 398 399 400 401 402 403 404 |
# File 'lib/dm-core/property.rb', line 396 def inherited(descendant) descendants << descendant # inherit accepted options descendant..concat() # inherit the option values .each { |key, value| descendant.send(key, value) } end |
.nullable(*args) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
432 433 434 435 436 |
# File 'lib/dm-core/property.rb', line 432 def nullable(*args) # :required is preferable to :allow_nil, but :nullable maps precisely to :allow_nil warn "#nullable is deprecated, use #required instead (#{caller[0]})" allow_nil(*args) end |
.options ⇒ Hash
Gives all the options set on this type
443 444 445 446 447 448 449 450 |
# File 'lib/dm-core/property.rb', line 443 def = {} .each do |method| value = send(method) [method] = send(method) unless value.nil? end end |
Instance Method Details
#allow_blank? ⇒ Boolean
Returns whether or not the property can be a blank value
591 592 593 |
# File 'lib/dm-core/property.rb', line 591 def allow_blank? @allow_blank end |
#allow_nil? ⇒ Boolean
Returns whether or not the property can accept ‘nil’ as it’s value
581 582 583 |
# File 'lib/dm-core/property.rb', line 581 def allow_nil? @allow_nil end |
#bind ⇒ Object
A hook to allow types to extend or modify property it’s bound to. Implementations are not supposed to modify the state of the type class, and should produce no side-effects on the type class.
458 459 460 |
# File 'lib/dm-core/property.rb', line 458 def bind # no op end |
#custom? ⇒ Boolean
Returns whether or not the property is custom (not provided by dm-core)
601 602 603 |
# File 'lib/dm-core/property.rb', line 601 def custom? @custom end |
#field(repository_name = Undefined) ⇒ String
Supplies the field in the data-store which the property corresponds to
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 |
# File 'lib/dm-core/property.rb', line 467 def field(repository_name = Undefined) self_repository_name = self.repository_name klass = self.class unless repository_name.equal?(Undefined) warn "Passing in +repository_name+ to #{klass}#field is deprecated (#{caller[0]})" if repository_name != self_repository_name raise ArgumentError, "Mismatching +repository_name+ with #{klass}#repository_name (#{repository_name.inspect} != #{self_repository_name.inspect})" end end # defer setting the field with the adapter specific naming # conventions until after the adapter has been setup @field ||= model.field_naming_convention(self_repository_name).call(self).freeze end |
#get(resource) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Standardized reader method for the property
616 617 618 |
# File 'lib/dm-core/property.rb', line 616 def get(resource) get!(resource) end |
#get!(resource) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Fetch the ivar value in the resource
629 630 631 |
# File 'lib/dm-core/property.rb', line 629 def get!(resource) resource.instance_variable_get(instance_variable_name) end |
#hash ⇒ Integer
Returns the hash of the property name
This is necessary to allow comparisons between different properties in different models, having the same base model
504 505 506 |
# File 'lib/dm-core/property.rb', line 504 def hash name.hash end |
#index ⇒ Boolean, ...
Returns index name if property has index.
517 518 519 |
# File 'lib/dm-core/property.rb', line 517 def index @index end |
#inspect ⇒ String
Returns a concise string representation of the property instance.
739 740 741 |
# File 'lib/dm-core/property.rb', line 739 def inspect "#<#{self.class.name} @model=#{model.inspect} @name=#{name.inspect}>" end |
#key? ⇒ Boolean
Returns whether or not the property is a key or a part of a key
551 552 553 |
# File 'lib/dm-core/property.rb', line 551 def key? @key end |
#lazy? ⇒ Boolean
Returns whether or not the property is to be lazy-loaded
541 542 543 |
# File 'lib/dm-core/property.rb', line 541 def lazy? @lazy end |
#lazy_load(resource) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Loads lazy columns when get or set is called.
684 685 686 687 |
# File 'lib/dm-core/property.rb', line 684 def lazy_load(resource) return if loaded?(resource) resource.__send__(:lazy_load, lazy_load_properties) end |
#lazy_load_properties ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
690 691 692 693 694 695 696 |
# File 'lib/dm-core/property.rb', line 690 def lazy_load_properties @lazy_load_properties ||= begin properties = self.properties properties.in_context(lazy? ? [ self ] : properties.defaults) end end |
#loaded?(resource) ⇒ Boolean
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Check if the attribute corresponding to the property is loaded
674 675 676 |
# File 'lib/dm-core/property.rb', line 674 def loaded?(resource) resource.instance_variable_defined?(instance_variable_name) end |
#primitive?(value) ⇒ Boolean
Test a value to see if it matches the primitive type
752 753 754 |
# File 'lib/dm-core/property.rb', line 752 def primitive?(value) value.kind_of?(primitive) end |
#properties ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
699 700 701 |
# File 'lib/dm-core/property.rb', line 699 def properties @properties ||= model.properties(repository_name) end |
#required? ⇒ Boolean
Returns whether or not the property must be non-nil and non-blank
571 572 573 |
# File 'lib/dm-core/property.rb', line 571 def required? @required end |
#serial? ⇒ Boolean
Returns whether or not the property is “serial” (auto-incrementing)
561 562 563 |
# File 'lib/dm-core/property.rb', line 561 def serial? @serial end |
#set(resource, value) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Provides a standardized setter method for the property
646 647 648 |
# File 'lib/dm-core/property.rb', line 646 def set(resource, value) set!(resource, typecast(value)) end |
#set!(resource, value) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Set the ivar value in the resource
661 662 663 |
# File 'lib/dm-core/property.rb', line 661 def set!(resource, value) resource.instance_variable_set(instance_variable_name, value) end |
#typecast(value) ⇒ Object
704 705 706 707 708 709 710 711 712 |
# File 'lib/dm-core/property.rb', line 704 def typecast(value) if @type && @type.respond_to?(:typecast) @type.typecast(value, self) elsif value.nil? || primitive?(value) value elsif respond_to?(:typecast_to_primitive) typecast_to_primitive(value) end end |
#unique? ⇒ Boolean
Returns true if property is unique. Serial properties and keys are unique by default.
491 492 493 |
# File 'lib/dm-core/property.rb', line 491 def unique? !!@unique end |
#unique_index ⇒ Boolean, ...
Returns true if property has unique index. Serial properties and keys are unique by default.
531 532 533 |
# File 'lib/dm-core/property.rb', line 531 def unique_index @unique_index end |
#valid?(value, negated = false) ⇒ Boolean
Test the value to see if it is a valid value for this Property
723 724 725 726 727 728 729 730 731 |
# File 'lib/dm-core/property.rb', line 723 def valid?(value, negated = false) dumped_value = dump(value) if required? && dumped_value.nil? negated || false else primitive?(dumped_value) || (dumped_value.nil? && (allow_nil? || negated)) end end |