Module: SmartProperties::ClassMethods

Defined in:
lib/smart_properties.rb

Instance Method Summary collapse

Instance Method Details

#propertiesHash<String, Property>

Returns a class’s smart properties. This includes the properties that have been defined in the parent classes.

Returns:

  • (Hash<String, Property>)

    A map of property names to property instances.



31
32
33
# File 'lib/smart_properties.rb', line 31

def properties
  @_smart_properties ||= PropertyCollection.for(self)
end

#property(name, **options) ⇒ Property (protected)

Defines a new property from a name and a set of options. This results results in creating an accessor that has additional features:

  1. Validation of input data by specifiying the :accepts option: If you use a class as value for this option, the setter will check if the value it is about to assign is of this type. If you use an array, the setter will check if the value it is about to assign is included in this array. Finally, if you specify a block, it will invoke the block with the value it is about to assign and check if the block returns a thruthy value, meaning anything but false and nil.

  2. Conversion of input data by specifiying the :converts option: If you use provide a symbol as value for this option, the setter will invoke this method on the object it is about to assign and take the result of this call instead. If you provide a block, it will invoke the block with the value it is about to assign and take the result of the block instead.

  3. Providing a default value by specifiying the :default option.

  4. Forcing a property to be present by setting the :required option to true.

Examples:

Definition of a property that makes use of all SmartProperties features.


property :language_code, :accepts => [:de, :en],
                         :converts => :to_sym,
                         :default  => :de,
                         :required => true

Parameters:

  • name (Symbol)

    the name of the property

  • options (Hash)

    the list of options used to configure the property

Options Hash (**options):

  • :accepts (Array, Class, Proc)

    specifies how the validation is done

  • :converts (Proc, Symbol)

    specifies how the conversion is done

  • :default (Object)

    specifies the default value of the property

  • :required (true, false)

    specifies whether or not this property is required

Returns:



82
83
84
# File 'lib/smart_properties.rb', line 82

def property(name, **options)
  properties[name] = Property.define(self, name, **options)
end

#property!(name, **options) ⇒ Object (protected)



87
88
89
90
# File 'lib/smart_properties.rb', line 87

def property!(name, **options)
  options[:required] = true
  property(name, **options)
end