Class: Apiwork::Representation::Base

Inherits:
Object
  • Object
show all
Includes:
Abstractable
Defined in:
lib/apiwork/representation/base.rb

Overview

Base class for representations.

Defines how an ActiveRecord model is represented in the API. Drives contracts and runtime behavior. Sensible defaults are auto-detected from database columns but can be overridden. Supports STI and polymorphic associations.

Examples:

Basic representation

class InvoiceRepresentation < Apiwork::Representation::Base
  attribute :id
  attribute :title
  attribute :status, filterable: true, sortable: true

  belongs_to :customer
  has_many :items
end

Contract

class InvoiceContract < Apiwork::Contract::Base
  representation InvoiceRepresentation
end

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(record, context: {}, include: nil) ⇒ Base

Returns a new instance of Base.



922
923
924
925
926
# File 'lib/apiwork/representation/base.rb', line 922

def initialize(record, context: {}, include: nil)
  @record = record
  @context = context
  @include = include
end

Instance Attribute Details

#contextHash (readonly)

The serialization context.

Passed from controller or directly to serialize. Use for data that isn’t on the record, like current user or permissions.

Examples:

Override in controller

def context
  { current_user: current_user }
end

Access in custom attribute

attribute :editable, type: :boolean

def editable
  context[:current_user]&.admin?
end

Returns:

  • (Hash)


109
110
111
# File 'lib/apiwork/representation/base.rb', line 109

def context
  @context
end

#recordObject (readonly)



109
110
# File 'lib/apiwork/representation/base.rb', line 109

attr_reader :context,
:record

Class Method Details

.abstract!void

This method returns an undefined value.

Marks this representation as abstract.

Abstract representations don’t require a model and serve as base classes for other representations. Use this when creating application-wide base representations. Subclasses automatically become non-abstract.

Examples:

Application base representation

class ApplicationRepresentation < Apiwork::Representation::Base
  abstract!
end


44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
# File 'lib/apiwork/representation/base.rb', line 44

