Module: Dolibarr::Api::Validations::ClassMethods

Defined in:
lib/dolibarr-api/validations.rb

Instance Method Summary collapse

Instance Method Details

#attribute(name, type:, json_key: name.to_s, required: false, **rules) ⇒ Object



17
18
19
20
# File 'lib/dolibarr-api/validations.rb', line 17

def attribute(name, type:, json_key: name.to_s, required: false, **rules)
  openapi_attributes[name] = { type: type, json_key: json_key, required: required, rules: rules }
  attr_accessor name
end

#build(**attrs) ⇒ Object

Deserialization/builder paths use allocate (not new) on purpose: they must stay resilient (a server response may legitimately omit fields the schema marks required, or drift from the spec), whereas the caller-facing initialize is strict and validating. Bypassing initialize keeps those two contracts separate.



26
27
28
29
30
# File 'lib/dolibarr-api/validations.rb', line 26

def build(**attrs)
  obj = allocate
  attrs.each { |k, v| obj.public_send("#{k}=", v) }
  obj
end

#from_hash(hash) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/dolibarr-api/validations.rb', line 32

def from_hash(hash)
  obj = allocate
  openapi_attributes.each do |name, attr|
    next unless hash.key?(attr[:json_key])

    obj.public_send("#{name}=", Dolibarr::Api::Polymorphism.coerce(attr[:type], hash[attr[:json_key]]))
  end
  if obj.respond_to?(:additional_properties=)
    known = openapi_attributes.values.map { |a| a[:json_key] }
    obj.additional_properties = hash.except(*known)
  end
  obj
end

#from_json(json) ⇒ Object



46
47
48
# File 'lib/dolibarr-api/validations.rb', line 46

def from_json(json)
  from_hash(JSON.parse(json))
end

#openapi_attributesObject



13
14
15
# File 'lib/dolibarr-api/validations.rb', line 13

def openapi_attributes
  @openapi_attributes ||= superclass.respond_to?(:openapi_attributes) ? superclass.openapi_attributes.dup : {}
end