Class: Ripple::Property

Inherits:
Object show all
Defined in:
lib/ripple/properties.rb

Overview

Encapsulates a single property on your Ripple::Document class.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key, type, options = {}) ⇒ Property

Create a new document property.

Parameters:

  • key (String, Symbol)

    the key of the property

  • type (Class)

    the Ruby type of the property. Use Boolean for true or false types.

  • options (Hash) (defaults to: {})

    configuration options

Options Hash (options):

  • :default (Object, Proc) — default: nil

    a default value for the property, or a lambda to evaluate when providing the default.



42
43
44
45
46
# File 'lib/ripple/properties.rb', line 42

def initialize(key, type, options={})
  @options = options.to_options
  @key = key.to_sym
  @type = type
end

Instance Attribute Details

#keySymbol (readonly)

Returns the key of this property in the Document.

Returns:

  • (Symbol)

    the key of this property in the Document



30
31
32
# File 'lib/ripple/properties.rb', line 30

def key
  @key
end

#optionsHash (readonly)

Returns configuration options.

Returns:

  • (Hash)

    configuration options



34
35
36
# File 'lib/ripple/properties.rb', line 34

def options
  @options
end

#typeClass (readonly)

Returns the Ruby type of property.

Returns:

  • (Class)

    the Ruby type of property.



32
33
34
# File 'lib/ripple/properties.rb', line 32

def type
  @type
end

Instance Method Details

#defaultObject

Returns The default value for this property if defined, or nil.

Returns:

  • (Object)

    The default value for this property if defined, or nil.



49
50
51
52
53
54
55
# File 'lib/ripple/properties.rb', line 49

def default
  default = options[:default]
  default = default.dup if default.duplicable?

  return nil if default.nil?
  type_cast(default.respond_to?(:call) ? default.call : default)
end

#type_cast(value) ⇒ Object

Attempt to coerce the passed value into this property’s type

Parameters:

  • value (Object)

    the value to coerce

Returns:

  • (Object)

    the value coerced into this property’s type

Raises:



66
67
68
69
70
71
72
# File 'lib/ripple/properties.rb', line 66

def type_cast(value)
  if @type.respond_to?(:ripple_cast)
    @type.ripple_cast(value)
  else
    value
  end
end

#validation_optionsHash

Returns options appropriate for the validates class method.

Returns:

  • (Hash)

    options appropriate for the validates class method



58
59
60
# File 'lib/ripple/properties.rb', line 58

def validation_options
  @options.dup.except(:default)
end