class Base
  include Abstractable

  # @!method self.attributes
  #   @api public
  #   The attributes for this representation.
  #
  #   @return [Hash{Symbol => Attribute}]
  class_attribute :attributes, default: {}, instance_accessor: false

  # @!method self.associations
  #   @api public
  #   The associations for this representation.
  #
  #   @return [Hash{Symbol => Association}]
  class_attribute :associations, default: {}, instance_accessor: false

  # @!method self.inheritance
  #   @api public
  #   The inheritance configuration for this representation.
  #
  #   Auto-configured when the model uses STI and representation classes mirror the model hierarchy.
  #   Subclasses share the parent's inheritance configuration.
  #
  #   @return [Representation::Inheritance, nil]
  class_attribute :inheritance, default: nil, instance_accessor: false

  class_attribute :_adapter_config, default: {}, instance_accessor: false
  class_attribute :type_definitions, default: {}, instance_accessor: false

  # @!attribute [r] context
  #   @api public
  #   The serialization context.
  #
  #   Passed from controller or directly to {.serialize}. Use for data that isn't on the record, like
  #   current user or permissions.
  #
  #   @return [Hash]
  #
  #   @example Override in controller
  #     def context
  #       { current_user: current_user }
  #     end
  #
  #   @example Access in custom attribute
  #     attribute :editable, type: :boolean
  #
  #     def editable
  #       context[:current_user]&.admin?
  #     end
  #
  # @!attribute [r] record
  #   @api public
  #   The record for this representation.
  #
  #   Available in custom attributes and associations.
  #
  #   @return [ActiveRecord::Base]
  #
  #   @example Custom attribute
  #     attribute :full_name, type: :string
  #
  #     def full_name
  #       "#{record.first_name} #{record.last_name}"
  #     end
  attr_reader :context,
              :record

  class << self
    # @api public
    # Configures the model class for this representation.
    #
    # Auto-detected from representation name when not set. Use {.model_class} to retrieve.
    #
    # @param value [Class<ActiveRecord::Base>]
    #   The model class.
    # @return [void]
    # @raise [ArgumentError] if value is not an ActiveRecord model class
    #
    # @example
    #   model Invoice
    def model(value)
      unless value.is_a?(Class)
        raise ConfigurationError,
              "model must be an ActiveRecord model class, got #{value.class}. " \
                                                             "Use: model Post (not 'Post' or :post)"
      end
      unless value < ActiveRecord::Base
        raise ConfigurationError,
              "model must be an ActiveRecord model class, got #{value}"
      end
      @model_class = value
    end

    # @api public
    # Configures the JSON root key for this representation.
    #
    # Auto-detected from model name when not set. Use {.root_key} to retrieve.
    #
    # @param singular [String, Symbol]
    #   The singular root key.
    # @param plural [String, Symbol] (singular.pluralize)
    #   The plural root key.
    # @return [void]
    #
    # @example
    #   root :bill, :bills
    def root(singular, plural = singular.to_s.pluralize)
      @root = { plural: plural.to_s, singular: singular.to_s }
    end

    # @api public
    # Configures adapter options for this representation.
    #
    # Overrides API-level options. Subclasses inherit parent adapter options.
    #
    # @yieldparam adapter [Configuration]
    # @return [void]
    #
    # @example
    #   adapter do
    #     pagination do
    #       strategy :cursor
    #       default_size 50
    #     end
    #   end
    def adapter(&block)
      return unless block

      self._adapter_config = _adapter_config.dup
      config = Configuration.new(api_class.adapter_class, _adapter_config)
      block.arity.positive? ? yield(config) : config.instance_eval(&block)
    end

    # @api public
    # Defines an attribute for this representation.
    #
    # Subclasses inherit parent attributes.
    #
    # @param name [Symbol]
    #   The attribute name.
    # @param decode [Proc, nil] (nil)
    #   Transform for request input (API to database). Must preserve the attribute type.
    # @param default [Object] (UNSET)
    #   The default value. Omit to declare no default. Pass `nil` for an explicit null default. If omitted and name maps to a database column, auto-detected from the column's static default.
    # @param deprecated [Boolean] (false)
    #   Whether deprecated. Metadata included in exports.
    # @param description [String, nil] (nil)
    #   The description. Metadata included in exports.
    # @param empty [Boolean, nil] (nil)
    #   Whether to use empty string instead of `null`. Serializes `nil` as `""` and deserializes `""` as `nil`. Only valid for `:string` type.
    # @param encode [Proc, nil] (nil)
    #   Transform for response output (database to API). Must preserve the attribute type.
    # @param enum [Array, nil] (nil)
    #   The allowed values. If `nil`, auto-detected from Rails enum definition.
    # @param example [Object, nil] (nil)
    #   The example. Metadata included in exports.
    # @param filterable [Boolean] (false)
    #   Whether the attribute is filterable.
    # @param format [Symbol, nil] (nil) [:date, :datetime, :double, :email, :float, :hostname, :int32, :int64, :ipv4, :ipv6, :password, :text, :url, :uuid]
    #   Format hint for exports. Does not change the type, but exports may add validation or
    #   documentation based on it. Valid formats by type: `:decimal`/`:number` (`:double`, `:float`),
    #   `:integer` (`:int32`, `:int64`), `:string` (`:date`, `:datetime`, `:email`, `:hostname`,
    #   `:ipv4`, `:ipv6`, `:password`, `:text`, `:url`, `:uuid`).
    # @param max [Integer, nil] (nil)
    #   The maximum. For `:array`: size. For `:decimal`, `:integer`, `:number`: value. For `:string`: length.
    # @param min [Integer, nil] (nil)
    #   The minimum. For `:array`: size. For `:decimal`, `:integer`, `:number`: value. For `:string`: length.
    # @param nullable [Boolean, nil] (nil)
    #   Whether the value can be `null`. If `nil` and name maps to a database column, auto-detected from column NULL constraint.
    # @param optional [Boolean, nil] (nil)
    #   Whether the attribute is optional for writes. If `nil` and name maps to a database column,
    #   auto-detected from column default or NULL constraint.
    # @param preload [Symbol, Array, Hash, nil] (nil)
    #   Associations to preload for this attribute. Use when custom attributes depend on associations.
    # @param sortable [Boolean] (false)
    #   Whether the attribute is sortable.
    # @param type [Symbol, nil] (nil) [:array, :binary, :boolean, :date, :datetime, :decimal, :integer, :number, :object, :string, :time, :unknown, :uuid]
    #   The type. If `nil` and name maps to a database column, auto-detected from column type.
    #   Defaults to `:unknown` for json/jsonb columns and when no column exists (custom attributes).
    #   Use an explicit type or block in those cases.
    # @param writable [Boolean, Symbol] (false) [:create, :update]
    #   The write access. `true` for both create and update, `:create` for create only, `:update` for update only.
    # @param write_only [Boolean] (false)
    #   Whether the attribute is write-only. Write-only attributes are excluded from response
    #   serialization and response types but remain in writable payloads.
    # @yieldparam element [Representation::Element]
    # @return [void]
    #
    # @example Basic
    #   attribute :title
    #   attribute :price, type: :decimal, min: 0
    #   attribute :status, filterable: true, sortable: true
    #
    # @example Custom attribute with preload
    #   attribute :total, type: :decimal, preload: :items
    #
    #   def total
    #     record.items.sum(:amount)
    #   end
    #
    # @example Nested preload
    #   attribute :total_with_tax, type: :decimal, preload: { items: :tax_rate }
    #
    #   def total_with_tax
    #     record.items.sum { |item| item.amount * (1 + item.tax_rate.rate) }
    #   end
    #
    # @example Inline type for JSON column
    #   attribute :settings do
    #     object do
    #       string :theme
    #       boolean :notifications
    #     end
    #   end
    #
    # @example Encode/decode transforms
    #   attribute :status, encode: ->(value) { value.upcase }, decode: ->(value) { value.downcase }
    #
    # @example Writable only on create
    #   attribute :slug, writable: :create
    #
    # @example Explicit enum values
    #   attribute :priority, enum: [:low, :medium, :high]
    #
    # @example Multiple preloads
    #   attribute :summary, type: :string, preload: [:items, :customer]
    #
    #   def summary
    #     "#{record.customer.name}: #{record.items.count} items"
    #   end
    def attribute(
      name,
      decode: nil,
      default: UNSET,
      deprecated: false,
      description: nil,
      empty: nil,
      encode: nil,
      enum: nil,
      example: nil,
      filterable: false,
      format: nil,
      max: nil,
      min: nil,
      nullable: nil,
      optional: nil,
      preload: nil,
      sortable: false,
      type: nil,
      writable: false,
      write_only: false,
      &block
    )
      self.attributes = attributes.merge(
        name => Attribute.new(
          name,
          self,
          decode:,
          default:,
          deprecated:,
          description:,
          empty:,
          encode:,
          enum:,
          example:,
          filterable:,
          format:,
          max:,
          min:,
          nullable:,
          optional:,
          preload:,
          sortable:,
          type:,
          writable:,
          write_only:,
          &block
        ),
      )
    end

    # @api public
    # Defines a has_one association for this representation.
    #
    # Subclasses inherit parent associations.
    #
    # @param name [Symbol]
    #   The association name.
    # @param deprecated [Boolean] (false)
    #   Whether deprecated. Metadata included in exports.
    # @param description [String, nil] (nil)
    #   The description. Metadata included in exports.
    # @param example [Object, nil] (nil)
    #   The example. Metadata included in exports.
    # @param filterable [Boolean] (false)
    #   Whether the association is filterable.
    # @param include [Symbol] (:optional) [:always, :optional]
    #   The inclusion mode.
    # @param nullable [Boolean, nil] (nil)
    #   Whether the association can be `null`.
    # @param representation [Class<Representation::Base>, nil] (nil)
    #   The representation class. If `nil`, inferred from the associated model in the same
    #   namespace (e.g., `CustomerRepresentation` for `Customer`).
    # @param sortable [Boolean] (false)
    #   Whether the association is sortable.
    # @param writable [Boolean, Symbol] (false) [:create, :update]
    #   The write access. `true` for both create and update, `:create` for create only, `:update` for update only.
    #   Requires `accepts_nested_attributes_for` on the model, where `allow_destroy: true` also enables deletion.
    # @return [void]
    #
    # @example Basic
    #   has_one :profile
    #
    # @example Explicit representation
    #   has_one :author, representation: AuthorRepresentation
    #
    # @example Always included
    #   has_one :customer, include: :always
    #
    # @example Custom association
    #   has_one :profile
    #
    #   def profile
    #     record.profile || record.build_profile
    #   end
    def has_one(
      name,
      deprecated: false,
      description: nil,
      example: nil,
      filterable: false,
      include: :optional,
      nullable: nil,
      representation: nil,
      sortable: false,
      writable: false
    )
      self.associations = associations.merge(
        name => Association.new(
          name,
          :has_one,
          self,
          deprecated:,
          description:,
          example:,
          filterable:,
          include:,
          nullable:,
          representation:,
          sortable:,
          writable:,
        ),
      )
    end

    # @api public
    # Defines a has_many association for this representation.
    #
    # Subclasses inherit parent associations.
    #
    # @param name [Symbol]
    #   The association name.
    # @param deprecated [Boolean] (false)
    #   Whether deprecated. Metadata included in exports.
    # @param description [String, nil] (nil)
    #   The description. Metadata included in exports.
    # @param example [Object, nil] (nil)
    #   The example. Metadata included in exports.
    # @param filterable [Boolean] (false)
    #   Whether the association is filterable.
    # @param include [Symbol] (:optional) [:always, :optional]
    #   The inclusion mode.
    # @param representation [Class<Representation::Base>, nil] (nil)
    #   The representation class. If `nil`, inferred from the associated model in the same
    #   namespace (e.g., `CustomerRepresentation` for `Customer`).
    # @param sortable [Boolean] (false)
    #   Whether the association is sortable.
    # @param writable [Boolean, Symbol] (false) [:create, :update]
    #   The write access. `true` for both create and update, `:create` for create only, `:update` for update only.
    #   Requires `accepts_nested_attributes_for` on the model, where `allow_destroy: true` also enables deletion.
    # @return [void]
    # @see #has_one
    #
    # @example Basic
    #   has_many :items
    #
    # @example Explicit representation
    #   has_many :comments, representation: CommentRepresentation
    #
    # @example Always included
    #   has_many :items, include: :always
    #
    # @example Custom association
    #   has_many :items
    #
    #   def items
    #     record.items.limit(5)
    #   end
    def has_many(
      name,
      deprecated: false,
      description: nil,
      example: nil,
      filterable: false,
      include: :optional,
      representation: nil,
      sortable: false,
      writable: false
    )
      self.associations = associations.merge(
        name => Association.new(
          name,
          :has_many,
          self,
          deprecated:,
          description:,
          example:,
          filterable:,
          include:,
          representation:,
          sortable:,
          writable:,
        ),
      )
    end

    # @api public
    # Defines a belongs_to association for this representation.
    #
    # Subclasses inherit parent associations.
    #
    # @param name [Symbol]
    #   The association name.
    # @param deprecated [Boolean] (false)
    #   Whether deprecated. Metadata included in exports.
    # @param description [String, nil] (nil)
    #   The description. Metadata included in exports.
    # @param example [Object, nil] (nil)
    #   The example. Metadata included in exports.
    # @param filterable [Boolean] (false)
    #   Whether the association is filterable.
    # @param include [Symbol] (:optional) [:always, :optional]
    #   The inclusion mode.
    # @param nullable [Boolean, nil] (nil)
    #   Whether the association can be `null`. If `nil`, auto-detected from foreign key column NULL constraint.
    # @param polymorphic [Array<Class<Representation::Base>>, nil] (nil)
    #   The allowed representation classes for polymorphic associations.
    # @param representation [Class<Representation::Base>, nil] (nil)
    #   The representation class. If `nil`, inferred from the associated model in the same
    #   namespace (e.g., `CustomerRepresentation` for `Customer`).
    # @param sortable [Boolean] (false)
    #   Whether the association is sortable.
    # @param writable [Boolean, Symbol] (false) [:create, :update]
    #   The write access. `true` for both create and update, `:create` for create only, `:update` for update only.
    #   Requires `accepts_nested_attributes_for` on the model, where `allow_destroy: true` also enables deletion.
    # @return [void]
    # @see #has_one
    #
    # @example Basic
    #   belongs_to :customer
    #
    # @example Explicit representation
    #   belongs_to :author, representation: AuthorRepresentation
    #
    # @example Always included
    #   belongs_to :customer, include: :always
    #
    # @example Polymorphic
    #   belongs_to :commentable, polymorphic: [PostRepresentation, CustomerRepresentation]
    #
    # @example Custom association
    #   belongs_to :customer
    #
    #   def customer
    #     record.customer || Customer.default
    #   end
    def belongs_to(
      name,
      deprecated: false,
      description: nil,
      example: nil,
      filterable: false,
      include: :optional,
      nullable: nil,
      polymorphic: nil,
      representation: nil,
      sortable: false,
      writable: false
    )
      self.associations = associations.merge(
        name => Association.new(
          name,
          :belongs_to,
          self,
          deprecated:,
          description:,
          example:,
          filterable:,
          include:,
          nullable:,
          polymorphic:,
          representation:,
          sortable:,
          writable:,
        ),
      )
    end

    # @api public
    # Defines an object type for this representation.
    #
    # The type is copied to the contract that uses this representation. Attributes can reference
    # it by name via `type:`. In exports, the type is scoped to the contract.
    #
    # @param name [Symbol]
    #   The object name.
    # @param deprecated [Boolean] (false)
    #   Whether deprecated. Metadata included in exports.
    # @param description [String, nil] (nil)
    #   The description. Metadata included in exports.
    # @param example [Object, nil] (nil)
    #   The example. Metadata included in exports.
    # @yieldparam object [API::Object]
    # @return [void]
    #
    # @example Define and reference
    #   object :address do
    #     string :street
    #     string :city
    #     string :postal_code
    #   end
    #
    #   attribute :shipping_address, type: :address
    #   attribute :billing_address, type: :address
    def object(
      name,
      deprecated: false,
      description: nil,
      example: nil,
      &block
    )
      self.type_definitions = type_definitions.merge(
        name.to_sym => {
          block:,
          kind: :object,
          options: {
            deprecated:,
            description:,
            example:,
          },
        },
      )
    end

    # @api public
    # Defines a union type for this representation.
    #
    # The type is copied to the contract that uses this representation. Attributes can reference
    # it by name via `type:`. In exports, the type is scoped to the contract.
    #
    # @param name [Symbol]
    #   The union name.
    # @param deprecated [Boolean] (false)
    #   Whether deprecated. Metadata included in exports.
    # @param description [String, nil] (nil)
    #   The description. Metadata included in exports.
    # @param discriminator [Symbol, nil] (nil)
    #   The discriminator field name.
    # @param example [Object, nil] (nil)
    #   The example. Metadata included in exports.
    # @yieldparam union [API::Union]
    # @return [void]
    #
    # @example Define and reference
    #   union :content_block, discriminator: :kind do
    #     variant tag: 'text' do
    #       object do
    #         string :body
    #       end
    #     end
    #     variant tag: 'image' do
    #       object do
    #         string :url
    #         integer :width
    #         integer :height
    #       end
    #     end
    #   end
    #
    #   attribute :content, type: :content_block
    def union(
      name,
      deprecated: false,
      description: nil,
      discriminator: nil,
      example: nil,
      &block
    )
      self.type_definitions = type_definitions.merge(
        name.to_sym => {
          block:,
          kind: :union,
          options: {
            deprecated:,
            description:,
            discriminator:,
            example:,
          },
        },
      )
    end

    # @api public
    # The type name for this representation.
    #
    # Overrides the model's default for STI and polymorphic types.
    #
    # @param value [String, Symbol, nil] (nil)
    #   The type name.
    # @return [String, nil]
    # @see .sti_name
    # @see .polymorphic_name
    #
    # @example
    #   type_name :person
    def type_name(value = nil)
      return @type_name = value.to_s if value

      @type_name
    end

    # @api public
    # The STI name for this representation.
    #
    # Uses {.type_name} if set, otherwise the model's `sti_name`.
    #
    # @return [String]
    def sti_name
      @type_name || model_class.sti_name
    end

    # @api public
    # The polymorphic name for this representation.
    #
    # Uses {.type_name} if set, otherwise the model's `polymorphic_name`.
    #
    # @return [String]
    def polymorphic_name
      @type_name || model_class.polymorphic_name
    end

    # @api public
    # Whether this representation is an STI subclass.
    #
    # @return [Boolean]
    def subclass?
      superclass.respond_to?(:inheritance) && superclass.inheritance&.subclass?(self)
    end

    # @api public
    # The description for this representation.
    #
    # Metadata included in exports.
    #
    # @param value [String, nil] (nil)
    #   The description.
    # @return [String, nil]
    #
    # @example
    #   description 'A customer invoice'
    def description(value = nil)
      return @description if value.nil?

      @description = value
    end

    # @api public
    # Marks this representation as deprecated.
    #
    # Metadata included in exports.
    #
    # @return [void]
    #
    # @example
    #   deprecated!
    def deprecated!
      @deprecated = true
    end

    # @api public
    # The example value for this representation.
    #
    # Metadata included in exports.
    #
    # @param value [Hash, nil] (nil)
    #   The example.
    # @return [Hash, nil]
    #
    # @example
    #   example id: 1, total: 99.00, status: 'paid'
    def example(value = nil)
      return @example if value.nil?

      @example = value
    end

    # @api public
    # Transforms a record or an array of records to hashes.
    #
    # Applies attribute encoders, maps STI and polymorphic type names,
    # and recursively serializes nested associations.
    #
    # @param resource [ActiveRecord::Base, Array<ActiveRecord::Base>]
    #   The resource to serialize.
    # @param context [Hash] ({})
    #   The serialization context.
    # @param include [Symbol, Array, Hash, nil] (nil)
    #   The associations to include.
    # @return [Hash, Array<Hash>]
    #
    # @example Basic
    #   InvoiceRepresentation.serialize(invoice)
    #   # => { id: 1, total: 99.00, status: 'paid' }
    #
    # @example Collection
    #   InvoiceRepresentation.serialize(invoices)
    #   # => [{ id: 1, ... }, { id: 2, ... }]
    #
    # @example With associations
    #   InvoiceRepresentation.serialize(invoice, include: [:customer, :items])
    #   # => { id: 1, ..., customer: { id: 1, name: 'Acme' }, items: [...] }
    #
    # @example Nested associations
    #   InvoiceRepresentation.serialize(invoice, include: { customer: [:address] })
    #   # => { id: 1, ..., customer: { id: 1, name: 'Acme', address: { ... } } }
    def serialize(resource, context: {}, include: nil)
      if resource.is_a?(Enumerable)
        resource.map { |record| serialize_record(record, context:, include:) }
      else
        serialize_record(resource, context:, include:)
      end
    end

    # @api public
    # Transforms a hash or an array of hashes for records.
    #
    # Applies attribute decoders, maps STI and polymorphic type names,
    # and recursively deserializes nested associations.
    #
    # @param payload [Hash, Array<Hash>]
    #   The payload to deserialize.
    # @return [Hash, Array<Hash>]
    #
    # @example
    #   InvoiceRepresentation.deserialize(params[:invoice])
    def deserialize(payload)
      Deserializer.deserialize(self, payload)
    end

    # @api public
    # The root key for this representation.
    #
    # Derived from model name when {.root} is not set.
    #
    # @return [RootKey]
    def root_key
      if @root
        RootKey.new(@root[:singular], @root[:plural])
      else
        RootKey.new(model_class.model_name.element)
      end
    end

    # @api public
    # The model class for this representation.
    #
    # Auto-detected from representation name or set via {.model}.
    #
    # @return [Class<ActiveRecord::Base>]
    def model_class
      ensure_auto_detection_complete
      ensure_sti_auto_configuration_complete
      @model_class
    end

    # @api public
    # Whether this representation is deprecated.
    #
    # @return [Boolean]
    def deprecated?
      @deprecated == true
    end

    def adapter_config
      @adapter_config ||= api_class.adapter_config.merge(_adapter_config)
    end

    def api_class
      return nil unless name

      namespace = name.deconstantize
      return nil if namespace.blank?

      API.find("/#{namespace.underscore.tr('::', '/')}")
    end

    def preloads
      attributes.values.filter_map(&:preload)
    end

    def polymorphic_association_for_type_column(column_name)
      associations.values.find do |association|
        association.polymorphic? && association.discriminator == column_name
      end
    end

    def inheritance_for_column(column_name)
      target_class = subclass? ? superclass : self
      target_inheritance = target_class.inheritance
      target_model = target_class.model_class

      return nil unless target_inheritance&.subclasses&.any?
      return nil unless target_model.respond_to?(:inheritance_column)

      target_inheritance if column_name.to_sym == target_model.inheritance_column.to_sym
    end

    def serialize_record(record, context: {}, include: nil)
      subclass_representation_class = inheritance.resolve(record) if inheritance&.subclasses&.any?
      representation_class = subclass_representation_class || self

      representation_class.new(record, context:, include:).as_json
    end

    private

    def ensure_auto_detection_complete
      return if @auto_detection_complete

      @auto_detection_complete = true
      return if @model_class.present?

      detected = ModelDetector.new(self).detect
      @model_class = detected if detected
    end

    def ensure_sti_auto_configuration_complete
      return if @sti_auto_configuration_complete

      @sti_auto_configuration_complete = true
      ensure_auto_detection_complete
      return unless @model_class

      model_detector = ModelDetector.new(self)

      auto_configure_inheritance if model_detector.sti_base?(@model_class) && inheritance.nil?

      return unless model_detector.sti_subclass?(@model_class)
      return unless model_detector.superclass_is_sti_base?(@model_class)
      return if subclass?

      auto_register_subclass
    end

    def auto_configure_inheritance
      self.inheritance = Inheritance.new(self)
    end

    def auto_register_subclass
      superclass.send(:ensure_sti_auto_configuration_complete)
      return unless superclass.inheritance

      superclass.inheritance.register(self)
      superclass._abstract = true
    end
  end

  def initialize(record, context: {}, include: nil)
    @record = record
    @context = context
    @include = include
  end

  def as_json
    Serializer.serialize(self, @include)
  end
