Class: Vets::Attributes::Value

Inherits:
Object
  • Object
show all
Defined in:
lib/vets/attributes/value.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, klass, array: false) ⇒ Value

Returns a new instance of Value.



10
11
12
13
14
# File 'lib/vets/attributes/value.rb', line 10

def initialize(name, klass, array: false)
  @name = name
  @klass = klass
  @array = array
end

Class Method Details

.cast(name, klass, value, array: false) ⇒ Object



6
7
8
# File 'lib/vets/attributes/value.rb', line 6

def self.cast(name, klass, value, array: false)
  new(name, klass, array:).setter_value(value)
end

Instance Method Details

#cast_boolean(value) ⇒ Object (private)



38
39
40
# File 'lib/vets/attributes/value.rb', line 38

def cast_boolean(value)
  ActiveModel::Type::Boolean.new.cast(value)
end

#coerce_to_class(value) ⇒ Object (private)



42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/vets/attributes/value.rb', line 42

def coerce_to_class(value)
  return value if value.is_a?(@klass) || value.nil?

  if @klass == DateTime
    begin
      value = DateTime.parse(value) if value.is_a?(String)
    rescue ArgumentError
      raise TypeError, "#{@name} could not be parsed into a DateTime"
    end
  end

  value.is_a?(Hash) ? @klass.new(value) : value
end

#setter_value(value) ⇒ Object



16
17
18
19
20
21
22
# File 'lib/vets/attributes/value.rb', line 16

def setter_value(value)
  validate_array(value) if @array
  value = cast_boolean(value) if @klass == Bool
  value = coerce_to_class(value)
  validate_type(value)
  value
end

#validate_array(value) ⇒ Object (private)

Raises:

  • (TypeError)


26
27
28
29
30
31
32
33
34
35
36
# File 'lib/vets/attributes/value.rb', line 26

def validate_array(value)
  raise TypeError, "#{@name} must be an Array" unless value.is_a?(Array)

  value.map! do |item|
    item.is_a?(Hash) ? @klass.new(item) : item
  end

  unless value.all? { |item| item.is_a?(@klass) }
    raise TypeError, "All elements of #{@name} must be of type #{@klass}"
  end
end

#validate_type(value) ⇒ Object (private)

Raises:

  • (TypeError)


56
57
58
59
60
# File 'lib/vets/attributes/value.rb', line 56

def validate_type(value)
  return if (@array && value.is_a?(Array)) || value.is_a?(@klass) || value.nil?

  raise TypeError, "#{@name} must be a #{@klass}"
end