Class: Ardm::Property

Inherits:
Object
  • Object
show all
Extended by:
Equalizer
Includes:
Assertions, Subject
Defined in:
lib/ardm/property.rb,
lib/ardm/property.rb,
lib/ardm/property/csv.rb,
lib/ardm/property/uri.rb,
lib/ardm/property/date.rb,
lib/ardm/property/enum.rb,
lib/ardm/property/flag.rb,
lib/ardm/property/json.rb,
lib/ardm/property/slug.rb,
lib/ardm/property/text.rb,
lib/ardm/property/time.rb,
lib/ardm/property/uuid.rb,
lib/ardm/property/yaml.rb,
lib/ardm/property/class.rb,
lib/ardm/property/float.rb,
lib/ardm/property/binary.rb,
lib/ardm/property/lookup.rb,
lib/ardm/property/object.rb,
lib/ardm/property/regexp.rb,
lib/ardm/property/serial.rb,
lib/ardm/property/string.rb,
lib/ardm/property/api_key.rb,
lib/ardm/property/boolean.rb,
lib/ardm/property/decimal.rb,
lib/ardm/property/integer.rb,
lib/ardm/property/numeric.rb,
lib/ardm/property/datetime.rb,
lib/ardm/property/file_path.rb,
lib/ardm/property/epoch_time.rb,
lib/ardm/property/ip_address.rb,
lib/ardm/property/validation.rb,
lib/ardm/property/bcrypt_hash.rb,
lib/ardm/property/discriminator.rb,
lib/ardm/property/support/flags.rb,
lib/ardm/property/paranoid_boolean.rb,
lib/ardm/property/paranoid_datetime.rb,
lib/ardm/property/invalid_value_error.rb,
lib/ardm/property/comma_separated_list.rb,
lib/ardm/property/support/dirty_minder.rb,
lib/ardm/property/support/paranoid_base.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 database.

If you are coming to Ardm 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 Ardm only cares about properties explicitly defined in your models, Ardm 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 < ActiveRecord::Base
  property :title,   String,  :required => true  # Cannot be null
  property :publish, Boolean, :default => false  # Default value for new records is false
end

By default, Ardm supports the following primitive (Ruby) types also called core properties:

  • Boolean

  • Class (datastore primitive is the same as String. Used for Inheritance)

  • Date

  • DateTime

  • Decimal

  • Float

  • Integer

  • Object (marshalled out during serialization)

  • String (default length is 50)

  • Text (limit of 65k characters by default)

  • Time

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 < ActiveRecord::Base
  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 < ActiveRecord::Base
  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 < ActiveRecord::Base
  property :title, String

  def title=(new_title)
    raise ArgumentError if new_title != 'Lee is l337'
    super(new_title)
  end
end

Calling super ensures that any validators defined for the property are kept active.

Lazy Loading

By default, some properties are not loaded when an object is fetched in Ardm. 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, Ardm::Property::Text fields are lazy loading by default, although you can over-ride this behavior if you wish:

Example:

class Post < ActiveRecord::Base
  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 multiple lazy properties to be loaded at one time. If you set :lazy to true, it is placed in the :default context

class Post < ActiveRecord::Base
  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, Ardm 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 Ardm 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 < ActiveRecord::Base
  property :title, String, :length => 250, :min => 0, :max => 250
  # => infers 'validates_length :title'

  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. 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 => lambda { |resource, property| resource. }

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 (not implemented yet)

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.

: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

Overriding default Property options

There is the ability to reconfigure a Property and it’s subclasses by explicitly setting a value in the Property, eg:

# set all String properties to have a default length of 255
Ardm::Property::String.length(255)

# set all Boolean properties to not allow nil (force true or false)
Ardm::Property::Boolean.allow_nil(false)

# set all properties to be required by default
Ardm::Property.required(true)

# turn off auto-validation for all properties by default
Ardm::Property.auto_validation(false)

# set all mutator methods to be private by default
Ardm::Property.writer(:private)