end

.abstract?Boolean

Whether this representation is abstract.

Returns:

  • (Boolean)


44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
# File 'lib/apiwork/representation/base.rb', line 44

class Base
  include Abstractable

  # @!method self.attributes
  #   @api public
  #   The attributes for this representation.
  #
  #   @return [Hash{Symbol => Attribute}]
  class_attribute :attributes, default: {}, instance_accessor: false

  # @!method self.associations
  #   @api public
  #   The associations for this representation.
  #
  #   @return [Hash{Symbol => Association}]
  class_attribute :associations, default: {}, instance_accessor: false

  # @!method self.inheritance
  #   @api public
  #   The inheritance configuration for this representation.
  #
  #   Auto-configured when the model uses STI and representation classes mirror the model hierarchy.
  #   Subclasses share the parent's inheritance configuration.
  #
  #   @return [Representation::Inheritance, nil]
  class_attribute :inheritance, default: nil, instance_accessor: false

  class_attribute :_adapter_config, default: {}, instance_accessor: false
  class_attribute :type_definitions, default: {}, instance_accessor: false

  # @!attribute [r] context
  #   @api public
  #   The serialization context.
  #
  #   Passed from controller or directly to {.serialize}. Use for data that isn't on the record, like
  #   current user or permissions.
  #
  #   @return [Hash]
  #
  #   @example Override in controller
  #     def context
  #       { current_user: current_user }
  #     end
  #
  #   @example Access in custom attribute
  #     attribute :editable, type: :boolean
  #
  #     def editable
  #       context[:current_user]&.admin?
  #     end
  #
  # @!attribute [r] record
  #   @api public
  #   The record for this representation.
  #
  #   Available in custom attributes and associations.
  #
  #   @return [ActiveRecord::Base]
  #
  #   @example Custom attribute
  #     attribute :full_name, type: :string
  #
  #     def full_name
  #       "#{record.first_name} #{record.last_name}"
  #     end
  attr_reader :context,
              :record

  class << self
    # @api public
    # Configures the model class for this representation.
    #
    # Auto-detected from representation name when not set. Use {.model_class} to retrieve.
    #
    # @param value [Class<ActiveRecord::Base>]
    #   The model class.
    # @return [void]
    # @raise [ArgumentError] if value is not an ActiveRecord model class
    #
    # @example
    #   model Invoice
    def model(value)
      unless value.is_a?(Class)
        raise ConfigurationError,
              "model must be an ActiveRecord model class, got #{value.class}. " \
                                                             "Use: model Post (not 'Post' or :post)"
      end
      unless value < ActiveRecord::Base
        raise ConfigurationError,
              "model must be an ActiveRecord model class, got #{value}"
      end
      @model_class = value
    end

    # @api public
    # Configures the JSON root key for this representation.
    #
    # Auto-detected from model name when not set. Use {.root_key} to retrieve.
    #
    # @param singular [String, Symbol]
    #   The singular root key.
    # @param plural [String, Symbol] (singular.pluralize)
    #   The plural root key.
    # @return [void]
    #
    # @example
    #   root :bill, :bills
    def root(singular, plural = singular.to_s.pluralize)
      @root = { plural: plural.to_s, singular: singular.to_s }
    end

    # @api public
    # Configures adapter options for this representation.
    #
    # Overrides API-level options. Subclasses inherit parent adapter options.
    #
    # @yieldparam adapter [Configuration]
    # @return [void]
    #
    # @example
    #   adapter do
    #     pagination do
    #       strategy :cursor
    #       default_size 50
    #     end
    #   end
    def adapter(&block)
      return unless block

      self._adapter_config = _adapter_config.dup
      config = Configuration.new(api_class.adapter_class, _adapter_config)
      block.arity.positive? ? yield(config) : config.instance_eval(&block)
    end

    # @api public
    # Defines an attribute for this representation.
    #
    # Subclasses inherit parent attributes.
    #
    # @param name [Symbol]
    #   The attribute name.
    # @param decode [Proc, nil] (nil)
    #   Transform for request input (API to database). Must preserve the attribute type.
    # @param default [Object] (UNSET)
    #   The default value. Omit to declare no default. Pass `nil` for an explicit null default. If omitted and name maps to a database column, auto-detected from the column's static default.
    # @param deprecated [Boolean] (false)
    #   Whether deprecated. Metadata included in exports.
    # @param description [String, nil] (nil)
    #   The description. Metadata included in exports.
    # @param empty [Boolean, nil] (nil)
    #   Whether to use empty string instead of `null`. Serializes `nil` as `""` and deserializes `""` as `nil`. Only valid for `:string` type.
    # @param encode [Proc, nil] (nil)
    #   Transform for response output (database to API). Must preserve the attribute type.
    # @param enum [Array, nil] (nil)
    #   The allowed values. If `nil`, auto-detected from Rails enum definition.
    # @param example [Object, nil] (nil)
    #   The example. Metadata included in exports.
    # @param filterable [Boolean] (false)
    #   Whether the attribute is filterable.
    # @param format [Symbol, nil] (nil) [:date, :datetime, :double, :email, :float, :hostname, :int32, :int64, :ipv4, :ipv6, :password, :text, :url, :uuid]
    #   Format hint for exports. Does not change the type, but exports may add validation or
    #   documentation based on it. Valid formats by type: `:decimal`/`:number` (`:double`, `:float`),
    #   `:integer` (`:int32`, `:int64`), `:string` (`:date`, `:datetime`, `:email`, `:hostname`,
    #   `:ipv4`, `:ipv6`, `:password`, `:text`, `:url`, `:uuid`).
    # @param max [Integer, nil] (nil)
    #   The maximum. For `:array`: size. For `:decimal`, `:integer`, `:number`: value. For `:string`: length.
    # @param min [Integer, nil] (nil)
    #   The minimum. For `:array`: size. For `:decimal`, `:integer`, `:number`: value. For `:string`: length.
    # @param nullable [Boolean, nil] (nil)
    #   Whether the value can be `null`. If `nil` and name maps to a database column, auto-detected from column NULL constraint.
    # @param optional [Boolean, nil] (nil)
    #   Whether the attribute is optional for writes. If `nil` and name maps to a database column,
    #   auto-detected from column default or NULL constraint.
    # @param preload [Symbol, Array, Hash, nil] (nil)
    #   Associations to preload for this attribute. Use when custom attributes depend on associations.
    # @param sortable [Boolean] (false)
    #   Whether the attribute is sortable.
    # @param type [Symbol, nil] (nil) [:array, :binary, :boolean, :date, :datetime, :decimal, :integer, :number, :object, :string, :time, :unknown, :uuid]
    #   The type. If `nil` and name maps to a database column, auto-detected from column type.
    #   Defaults to `:unknown` for json/jsonb columns and when no column exists (custom attributes).
    #   Use an explicit type or block in those cases.
    # @param writable [Boolean, Symbol] (false) [:create, :update]
    #   The write access. `true` for both create and update, `:create` for create only, `:update` for update only.
    # @param write_only [Boolean] (false)
    #   Whether the attribute is write-only. Write-only attributes are excluded from response
    #   serialization and response types but remain in writable payloads.
    # @yieldparam element [Representation::Element]
    # @return [void]
    #
    # @example Basic
    #   attribute :title
    #   attribute :price, type: :decimal, min: 0
    #   attribute :status, filterable: true, sortable: true
    #
    # @example Custom attribute with preload
    #   attribute :total, type: :decimal, preload: :items
    #
    #   def total
    #     record.items.sum(:amount)
    #   end
    #
    # @example Nested preload
    #   attribute :total_with_tax, type: :decimal, preload: { items: :tax_rate }
    #
    #   def total_with_tax
    #     record.items.sum { |item| item.amount * (1 + item.tax_rate.rate) }
    #   end
    #
    # @example Inline type for JSON column
    #   attribute :settings do
    #     object do
    #       string :theme
    #       boolean :notifications
    #     end
    #   end
    #
    # @example Encode/decode transforms
    #   attribute :status, encode: ->(value) { value.upcase }, decode: ->(value) { value.downcase }
    #
    # @example Writable only on create
    #   attribute :slug, writable: :create
    #
    # @example Explicit enum values
    #   attribute :priority, enum: [:low, :medium, :high]
    #
    # @example Multiple preloads
    #   attribute :summary, type: :string, preload: [:items, :customer]
    #
    #   def summary
    #     "#{record.customer.name}: #{record.items.count} items"
    #   end
    def attribute(
      name,
      decode: nil,
      default: UNSET,
      deprecated: false,
      description: nil,
      empty: nil,
      encode: nil,
      enum: nil,
      example: nil,
      filterable: false,
      format: nil,
      max: nil,
      min: nil,
      nullable: nil,
      optional: nil,
      preload: nil,
      sortable: false,
      type: nil,
      writable: false,
      write_only: false,
      &block
    )
      self.attributes = attributes.merge(
        name => Attribute.new(
          name,
          self,
          decode:,
          default:,
          deprecated:,
          description:,
          empty:,
          encode:,
          enum:,
          example:,
          filterable:,
          format:,
          max:,
          min:,
          nullable:,
          optional:,
          preload:,
          sortable:,
          type:,
          writable:,
          write_only:,
          &block
        ),
      )
    end

    # @api public
    # Defines a has_one association for this representation.
    #
    # Subclasses inherit parent associations.
    #
    # @param name [Symbol]
    #   The association name.
    # @param deprecated [Boolean] (false)
    #   Whether deprecated. Metadata included in exports.
    # @param description [String, nil] (nil)
    #   The description. Metadata included in exports.
    # @param example [Object, nil] (nil)
    #   The example. Metadata included in exports.
    # @param filterable [Boolean] (false)
    #   Whether the association is filterable.
    # @param include [Symbol] (:optional) [:always, :optional]
    #   The inclusion mode.
    # @param nullable [Boolean, nil] (nil)
    #   Whether the association can be `null`.
    # @param representation [Class<Representation::Base>, nil] (nil)
    #   The representation class. If `nil`, inferred from the associated model in the same
    #   namespace (e.g., `CustomerRepresentation` for `Customer`).
    # @param sortable [Boolean] (false)
    #   Whether the association is sortable.
    # @param writable [Boolean, Symbol] (false) [:create, :update]
    #   The write access. `true` for both create and update, `:create` for create only, `:update` for update only.
    #   Requires `accepts_nested_attributes_for` on the model, where `allow_destroy: true` also enables deletion.
    # @return [void]
    #
    # @example Basic
    #   has_one :profile
    #
    # @example Explicit representation
    #   has_one :author, representation: AuthorRepresentation
    #
    # @example Always included
    #   has_one :customer, include: :always
    #
    # @example Custom association
    #   has_one :profile
    #
    #   def profile
    #     record.profile || record.build_profile
    #   end
    def has_one(
      name,
      deprecated: false,
      description: nil,
      example: nil,
      filterable: false,
      include: :optional,
      nullable: nil,
      representation: nil,
      sortable: false,
      writable: false
    )
      self.associations = associations.merge(
        name => Association.new(
          name,
          :has_one,
          self,
          deprecated:,
          description:,
          example:,
          filterable:,
          include:,
          nullable:,
          representation:,
          sortable:,
          writable:,
        ),
      )
    end

    # @api public
    # Defines a has_many association for this representation.
    #
    # Subclasses inherit parent associations.
    #
    # @param name [Symbol]
    #   The association name.
    # @param deprecated [Boolean] (false)
    #   Whether deprecated. Metadata included in exports.
    # @param description [String, nil] (nil)
    #   The description. Metadata included in exports.
    # @param example [Object, nil] (nil)
    #   The example. Metadata included in exports.
    # @param filterable [Boolean] (false)
    #   Whether the association is filterable.
    # @param include [Symbol] (:optional) [:always, :optional]
    #   The inclusion mode.
    # @param representation [Class<Representation::Base>, nil] (nil)
    #   The representation class. If `nil`, inferred from the associated model in the same
    #   namespace (e.g., `CustomerRepresentation` for `Customer`).
    # @param sortable [Boolean] (false)
    #   Whether the association is sortable.
    # @param writable [Boolean, Symbol] (false) [:create, :update]
    #   The write access. `true` for both create and update, `:create` for create only, `:update` for update only.
    #   Requires `accepts_nested_attributes_for` on the model, where `allow_destroy: true` also enables deletion.
    # @return [void]
    # @see #has_one
    #
    # @example Basic
    #   has_many :items
    #
    # @example Explicit representation
    #   has_many :comments, representation: CommentRepresentation
    #
    # @example Always included
    #   has_many :items, include: :always
    #
    # @example Custom association
    #   has_many :items
    #
    #   def items
    #     record.items.limit(5)
    #   end
    def has_many(
      name,
      deprecated: false,
      description: nil,
      example: nil,
      filterable: false,
      include: :optional,
      representation: nil,
      sortable: false,
      writable: false
    )
      self.associations = associations.merge(
        name => Association.new(
          name,
          :has_many,
          self,
          deprecated:,
          description:,
          example:,
          filterable:,
          include:,
          representation:,
          sortable:,
          writable:,
        ),
      )
    end

    # @api public
    # Defines a belongs_to association for this representation.
    #
    # Subclasses inherit parent associations.
    #
    # @param name [Symbol]
    #   The association name.
    # @param deprecated [Boolean] (false)
    #   Whether deprecated. Metadata included in exports.
    # @param description [String, nil] (nil)
    #   The description. Metadata included in exports.
    # @param example [Object, nil] (nil)
    #   The example. Metadata included in exports.
    # @param filterable [Boolean] (false)
    #   Whether the association is filterable.
    # @param include [Symbol] (:optional) [:always, :optional]
    #   The inclusion mode.
    # @param nullable [Boolean, nil] (nil)
    #   Whether the association can be `null`. If `nil`, auto-detected from foreign key column NULL constraint.
    # @param polymorphic [Array<Class<Representation::Base>>, nil] (nil)
    #   The allowed representation classes for polymorphic associations.
    # @param representation [Class<Representation::Base>, nil] (nil)
    #   The representation class. If `nil`, inferred from the associated model in the same
    #   namespace (e.g., `CustomerRepresentation` for `Customer`).
    # @param sortable [Boolean] (false)
    #   Whether the association is sortable.
    # @param writable [Boolean, Symbol] (false) [:create, :update]
    #   The write access. `true` for both create and update, `:create` for create only, `:update` for update only.
    #   Requires `accepts_nested_attributes_for` on the model, where `allow_destroy: true` also enables deletion.
    # @return [void]
    # @see #has_one
    #
    # @example Basic
    #   belongs_to :customer
    #
    # @example Explicit representation
    #   belongs_to :author, representation: AuthorRepresentation
    #
    # @example Always included
    #   belongs_to :customer, include: :always
    #
    # @example Polymorphic
    #   belongs_to :commentable, polymorphic: [PostRepresentation, CustomerRepresentation]
    #
    # @example Custom association
    #   belongs_to :customer
    #
    #   def customer
    #     record.customer || Customer.default
    #   end
    def belongs_to(
      name,
      deprecated: false,
      description: nil,
      example: nil,
      filterable: false,
      include: :optional,
      nullable: nil,
      polymorphic: nil,
      representation: nil,
      sortable: false,
      writable: false
    )
      self.associations = associations.merge(
        name => Association.new(
          name,
          :belongs_to,
          self,
          deprecated:,
          description:,
          example:,
          filterable:,
          include:,
          nullable:,
          polymorphic:,
          representation:,
          sortable:,
          writable:,
        ),
      )
    end

    # @api public
    # Defines an object type for this representation.
    #
    # The type is copied to the contract that uses this representation. Attributes can reference
    # it by name via `type:`. In exports, the type is scoped to the contract.
    #
    # @param name [Symbol]
    #   The object name.
    # @param deprecated [Boolean] (false)
    #   Whether deprecated. Metadata included in exports.
    # @param description [String, nil] (nil)
    #   The description. Metadata included in exports.
    # @param example [Object, nil] (nil)
    #   The example. Metadata included in exports.
    # @yieldparam object [API::Object]
    # @return [void]
    #
    # @example Define and reference
    #   object :address do
    #     string :street
    #     string :city
    #     string :postal_code
    #   end
    #
    #   attribute :shipping_address, type: :address
    #   attribute :billing_address, type: :address
    def object(
      name,
      deprecated: false,
      description: nil,
      example: nil,
      &block
    )
      self.type_definitions = type_definitions.merge(
        name.to_sym => {
          block:,
          kind: :object,
          options: {
            deprecated:,
            description:,
            example:,
          },
        },
      )
    end

    # @api public
    # Defines a union type for this representation.
    #
    # The type is copied to the contract that uses this representation. Attributes can reference
    # it by name via `type:`. In exports, the type is scoped to the contract.
    #
    # @param name [Symbol]
    #   The union name.
    # @param deprecated [Boolean] (false)
    #   Whether deprecated. Metadata included in exports.
    # @param description [String, nil] (nil)
    #   The description. Metadata included in exports.
    # @param discriminator [Symbol, nil] (nil)
    #   The discriminator field name.
    # @param example [Object, nil] (nil)
    #   The example. Metadata included in exports.
    # @yieldparam union [API::Union]
    # @return [void]
    #
    # @example Define and reference
    #   union :content_block, discriminator: :kind do
    #     variant tag: 'text' do
    #       object do
    #         string :body
    #       end
    #     end
    #     variant tag: 'image' do
    #       object do
    #         string :url
    #         integer :width
    #         integer :height
    #       end
    #     end
    #   end
    #
    #   attribute :content, type: :content_block
    def union(
      name,
      deprecated: false,
      description: nil,
      discriminator: nil,
      example: nil,
      &block
    )
      self.type_definitions = type_definitions.merge(
        name.to_sym => {
          block:,
          kind: :union,
          options: {
            deprecated:,
            description:,
            discriminator:,
            example:,
          },
        },
      )
    end

    # @api public
    # The type name for this representation.
    #
    # Overrides the model's default for STI and polymorphic types.
    #
    # @param value [String, Symbol, nil] (nil)
    #   The type name.
    # @return [String, nil]
    # @see .sti_name
    # @see .polymorphic_name
    #
    # @example
    #   type_name :person
    def type_name(value = nil)
      return @type_name = value.to_s if value

      @type_name
    end

    # @api public
    # The STI name for this representation.
    #
    # Uses {.type_name} if set, otherwise the model's `sti_name`.
    #
    # @return [String]
    def sti_name
      @type_name || model_class.sti_name
    end

    # @api public
    # The polymorphic name for this representation.
    #
    # Uses {.type_name} if set, otherwise the model's `polymorphic_name`.
    #
    # @return [String]
    def polymorphic_name
      @type_name || model_class.polymorphic_name
    end

    # @api public
    # Whether this representation is an STI subclass.
    #
    # @return [Boolean]
    def subclass?
      superclass.respond_to?(:inheritance) && superclass.inheritance&.subclass?(self)
    end

    # @api public
    # The description for this representation.
    #
    # Metadata included in exports.
    #
    # @param value [String, nil] (nil)
    #   The description.
    # @return [String, nil]
    #
    # @example
    #   description 'A customer invoice'
    def description(value = nil)
      return @description if value.nil?

      @description = value
    end

    # @api public
    # Marks this representation as deprecated.
    #
    # Metadata included in exports.
    #
    # @return [void]
    #
    # @example
    #   deprecated!
    def deprecated!
      @deprecated = true
    end

    # @api public
    # The example value for this representation.
    #
    # Metadata included in exports.
    #
    # @param value [Hash, nil] (nil)
    #   The example.
    # @return [Hash, nil]
    #
    # @example
    #   example id: 1, total: 99.00, status: 'paid'
    def example(value = nil)
      return @example if value.nil?

      @example = value
    end

    # @api public
    # Transforms a record or an array of records to hashes.
    #
    # Applies attribute encoders, maps STI and polymorphic type names,
    # and recursively serializes nested associations.
    #
    # @param resource [ActiveRecord::Base, Array<ActiveRecord::Base>]
    #   The resource to serialize.
    # @param context [Hash] ({})
    #   The serialization context.
    # @param include [Symbol, Array, Hash, nil] (nil)
    #   The associations to include.
    # @return [Hash, Array<Hash>]
    #
    # @example Basic
    #   InvoiceRepresentation.serialize(invoice)
    #   # => { id: 1, total: 99.00, status: 'paid' }
    #
    # @example Collection
    #   InvoiceRepresentation.serialize(invoices)
    #   # => [{ id: 1, ... }, { id: 2, ... }]
    #
    # @example With associations
    #   InvoiceRepresentation.serialize(invoice, include: [:customer, :items])
    #   # => { id: 1, ..., customer: { id: 1, name: 'Acme' }, items: [...] }
    #
    # @example Nested associations
    #   InvoiceRepresentation.serialize(invoice, include: { customer: [:address] })
    #   # => { id: 1, ..., customer: { id: 1, name: 'Acme', address: { ... } } }
    def serialize(resource, context: {}, include: nil)
      if resource.is_a?(Enumerable)
        resource.map { |record| serialize_record(record, context:, include:) }
      else
        serialize_record(resource, context:, include:)
      end
    end

    # @api public
    # Transforms a hash or an array of hashes for records.
    #
    # Applies attribute decoders, maps STI and polymorphic type names,
    # and recursively deserializes nested associations.
    #
    # @param payload [Hash, Array<Hash>]
    #   The payload to deserialize.
    # @return [Hash, Array<Hash>]
    #
    # @example
    #   InvoiceRepresentation.deserialize(params[:invoice])
    def deserialize(payload)
      Deserializer.deserialize(self, payload)
    end

    # @api public
    # The root key for this representation.
    #
    # Derived from model name when {.root} is not set.
    #
    # @return [RootKey]
    def root_key
      if @root
        RootKey.new(@root[:singular], @root[:plural])
      else
        RootKey.new(model_class.model_name.element)
      end
    end

    # @api public
    # The model class for this representation.
    #
    # Auto-detected from representation name or set via {.model}.
    #
    # @return [Class<ActiveRecord::Base>]
    def model_class
      ensure_auto_detection_complete
      ensure_sti_auto_configuration_complete
      @model_class
    end

    # @api public
    # Whether this representation is deprecated.
    #
    # @return [Boolean]
    def deprecated?
      @deprecated == true
    end

    def adapter_config
      @adapter_config ||= api_class.adapter_config.merge(_adapter_config)
    end

    def api_class
      return nil unless name

      namespace = name.deconstantize
      return nil if namespace.blank?

      API.find("/#{namespace.underscore.tr('::', '/')}")
    end

    def preloads
      attributes.values.filter_map(&:preload)
    end

    def polymorphic_association_for_type_column(column_name)
      associations.values.find do |association|
        association.polymorphic? && association.discriminator == column_name
      end
    end

    def inheritance_for_column(column_name)
      target_class = subclass? ? superclass : self
      target_inheritance = target_class.inheritance
      target_model = target_class.model_class

      return nil unless target_inheritance&.subclasses&.any?
      return nil unless target_model.respond_to?(:inheritance_column)

      target_inheritance if column_name.to_sym == target_model.inheritance_column.to_sym
    end

    def serialize_record(record, context: {}, include: nil)
      subclass_representation_class = inheritance.resolve(record) if inheritance&.subclasses&.any?
      representation_class = subclass_representation_class || self

      representation_class.new(record, context:, include:).as_json
    end

    private

    def ensure_auto_detection_complete
      return if @auto_detection_complete

      @auto_detection_complete = true
      return if @model_class.present?

      detected = ModelDetector.new(self).detect
      @model_class = detected if detected
    end

    def ensure_sti_auto_configuration_complete
      return if @sti_auto_configuration_complete

      @sti_auto_configuration_complete = true
      ensure_auto_detection_complete
      return unless @model_class

      model_detector = ModelDetector.new(self)

      auto_configure_inheritance if model_detector.sti_base?(@model_class) && inheritance.nil?

      return unless model_detector.sti_subclass?(@model_class)
      return unless model_detector.superclass_is_sti_base?(@model_class)
      return if subclass?

      auto_register_subclass
    end

    def auto_configure_inheritance
      self.inheritance = Inheritance.new(self)
    end

    def auto_register_subclass
      superclass.send(:ensure_sti_auto_configuration_complete)
      return unless superclass.inheritance

      superclass.inheritance.register(self)
      superclass._abstract = true
    end
  end

  def initialize(record, context: {}, include: nil)
    @record = record
    @context = context
    @include = include
  end

  def as_json
    Serializer.serialize(self, @include)
  end
