Class: Mozaik::Service::AttributeValue

Inherits:
Object
  • Object
show all
Defined in:
lib/mozaik/service/attribute_value.rb

Constant Summary collapse

AttributeBlank =
Class.new(StandardError)
AttributeWithWrongType =
Class.new(StandardError)

Instance Method Summary collapse

Constructor Details

#initialize(value, options) ⇒ AttributeValue

Returns a new instance of AttributeValue.



9
10
11
12
# File 'lib/mozaik/service/attribute_value.rb', line 9

def initialize(value, options)
  @value = value
  @options = options
end

Instance Method Details

#callObject



14
15
16
17
18
19
20
21
22
# File 'lib/mozaik/service/attribute_value.rb', line 14

def call
  value = @value
  value = @options[:default] if value.nil? && @options.key?(:default)
  type[value]
rescue Dry::Types::CoercionError, Dry::Types::MissingKeyError, Dry::Types::SchemaError
  raise AttributeBlank if @value.nil? && @options[:required]

  raise AttributeWithWrongType
end

#determine_type(type) ⇒ Object



32
33
34
35
36
37
38
39
40
41
# File 'lib/mozaik/service/attribute_value.rb', line 32

def determine_type(type)
  case type
  when Dry::Types::Type
    type
  when Array
    Types::Array(determine_type(type.first))
  else
    Types.Instance(type)
  end
end

#typeObject



24
25
26
27
28
29
30
# File 'lib/mozaik/service/attribute_value.rb', line 24

def type
  return @type if @type

  @type = determine_type(@options[:type])
  @type = @type.optional unless @options[:required]
  @type
end