Please note that this has no effect when a subclass has explicitly defined it’s own option. For example, setting the String length to 255 will not affect the Text property even though it inherits from String, because it sets it’s own default length to 65535.

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 Ardm does not introspect for properties, this means that legacy database tables may need their String 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 use Class columns.

Direct Known Subclasses

Object

Defined Under Namespace

Modules: DirtyMinder, Flags, Lookup, ParanoidBase, Undefined, Validation Classes: APIKey, BCryptHash, Binary, Boolean, Class, CommaSeparatedList, Csv, Date, DateTime, Decimal, Discriminator, Enum, EpochTime, FilePath, Flag, Float, IPAddress, Integer, InvalidValueError, Json, Numeric, Object, ParanoidBoolean, ParanoidDateTime, Regexp, Serial, Slug, String, Text, Time, URI, UUID, Yaml

Constant Summary collapse

PRIMITIVES =
[
  TrueClass,
  ::String,
  ::Float,
  ::Integer,
  ::BigDecimal,
  ::DateTime,
  ::Date,
  ::Time,
  ::Class
].to_set.freeze
OPTIONS =
[
  :load_as, :dump_as, :coercion_method,
  :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
INVALID_NAMES =

Invalid property names

%w[
JSON =

class Json

Json
Infinity =
1.0/0

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Equalizer

equalize

Methods included from Subject

#default?, #default_for

Methods included from Assertions

#assert_kind_of

Instance Attribute Details

#allow_blankObject (readonly)

::ActiveRecord::Base.private_instance_methods ).map { |name| name.to_s }



352
353
354
# File 'lib/ardm/property.rb', line 352

def allow_blank
  @allow_blank
end

#allow_nilObject (readonly)

::ActiveRecord::Base.private_instance_methods ).map { |name| name.to_s }



352
353
354
# File 'lib/ardm/property.rb', line 352

def allow_nil
  @allow_nil
end

#coercion_methodObject (readonly)

::ActiveRecord::Base.private_instance_methods ).map { |name| name.to_s }



352
353
354
# File 'lib/ardm/property.rb', line 352

def coercion_method
  @coercion_method
end

#defaultObject (readonly)

::ActiveRecord::Base.private_instance_methods ).map { |name| name.to_s }



352
353
354
# File 'lib/ardm/property.rb', line 352

def default
  @default
end

#dump_asObject (readonly) Also known as: dump_class

::ActiveRecord::Base.private_instance_methods ).map { |name| name.to_s }



352
353
354
# File 'lib/ardm/property.rb', line 352

def dump_as
  @dump_as
end

#indexBoolean, ... (readonly)

Returns index name if property has index.

Returns:

  • (Boolean, Symbol, Array)

    returns true if property is indexed by itself returns a Symbol if the property is indexed with other properties returns an Array if the property belongs to multiple indexes returns false if the property does not belong to any indexes



508
509
510
# File 'lib/ardm/property.rb', line 508

def index
  @index
end

#instance_variable_nameObject (readonly)

::ActiveRecord::Base.private_instance_methods ).map { |name| name.to_s }



352
353
354
# File 'lib/ardm/property.rb', line 352

def instance_variable_name
  @instance_variable_name
end

#load_asObject (readonly) Also known as: load_class

::ActiveRecord::Base.private_instance_methods ).map { |name| name.to_s }



352
353
354
# File 'lib/ardm/property.rb', line 352

def load_as
  @load_as
end

#modelObject (readonly)

::ActiveRecord::Base.private_instance_methods ).map { |name| name.to_s }



352
353
354
# File 'lib/ardm/property.rb', line 352

def model
  @model
end

#nameObject (readonly)

::ActiveRecord::Base.private_instance_methods ).map { |name| name.to_s }



352
353
354
# File 'lib/ardm/property.rb', line 352

def name
  @name
end

#optionsObject (readonly)

::ActiveRecord::Base.private_instance_methods ).map { |name| name.to_s }