end

.adapter {|adapter| ... } ⇒ void

This method returns an undefined value.

Configures adapter options for this representation.

Overrides API-level options. Subclasses inherit parent adapter options.

Examples:

adapter do
  pagination do
    strategy :cursor
    default_size 50
  end
end

Yield Parameters:



170
171
172
173
174
175
176
# File 'lib/apiwork/representation/base.rb', line 170

def adapter(&block)
  return unless block

  self._adapter_config = _adapter_config.dup
  config = Configuration.new(api_class.adapter_class, _adapter_config)
  block.arity.positive? ? yield(config) : config.instance_eval(&block)
end

.adapter_configObject



838
839
840
# File 'lib/apiwork/representation/base.rb', line 838

def adapter_config
  @adapter_config ||= api_class.adapter_config.merge(_adapter_config)
end

.api_classObject



842
843
844
845
846
847
848
849
# File 'lib/apiwork/representation/base.rb', line 842

def api_class
  return nil unless name

  namespace = name.deconstantize
  return nil if namespace.blank?

  API.find("/#{namespace.underscore.tr('::', '/')}")
end

.associationsHash{Symbol => Association}

The associations for this representation.

Returns:



59
# File 'lib/apiwork/representation/base.rb', line 59

class_attribute :associations, default: {}, instance_accessor: false

