Class: Nova::API::Utils::BaseStruct

Inherits:
Dry::Struct
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/nova/api/utils/base_struct.rb

Constant Summary collapse

DATE_REGEX =
/\A\d{4}-\d{2}-\d{2}\z/

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.generate_valid_value_for(type) ⇒ Object



66
67
68
69
70
71
72
73
74
75
# File 'lib/nova/api/utils/base_struct.rb', line 66

def self.generate_valid_value_for(type)
  case type.name
  when Dry::Types['integer'].name, Dry::Types['float'].name, Dry::Types['decimal'].name
    0
  when Dry::Types['bool'].name
    false
  else
    nil
  end
end

.initialize_empty_model_with_id(klass, id, additional_attributes = {}) ⇒ Object



32
33
34
35
36
37
38
39
40
# File 'lib/nova/api/utils/base_struct.rb', line 32

def self.initialize_empty_model_with_id(klass, id, additional_attributes = {})
  values = Hash.new.tap do |hash|
    klass.schema.type.keys.each do |field|
      hash[field.name] = value_for_field(additional_attributes[field.name], field)
    end
  end

  klass.new(values.merge(id: id))
end

.value_for_field(override_value, field) ⇒ Object



58
59
60
61
62
63
64
# File 'lib/nova/api/utils/base_struct.rb', line 58

def self.value_for_field(override_value, field)
  return override_value if override_value

  type = field.type

  type.optional? ? nil :  generate_valid_value_for(type)
end

Instance Method Details

#allowed_attributesObject



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/nova/api/utils/base_struct.rb', line 14

def allowed_attributes
  return attributes unless self.class.const_defined?('ALLOWED_ATTRIBUTES')

  data = {}

  self.class.const_get('ALLOWED_ATTRIBUTES').each do |key|
    next unless attributes.keys.include? key

    value = attributes[key]

    data[key.to_sym] = extract_value(key, value)
  end

  data
end