352
353
354
# File 'lib/ardm/property.rb', line 352

def options
  @options
end

#reader_visibilityObject (readonly)

::ActiveRecord::Base.private_instance_methods ).map { |name| name.to_s }



352
353
354
# File 'lib/ardm/property.rb', line 352

def reader_visibility
  @reader_visibility
end

#requiredObject (readonly)

::ActiveRecord::Base.private_instance_methods ).map { |name| name.to_s }



352
353
354
# File 'lib/ardm/property.rb', line 352

def required
  @required
end

#unique_indexBoolean, ... (readonly)

Returns true if property has unique index. Serial properties and keys are unique by default.

Returns:

  • (Boolean, Symbol, Array)

    returns true if property is indexed by itself returns a Symbol if the property is indexed with other properties returns an Array if the property belongs to multiple indexes returns false if the property does not belong to any indexes



520
521
522
# File 'lib/ardm/property.rb', line 520

def unique_index
  @unique_index
end

#writer_visibilityObject (readonly)

::ActiveRecord::Base.private_instance_methods ).map { |name| name.to_s }



352
353
354
# File 'lib/ardm/property.rb', line 352

def writer_visibility
  @writer_visibility
end

Class Method Details

.accept_options(*args) ⇒ Object



427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
# File 'lib/ardm/property.rb', line 427