.attribute(name, decode: nil, default: UNSET, deprecated: false, description: nil, empty: nil, encode: nil, enum: nil, example: nil, filterable: false, format: nil, max: nil, min: nil, nullable: nil, optional: nil, preload: nil, sortable: false, type: nil, writable: false, write_only: false) {|element| ... } ⇒ void

This method returns an undefined value.

Defines an attribute for this representation.

Subclasses inherit parent attributes.

Examples:

Basic

attribute :title
attribute :price, type: :decimal, min: 0
attribute :status, filterable: true, sortable: true

Custom attribute with preload

attribute :total, type: :decimal, preload: :items

def total
  record.items.sum(:amount)
end

Nested preload

attribute :total_with_tax, type: :decimal, preload: { items: :tax_rate }

def total_with_tax
  record.items.sum { |item| item.amount * (1 + item.tax_rate.rate) }
end

Inline type for JSON column

attribute :settings do
  object do
    string :theme
    boolean :notifications
  end
end

Encode/decode transforms

attribute :status, encode: ->(value) { value.upcase }, decode: ->(value) { value.downcase }

Writable only on create

attribute :slug, writable: :create

Explicit enum values

attribute :priority, enum: [:low, :medium, :high]

Multiple preloads

attribute :summary, type: :string, preload: [:items, :customer]

