Class: Smartbill::Sdk::Models::Struct

Inherits:
Dry::Struct
  • Object
show all
Defined in:
lib/smartbill/sdk/models/struct.rb

Overview

Base class for every SmartBill request/response model.

A thin adapter over ‘Dry::Struct` that gives the SDK:

  • snake_case Ruby attributes aliased to camelCase JSON keys — both ‘company_vat_code` and `“companyVatCode”` are accepted on input, and #to_h emits camelCase keys (matching the SmartBill API);

  • type coercion of scalars and nested structs / arrays of structs;

  • required-attribute presence (a missing required attribute raises ValidationError, translated from ‘Dry::Struct::Error`);

  • permissive parsing — unknown input keys are ignored so new API fields don’t break parsing;

  • #to_attributes returning the snake_case hash (with nils) used by the dry-validation contracts.

Subclasses declare attributes with the dry-struct ‘attribute` DSL:

class MyThing < Struct
  attribute :company_vat_code, Types::Strict::String
  attribute :client, Client.optional.default(nil)
  attribute :products, Types::Array.of(Product).default([].freeze)
end

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.new(attrs = Dry::Core::Constants::EMPTY_HASH) ⇒ Object

Construct a struct, translating dry-struct type errors (e.g. a missing required attribute) into the SDK’s ValidationError.



38
39
40
41
42
# File 'lib/smartbill/sdk/models/struct.rb', line 38

def new(attrs = Dry::Core::Constants::EMPTY_HASH, &)
  super
rescue Dry::Struct::Error => e
  raise ValidationError, e.message
end

Instance Method Details

#to_attributesObject

Return a snake_case Symbol-keyed Hash (including nils) reflecting the Ruby attributes, with nested structs and arrays of structs recursively converted to hashes. Used as input to the validation contracts (which operate on hashes, not struct instances).



67
68
69
70
71
# File 'lib/smartbill/sdk/models/struct.rb', line 67

def to_attributes
  self.class.schema.keys.to_h do |key|
    [key.name, attribute_value(public_send(key.name))]
  end
end

#to_h(exclude_none: true) ⇒ Object

Serialize to a camelCase-keyed Hash matching the SmartBill API, omitting nil values by default. Nested structs and arrays of structs are serialized recursively.

Parameters:

  • exclude_none (Boolean) (defaults to: true)

    skip nil values (default true).



50
51
52
53
54
55
56
57
# File 'lib/smartbill/sdk/models/struct.rb', line 50

def to_h(exclude_none: true)
  self.class.schema.keys.each_with_object({}) do |key, hash|
    value = public_send(key.name)
    next if exclude_none && value.nil?

    hash[camelize_key(key.name)] = serialize_value(value, exclude_none)
  end
end

#to_jsonObject



59
60
61
# File 'lib/smartbill/sdk/models/struct.rb', line 59

def to_json(*)
  to_h.to_json(*)
end