def accept_options(*args)
  accepted_options.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|
          unless descendant.instance_variable_defined?(:@#{property_option}) #     unless descendant.instance_variable_defined?(:@unique)
            descendant.#{property_option}(value)                             #       descendant.unique(value)
          end                                                                #     end
        end                                                                  #   end
        @#{property_option} = value                                          #   @unique = value
      end                                                                    # end
    RUBY
  end

  descendants.each { |descendant| descendant.accepted_options.concat(args) }
end

.accepted_optionsObject



422
423
424
# File 'lib/ardm/property.rb', line 422

def accepted_options
  @accepted_options ||= []
end

.demodulize(name) ⇒ Object



367
368
369
# File 'lib/ardm/property.rb', line 367

def demodulize(name)
  name.to_s.gsub(/^.*::/,'')
end

.demodulized_namesObject

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.



372
373
374
# File 'lib/ardm/property.rb', line 372

def demodulized_names
  @demodulized_names ||= {}
end

.descendantsObject



384
385
386
# File 'lib/ardm/property.rb', line 384

def descendants
  @descendants ||= DescendantSet.new
end

.determine_class(type) ⇒ Object



362
363
364
365
# File 'lib/ardm/property.rb', line 362

def determine_class(type)
  return type if type < Ardm::Property::Object
  find_class(demodulize(type.name))
end

.find_class(name) ⇒ Object



377
378
379
380
381
# File 'lib/ardm/property.rb', line 377

def find_class(name)
  klass   = demodulized_names[name]
  klass ||= const_get(name) if const_defined?(name)
  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.



389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
# File 'lib/ardm/property.rb', line 389

def inherited(descendant)
  # Descendants is a tree rooted in Ardm::Property that tracks
  # inheritance.  We pre-calculate each comparison value (demodulized
  # class name) to achieve a Hash[]-time lookup, rather than walk the
  # entire descendant tree and calculate names on-demand (expensive,
  # redundant).
  #
  # Since the algorithm relegates property class name lookups to a flat
  # namespace, we need to ensure properties defined outside of DM don't
  # override built-ins (Serial, String, etc) by merely defining a property
  # of a same name.  We avoid this by only ever adding to the lookup
  # table.  Given that DM loads its own property classes first, we can
  # assume that their names are "reserved" when added to the table.
  #
  # External property authors who want to provide "replacements" for
  # builtins (e.g. in a non-DM-supported adapter) should follow the
  # convention of wrapping those properties in a module, and include'ing
  # the module on the model class directly.  This bypasses the DM-hooked
  # const_missing lookup that would normally check this table.
  descendants << descendant

  Property.demodulized_names[demodulize(descendant.name)] ||= descendant

  # inherit accepted options
  descendant.accepted_options.concat(accepted_options)

  # inherit the option values
  options.each { |key, value| descendant.send(key, value) }

  super
end

.optionsHash

Gives all the options set on this property

Returns:

  • (Hash)

    with all options and their values set on this property



453
454
455
456
457
458
459
# File 'lib/ardm/property.rb', line 453

def options
  options = {}
  accepted_options.each do |name|
    options[name] = send(name) if instance_variable_defined?("@#{name}")
  end
  options
end

.primitive(*args) ⇒ Object



462
463
464
465
# File 'lib/ardm/property.rb', line 462

def primitive(*args)
  warn "Ardm::Property.primitive is deprecated, use .load_as instead (#{caller.first})"
  load_as(*args)
end

Instance Method Details

#allow_blank?Boolean

Returns whether or not the property can be a blank value

Returns:

  • (Boolean)

    whether or not the property can be blank



578
579
580
# File 'lib/ardm/property.rb', line 578

def allow_blank?
  @allow_blank
end

#allow_nil?Boolean

Returns whether or not the property can accept ‘nil’ as it’s value

Returns:

  • (Boolean)

    whether or not the property can accept ‘nil’



568
569
570
# File 'lib/ardm/property.rb', line 568

def allow_nil?
  @allow_nil
end

#assert_valid_value(value) ⇒ Boolean

Asserts value is valid

Parameters:

  • loaded_value (Object)

    the value to be tested

Returns:

  • (Boolean)

    true if the value is valid

Raises:



716
717
718
719
720
721
# File 'lib/ardm/property.rb', line 716

def assert_valid_value(value)
  unless valid?(value)
    raise Property::InvalidValueError.new(self,value)
  end
  true
end

#bindObject

A hook to allow properties to extend or modify the model it’s bound to. Implementations are not supposed to modify the state of the property class, and should produce no side-effects on the property instance.



473
474
475
# File 'lib/ardm/property.rb', line 473

def bind
  # no op
end

#fieldString

Supplies the field in the data-store which the property corresponds to

Returns:

  • (String)

    name of field in data-store



482
483
484
485
486
# File 'lib/ardm/property.rb', line 482

def field
  # defer setting the field with the adapter specific naming
  # conventions until after the adapter has been setup
  @field ||= model.field_naming_convention.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

Parameters:

  • resource (Resource)

    model instance for which this property is to be loaded

Returns:

  • (Object)

    the value of this property for the provided instance

Raises:

  • (ArgumentError)

    resource should be a Resource, but was .…”



593
594
595
# File 'lib/ardm/property.rb', line 593

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

Parameters:

  • resource (Resource)

    model instance for which this property is to be unsafely loaded

Returns:

  • (Object)

    current @ivar value of this property in resource



606
607
608
609
610
611
612
613
614
# File 'lib/ardm/property.rb', line 606

def get!(resource)
  #resource.instance_variable_get(instance_variable_name)
  val = resource.send :read_attribute, field
  if val.nil?
    set_default_value(resource)
  else
    val
  end
end

#inspectString

Returns a concise string representation of the property instance.

Returns:

  • (String)

    Concise string representation of the property instance.



729
730
731
# File 'lib/ardm/property.rb', line 729

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

Returns:

  • (Boolean)

    true if the property is a key or a part of a key



538
539
540
# File 'lib/ardm/property.rb', line 538

def key?
  @key
end

#lazy?Boolean

Returns whether or not the property is to be lazy-loaded

Returns:

  • (Boolean)

    true if the property is to be lazy-loaded



528
529
530
# File 'lib/ardm/property.rb', line 528

def lazy?
  @lazy
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

Parameters:

  • resource (Resource)

    model instance for which the attribute is to be tested

Returns:

  • (Boolean)

    true if the attribute is loaded in the resource



664
665
666
667
668
# File 'lib/ardm/property.rb', line 664

def loaded?(resource)
  resource.send(:read_attribute, field) != nil
  #resource.instance_variable_defined?(instance_variable_name)
  #true
end

#primitiveObject



747
748
749
750
# File 'lib/ardm/property.rb', line 747

def primitive
  warn "#primitive is deprecated, use #dump_as instead (#{caller.first})"
  dump_as
end

#primitive?(value) ⇒ Boolean

Test a value to see if it matches the primitive type

Parameters:

  • value (Object)

    value to test

Returns:

  • (Boolean)

    true if the value is the correct type



742
743
744
745
# File 'lib/ardm/property.rb', line 742

def primitive?(value)
  warn "#primitive? is deprecated, use #value_dumped? instead (#{caller.first})"
  value_dumped?(value)
end

#propertiesObject

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.



671
672
673
# File 'lib/ardm/property.rb', line 671

def properties
  @properties ||= model.properties
end

#required?Boolean

Returns whether or not the property must be non-nil and non-blank

Returns:

  • (Boolean)

    whether or not the property is required



558
559
560
# File 'lib/ardm/property.rb', line 558

def required?
  @required
end

#serial?Boolean

Returns whether or not the property is “serial” (auto-incrementing)

Returns:

  • (Boolean)

    whether or not the property is “serial”



548
549
550
# File 'lib/ardm/property.rb', line 548

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

Parameters:

  • resource (Resource)

    the resource to get the value from

  • value (Object)

    the value to set in the resource

Returns:

  • (Object)

    value after being typecasted according to this property’s primitive

Raises:

  • (ArgumentError)

    resource should be a Resource, but was .…”



634
635
636
# File 'lib/ardm/property.rb', line 634

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

Parameters:

  • resource (Resource)

    the resource to set

  • value (Object)

    the value to set in the resource

Returns:

  • (Object)

    the value set in the resource



649
650
651
652
653
# File 'lib/ardm/property.rb', line 649

def set!(resource, value)
  #resource.instance_variable_set(instance_variable_name, value)
  resource.send :write_attribute, field, value
  resource.send :read_attribute, field
end

#set_default_value(resource) ⇒ Object



616
617
618
619
# File 'lib/ardm/property.rb', line 616

def set_default_value(resource)
  return if loaded?(resource) || !default?
  set(resource, default_for(resource))
end

#typecast(value) ⇒ Object



676
677
678
679
680
681
682
683
684
685
# File 'lib/ardm/property.rb', line 676

def typecast(value)
  @coercer ||= Coercible::Coercer.new
  if Array === value
    value.map { |v| typecast(v) }
  else
    @coercer[value.class].send(coercion_method, value)
  end
rescue Coercible::UnsupportedCoercion
  value
end

#unique?Boolean

Returns true if property is unique. Serial properties and keys are unique by default.

Returns:

  • (Boolean)

    true if property has uniq index defined, false otherwise



495
496
497
# File 'lib/ardm/property.rb', line 495

def unique?
  !!@unique
end

#valid?(value, negated = false) ⇒ Boolean

Test the value to see if it is a valid value for this Property

Parameters:

  • loaded_value (Object)

    the value to be tested

Returns:

  • (Boolean)

    true if the value is valid



696
697
698
699
700
701
702
703
704
# File 'lib/ardm/property.rb', line 696

def valid?(value, negated = false)
  dumped_value = dump(value)

  if required? && dumped_value.nil?
    negated || false
  else
    value_dumped?(dumped_value) || (dumped_value.nil? && (allow_nil? || negated))
  end
end

#value_dumped?(value) ⇒ Boolean

Returns:



753
754
755
# File 'lib/ardm/property.rb', line 753

def value_dumped?(value)
  value.kind_of?(dump_as)
end

#value_loaded?(value) ⇒ Boolean

Returns:



758
759
760
# File 'lib/ardm/property.rb', line 758

def value_loaded?(value)
  value.kind_of?(load_as)
end