def summary
  "#{record.customer.name}: #{record.items.count} items"
end

Parameters:

  • name (Symbol)

    The attribute name.

  • decode (Proc, nil) (defaults to: nil)

    (nil) Transform for request input (API to database). Must preserve the attribute type.

  • default (Object) (defaults to: UNSET)

    (UNSET) The default value. Omit to declare no default. Pass ‘nil` for an explicit null default. If omitted and name maps to a database column, auto-detected from the column’s static default.

  • deprecated (Boolean) (defaults to: false)

    (false) Whether deprecated. Metadata included in exports.

  • description (String, nil) (defaults to: nil)

    (nil) The description. Metadata included in exports.

  • empty (Boolean, nil) (defaults to: nil)

    (nil) Whether to use empty string instead of ‘null`. Serializes `nil` as `“”` and deserializes `“”` as `nil`. Only valid for `:string` type.

  • encode (Proc, nil) (defaults to: nil)

    (nil) Transform for response output (database to API). Must preserve the attribute type.

  • enum (Array, nil) (defaults to: nil)

    (nil) The allowed values. If ‘nil`, auto-detected from Rails enum definition.

  • example (Object, nil) (defaults to: nil)

    (nil) The example. Metadata included in exports.

  • filterable (Boolean) (defaults to: false)

    (false) Whether the attribute is filterable.

  • format (Symbol, nil) (defaults to: nil)

    (nil) [:date, :datetime, :double, :email, :float, :hostname, :int32, :int64, :ipv4, :ipv6, :password, :text, :url, :uuid] Format hint for exports. Does not change the type, but exports may add validation or documentation based on it. Valid formats by type: ‘:decimal`/`:number` (`:double`, `:float`), `:integer` (`:int32`, `:int64`), `:string` (`:date`, `:datetime`, `:email`, `:hostname`, `:ipv4`, `:ipv6`, `:password`, `:text`, `:url`, `:uuid`).

  • max (Integer, nil) (defaults to: nil)

    (nil) The maximum. For ‘:array`: size. For `:decimal`, `:integer`, `:number`: value. For `:string`: length.

  • min (Integer, nil) (defaults to: nil)

    (nil) The minimum. For ‘:array`: size. For `:decimal`, `:integer`, `:number`: value. For `:string`: length.

  • nullable (Boolean, nil) (defaults to: nil)

    (nil) Whether the value can be ‘null`. If `nil` and name maps to a database column, auto-detected from column NULL constraint.

  • optional (Boolean, nil) (defaults to: nil)

    (nil) Whether the attribute is optional for writes. If ‘nil` and name maps to a database column, auto-detected from column default or NULL constraint.

  • preload (Symbol, Array, Hash, nil) (defaults to: nil)

    (nil) Associations to preload for this attribute. Use when custom attributes depend on associations.

  • sortable (Boolean) (defaults to: false)

    (false) Whether the attribute is sortable.

  • type (Symbol, nil) (defaults to: nil)

    (nil) [:array, :binary, :boolean, :date, :datetime, :decimal, :integer, :number, :object, :string, :time, :unknown, :uuid] The type. If ‘nil` and name maps to a database column, auto-detected from column type. Defaults to `:unknown` for json/jsonb columns and when no column exists (custom attributes). Use an explicit type or block in those cases.

  • writable (Boolean, Symbol) (defaults to: false)

    (false) [:create, :update] The write access. ‘true` for both create and update, `:create` for create only, `:update` for update only.

  • write_only (Boolean) (defaults to: false)

    (false) Whether the attribute is write-only. Write-only attributes are excluded from response serialization and response types but remain in writable payloads.

Yield Parameters:



