Class: BCDD::Value::Properties

Inherits:
Object
  • Object
show all
Defined in:
lib/bcdd/ext/value.rb

Defined Under Namespace

Modules: Contract

Constant Summary collapse

Default =
->(options) do
  value = options[:default]

  return value unless value.is_a?(Proc)
  return value if value.lambda? && value.arity.zero?

  raise ArgumentError, 'Default value must be a lambda with zero arity'
end
Normalize =
->(options) do
  value = options[:normalize]

  return value if value.is_a?(Proc)

  raise ArgumentError, 'normalize value must be a lambda'
end
Type =
->(options) do
  type = options[:type]

  return type if type.is_a?(::Module)

  raise ArgumentError, 'type must be a Module or a Class'
end

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ Properties

Returns a new instance of Properties.



68
69
70
71
72
73
74
75
76
77
78
# File 'lib/bcdd/ext/value.rb', line 68

def initialize(options)
  @contract = false

  contract = Contract[options]

  @spec = {}
  @spec[:type] = Type[options] if options.key?(:type)
  @spec[:default] = Default[options] if options.key?(:default)
  @spec[:contract] = contract if contract
  @spec[:normalize] = Normalize[options] if options.key?(:normalize)
end

Instance Attribute Details

#contractObject (readonly)

Returns the value of attribute contract.



66
67
68
# File 'lib/bcdd/ext/value.rb', line 66

def contract
  @contract
end

#specObject (readonly)

Returns the value of attribute spec.



66
67
68
# File 'lib/bcdd/ext/value.rb', line 66

def spec
  @spec
end

Instance Method Details

#contract?Boolean

Returns:

  • (Boolean)


88
89
90
# File 'lib/bcdd/ext/value.rb', line 88

def contract?
  contract
end

#freezeObject



80
81
82
83
84
85
86
# File 'lib/bcdd/ext/value.rb', line 80

def freeze
  @contract = spec.key?(:contract)

  spec.freeze

  super
end

#map(value) ⇒ Object



92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/bcdd/ext/value.rb', line 92

def map(value)
  if !value && spec.key?(:default)
    default = spec[:default]

    value = default.is_a?(::Proc) ? default.call : default
  end

  type = spec[:type]

  value = spec[:normalize].call(value) if spec.key?(:normalize) && (!type || type === value)

  spec.key?(:contract) ? spec[:contract][value] : Contract.null(value)
end