275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
# File 'lib/apiwork/representation/base.rb', line 275

def attribute(
  name,
  decode: nil,
  default: UNSET,
  deprecated: false,
  description: nil,
  empty: nil,
  encode: nil,
  enum: nil,
  example: nil,
  filterable: false,
  format: nil,
  max: nil,
  min: nil,
  nullable: nil,
  optional: nil,
  preload: nil,
  sortable: false,
  type: nil,
  writable: false,
  write_only: false,
  &block
)
  self.attributes = attributes.merge(
    name => Attribute.new(
      name,
      self,
      decode:,
      default:,
      deprecated:,
      description:,
      empty:,
      encode:,
      enum:,
      example:,
      filterable:,
      format:,
      max:,
      min:,
      nullable:,
      optional:,
      preload:,
      sortable:,
      type:,
      writable:,
      write_only:,
      &block
    ),
  )
end

.attributesHash{Symbol => Attribute}

The attributes for this representation.

Returns:



52
# File 'lib/apiwork/representation/base.rb', line 52

class_attribute :attributes, default: {}, instance_accessor: false

.belongs_to(name, deprecated: false, description: nil, example: nil, filterable: false, include: :optional, nullable: nil, polymorphic: nil, representation: nil, sortable: false, writable: false) ⇒ void

This method returns an undefined value.

Defines a belongs_to association for this representation.

Subclasses inherit parent associations.

Examples:

Basic

belongs_to :customer

Explicit representation

belongs_to :author, representation: AuthorRepresentation

Always included

belongs_to :customer, include: :always

Polymorphic

belongs_to :commentable, polymorphic: [PostRepresentation, CustomerRepresentation]

Custom association

belongs_to :customer

def customer
  record.customer || Customer.default
end

Parameters:

  • name (Symbol)

    The association name.

  • deprecated (Boolean) (defaults to: false)

    (false) Whether deprecated. Metadata included in exports.

  • description (String, nil) (defaults to: nil)

    (nil) The description. Metadata included in exports.

  • example (Object, nil) (defaults to: nil)

    (nil) The example. Metadata included in exports.

  • filterable (Boolean) (defaults to: false)

    (false) Whether the association is filterable.

  • include (Symbol) (defaults to: :optional)

    (:optional) [:always, :optional] The inclusion mode.

  • nullable (Boolean, nil) (defaults to: nil)

    (nil) Whether the association can be ‘null`. If `nil`, auto-detected from foreign key column NULL constraint.

  • polymorphic (Array<Class<Representation::Base>>, nil) (defaults to: nil)

    (nil) The allowed representation classes for polymorphic associations.

  • representation (Class<Representation::Base>, nil) (defaults to: nil)

    (nil) The representation class. If ‘nil`, inferred from the associated model in the same namespace (e.g., `CustomerRepresentation` for `Customer`).

  • sortable (Boolean) (defaults to: false)

    (false) Whether the association is sortable.

  • writable (Boolean, Symbol) (defaults to: false)

    (false) [:create, :update] The write access. ‘true` for both create and update, `:create` for create only, `:update` for update only. Requires `accepts_nested_attributes_for` on the model, where `allow_destroy: true` also enables deletion.

See Also:

  • #has_one


521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
# File 'lib/apiwork/representation/base.rb', line 521

def belongs_to(
  name,
  deprecated: false,
  description: nil,
  example: nil,
  filterable: false,
  include: :optional,
  nullable: nil,
  polymorphic: nil,
  representation: nil,
  sortable: false,
  writable: false
)
  self.associations = associations.merge(
    name => Association.new(
      name,
      :belongs_to,
      self,
      deprecated:,
      description:,
      example:,
      filterable:,
      include:,
      nullable:,
      polymorphic:,
      representation:,
      sortable:,
      writable:,
    ),
  )
end

.deprecated!void

This method returns an undefined value.

Marks this representation as deprecated.

Metadata included in exports.

Examples:

deprecated!


730
731
732
# File 'lib/apiwork/representation/base.rb', line 730

def deprecated!
  @deprecated = true
end

.deprecated?Boolean

Whether this representation is deprecated.

Returns:

  • (Boolean)


834
835
836
# File 'lib/apiwork/representation/base.rb', line 834

def deprecated?
  @deprecated == true
end

.description(value = nil) ⇒ String?

The description for this representation.

Metadata included in exports.

Examples:

description 'A customer invoice'

Parameters:

  • value (String, nil) (defaults to: nil)

    (nil) The description.

Returns:

  • (String, nil)


715
716
717
718
719
# File 'lib/apiwork/representation/base.rb', line 715

def description(value = nil)
  return @description if value.nil?

  @description = value
end

.deserialize(payload) ⇒ Hash+

Transforms a hash or an array of hashes for records.

Applies attribute decoders, maps STI and polymorphic type names, and recursively deserializes nested associations.

Examples:

InvoiceRepresentation.deserialize(params[:invoice])

Parameters:

  • payload (Hash, Array<Hash>)

    The payload to deserialize.

Returns:

  • (Hash, Array<Hash>)


800
801
802
# File 'lib/apiwork/representation/base.rb', line 800

def deserialize(payload)
  Deserializer.deserialize(self, payload)
end

.example(value = nil) ⇒ Hash?

The example value for this representation.

Metadata included in exports.

Examples:

example id: 1, total: 99.00, status: 'paid'

Parameters:

  • value (Hash, nil) (defaults to: nil)

    (nil) The example.

Returns:

  • (Hash, nil)


745
746
747
748
749
# File 'lib/apiwork/representation/base.rb', line 745

def example(value = nil)
  return @example if value.nil?

  @example = value
end

.has_many(name, deprecated: false, description: nil, example: nil, filterable: false, include: :optional, representation: nil, sortable: false, writable: false) ⇒ void

This method returns an undefined value.

Defines a has_many association for this representation.

Subclasses inherit parent associations.

Examples:

Basic

has_many :items

Explicit representation

has_many :comments, representation: CommentRepresentation

Always included

has_many :items, include: :always

Custom association

has_many :items

def items
  record.items.limit(5)
end

Parameters:

  • name (Symbol)

    The association name.

  • deprecated (Boolean) (defaults to: false)

    (false) Whether deprecated. Metadata included in exports.

  • description (String, nil) (defaults to: nil)

    (nil) The description. Metadata included in exports.

  • example (Object, nil) (defaults to: nil)

    (nil) The example. Metadata included in exports.

  • filterable (Boolean) (defaults to: false)

    (false) Whether the association is filterable.

  • include (Symbol) (defaults to: :optional)

    (:optional) [:always, :optional] The inclusion mode.

  • representation (Class<Representation::Base>, nil) (defaults to: nil)

    (nil) The representation class. If ‘nil`, inferred from the associated model in the same namespace (e.g., `CustomerRepresentation` for `Customer`).

  • sortable (Boolean) (defaults to: false)

    (false) Whether the association is sortable.

  • writable (Boolean, Symbol) (defaults to: false)

    (false) [:create, :update] The write access. ‘true` for both create and update, `:create` for create only, `:update` for update only. Requires `accepts_nested_attributes_for` on the model, where `allow_destroy: true` also enables deletion.

See Also:

  • #has_one


443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
# File 'lib/apiwork/representation/base.rb', line 443

def has_many(
  name,
  deprecated: false,
  description: nil,
  example: nil,
  filterable: false,
  include: :optional,
  representation: nil,
  sortable: false,
  writable: false
)
  self.associations = associations.merge(
    name => Association.new(
      name,
      :has_many,
      self,
      deprecated:,
      description:,
      example:,
      filterable:,
      include:,
      representation:,
      sortable:,
      writable:,
    ),
  )
end

.has_one(name, deprecated: false, description: nil, example: nil, filterable: false, include: :optional, nullable: nil, representation: nil, sortable: false, writable: false) ⇒ void

This method returns an undefined value.

Defines a has_one association for this representation.

Subclasses inherit parent associations.

Examples:

Basic

has_one :profile

Explicit representation

has_one :author, representation: AuthorRepresentation

Always included

has_one :customer, include: :always

Custom association

has_one :profile

def profile
  record.profile || record.build_profile
end

Parameters:

  • name (Symbol)

    The association name.

  • deprecated (Boolean) (defaults to: false)

    (false) Whether deprecated. Metadata included in exports.

  • description (String, nil) (defaults to: nil)

    (nil) The description. Metadata included in exports.

  • example (Object, nil) (defaults to: nil)

    (nil) The example. Metadata included in exports.

  • filterable (Boolean) (defaults to: false)

    (false) Whether the association is filterable.

  • include (Symbol) (defaults to: :optional)

    (:optional) [:always, :optional] The inclusion mode.

  • nullable (Boolean, nil) (defaults to: nil)

    (nil) Whether the association can be ‘null`.

  • representation (Class<Representation::Base>, nil) (defaults to: nil)

    (nil) The representation class. If ‘nil`, inferred from the associated model in the same namespace (e.g., `CustomerRepresentation` for `Customer`).

  • sortable (Boolean) (defaults to: false)

    (false) Whether the association is sortable.

  • writable (Boolean, Symbol) (defaults to: false)

    (false) [:create, :update] The write access. ‘true` for both create and update, `:create` for create only, `:update` for update only. Requires `accepts_nested_attributes_for` on the model, where `allow_destroy: true` also enables deletion.



370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
# File 'lib/apiwork/representation/base.rb', line 370

def has_one(
  name,
  deprecated: false,
  description: nil,
  example: nil,
  filterable: false,
  include: :optional,
  nullable: nil,
  representation: nil,
  sortable: false,
  writable: false
)
  self.associations = associations.merge(
    name => Association.new(
      name,
      :has_one,
      self,
      deprecated:,
      description:,
      example:,
      filterable:,
      include:,
      nullable:,
      representation:,
      sortable:,
      writable:,
    ),
  )
end

.inheritanceRepresentation::Inheritance?

The inheritance configuration for this representation.

Auto-configured when the model uses STI and representation classes mirror the model hierarchy. Subclasses share the parent’s inheritance configuration.

Returns:



69
# File 'lib/apiwork/representation/base.rb', line 69

class_attribute :inheritance, default: nil, instance_accessor: false

.inheritance_for_column(column_name) ⇒ Object



861
862
863
864
865
866
867
868
869
870
# File 'lib/apiwork/representation/base.rb', line 861

def inheritance_for_column(column_name)
  target_class = subclass? ? superclass : self
  target_inheritance = target_class.inheritance
  target_model = target_class.model_class

  return nil unless target_inheritance&.subclasses&.any?
  return nil unless target_model.respond_to?(:inheritance_column)

  target_inheritance if column_name.to_sym == target_model.inheritance_column.to_sym
end

.model(value) ⇒ void

This method returns an undefined value.

Configures the model class for this representation.

Auto-detected from representation name when not set. Use model_class to retrieve.

Examples:

model Invoice

Parameters:

  • value (Class<ActiveRecord::Base>)

    The model class.

Raises:

  • (ArgumentError)

    if value is not an ActiveRecord model class



125
126
127
128
129
130
131
132
133
134
135
136
# File 'lib/apiwork/representation/base.rb', line 125

def model(value)
  unless value.is_a?(Class)
    raise ConfigurationError,
          "model must be an ActiveRecord model class, got #{value.class}. " \
                                                         "Use: model Post (not 'Post' or :post)"
  end
  unless value < ActiveRecord::Base
    raise ConfigurationError,
          "model must be an ActiveRecord model class, got #{value}"
  end
  @model_class = value
end

.model_classClass<ActiveRecord::Base>

The model class for this representation.

Auto-detected from representation name or set via model.

Returns:

  • (Class<ActiveRecord::Base>)


824
825
826
827
828
# File 'lib/apiwork/representation/base.rb', line 824

def model_class
  ensure_auto_detection_complete
  ensure_sti_auto_configuration_complete
  @model_class
end

.object(name, deprecated: false, description: nil, example: nil) {|object| ... } ⇒ void

This method returns an undefined value.

Defines an object type for this representation.

The type is copied to the contract that uses this representation. Attributes can reference it by name via ‘type:`. In exports, the type is scoped to the contract.

Examples:

Define and reference

object :address do
  string :street
  string :city
  string :postal_code
end

attribute :shipping_address, type: :address
attribute :billing_address, type: :address

Parameters:

  • name (Symbol)

    The object name.

  • deprecated (Boolean) (defaults to: false)

    (false) Whether deprecated. Metadata included in exports.

  • description (String, nil) (defaults to: nil)

    (nil) The description. Metadata included in exports.

  • example (Object, nil) (defaults to: nil)

    (nil) The example. Metadata included in exports.

Yield Parameters:



579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
# File 'lib/apiwork/representation/base.rb', line 579

def object(
  name,
  deprecated: false,
  description: nil,
  example: nil,
  &block
)
  self.type_definitions = type_definitions.merge(
    name.to_sym => {
      block:,
      kind: :object,
      options: {
        deprecated:,
        description:,
        example:,
      },
    },
  )
end

.polymorphic_association_for_type_column(column_name) ⇒ Object



855
856
857
858
859
# File 'lib/apiwork/representation/base.rb', line 855

def polymorphic_association_for_type_column(column_name)
  associations.values.find do |association|
    association.polymorphic? && association.discriminator == column_name
  end
end

.polymorphic_nameString

The polymorphic name for this representation.

Uses type_name if set, otherwise the model’s ‘polymorphic_name`.

Returns:

  • (String)


692
693
694
# File 'lib/apiwork/representation/base.rb', line 692

def polymorphic_name
  @type_name || model_class.polymorphic_name
end

.preloadsObject



851
852
853
# File 'lib/apiwork/representation/base.rb', line 851

def preloads
  attributes.values.filter_map(&:preload)
end

.root(singular, plural = singular.to_s.pluralize) ⇒ void

This method returns an undefined value.

Configures the JSON root key for this representation.

Auto-detected from model name when not set. Use root_key to retrieve.

Examples:

root :bill, :bills

Parameters:

  • singular (String, Symbol)

    The singular root key.

  • plural (String, Symbol) (defaults to: singular.to_s.pluralize)

    (singular.pluralize) The plural root key.



151
152
153
# File 'lib/apiwork/representation/base.rb', line 151

def root(singular, plural = singular.to_s.pluralize)
  @root = { plural: plural.to_s, singular: singular.to_s }
end

.root_keyRootKey

The root key for this representation.

Derived from model name when root is not set.

Returns:



810
811
812
813
814
815
816
# File 'lib/apiwork/representation/base.rb', line 810

def root_key
  if @root
    RootKey.new(@root[:singular], @root[:plural])
  else
    RootKey.new(model_class.model_name.element)
  end
end

.serialize(resource, context: {}, include: nil) ⇒ Hash+

Transforms a record or an array of records to hashes.

Applies attribute encoders, maps STI and polymorphic type names, and recursively serializes nested associations.

Examples:

Basic

InvoiceRepresentation.serialize(invoice)
# => { id: 1, total: 99.00, status: 'paid' }

Collection

InvoiceRepresentation.serialize(invoices)
# => [{ id: 1, ... }, { id: 2, ... }]

With associations

InvoiceRepresentation.serialize(invoice, include: [:customer, :items])
# => { id: 1, ..., customer: { id: 1, name: 'Acme' }, items: [...] }

Nested associations

InvoiceRepresentation.serialize(invoice, include: { customer: [:address] })
# => { id: 1, ..., customer: { id: 1, name: 'Acme', address: { ... } } }

Parameters:

  • resource (ActiveRecord::Base, Array<ActiveRecord::Base>)

    The resource to serialize.

  • context (Hash) (defaults to: {})

    ({}) The serialization context.

  • include (Symbol, Array, Hash, nil) (defaults to: nil)

    (nil) The associations to include.

Returns:

  • (Hash, Array<Hash>)


780
781
782
783
784
785
786
# File 'lib/apiwork/representation/base.rb', line 780

def serialize(resource, context: {}, include: nil)
  if resource.is_a?(Enumerable)
    resource.map { |record| serialize_record(record, context:, include:) }
  else
    serialize_record(resource, context:, include:)
  end
end

.serialize_record(record, context: {}, include: nil) ⇒ Object



872
873
874
875
876
877
# File 'lib/apiwork/representation/base.rb', line 872

def serialize_record(record, context: {}, include: nil)
  subclass_representation_class = inheritance.resolve(record) if inheritance&.subclasses&.any?
  representation_class = subclass_representation_class || self

  representation_class.new(record, context:, include:).as_json
end

.sti_nameString

The STI name for this representation.

Uses type_name if set, otherwise the model’s ‘sti_name`.

Returns:

  • (String)


682
683
684
# File 'lib/apiwork/representation/base.rb', line 682

def sti_name
  @type_name || model_class.sti_name
end

.subclass?Boolean

Whether this representation is an STI subclass.

Returns:

  • (Boolean)


700
701
702
# File 'lib/apiwork/representation/base.rb', line 700

def subclass?
  superclass.respond_to?(:inheritance) && superclass.inheritance&.subclass?(self)
end

.type_name(value = nil) ⇒ String?

The type name for this representation.

Overrides the model’s default for STI and polymorphic types.

Examples:

type_name :person

Parameters:

  • value (String, Symbol, nil) (defaults to: nil)

    (nil) The type name.

Returns:

  • (String, nil)

See Also:



670
671
672
673
674
# File 'lib/apiwork/representation/base.rb', line 670

def type_name(value = nil)
  return @type_name = value.to_s if value

  @type_name
end

.union(name, deprecated: false, description: nil, discriminator: nil, example: nil) {|union| ... } ⇒ void

This method returns an undefined value.

Defines a union type for this representation.

The type is copied to the contract that uses this representation. Attributes can reference it by name via ‘type:`. In exports, the type is scoped to the contract.

Examples:

Define and reference

union :content_block, discriminator: :kind do
  variant tag: 'text' do
    object do
      string :body
    end
  end
  variant tag: 'image' do
    object do
      string :url
      integer :width
      integer :height
    end
  end
end

attribute :content, type: :content_block

Parameters:

  • name (Symbol)

    The union name.

  • deprecated (Boolean) (defaults to: false)

    (false) Whether deprecated. Metadata included in exports.

  • description (String, nil) (defaults to: nil)

    (nil) The description. Metadata included in exports.

  • discriminator (Symbol, nil) (defaults to: nil)

    (nil) The discriminator field name.

  • example (Object, nil) (defaults to: nil)

    (nil) The example. Metadata included in exports.

Yield Parameters:



635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
# File 'lib/apiwork/representation/base.rb', line 635

def union(
  name,
  deprecated: false,
  description: nil,
  discriminator: nil,
  example: nil,
  &block
)
  self.type_definitions = type_definitions.merge(
    name.to_sym => {
      block:,
      kind: :union,
      options: {
        deprecated:,
        description:,
        discriminator:,
        example:,
      },
    },
  )
end

Instance Method Details

#as_jsonObject



928
929
930
# File 'lib/apiwork/representation/base.rb', line 928

def as_json
  Serializer.serialize(self, @include)
end