Skip to content

A platform for community discussion. Free, open, simple.

DEV: Allow to merge attributes in JSON:API versions (#43407)

Loïc Guitautd0fdaa3fe5f5
diff --git a/lib/json_api_kit/anchoring.rb b/lib/json_api_kit/anchoring.rb
index 47be39f88bd..cabf6bda5a5 100644
--- a/lib/json_api_kit/anchoring.rb
+++ b/lib/json_api_kit/anchoring.rb
@@ -16,6 +16,8 @@ module JsonApiKit
@value = value
end
- def computed? = value.nil?
+ def single_value? = !without_value? && !value.is_a?(Enumerable)
+
+ def without_value? = value.nil?
end
end
diff --git a/lib/json_api_kit/bad_parameter.rb b/lib/json_api_kit/bad_parameter.rb
new file mode 100644
index 00000000000..f5d4d680daf
--- /dev/null
+++ b/lib/json_api_kit/bad_parameter.rb
@@ -0,0 +1,18 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class BadParameter < BadRequest
+ def initialize(message, parameter: nil)
+ @parameter = parameter
+ super(message)
+ end
+
+ def source = { parameter: }.compact
+
+ def at(parameter) = self.class.new(*arguments, parameter:)
+
+ private
+
+ attr_reader :parameter
+ end
+end
diff --git a/lib/json_api_kit/declarations/anchor.rb b/lib/json_api_kit/declarations/anchor.rb
index b542806ed53..2a0ce1b8e5b 100644
--- a/lib/json_api_kit/declarations/anchor.rb
+++ b/lib/json_api_kit/declarations/anchor.rb
@@ -20,33 +20,19 @@ module JsonApiKit
IDENTITY = "id"
- attr_reader :name
-
- def initialize(name, &condition)
- @name = name.to_s
- @condition = condition
- end
-
- def locatable_in?(order) = computed? || order.leading.named?(name) || identity?
-
- def locate(scope, value:, order:, guardian:)
- kind_for(order.leading, value, guardian).locate(scope, order:)
+ class << self
+ def for(name, &condition)
+ return Computed.new(name, &condition) if condition
+ return Identity.new(name) if name.to_s == IDENTITY
+ Attribute.new(name)
+ end
end
- private
-
- attr_reader :condition
+ attr_reader :name
- def kind_for(key, value, guardian)
- return Computed.new(condition, guardian) if computed?
- return Value.new(key, value) if key.named?(name)
- return Identity.new(name, value) if identity?
- raise ArgumentError, "The anchor is #{name}, but this request sorts by #{key}."
+ def initialize(name)
+ @name = name.to_s
end
-
- def computed? = condition.present?
-
- def identity? = name == IDENTITY
end
end
end
diff --git a/lib/json_api_kit/declarations/anchor/attribute.rb b/lib/json_api_kit/declarations/anchor/attribute.rb
new file mode 100644
index 00000000000..c7c52592884
--- /dev/null
+++ b/lib/json_api_kit/declarations/anchor/attribute.rb
@@ -0,0 +1,21 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ module Declarations
+ class Anchor
+ class Attribute < Anchor
+ def accepts?(anchoring) = anchoring.single_value?
+
+ def locatable_in?(order) = order.leading.named?(name)
+
+ def locate(anchoring, scope:, order:, guardian:)
+ unless locatable_in?(order)
+ raise ArgumentError,
+ "The anchor is #{name}, but this request sorts by #{order.leading}."
+ end
+ order.enter(scope, at_or_after: order.leading.at_or_after(scope, anchoring.value))
+ end
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/declarations/anchor/computed.rb b/lib/json_api_kit/declarations/anchor/computed.rb
index 1d2d9b51e5f..0791479589a 100644
--- a/lib/json_api_kit/declarations/anchor/computed.rb
+++ b/lib/json_api_kit/declarations/anchor/computed.rb
@@ -3,17 +3,22 @@
module JsonApiKit
module Declarations
class Anchor
- class Computed
- def initialize(condition, guardian)
+ class Computed < Anchor
+ def initialize(name, &condition)
+ super(name)
@condition = condition
- @guardian = guardian
end
- def locate(scope, order:) = order.locate(condition.call(scope, guardian))
+ def accepts?(anchoring) = anchoring.without_value?
+
+ def locatable_in?(_order) = true
+
+ def locate(_anchoring, scope:, order:, guardian:) =
+ order.locate(condition.call(scope, guardian))
private
- attr_reader :condition, :guardian
+ attr_reader :condition
end
end
end
diff --git a/lib/json_api_kit/declarations/anchor/identity.rb b/lib/json_api_kit/declarations/anchor/identity.rb
index 4dae9ddff4d..4a143d9141b 100644
--- a/lib/json_api_kit/declarations/anchor/identity.rb
+++ b/lib/json_api_kit/declarations/anchor/identity.rb
@@ -3,19 +3,15 @@
module JsonApiKit
module Declarations
class Anchor
- class Identity
- def initialize(name, value)
- @name = name
- @value = value
- end
-
- def locate(scope, order:)
- order.locate(scope.where(scope.primary_key => value)) or raise NoRow.new(name, value)
- end
+ class Identity < Anchor
+ def accepts?(anchoring) = anchoring.single_value?
- private
+ def locatable_in?(_order) = true
- attr_reader :name, :value
+ def locate(anchoring, scope:, order:, guardian:)
+ order.locate(scope.where(scope.primary_key => anchoring.value)) or
+ raise NoRow.new(name, anchoring.value)
+ end
end
end
end
diff --git a/lib/json_api_kit/declarations/anchor/value.rb b/lib/json_api_kit/declarations/anchor/value.rb
deleted file mode 100644
index 394634d09f0..00000000000
--- a/lib/json_api_kit/declarations/anchor/value.rb
+++ /dev/null
@@ -1,22 +0,0 @@
-# frozen_string_literal: true
-
-module JsonApiKit
- module Declarations
- class Anchor
- class Value
- def initialize(key, value)
- @key = key
- @value = value
- end
-
- def locate(scope, order:)
- order.enter(scope, at_or_after: key.at_or_after(scope, value))
- end
-
- private
-
- attr_reader :key, :value
- end
- end
- end
-end
diff --git a/lib/json_api_kit/declarations/anchors.rb b/lib/json_api_kit/declarations/anchors.rb
index e7f5c3d14c7..7aad32381e3 100644
--- a/lib/json_api_kit/declarations/anchors.rb
+++ b/lib/json_api_kit/declarations/anchors.rb
@@ -11,7 +11,7 @@ module JsonApiKit
end
def locate(anchoring, scope:, order:)
- fetch(anchoring.name).locate(scope, value: anchoring.value, order:, guardian:)
+ fetch(anchoring.name).locate(anchoring, scope:, order:, guardian:)
end
private
diff --git a/lib/json_api_kit/document.rb b/lib/json_api_kit/document.rb
index bc0e29694bd..e39cb6526d1 100644
--- a/lib/json_api_kit/document.rb
+++ b/lib/json_api_kit/document.rb
@@ -2,32 +2,26 @@
module JsonApiKit
class Document
- def self.build(parameters, resource:, urls:, glossary:)
- declared_parameters =
- Request::Parameters.new(parameters.to_hash.deep_stringify_keys, glossary:, resource:).to_h
- contract_class
- .new(
- **declared_parameters.deep_dup,
- options: {
- resource:,
- raw_parameters: declared_parameters.with_indifferent_access,
- },
- )
- .then do |contract|
- if contract.invalid?
- next(Errors.new(*Request::Contract::Mapper.new(contract.errors, glossary:).to_a))
- end
- new(yield(contract.to_hash), urls:, glossary:).tap(&:to_h)
- end
- rescue Error => error
- Errors.new(error)
+ class << self
+ private
+
+ def build(raw, resource:, urls:, glossary:)
+ parameters = Request::Parameters.new(raw.to_hash.deep_stringify_keys, glossary:, resource:)
+ contract = contract_class.for(parameters.to_h, resource:, glossary:)
+ return Errors.new(*contract.refusals) if contract.invalid?
+ assemble(new(yield(contract.to_hash), urls:, glossary:, fieldsets: parameters.fieldsets))
+ rescue Error => error
+ Errors.new(error)
+ end
+
+ def assemble(document) = document.tap(&:to_h)
end
- private_class_method :build
- def initialize(query, urls:, glossary:)
+ def initialize(query, urls:, glossary:, fieldsets:)
@query = query
@urls = urls
@glossary = glossary
+ @fieldsets = fieldsets
end
def to_h = @to_h ||= { data:, included:, links: }
@@ -36,12 +30,14 @@ module JsonApiKit
private
- attr_reader :query, :urls, :glossary
+ attr_reader :query, :urls, :glossary, :fieldsets
def contents = @contents ||= Contents.new(primary_records, query.included)
def links = { self: { href: urls.current.to_s, type: Pagination::Profile::MEDIA_TYPE } }
- def included = contents.related.map { ResourceObject.new(it, urls:, glossary:).to_h }
+ def included
+ contents.related.map { ResourceObject.new(it, urls:, glossary:, fieldsets:).to_h }
+ end
end
end
diff --git a/lib/json_api_kit/document/collection.rb b/lib/json_api_kit/document/collection.rb
index aad1850c428..aecfda408b0 100644
--- a/lib/json_api_kit/document/collection.rb
+++ b/lib/json_api_kit/document/collection.rb
@@ -16,7 +16,9 @@ module JsonApiKit
def primary_records = query.records
def data
- contents.primary.map { ResourceObject.new(it, urls:, glossary:, meta: page_meta(it)).to_h }
+ contents.primary.map do
+ ResourceObject.new(it, urls:, glossary:, fieldsets:, meta: page_meta(it)).to_h
+ end
end
def page_meta(record)
diff --git a/lib/json_api_kit/document/individual.rb b/lib/json_api_kit/document/individual.rb
index a0d1cf4f605..44967d4ab39 100644
--- a/lib/json_api_kit/document/individual.rb
+++ b/lib/json_api_kit/document/individual.rb
@@ -15,7 +15,7 @@ module JsonApiKit
def primary_records = [query.record]
- def data = ResourceObject.new(contents.primary.sole, urls:, glossary:).to_h
+ def data = ResourceObject.new(contents.primary.sole, urls:, glossary:, fieldsets:).to_h
end
end
end
diff --git a/lib/json_api_kit/document/resource_object.rb b/lib/json_api_kit/document/resource_object.rb
index bab7bd87602..455499190b4 100644
--- a/lib/json_api_kit/document/resource_object.rb
+++ b/lib/json_api_kit/document/resource_object.rb
@@ -5,10 +5,11 @@ module JsonApiKit
class ResourceObject
delegate :type, :id, to: :record, private: true
- def initialize(record, urls:, glossary:, meta: {})
+ def initialize(record, urls:, glossary:, fieldsets:, meta: {})
@record = record
@urls = urls
@glossary = glossary
+ @fieldsets = fieldsets
@meta = meta
end
@@ -16,13 +17,15 @@ module JsonApiKit
private
- attr_reader :record, :urls, :glossary, :meta
+ attr_reader :record, :urls, :glossary, :fieldsets, :meta
def relationship(value) = Name::Relationship.new(value:, type:)
def member_value(name) = glossary.member_name(name).value
- def attributes = glossary.member_attributes(record.attributes).transform_keys(&:value)
+ def attributes
+ fieldsets.keep(type, glossary.member_attributes(record.attributes).transform_keys(&:value))
+ end
def relationships
record.relationships.to_h do |name, linkage|
diff --git a/lib/json_api_kit/glossary.rb b/lib/json_api_kit/glossary.rb
index 8549970d2f0..6d907440c63 100644
--- a/lib/json_api_kit/glossary.rb
+++ b/lib/json_api_kit/glossary.rb
@@ -11,21 +11,35 @@ module JsonApiKit
end
end
- class NotAMemberName < BadRequest
+ class NotAMemberName < BadParameter
attr_reader :raw, :member
def initialize(raw, member, parameter: nil)
@raw = raw
@member = member
- @parameter = parameter
- super("Use #{member}, not #{raw}.")
+ super("Use #{member}, not #{raw}.", parameter:)
end
def title = "Invalid member name"
- def source = { parameter: @parameter }.compact
+ private
- def at(parameter) = self.class.new(raw, member, parameter:)
+ def arguments = [raw, member]
+ end
+
+ class BadValue < BadParameter
+ def initialize(names, parameter: nil)
+ @names = names
+ super("This version cannot convert the value of #{names.join(", ")}.", parameter:)
+ end
+
+ def title = "Invalid value"
+
+ private
+
+ attr_reader :names
+
+ def arguments = [names]
end
class << self
@@ -43,6 +57,8 @@ module JsonApiKit
def declared_attributes(attributes)
attributes.each_key { declared_name(it) }
rules.reduce(attributes) { |result, rule| rule.declared_attributes(result) }
+ rescue VersionChange::Converter::Failure => failure
+ raise BadValue.new(failure.names.map { member_name(it) })
end
def declared_name(name)
diff --git a/lib/json_api_kit/glossary/version_rule.rb b/lib/json_api_kit/glossary/version_rule.rb
index 483301b3390..57eb5d3e4d0 100644
--- a/lib/json_api_kit/glossary/version_rule.rb
+++ b/lib/json_api_kit/glossary/version_rule.rb
@@ -12,7 +12,7 @@ module JsonApiKit
end
def declared_name(name)
- current_name(name).tap { raise Correction.new(it) unless member_name(it) == name }
+ current_name(name).tap { raise Correction.new(it) if member_names(it).exclude?(name) }
end
def member_name(name)
@@ -30,6 +30,12 @@ module JsonApiKit
attr_reader :changes
def current_name(name) = changes.reduce(name) { |result, change| change.current(result) }
+
+ def member_names(name)
+ changes
+ .reverse_each
+ .reduce([name]) { |names, change| names.flat_map { change.previous_names(it) } }
+ end
end
end
end
diff --git a/lib/json_api_kit/page/requested/around.rb b/lib/json_api_kit/page/requested/around.rb
index fb3013837e9..4e323a9454d 100644
--- a/lib/json_api_kit/page/requested/around.rb
+++ b/lib/json_api_kit/page/requested/around.rb
@@ -21,7 +21,7 @@ module JsonApiKit
def paginate(scope, order:, limits:, anchors:)
row = anchors.locate(anchoring, scope:, order:)
return window(limits).paginate(scope, order:, row:) if row
- return Pagination::EmptyPage.new unless anchoring.computed?
+ return Pagination::EmptyPage.new unless anchoring.without_value?
First.new(size:).paginate(scope, order:, limits:)
end
diff --git a/lib/json_api_kit/request.rb b/lib/json_api_kit/request.rb
index 030d994ed8a..b95e04b3d0e 100644
--- a/lib/json_api_kit/request.rb
+++ b/lib/json_api_kit/request.rb
@@ -2,6 +2,9 @@
module JsonApiKit
class Request
+ LIST = ","
+ SORT_DIRECTIONS = { "-" => :desc, "" => :asc }.freeze
+
attr_reader :guardian
def initialize(params = {}, guardian:)
diff --git a/lib/json_api_kit/request/contract.rb b/lib/json_api_kit/request/contract.rb
index c053eaed075..483e099a263 100644
--- a/lib/json_api_kit/request/contract.rb
+++ b/lib/json_api_kit/request/contract.rb
@@ -19,6 +19,19 @@ module JsonApiKit
INDIFFERENT_HASH = IndifferentHashType.new
+ class << self
+ def for(parameters, resource:, glossary:)
+ new(
+ **parameters.deep_dup,
+ options: {
+ resource:,
+ glossary:,
+ raw_parameters: parameters.with_indifferent_access,
+ },
+ )
+ end
+ end
+
include RawAttributes
validate :check_shapes
@@ -29,10 +42,14 @@ module JsonApiKit
super
end
+ def refusals = Mapper.new(errors, glossary:).to_a
+
private
def resource = options[:resource]
+ def glossary = options[:glossary]
+
def raw_parameters = options[:raw_parameters]
def comparable?(value) = !value.is_a?(Enumerable)
diff --git a/lib/json_api_kit/request/contract/fields.rb b/lib/json_api_kit/request/contract/fields.rb
index d473c01cce5..687726472bc 100644
--- a/lib/json_api_kit/request/contract/fields.rb
+++ b/lib/json_api_kit/request/contract/fields.rb
@@ -13,16 +13,7 @@ module JsonApiKit
private
- def fields(value)
- case value
- when String
- value.split(",")
- when Array
- value.map(&:to_s)
- else
- value
- end
- end
+ def fields(value) = value.is_a?(Array) ? value.map(&:to_s) : value
end
included do
diff --git a/lib/json_api_kit/request/contract/including.rb b/lib/json_api_kit/request/contract/including.rb
index d3203a3680b..6227d6ed43f 100644
--- a/lib/json_api_kit/request/contract/including.rb
+++ b/lib/json_api_kit/request/contract/including.rb
@@ -10,7 +10,7 @@ module JsonApiKit
def cast_value(value)
case value
when String
- value.split(",")
+ value.split(LIST)
else
value
end
diff --git a/lib/json_api_kit/request/contract/paging.rb b/lib/json_api_kit/request/contract/paging.rb
index c000f826f30..dd5cb0342b8 100644
--- a/lib/json_api_kit/request/contract/paging.rb
+++ b/lib/json_api_kit/request/contract/paging.rb
@@ -59,7 +59,8 @@ module JsonApiKit
validate :check_cursors, if: -> { raw_cursors.present? }
validate :check_cursor_ordering, if: -> { cursors.present? && sortable? }
validate :check_anchor_name, if: -> { anchor.present? }
- validate :check_anchor_value, if: -> { anchor.present? }
+ validate :check_anchor_value,
+ if: -> { anchor.present? && anchoring.name.in?(resource.anchor_names) }
validate :check_anchor_ordering, if: -> { anchor.present? && sortable? }
def cursor? = after.present? || before.present?
@@ -84,11 +85,11 @@ module JsonApiKit
def raw_sort = options[:raw_parameters][:sort]
- def ordering = raw_sort.nil? ? {} : Sorting::SORT.cast(raw_sort)
+ def ordering = raw_sort.nil? ? {} : INDIFFERENT_HASH.cast(raw_sort)
def sortable?
return false unless ordering
- ordering.values.all? { it.in?(Sorting::DIRECTIONS.values) } &&
+ ordering.values.all? { it.in?(SORT_DIRECTIONS.values) } &&
resource.sortable_by?(ordering:)
end
@@ -114,7 +115,7 @@ module JsonApiKit
end
def check_anchor_name
- ([anchor_name.to_s] - resource.anchor_names).each do
+ ([anchoring.name] - resource.anchor_names).each do
errors.add(
:anchor,
:no_such_name,
@@ -125,21 +126,21 @@ module JsonApiKit
end
def check_anchor_value
- return unless anchor_value.is_a?(Enumerable)
+ return if resource.anchor_accepts?(anchoring)
errors.add(
:anchor,
:bad_value,
- name: Name::Anchor.new(value: anchor_name.to_s, type: resource.type),
+ name: Name::Anchor.new(value: anchoring.name, type: resource.type),
message: "bad value",
)
end
def check_anchor_ordering
- return if resource.anchored_by?(anchor_name:, ordering:)
+ return if resource.anchored_by?(anchor_name: anchoring.name, ordering:)
errors.add(
:anchor,
:not_the_sort,
- name: Name::Anchor.new(value: anchor_name.to_s, type: resource.type),
+ name: Name::Anchor.new(value: anchoring.name, type: resource.type),
key:
Name::Sort.new(
value: resource.order(ordering).leading.name.to_s,
@@ -149,11 +150,7 @@ module JsonApiKit
)
end
- def anchor_pair = Array(anchor.to_a.first)
-
- def anchor_name = anchor_pair.first
-
- def anchor_value = anchor_pair.last
+ def anchoring = @anchoring ||= Anchoring.for(anchor)
end
end
end
diff --git a/lib/json_api_kit/request/contract/sorting.rb b/lib/json_api_kit/request/contract/sorting.rb
index 37bac101a2d..7c50fa76141 100644
--- a/lib/json_api_kit/request/contract/sorting.rb
+++ b/lib/json_api_kit/request/contract/sorting.rb
@@ -6,30 +6,8 @@ module JsonApiKit
module Sorting
extend ActiveSupport::Concern
- DIRECTIONS = { "-" => :desc, "" => :asc }.freeze
-
- class SortType < IndifferentHashType
- def cast_value(value)
- super(value.is_a?(String) ? sorts(value) : value)
- end
-
- private
-
- def sorts(value)
- value
- .split(",")
- .to_h do |raw_sort|
- raw_sort
- .partition(/\A-/)
- .then { |head, match, tail| [head.presence || tail, DIRECTIONS[match]] }
- end
- end
- end
-
- SORT = SortType.new
-
included do
- attribute :sort, SORT
+ attribute :sort, INDIFFERENT_HASH
validate :check_sort_names, if: -> { sort.present? }
validate :check_sort_directions, if: -> { sort.present? }
@@ -48,7 +26,7 @@ module JsonApiKit
def check_sort_directions
sort.each_value do |direction|
- next if direction.in?(DIRECTIONS.values)
+ next if direction.in?(SORT_DIRECTIONS.values)
errors.add(:sort, :unknown_direction, direction:, message: "unknown direction")
end
end
diff --git a/lib/json_api_kit/request/family.rb b/lib/json_api_kit/request/family.rb
index 83905dbf525..4a7e81bc857 100644
--- a/lib/json_api_kit/request/family.rb
+++ b/lib/json_api_kit/request/family.rb
@@ -3,7 +3,6 @@
module JsonApiKit
class Request
class Family
- LIST = ","
LIST_ITEM = /\A(?<direction>-?)(?<name>.*)\z/m
def initialize(glossary:, type:)
@@ -17,8 +16,6 @@ module JsonApiKit
def names(value, path, &name_for)
case value
- when Hash
- value.transform_keys { declared_name(name_for.call(it), path + [it]) }
when Array
value.map { names(it, path, &name_for) }
when String, Symbol
diff --git a/lib/json_api_kit/request/family/fields.rb b/lib/json_api_kit/request/family/fields.rb
index 519f372a8d2..bd44f82d7b6 100644
--- a/lib/json_api_kit/request/family/fields.rb
+++ b/lib/json_api_kit/request/family/fields.rb
@@ -6,14 +6,17 @@ module JsonApiKit
class Fields < Family
def declared_value(value, path)
return value unless value.is_a?(Hash)
- value.to_h do |fieldset_type, fields|
- [
- fieldset_type,
- names(fields, path + [fieldset_type]) do |field|
- Name::Field.new(value: field, type: fieldset_type)
- end,
- ]
- end
+ value.to_h { |type, raw| [type, declared_fieldset(raw, type, path + [type])] }
+ end
+
+ private
+
+ def declared_fieldset(raw, type, path)
+ Fieldsets::Fieldset
+ .parse(raw)
+ .try do |fieldset|
+ fieldset.names.map { declared_name(Name::Field.new(value: it, type:), path) }
+ end || raw
end
end
end
diff --git a/lib/json_api_kit/request/family/page.rb b/lib/json_api_kit/request/family/page.rb
index 055d294455b..804b9902755 100644
--- a/lib/json_api_kit/request/family/page.rb
+++ b/lib/json_api_kit/request/family/page.rb
@@ -22,13 +22,15 @@ module JsonApiKit
end
def declared_anchor(value, path)
- glossary.declared_attributes(value.transform_keys { anchor_name(it) }).transform_keys(
- &:value
- )
+ glossary.declared_attributes(anchor_attributes(value)).transform_keys(&:value)
rescue Glossary::NotAMemberName => error
raise error.at(ParameterName.new(*path, error.raw.value).to_s)
+ rescue Glossary::BadValue => error
+ raise error.at(ParameterName.new(*path).to_s)
end
+ def anchor_attributes(value) = value.transform_keys { anchor_name(it) }
+
def anchor_name(value) = Name::Anchor.new(value:, type:)
end
end
diff --git a/lib/json_api_kit/request/family/sort.rb b/lib/json_api_kit/request/family/sort.rb
index 841e9fe6849..52cc008bf50 100644
--- a/lib/json_api_kit/request/family/sort.rb
+++ b/lib/json_api_kit/request/family/sort.rb
@@ -4,7 +4,30 @@ module JsonApiKit
class Request
class Family
class Sort < Family
- def declared_value(value, path) = names(value, path) { Name::Sort.new(value: it, type:) }
+ class TwoDirections < BadParameter
+ def initialize(names, parameter: nil)
+ @names = names
+ super("#{names.join(" and ")} sort by one attribute in two directions.", parameter:)
+ end
+
+ def title = "Invalid sort"
+
+ private
+
+ attr_reader :names
+
+ def arguments = [names]
+ end
+
+ def declared_value(value, path)
+ Keys
+ .parse(value, path)
+ .try { it.declare { |key| declared_name(sort_name(key.name), key.path) } } || value
+ end
+
+ private
+
+ def sort_name(value) = Name::Sort.new(value:, type:)
end
end
end
diff --git a/lib/json_api_kit/request/family/sort/keys.rb b/lib/json_api_kit/request/family/sort/keys.rb
new file mode 100644
index 00000000000..25a7e312606
--- /dev/null
+++ b/lib/json_api_kit/request/family/sort/keys.rb
@@ -0,0 +1,58 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Request
+ class Family
+ class Sort
+ class Keys
+ Key = Data.define(:name, :direction, :path)
+
+ class << self
+ def parse(value, path)
+ case value
+ when Hash
+ new(
+ value.map { |name, direction| Key.new(name.to_s, direction, path + [name.to_s]) },
+ path,
+ )
+ when String, Symbol
+ new(value.to_s.split(LIST, -1).map { key(it, path) }, path)
+ end
+ end
+
+ private
+
+ def key(item, path)
+ prefix, name = LIST_ITEM.match(item).captures
+ Key.new(name, SORT_DIRECTIONS[prefix], path)
+ end
+ end
+
+ def initialize(keys, path)
+ @keys = keys
+ @path = path
+ end
+
+ def declare
+ keys
+ .group_by { yield(it) }
+ .to_h { |declared, same_name| [declared, shared_direction(same_name)] }
+ end
+
+ private
+
+ attr_reader :keys, :path
+
+ def shared_direction(keys)
+ raise TwoDirections.new(keys.map(&:name), parameter:) unless one_direction?(keys)
+ keys.first.direction
+ end
+
+ def one_direction?(keys) = keys.map(&:direction).uniq(&:to_s).one?
+
+ def parameter = ParameterName.new(*path).to_s
+ end
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/request/fieldsets.rb b/lib/json_api_kit/request/fieldsets.rb
new file mode 100644
index 00000000000..9b308be3a84
--- /dev/null
+++ b/lib/json_api_kit/request/fieldsets.rb
@@ -0,0 +1,19 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Request
+ class Fieldsets
+ def self.parse(raw) = new(raw.to_h.transform_values { Fieldset.parse(it) }.compact)
+
+ def initialize(fieldsets)
+ @fieldsets = fieldsets
+ end
+
+ def keep(type, attributes) = fieldsets.fetch(type, Fieldset::All).keep(attributes)
+
+ private
+
+ attr_reader :fieldsets
+ end
+ end
+end
diff --git a/lib/json_api_kit/request/fieldsets/fieldset.rb b/lib/json_api_kit/request/fieldsets/fieldset.rb
new file mode 100644
index 00000000000..8e113856b63
--- /dev/null
+++ b/lib/json_api_kit/request/fieldsets/fieldset.rb
@@ -0,0 +1,32 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Request
+ class Fieldsets
+ class Fieldset
+ module All
+ def self.keep(attributes) = attributes
+ end
+
+ class << self
+ def parse(raw)
+ case raw
+ when String
+ new(raw.split(LIST, -1))
+ when Array
+ new(raw.map(&:to_s))
+ end
+ end
+ end
+
+ attr_reader :names
+
+ def initialize(names)
+ @names = names
+ end
+
+ def keep(attributes) = attributes.select { |name, _value| names.include?(name) }
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/request/parameters.rb b/lib/json_api_kit/request/parameters.rb
index 8f5f272a397..ad8a66d13c0 100644
--- a/lib/json_api_kit/request/parameters.rb
+++ b/lib/json_api_kit/request/parameters.rb
@@ -24,6 +24,8 @@ module JsonApiKit
end
end
+ def fieldsets = Fieldsets.parse(raw["fields"])
+
private
attr_reader :raw, :glossary, :resource
diff --git a/lib/json_api_kit/resource/anchoring.rb b/lib/json_api_kit/resource/anchoring.rb
index 0404bfb17ca..66d1b4bc129 100644
--- a/lib/json_api_kit/resource/anchoring.rb
+++ b/lib/json_api_kit/resource/anchoring.rb
@@ -15,18 +15,24 @@ module JsonApiKit
class_methods do
def anchor(name, &condition)
- self.declared_anchors = declared_anchors + [Declarations::Anchor.new(name, &condition)]
+ self.declared_anchors = declared_anchors + [Declarations::Anchor.for(name, &condition)]
end
def anchor_names = declared_anchors.map(&:name)
+ def anchor_accepts?(anchoring)
+ declared_anchor(anchoring.name).try { it.accepts?(anchoring) } || false
+ end
+
def anchored_by?(anchor_name:, ordering: {})
- declared_anchors
- .detect { it.name == anchor_name.to_s }
- .then { it.nil? || it.locatable_in?(order(ordering)) }
+ declared_anchor(anchor_name).then { it.nil? || it.locatable_in?(order(ordering)) }
end
def anchors(guardian) = Declarations::Anchors.new(declared_anchors, guardian:)
+
+ private
+
+ def declared_anchor(name) = declared_anchors.detect { it.name == name.to_s }
end
end
end
diff --git a/lib/json_api_kit/version_change.rb b/lib/json_api_kit/version_change.rb
index 7e641bf2f41..c43071a7e28 100644
--- a/lib/json_api_kit/version_change.rb
+++ b/lib/json_api_kit/version_change.rb
@@ -53,8 +53,8 @@ module JsonApiKit
def initialize(source)
@source = source
- @upward = index_by(&:from)
- @downward = index_by(&:to)
+ @upward = index_by(&:previous_names)
+ @downward = index_by { [it.current] }
end
def verify!
@@ -64,8 +64,10 @@ module JsonApiKit
raise ArgumentError, "#{source} is dated on or before the first release."
end
raise ArgumentError, "#{source} has no description." if description.blank?
- duplicate_name(:from).try { raise ArgumentError, "#{source} renames #{it} twice." }
- duplicate_name(:to).try { raise ArgumentError, "#{source} renames two names to #{it}." }
+ duplicate_name(&:previous_names).try { raise ArgumentError, "#{source} changes #{it} twice." }
+ duplicate_name { [it.current] }.try do
+ raise ArgumentError, "#{source} changes two names into #{it}."
+ end
return if File.basename(source).start_with?(version.to_s)
raise ArgumentError, "The file name must start with the version #{version}: #{source}."
end
@@ -73,10 +75,12 @@ module JsonApiKit
def current(name) = upward[name].current
def current_attributes(attributes)
- attributes.flat_map { |name, value| upward[name].current_pairs(value) }.to_h
+ attributes.keys.map { upward[it] }.uniq.flat_map { it.current_pairs(attributes) }.to_h
end
- def previous(name) = downward[name].previous
+ def previous(name) = downward[name].previous_names.first
+
+ def previous_names(name) = downward[name].previous_names
def previous_attributes(attributes)
attributes.flat_map { |name, value| downward[name].previous_pairs(value) }.to_h
@@ -86,10 +90,15 @@ module JsonApiKit
attr_reader :upward, :downward
- def index_by(&) = transformations.index_by(&).tap { it.default_proc = PASS_THROUGH }
+ def index_by(&names)
+ transformations
+ .flat_map { |transformation| names.call(transformation).map { [it, transformation] } }
+ .to_h
+ .tap { it.default_proc = PASS_THROUGH }
+ end
- def duplicate_name(field)
- transformations.map(&field).tally.detect { |_name, count| count > 1 }&.first
+ def duplicate_name(&)
+ transformations.flat_map(&).tally.detect { |_name, count| count > 1 }&.first
end
end
end
diff --git a/lib/json_api_kit/version_change/converter.rb b/lib/json_api_kit/version_change/converter.rb
new file mode 100644
index 00000000000..a46b3515b18
--- /dev/null
+++ b/lib/json_api_kit/version_change/converter.rb
@@ -0,0 +1,42 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class VersionChange
+ class Converter
+ class Failure < StandardError
+ attr_reader :names
+
+ def initialize(names)
+ @names = names
+ super("cannot convert the value of #{names.join(", ")}")
+ end
+ end
+
+ def initialize(direction, callable, names)
+ @direction = direction
+ @callable = callable
+ @names = names
+ verify!
+ end
+
+ def call(*values)
+ callable.call(*values)
+ rescue StandardError
+ raise Failure.new(names)
+ end
+
+ private
+
+ attr_reader :direction, :callable, :names
+
+ def verify!
+ raise ArgumentError, "#{direction}: must respond to call" unless callable.respond_to?(:call)
+ return if arity.negative? || arity == names.size
+ raise ArgumentError,
+ "#{direction}: must take #{names.size} #{"value".pluralize(names.size)}"
+ end
+
+ def arity = callable.try(:arity) || callable.method(:call).arity
+ end
+ end
+end
diff --git a/lib/json_api_kit/version_change/declaration.rb b/lib/json_api_kit/version_change/declaration.rb
new file mode 100644
index 00000000000..c7c5fc963df
--- /dev/null
+++ b/lib/json_api_kit/version_change/declaration.rb
@@ -0,0 +1,53 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class VersionChange
+ class Declaration
+ class Fault < ArgumentError
+ def initialize(message, from:, to:)
+ super("#{message}, to change #{Array(from).join(", ")} into #{to}.")
+ end
+ end
+
+ DERIVED_FROM_AN_ATTRIBUTE = [Name::Field, Name::Sort, Name::Anchor].freeze
+
+ def initialize(type, from:, to:, up:, down:)
+ @type = type.to_s
+ @from = from
+ @to = to
+ @up = up
+ @down = down
+ end
+
+ def transformations
+ verify!
+ DERIVED_FROM_AN_ATTRIBUTE.map { transformation(it) }
+ end
+
+ private
+
+ attr_reader :type, :from, :to, :up, :down
+
+ def verify! = nil
+
+ def transformation(_kind)
+ raise NotImplementedError, "#{self.class} must implement transformation(kind)"
+ end
+
+ def converters
+ @converters ||= {
+ up: Converter.new(:up, up, names(Name::Field, from)),
+ down: Converter.new(:down, down, names(Name::Field, to)),
+ }
+ rescue ArgumentError => error
+ raise fault(error.message)
+ end
+
+ def names(kind, values) = Array(values).map { name(kind, it) }
+
+ def name(kind, value) = kind.new(value: value.to_s, type:)
+
+ def fault(message) = Fault.new(message, from:, to:)
+ end
+ end
+end
diff --git a/lib/json_api_kit/version_change/declaration/merged_attributes.rb b/lib/json_api_kit/version_change/declaration/merged_attributes.rb
new file mode 100644
index 00000000000..2551d859b5a
--- /dev/null
+++ b/lib/json_api_kit/version_change/declaration/merged_attributes.rb
@@ -0,0 +1,23 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class VersionChange
+ class Declaration
+ class MergedAttributes < Declaration
+ def initialize(type, from:, to:, up:, down:)
+ super(type, from: Array(from), to:, up:, down:)
+ end
+
+ private
+
+ def verify!
+ raise fault("Declare at least two names") unless from.many?
+ end
+
+ def transformation(kind)
+ Merge.new(from: names(kind, from), to: name(kind, to), **converters)
+ end
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/version_change/declaration/renamed_attribute.rb b/lib/json_api_kit/version_change/declaration/renamed_attribute.rb
new file mode 100644
index 00000000000..fc9fb4294eb
--- /dev/null
+++ b/lib/json_api_kit/version_change/declaration/renamed_attribute.rb
@@ -0,0 +1,25 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class VersionChange
+ class Declaration
+ class RenamedAttribute < Declaration
+ NO_CONVERSION = ->(value) { value }
+
+ def initialize(type, from:, to:, up: NO_CONVERSION, down: NO_CONVERSION)
+ super
+ end
+
+ private
+
+ def verify!
+ raise fault("Declare both up: and down:") if [up, down].count(NO_CONVERSION) == 1
+ end
+
+ def transformation(kind)
+ Rename.new(from: name(kind, from), to: name(kind, to), **converters)
+ end
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/version_change/declarations.rb b/lib/json_api_kit/version_change/declarations.rb
index 7890225a357..65da05cb252 100644
--- a/lib/json_api_kit/version_change/declarations.rb
+++ b/lib/json_api_kit/version_change/declarations.rb
@@ -3,36 +3,22 @@
module JsonApiKit
class VersionChange
class Declarations
- DERIVED_FROM_AN_ATTRIBUTE = [Name::Field, Name::Sort, Name::Anchor].freeze
- NO_CONVERSION = ->(value) { value }
-
def initialize(type)
- @type = type.to_s
+ @type = type
@transformations = []
end
- def renamed_attribute(from:, to:, up: NO_CONVERSION, down: NO_CONVERSION)
- if [up, down].count(NO_CONVERSION) == 1
- raise ArgumentError, "Declare both up: and down: to rename #{from} to #{to}."
- end
- unless [up, down].all? { it.respond_to?(:call) }
- raise ArgumentError, "up: and down: must respond to call, to rename #{from} to #{to}."
- end
- DERIVED_FROM_AN_ATTRIBUTE.each do |kind|
- transformations << Rename.new(
- from: kind.new(value: from.to_s, type:),
- to: kind.new(value: to.to_s, type:),
- up:,
- down:,
- )
- end
- end
+ def renamed_attribute(**) = declare(Declaration::RenamedAttribute.new(type, **))
+
+ def merged_attributes(**) = declare(Declaration::MergedAttributes.new(type, **))
def to_a = transformations
private
attr_reader :type, :transformations
+
+ def declare(declaration) = transformations.concat(declaration.transformations)
end
end
end
diff --git a/lib/json_api_kit/version_change/merge.rb b/lib/json_api_kit/version_change/merge.rb
new file mode 100644
index 00000000000..f1e2f18b03b
--- /dev/null
+++ b/lib/json_api_kit/version_change/merge.rb
@@ -0,0 +1,27 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class VersionChange
+ Merge =
+ Data.define(:from, :to, :up, :down) do
+ def current = to
+
+ def current_pairs(attributes) = [[to, up.call(*attributes.values_at(*from))]]
+
+ def previous_names = from
+
+ def previous_pairs(value) = from.zip(previous_values(value))
+
+ private
+
+ def previous_values(value)
+ Array(down.call(value)).tap do |values|
+ next if values.size == from.size
+ raise ArgumentError,
+ "down: answers #{values.size} #{"value".pluralize(values.size)} for " \
+ "#{from.size} names, to split #{to}."
+ end
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/version_change/pass_through.rb b/lib/json_api_kit/version_change/pass_through.rb
index 369ca575edd..ab381e769b4 100644
--- a/lib/json_api_kit/version_change/pass_through.rb
+++ b/lib/json_api_kit/version_change/pass_through.rb
@@ -6,9 +6,9 @@ module JsonApiKit
Data.define(:name) do
def current = name
- def current_pairs(value) = [[name, value]]
+ def current_pairs(attributes) = [[name, attributes[name]]]
- def previous = name
+ def previous_names = [name]
def previous_pairs(value) = [[name, value]]
end
diff --git a/lib/json_api_kit/version_change/rename.rb b/lib/json_api_kit/version_change/rename.rb
index 804f998de73..15d22aa1c2f 100644
--- a/lib/json_api_kit/version_change/rename.rb
+++ b/lib/json_api_kit/version_change/rename.rb
@@ -6,9 +6,9 @@ module JsonApiKit
Data.define(:from, :to, :up, :down) do
def current = to
- def current_pairs(value) = [[to, up.call(value)]]
+ def current_pairs(attributes) = [[to, up.call(attributes[from])]]
- def previous = from
+ def previous_names = [from]
def previous_pairs(value) = [[from, down.call(value)]]
end
diff --git a/spec/integration/json_api_kit/merged_attributes_spec.rb b/spec/integration/json_api_kit/merged_attributes_spec.rb
new file mode 100644
index 00000000000..1ab82c611b4
--- /dev/null
+++ b/spec/integration/json_api_kit/merged_attributes_spec.rb
@@ -0,0 +1,204 @@
+# frozen_string_literal: true
+
+require_relative "support"
+
+module JsonApiKitSpec
+ class MergedTopicsController < JsonApiKit::BaseController
+ resource :topics
+ end
+
+ class MergeTopicsPostedDateAndTimeIntoPostedAt < JsonApiKit::VersionChange
+ version "2026-09-15"
+ description "The `posted_date` and `posted_time` attributes of the topics resource become `posted_at`."
+
+ resource :topics do
+ merged_attributes from: %i[posted_date posted_time],
+ to: :posted_at,
+ up: ->(date, time) { Time.zone.parse("#{date} #{time}") },
+ down: ->(posted_at) do
+ next nil, nil if posted_at.nil?
+ [posted_at.to_date.iso8601, posted_at.strftime("%H:%M:%S")]
+ end
+ end
+ end
+
+ class RenameMergedTopicsPostedAtToCreatedAt < JsonApiKit::VersionChange
+ version "2026-10-01"
+ description "The `posted_at` attribute of the topics resource is renamed to `created_at`."
+
+ resource :topics do
+ renamed_attribute from: :posted_at, to: :created_at
+ end
+ end
+end
+
+RSpec.describe "JSON:API merged attributes", type: :request do
+ include_context "with a listing of topics"
+
+ let(:first_version) { JsonApiKit::Timeline::FIRST_RELEASE }
+ let(:merge) { JsonApiKitSpec::MergeTopicsPostedDateAndTimeIntoPostedAt.new(__FILE__) }
+ let(:rename) { JsonApiKitSpec::RenameMergedTopicsPostedAtToCreatedAt.new(__FILE__) }
+ let(:version) { first_version.to_s }
+ let(:parsed_body) { JSON.parse(response.body) }
+ let(:error) { parsed_body["errors"].sole }
+ let(:attributes) { parsed_body["data"].first["attributes"] }
+ let(:ids) { parsed_body["data"].map { it["id"] } }
+
+ before do
+ freeze_time(rename.version.date + 1.day)
+ allow(JsonApiKit::VersionChange).to receive(:all).and_return([merge, rename])
+ Rails.application.routes.disable_clear_and_finalize = true
+ Rails.application.routes.draw do
+ get "/api/merged-topics" => "json_api_kit_spec/merged_topics#index"
+ end
+ Rails.application.routes.disable_clear_and_finalize = false
+ get "/api/merged-topics", headers: { "HTTP_API_VERSION" => version }, params: query
+ end
+
+ after { Rails.application.reload_routes! }
+
+ context "when the client is pinned before the merge" do
+ it "sends the attributes under the names of that version" do
+ expect(attributes.keys).to contain_exactly("title", "postedDate", "postedTime")
+ end
+
+ it "sends the merged attribute as the two values of that version" do
+ expect(attributes.slice("postedDate", "postedTime")).to eq(
+ "postedDate" => "2026-08-03",
+ "postedTime" => "00:00:00",
+ )
+ end
+
+ context "when the request selects one of the merged fields" do
+ let(:query) { { "fields" => { "topics" => "postedDate" } } }
+
+ it "sends that field only" do
+ expect(attributes.keys).to contain_exactly("postedDate")
+ end
+ end
+
+ context "when the request selects both merged fields" do
+ let(:query) { { "fields" => { "topics" => "postedDate,postedTime" } } }
+
+ it "sends those fields only" do
+ expect(attributes.keys).to contain_exactly("postedDate", "postedTime")
+ end
+ end
+
+ context "when the request sorts by one of the merged fields" do
+ let(:query) { { "sort" => "postedDate" } }
+
+ it "orders the rows by the merged attribute" do
+ expect(ids).to eq([oldest.id.to_s, middle.id.to_s, newest.id.to_s])
+ end
+ end
+
+ context "when the request sorts by both merged fields in one direction" do
+ let(:query) { { "sort" => "postedDate,postedTime" } }
+
+ it "orders the rows by the merged attribute" do
+ expect(ids).to eq([oldest.id.to_s, middle.id.to_s, newest.id.to_s])
+ end
+ end
+
+ context "when the request sorts by both merged fields in two directions" do
+ let(:query) { { "sort" => "postedDate,-postedTime" } }
+
+ it "sends a refusal with both field names" do
+ expect(error).to eq(
+ refusal(
+ title: "Invalid sort",
+ detail: "postedDate and postedTime sort by one attribute in two directions.",
+ parameter: "sort",
+ ).deep_stringify_keys,
+ )
+ end
+ end
+
+ context "when the request anchors a window on the merged fields" do
+ let(:query) do
+ {
+ "sort" => "postedDate",
+ "page" => {
+ "anchor" => {
+ "postedDate" => "2026-08-02",
+ "postedTime" => "00:00:00",
+ },
+ "beforeSize" => "1",
+ "afterSize" => "0",
+ },
+ }
+ end
+
+ it "sends the rows of the window" do
+ expect(ids).to eq([oldest.id.to_s, middle.id.to_s])
+ end
+ end
+
+ context "when the anchor holds a value this version cannot convert" do
+ let(:query) do
+ {
+ "sort" => "postedDate",
+ "page" => {
+ "anchor" => {
+ "postedDate" => "2026-13-45",
+ "postedTime" => "00:00:00",
+ },
+ "beforeSize" => "1",
+ },
+ }
+ end
+
+ it "sends a refusal on the anchor parameter" do
+ expect(error).to eq(
+ refusal(
+ title: "Invalid value",
+ detail: "This version cannot convert the value of postedDate, postedTime.",
+ parameter: "page[anchor]",
+ ).deep_stringify_keys,
+ )
+ end
+ end
+
+ context "when a refusal includes the merged field" do
+ let(:query) do
+ {
+ "sort" => "title",
+ "page" => {
+ "anchor" => {
+ "postedDate" => "2026-08-02",
+ "postedTime" => "00:00:00",
+ },
+ },
+ }
+ end
+
+ it "sends the first name of that version" do
+ expect(error).to eq(
+ refusal(
+ title: "Anchor does not match the sort",
+ detail: "The anchor is postedDate, but this request sorts by title.",
+ parameter: "page[anchor][postedDate]",
+ ).deep_stringify_keys,
+ )
+ end
+ end
+ end
+
+ context "when the client is pinned between the merge and the rename" do
+ let(:version) { merge.version.to_s }
+
+ it "sends the attributes under the names of that version" do
+ expect(attributes.keys).to contain_exactly("title", "postedAt")
+ end
+ end
+
+ context "when the client is pinned at the rename" do
+ let(:version) { rename.version.to_s }
+ let(:query) { { "fields" => { "topics" => "createdAt" } } }
+
+ it "sends the field it selects" do
+ expect(attributes.keys).to contain_exactly("createdAt")
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/anchoring_spec.rb b/spec/lib/json_api_kit/anchoring_spec.rb
index 45f830d8df6..408fc58289d 100644
--- a/spec/lib/json_api_kit/anchoring_spec.rb
+++ b/spec/lib/json_api_kit/anchoring_spec.rb
@@ -50,4 +50,30 @@ RSpec.describe JsonApiKit::Anchoring do
end
end
end
+
+ describe "#single_value?" do
+ it { is_expected.to be_a_single_value }
+
+ context "when the value is an array" do
+ let(:anchor) { { id: [12] } }
+
+ it { is_expected.not_to be_a_single_value }
+ end
+
+ context "when the anchor is a name alone" do
+ let(:anchor) { :first_unread }
+
+ it { is_expected.not_to be_a_single_value }
+ end
+ end
+
+ describe "#without_value?" do
+ it { is_expected.not_to be_without_value }
+
+ context "when the anchor is a name alone" do
+ let(:anchor) { :first_unread }
+
+ it { is_expected.to be_without_value }
+ end
+ end
end
diff --git a/spec/lib/json_api_kit/declarations/anchor/attribute_spec.rb b/spec/lib/json_api_kit/declarations/anchor/attribute_spec.rb
new file mode 100644
index 00000000000..6ea1461e626
--- /dev/null
+++ b/spec/lib/json_api_kit/declarations/anchor/attribute_spec.rb
@@ -0,0 +1,55 @@
+# frozen_string_literal: true
+
+RSpec::Matchers.alias_matcher :accept, :be_accepts
+
+RSpec.describe JsonApiKit::Declarations::Anchor::Attribute do
+ subject(:anchor) { described_class.new(:created_at) }
+
+ fab!(:oldest) { Fabricate(:topic, created_at: Time.utc(2026, 8, 1)) }
+ fab!(:newest) { Fabricate(:topic, created_at: Time.utc(2026, 8, 3)) }
+ let(:resource) do
+ Class.new(JsonApiKit::Resource) do
+ model Topic
+ type :topics
+ sort :created_at
+ sort :title
+ default_sort created_at: :asc
+ end
+ end
+ let(:order) { resource.order("created_at" => :asc) }
+ let(:anchoring) { JsonApiKit::Anchoring.for(created_at: Time.utc(2026, 8, 3)) }
+
+ describe "#accepts?" do
+ it { is_expected.to accept(anchoring) }
+ it { is_expected.not_to accept(JsonApiKit::Anchoring.for(created_at: [Time.utc(2026, 8, 3)])) }
+ it { is_expected.not_to accept(JsonApiKit::Anchoring.for(:created_at)) }
+ end
+
+ describe "#locatable_in?" do
+ it { is_expected.to be_locatable_in(order) }
+
+ context "when the attribute is not the leading key of the order" do
+ let(:order) { resource.order("title" => :asc) }
+
+ it { is_expected.not_to be_locatable_in(order) }
+ end
+ end
+
+ describe "#locate" do
+ subject(:located_row) do
+ anchor.locate(anchoring, scope: Topic.all, order:, guardian: Guardian.new)
+ end
+
+ it "returns the row the listing enters at that value" do
+ expect(located_row.record).to eq(newest)
+ end
+
+ context "when the attribute is not the leading key of the order" do
+ let(:order) { resource.order("title" => :asc) }
+
+ it "raises with the anchor name" do
+ expect { located_row }.to raise_error(ArgumentError, /created_at/)
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/declarations/anchor/computed_spec.rb b/spec/lib/json_api_kit/declarations/anchor/computed_spec.rb
new file mode 100644
index 00000000000..19319d93d1f
--- /dev/null
+++ b/spec/lib/json_api_kit/declarations/anchor/computed_spec.rb
@@ -0,0 +1,41 @@
+# frozen_string_literal: true
+
+RSpec::Matchers.alias_matcher :accept, :be_accepts
+
+RSpec.describe JsonApiKit::Declarations::Anchor::Computed do
+ subject(:anchor) do
+ described_class.new(:mine) { |topics, guardian| topics.where(user: guardian.user) }
+ end
+
+ fab!(:oldest) { Fabricate(:topic, created_at: Time.utc(2026, 8, 1)) }
+ fab!(:newest) { Fabricate(:topic, created_at: Time.utc(2026, 8, 3)) }
+ let(:resource) do
+ Class.new(JsonApiKit::Resource) do
+ model Topic
+ type :topics
+ sort :created_at
+ default_sort created_at: :asc
+ end
+ end
+ let(:order) { resource.order("created_at" => :asc) }
+ let(:anchoring) { JsonApiKit::Anchoring.for(:mine) }
+
+ describe "#accepts?" do
+ it { is_expected.to accept(anchoring) }
+ it { is_expected.not_to accept(JsonApiKit::Anchoring.for(mine: 12)) }
+ end
+
+ describe "#locatable_in?" do
+ it { is_expected.to be_locatable_in(order) }
+ end
+
+ describe "#locate" do
+ subject(:located_row) do
+ anchor.locate(anchoring, scope: Topic.all, order:, guardian: Guardian.new(newest.user))
+ end
+
+ it "returns the row the declaration calculates for the guardian" do
+ expect(located_row.record).to eq(newest)
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/declarations/anchor/identity_spec.rb b/spec/lib/json_api_kit/declarations/anchor/identity_spec.rb
new file mode 100644
index 00000000000..855e99aa5e9
--- /dev/null
+++ b/spec/lib/json_api_kit/declarations/anchor/identity_spec.rb
@@ -0,0 +1,48 @@
+# frozen_string_literal: true
+
+RSpec::Matchers.alias_matcher :accept, :be_accepts
+
+RSpec.describe JsonApiKit::Declarations::Anchor::Identity do
+ subject(:anchor) { described_class.new(:id) }
+
+ fab!(:oldest) { Fabricate(:topic, created_at: Time.utc(2026, 8, 1)) }
+ fab!(:newest) { Fabricate(:topic, created_at: Time.utc(2026, 8, 3)) }
+ let(:resource) do
+ Class.new(JsonApiKit::Resource) do
+ model Topic
+ type :topics
+ sort :created_at
+ default_sort created_at: :asc
+ end
+ end
+ let(:order) { resource.order("created_at" => :asc) }
+ let(:anchoring) { JsonApiKit::Anchoring.for(id: newest.id) }
+
+ describe "#accepts?" do
+ it { is_expected.to accept(anchoring) }
+ it { is_expected.not_to accept(JsonApiKit::Anchoring.for(id: [newest.id])) }
+ it { is_expected.not_to accept(JsonApiKit::Anchoring.for(:id)) }
+ end
+
+ describe "#locatable_in?" do
+ it { is_expected.to be_locatable_in(order) }
+ end
+
+ describe "#locate" do
+ subject(:located_row) do
+ anchor.locate(anchoring, scope: Topic.all, order:, guardian: Guardian.new)
+ end
+
+ it "returns the row with that id" do
+ expect(located_row.record).to eq(newest)
+ end
+
+ context "when no row holds that id" do
+ let(:anchoring) { JsonApiKit::Anchoring.for(id: -1) }
+
+ it "raises no row for the anchor" do
+ expect { located_row }.to raise_error(JsonApiKit::Declarations::Anchor::NoRow)
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/declarations/anchor_spec.rb b/spec/lib/json_api_kit/declarations/anchor_spec.rb
index 5f0c6b04403..bb3ee5e6553 100644
--- a/spec/lib/json_api_kit/declarations/anchor_spec.rb
+++ b/spec/lib/json_api_kit/declarations/anchor_spec.rb
@@ -1,108 +1,36 @@
# frozen_string_literal: true
RSpec.describe JsonApiKit::Declarations::Anchor do
- subject(:anchor) { described_class.new(:created_at) }
+ describe ".for" do
+ subject(:anchor) { described_class.for(:created_at) }
- fab!(:oldest) { Fabricate(:topic, created_at: Time.utc(2026, 8, 1)) }
- fab!(:newest) { Fabricate(:topic, created_at: Time.utc(2026, 8, 3)) }
-
- let(:resource) do
- Class.new(JsonApiKit::Resource) do
- model Topic
- type :topics
- sort :created_at
- sort :title
- default_sort created_at: :asc
+ it "returns an anchor on an attribute" do
+ expect(anchor).to be_a(described_class::Attribute)
end
- end
- let(:order) { resource.order("created_at" => :asc) }
- let(:guardian) { Guardian.new }
- let(:located_row) { anchor.locate(Topic.all, value:, order:, guardian:) }
- let(:value) { Time.utc(2026, 8, 3) }
- describe "#name" do
- it "returns the name a request anchors by" do
+ it "gives it the name a request anchors by" do
expect(anchor.name).to eq("created_at")
end
- end
-
- describe "#locatable_in?" do
- context "when the anchor is the leading key" do
- it { is_expected.to be_locatable_in(order) }
- end
-
- context "when the anchor is the primary key" do
- subject(:anchor) { described_class.new(:id) }
-
- it { is_expected.to be_locatable_in(order) }
- end
- context "when the resource declares how to calculate the anchor" do
- subject(:anchor) do
- described_class.new(:mine) { |topics, guardian| topics.where(user: guardian.user) }
- end
-
- it { is_expected.to be_locatable_in(order) }
- end
-
- context "when the anchor is not in the order" do
- subject(:anchor) { described_class.new(:title) }
-
- it { is_expected.not_to be_locatable_in(order) }
- end
- end
+ context "when the name is the primary key" do
+ subject(:anchor) { described_class.for(:id) }
- describe "#locate" do
- context "when the anchor is the leading key" do
- it "returns the row the listing enters at that value" do
- expect(located_row.record).to eq(newest)
- end
- end
-
- context "when the anchor is the primary key" do
- subject(:anchor) { described_class.new(:id) }
-
- let(:value) { newest.id }
-
- it "returns the row with that id" do
- expect(located_row.record).to eq(newest)
- end
-
- context "when no row holds that id" do
- let(:value) { -1 }
-
- it "refuses the request" do
- expect { located_row }.to raise_error(described_class::NoRow)
- end
- end
- end
-
- context "when the anchor is not in the order" do
- subject(:anchor) { described_class.new(:title) }
-
- let(:value) { newest.title }
-
- it "refuses the request" do
- expect { located_row }.to raise_error(ArgumentError, /title/)
+ it "returns an anchor on the identity" do
+ expect(anchor).to be_a(described_class::Identity)
end
end
context "when the resource declares how to calculate the anchor" do
- subject(:anchor) do
- described_class.new(:mine) { |topics, guardian| topics.where(user: guardian.user) }
- end
-
- let(:guardian) { Guardian.new(newest.user) }
- let(:value) { nil }
+ subject(:anchor) { described_class.for(:mine) { |topics, _guardian| topics } }
- it "returns the row that declaration calculates for the guardian" do
- expect(located_row.record).to eq(newest)
+ it "returns a computed anchor" do
+ expect(anchor).to be_a(described_class::Computed)
end
end
end
describe described_class::NoRow do
- subject(:error) { described_class.new("created_at", value) }
+ subject(:error) { described_class.new("created_at", Time.utc(2026, 8, 3)) }
describe "#title" do
it "returns the title of the error" do
diff --git a/spec/lib/json_api_kit/declarations/anchors_spec.rb b/spec/lib/json_api_kit/declarations/anchors_spec.rb
index a7afabc5031..a00adb0981c 100644
--- a/spec/lib/json_api_kit/declarations/anchors_spec.rb
+++ b/spec/lib/json_api_kit/declarations/anchors_spec.rb
@@ -4,8 +4,8 @@ RSpec.describe JsonApiKit::Declarations::Anchors do
subject(:anchors) { described_class.new(declarations, guardian:) }
let(:anchor_class) { JsonApiKit::Declarations::Anchor }
- let(:created_at_anchor) { anchor_class.new(:created_at) }
- let(:declarations) { [anchor_class.new(:id), created_at_anchor] }
+ let(:created_at_anchor) { anchor_class.for(:created_at) }
+ let(:declarations) { [anchor_class.for(:id), created_at_anchor] }
let(:guardian) { Guardian.new }
let(:resource) do
Class.new(JsonApiKit::Resource) do
@@ -27,7 +27,7 @@ RSpec.describe JsonApiKit::Declarations::Anchors do
context "when the resource declares no anchor by that name" do
subject(:anchor_declaration) { anchors.fetch("secrets") }
- it "refuses the request" do
+ it "raises a key error" do
expect { anchor_declaration }.to raise_error(KeyError)
end
end
@@ -45,12 +45,7 @@ RSpec.describe JsonApiKit::Declarations::Anchors do
it "asks the matching anchor to locate the row" do
located_row
- expect(created_at_anchor).to have_received(:locate).with(
- scope,
- value: Time.utc(2026, 8, 3),
- order:,
- guardian:,
- )
+ expect(created_at_anchor).to have_received(:locate).with(anchoring, scope:, order:, guardian:)
end
it "returns the row that anchor locates" do
diff --git a/spec/lib/json_api_kit/document/collection_spec.rb b/spec/lib/json_api_kit/document/collection_spec.rb
index 9394547fbd0..3ec4b647781 100644
--- a/spec/lib/json_api_kit/document/collection_spec.rb
+++ b/spec/lib/json_api_kit/document/collection_spec.rb
@@ -1,9 +1,7 @@
# frozen_string_literal: true
RSpec.describe JsonApiKit::Document::Collection do
- subject(:document) { described_class.new(listing, urls:, glossary:) }
-
- let(:glossary) { JsonApiKit::Glossary.kit }
+ subject(:document) { described_class.new(listing, urls:, glossary:, fieldsets:) }
fab!(:first_topic) do
Fabricate(:topic, title: "Segments of a listing", created_at: Time.utc(2026, 8, 1))
@@ -11,7 +9,8 @@ RSpec.describe JsonApiKit::Document::Collection do
fab!(:second_topic) do
Fabricate(:topic, title: "Cursors and their values", created_at: Time.utc(2026, 8, 2))
end
-
+ let(:glossary) { JsonApiKit::Glossary.kit }
+ let(:fieldsets) { JsonApiKit::Request::Fieldsets.parse({}) }
let(:resource) do
Class.new(JsonApiKit::Resource) do
model Topic
@@ -45,6 +44,7 @@ RSpec.describe JsonApiKit::Document::Collection do
first_record,
urls:,
glossary:,
+ fieldsets:,
meta: {
},
)
@@ -52,6 +52,7 @@ RSpec.describe JsonApiKit::Document::Collection do
second_record,
urls:,
glossary:,
+ fieldsets:,
meta: {
},
)
@@ -67,6 +68,7 @@ RSpec.describe JsonApiKit::Document::Collection do
first_record,
urls:,
glossary:,
+ fieldsets:,
meta: {
page: {
cursor: first_record.cursor.to_s,
@@ -77,6 +79,7 @@ RSpec.describe JsonApiKit::Document::Collection do
second_record,
urls:,
glossary:,
+ fieldsets:,
meta: {
page: {
cursor: second_record.cursor.to_s,
@@ -86,7 +89,7 @@ RSpec.describe JsonApiKit::Document::Collection do
end
end
- context "when the listing reads no row" do
+ context "when the listing has no row" do
let(:listing) { resource.all({}, guardian:, scoped_to: Topic.where(id: -1)) }
it "renders an empty document" do
diff --git a/spec/lib/json_api_kit/document/individual_spec.rb b/spec/lib/json_api_kit/document/individual_spec.rb
index 935a3ee63de..2c57f541d82 100644
--- a/spec/lib/json_api_kit/document/individual_spec.rb
+++ b/spec/lib/json_api_kit/document/individual_spec.rb
@@ -1,12 +1,11 @@
# frozen_string_literal: true
RSpec.describe JsonApiKit::Document::Individual do
- subject(:document) { described_class.new(reading, urls:, glossary:) }
-
- let(:glossary) { JsonApiKit::Glossary.kit }
+ subject(:document) { described_class.new(reading, urls:, glossary:, fieldsets:) }
fab!(:topic) { Fabricate(:topic, title: "One record read on its own") }
-
+ let(:glossary) { JsonApiKit::Glossary.kit }
+ let(:fieldsets) { JsonApiKit::Request::Fieldsets.parse({}) }
let(:resource) do
Class.new(JsonApiKit::Resource) do
model Topic
diff --git a/spec/lib/json_api_kit/document/resource_object_spec.rb b/spec/lib/json_api_kit/document/resource_object_spec.rb
index 08ad1c9726b..d005575c1ba 100644
--- a/spec/lib/json_api_kit/document/resource_object_spec.rb
+++ b/spec/lib/json_api_kit/document/resource_object_spec.rb
@@ -1,12 +1,11 @@
# frozen_string_literal: true
RSpec.describe JsonApiKit::Document::ResourceObject do
- subject(:resource_object) { described_class.new(record, urls:, glossary:, meta:) }
-
- let(:glossary) { JsonApiKit::Glossary.kit }
+ subject(:resource_object) { described_class.new(record, urls:, glossary:, fieldsets:, meta:) }
fab!(:topic) { Fabricate(:topic, title: "A row a document renders") }
-
+ let(:glossary) { JsonApiKit::Glossary.kit }
+ let(:fieldsets) { JsonApiKit::Request::Fieldsets.parse({}) }
let(:guardian) { Guardian.new }
let(:resource) do
Class.new(JsonApiKit::Resource) do
@@ -57,6 +56,22 @@ RSpec.describe JsonApiKit::Document::ResourceObject do
end
end
+ context "when a fieldset holds some of the attributes" do
+ let(:resource) do
+ Class.new(JsonApiKit::Resource) do
+ model Topic
+ type :topics
+ attribute :title
+ attribute :closed
+ end
+ end
+ let(:fieldsets) { JsonApiKit::Request::Fieldsets.parse("topics" => "closed") }
+
+ it "renders those attributes only" do
+ expect(resource_object.to_h[:attributes]).to eq("closed" => false)
+ end
+ end
+
context "when the record holds no attribute" do
let(:fields) { resource.fields(["secrets"], guardian:) }
@@ -104,7 +119,6 @@ RSpec.describe JsonApiKit::Document::ResourceObject do
context "when the record holds a relationship to many records" do
fab!(:post)
-
let(:posts_resource) do
Class.new(JsonApiKit::Resource) do
model Post
diff --git a/spec/lib/json_api_kit/glossary/version_rule_spec.rb b/spec/lib/json_api_kit/glossary/version_rule_spec.rb
index 60c6431fb57..62ee9992d23 100644
--- a/spec/lib/json_api_kit/glossary/version_rule_spec.rb
+++ b/spec/lib/json_api_kit/glossary/version_rule_spec.rb
@@ -19,6 +19,18 @@ module JsonApiKitSpec
end
end
+ class MergeRuleChange < JsonApiKit::VersionChange
+ version "2026-09-10"
+ description "The `posted_date` and `posted_time` attributes of the topics resource become `posted_at`."
+
+ resource :topics do
+ merged_attributes from: %i[posted_date posted_time],
+ to: :posted_at,
+ up: ->(date, time) { "#{date} #{time}" },
+ down: ->(posted_at) { posted_at.to_s.split(" ") }
+ end
+ end
+
class NameToTitleChange < JsonApiKit::VersionChange
version "2026-09-15"
description "The `name` attribute of the topics resource is renamed to `title`."
@@ -44,21 +56,30 @@ RSpec.describe JsonApiKit::Glossary::VersionRule do
let(:version) { JsonApiKit::ApiVersion.parse("2026-09-01") }
let(:first_change) { JsonApiKitSpec::FirstRuleChange.new(__FILE__) }
let(:second_change) { JsonApiKitSpec::SecondRuleChange.new(__FILE__) }
+ let(:changes) { [first_change, second_change] }
let(:name) { JsonApiKit::Name::Field.new(value:, type: "topics") }
let(:value) { "posted_at" }
- before do
- allow(JsonApiKit::VersionChange).to receive(:after).with(version).and_return(
- [first_change, second_change],
- )
- end
+ before { allow(JsonApiKit::VersionChange).to receive(:after).with(version).and_return(changes) }
describe "#declared_attributes" do
- subject(:declared_attributes) { rule.declared_attributes(name => "2026-08-01") }
+ subject(:declared_attributes) { rule.declared_attributes(attributes) }
+
+ let(:attributes) { { name => "2026-08-01" } }
it "returns the attributes with their current names" do
expect(declared_attributes).to eq(name.with(value: "published_at") => "2026-08-01")
end
+
+ context "when a change merges two of the attributes" do
+ let(:changes) { [JsonApiKitSpec::MergeRuleChange.new(__FILE__), first_change, second_change] }
+ let(:attributes) { { name => "2026-08-01", name.with(value: "posted_time") => "00:00:00" } }
+ let(:value) { "posted_date" }
+
+ it "returns one attribute under the current name" do
+ expect(declared_attributes).to eq(name.with(value: "published_at") => "2026-08-01 00:00:00")
+ end
+ end
end
describe "#declared_name" do
@@ -94,6 +115,25 @@ RSpec.describe JsonApiKit::Glossary::VersionRule do
end
end
+ context "when the name is one of several a change merges" do
+ let(:changes) { [JsonApiKitSpec::MergeRuleChange.new(__FILE__), first_change, second_change] }
+ let(:value) { "posted_time" }
+
+ it "returns the current name" do
+ expect(declared_name).to eq(name.with(value: "published_at"))
+ end
+
+ context "when the name is the one they merge into" do
+ let(:value) { "posted_at" }
+
+ it "raises a correction with the declared name" do
+ expect { declared_name }.to raise_error(
+ having_attributes(name: name.with(value: "published_at")),
+ )
+ end
+ end
+ end
+
context "when the name belongs to a later version" do
let(:value) { "published_at" }
@@ -106,12 +146,23 @@ RSpec.describe JsonApiKit::Glossary::VersionRule do
end
describe "#member_attributes" do
- subject(:member_attributes) { rule.member_attributes(name => "2026-08-01") }
+ subject(:member_attributes) { rule.member_attributes(name => "2026-08-01 00:00:00") }
let(:value) { "published_at" }
it "returns the attributes with the names of this version" do
- expect(member_attributes).to eq(name.with(value: "posted_at") => "2026-08-01")
+ expect(member_attributes).to eq(name.with(value: "posted_at") => "2026-08-01 00:00:00")
+ end
+
+ context "when a change merges two names of this version into the attribute" do
+ let(:changes) { [JsonApiKitSpec::MergeRuleChange.new(__FILE__), first_change, second_change] }
+
+ it "returns the two attributes under those names" do
+ expect(member_attributes).to eq(
+ name.with(value: "posted_date") => "2026-08-01",
+ name.with(value: "posted_time") => "00:00:00",
+ )
+ end
end
end
@@ -131,5 +182,14 @@ RSpec.describe JsonApiKit::Glossary::VersionRule do
expect(member_name).to eq(name)
end
end
+
+ context "when a change merges several names of this version into the current one" do
+ let(:changes) { [JsonApiKitSpec::MergeRuleChange.new(__FILE__), first_change, second_change] }
+ let(:value) { "published_at" }
+
+ it "returns the first of them" do
+ expect(member_name).to eq(name.with(value: "posted_date"))
+ end
+ end
end
end
diff --git a/spec/lib/json_api_kit/glossary_spec.rb b/spec/lib/json_api_kit/glossary_spec.rb
index 4407d61444c..4f86f8f3dfb 100644
--- a/spec/lib/json_api_kit/glossary_spec.rb
+++ b/spec/lib/json_api_kit/glossary_spec.rb
@@ -12,6 +12,12 @@ module JsonApiKitSpec
def member_attributes(attributes) = attributes.transform_keys { member_name(it) }
end
+ module BrokenRule
+ def self.declared_name(name) = name
+
+ def self.declared_attributes(_attributes) = raise NoMethodError, "a fault in the kit"
+ end
+
class GlossaryChange < JsonApiKit::VersionChange
version "2026-09-15"
description "The `posted_at` attribute of the topics resource is renamed to `created_at`."
@@ -123,6 +129,25 @@ RSpec.describe JsonApiKit::Glossary do
expect { declared_attributes }.to raise_error(/Use words, not title\./)
end
end
+
+ context "when a converter cannot convert a value" do
+ let(:attributes) { { name => 5, name.with(value: "size") => "L" } }
+
+ it "raises a bad value with the names of that attribute only" do
+ expect { declared_attributes }.to raise_error(
+ described_class::BadValue,
+ /cannot convert the value of words\./,
+ )
+ end
+ end
+ end
+
+ context "when a rule raises" do
+ subject(:glossary) { described_class.new([JsonApiKitSpec::BrokenRule]) }
+
+ it "raises the error of the rule" do
+ expect { declared_attributes }.to raise_error(NoMethodError, /a fault in the kit/)
+ end
end
context "with several rules" do
diff --git a/spec/lib/json_api_kit/request/contract/collection_spec.rb b/spec/lib/json_api_kit/request/contract/collection_spec.rb
index 4a6a33595c6..005ba3b0247 100644
--- a/spec/lib/json_api_kit/request/contract/collection_spec.rb
+++ b/spec/lib/json_api_kit/request/contract/collection_spec.rb
@@ -1,17 +1,10 @@
# frozen_string_literal: true
RSpec.describe JsonApiKit::Request::Contract::Collection, type: :model do
- subject(:contract) do
- described_class.new(
- **params,
- options: {
- resource:,
- raw_parameters: params.with_indifferent_access,
- },
- )
- end
+ subject(:contract) { described_class.for(params, resource:, glossary:) }
let(:params) { {} }
+ let(:glossary) { JsonApiKit::Glossary.kit }
let(:cursor) { JsonApiKit::Pagination::Cursor.new([resource.order.digest, 0, 12]).to_s }
let(:related) do
Class.new(JsonApiKit::Resource) do
@@ -35,6 +28,33 @@ RSpec.describe JsonApiKit::Request::Contract::Collection, type: :model do
end
end
+ describe ".for" do
+ let(:params) { { "sort" => { "created_at" => :desc } } }
+
+ it "returns a contract over the declared parameters" do
+ expect(contract.sort).to eq("created_at" => :desc)
+ end
+
+ it "checks the parameters against the resource" do
+ expect(contract).to be_valid
+ end
+ end
+
+ describe "#refusals" do
+ subject(:refusals) { contract.refusals }
+
+ let(:params) { { "sort" => { "posted_at" => :asc } } }
+
+ before { contract.invalid? }
+
+ it "returns the errors of the contract with the names the client sent" do
+ expect(refusals.sole).to have_attributes(
+ title: "No such sort",
+ detail: "There is no sort named postedAt.",
+ )
+ end
+ end
+
describe "Unknown parameters" do
context "when a parameter is unknown" do
let(:params) { { sorts: { created_at: :asc } } }
@@ -58,8 +78,7 @@ RSpec.describe JsonApiKit::Request::Contract::Collection, type: :model do
describe "Sorting" do
it { is_expected.to allow_value(nil, {}, { created_at: :asc }).for(:sort) }
it { is_expected.to allow_value({ created_at: :desc, title: :asc }).for(:sort) }
- it { is_expected.to allow_value("", "created_at", "-created_at").for(:sort) }
- it { is_expected.to allow_value("created_at,-title").for(:sort) }
+ it { is_expected.not_to allow_value("", "created_at", "created_at,-title").for(:sort) }
it { is_expected.not_to allow_value({ secrets: :asc }).for(:sort) }
it do
@@ -81,35 +100,19 @@ RSpec.describe JsonApiKit::Request::Contract::Collection, type: :model do
end
end
- context "when sort is a string" do
- let(:params) { { sort: "-created_at,title" } }
-
- it "converts it as a hash" do
- expect(contract.sort).to eq("created_at" => :desc, "title" => :asc)
- end
-
- context "when the sort name has a hyphen" do
- let(:params) { { sort: "last-posted-at" } }
-
- it "converts it as a hash" do
- expect(contract.sort).to eq("last-posted-at" => :asc)
- end
- end
+ context "when a cursor comes with the sort" do
+ let(:params) { { sort: { title: :asc }, page: { after: cursor } } }
- context "when a cursor comes with the sort" do
- let(:params) { { sort: "title", page: { after: cursor } } }
-
- it "checks the cursor against that sort" do
- expect(contract).to be_invalid
- expect(contract.errors).to be_of_kind(:"page.after", :unreadable_cursor)
- end
+ it "checks the cursor against that sort" do
+ expect(contract).to be_invalid
+ expect(contract.errors).to be_of_kind(:"page.after", :unreadable_cursor)
end
end
context "when sort is a hash" do
let(:params) { { sort: { created_at: :desc } } }
- it "returns it as a hash" do
+ it "returns it with string keys" do
expect(contract.sort).to eq("created_at" => :desc)
end
end
@@ -139,23 +142,10 @@ RSpec.describe JsonApiKit::Request::Contract::Collection, type: :model do
describe "Fieldsets" do
it { is_expected.to allow_value(nil, {}, { topics: %w[title created_at] }).for(:fields) }
- it { is_expected.to allow_value({ topics: "title" }, { topics: "" }).for(:fields) }
- it { is_expected.not_to allow_value("title", [1], { topics: 42 }).for(:fields) }
-
- context "when fieldset is a string" do
- let(:params) { { fields: { topics: "title,created_at" } } }
+ it { is_expected.to allow_value({ topics: [] }).for(:fields) }
- it "converts it as a list of fields" do
- expect(contract.fields).to eq("topics" => %w[title created_at])
- end
- end
-
- context "when fieldset is empty" do
- let(:params) { { fields: { topics: "" } } }
-
- it "converts it as an empty list" do
- expect(contract.fields).to eq("topics" => [])
- end
+ it do
+ is_expected.not_to allow_value("title", [1], { topics: 42 }, { topics: "title" }).for(:fields)
end
context "when fieldset is a list of symbols" do
@@ -179,6 +169,8 @@ RSpec.describe JsonApiKit::Request::Contract::Collection, type: :model do
it { is_expected.not_to allow_value({}, { id: 12, title: "a topic" }).for(:anchor) }
it { is_expected.not_to allow_value({ id: { a: 1 } }, { id: %w[a b] }).for(:anchor) }
it { is_expected.not_to allow_value({ secrets: 12 }, :guesswork).for(:anchor) }
+ it { is_expected.not_to allow_value({ id: nil }).for(:anchor) }
+ it { is_expected.to allow_value({ first_unread: nil }).for(:anchor) }
context "when the anchor is not the sort" do
let(:params) { { sort: { created_at: :asc }, page: { anchor: { title: "A" } } } }
diff --git a/spec/lib/json_api_kit/request/contract/individual_spec.rb b/spec/lib/json_api_kit/request/contract/individual_spec.rb
index ad07cddb175..f8310c03787 100644
--- a/spec/lib/json_api_kit/request/contract/individual_spec.rb
+++ b/spec/lib/json_api_kit/request/contract/individual_spec.rb
@@ -1,17 +1,10 @@
# frozen_string_literal: true
RSpec.describe JsonApiKit::Request::Contract::Individual, type: :model do
- subject(:contract) do
- described_class.new(
- **params,
- options: {
- resource:,
- raw_parameters: params.with_indifferent_access,
- },
- )
- end
+ subject(:contract) { described_class.for(params, resource:, glossary:) }
let(:params) { {} }
+ let(:glossary) { JsonApiKit::Glossary.kit }
let(:related) do
Class.new(JsonApiKit::Resource) do
model User
@@ -34,7 +27,7 @@ RSpec.describe JsonApiKit::Request::Contract::Individual, type: :model do
context "when a parameter is unknown" do
let(:params) { { fieldsets: { topics: %w[title] } } }
- it "refuses the parameter" do
+ it "adds an error on the parameter" do
expect(contract).to be_invalid
expect(contract.errors).to include(:fieldsets)
end
@@ -58,7 +51,7 @@ RSpec.describe JsonApiKit::Request::Contract::Individual, type: :model do
}
end
- it "refuses each of them, though the resource declares them" do
+ it "adds an error for each of them, though the resource declares them" do
expect(contract).to be_invalid
expect(contract.errors).to include(:sort, :filter, :page)
end
@@ -73,7 +66,10 @@ RSpec.describe JsonApiKit::Request::Contract::Individual, type: :model do
describe "Fieldsets" do
it { is_expected.to allow_value(nil, {}, { topics: %w[title created_at] }).for(:fields) }
- it { is_expected.to allow_value({ topics: "title" }, { topics: "" }).for(:fields) }
- it { is_expected.not_to allow_value("title", [1], { topics: 42 }).for(:fields) }
+ it { is_expected.to allow_value({ topics: [] }).for(:fields) }
+
+ it do
+ is_expected.not_to allow_value("title", [1], { topics: 42 }, { topics: "title" }).for(:fields)
+ end
end
end
diff --git a/spec/lib/json_api_kit/request/family/sort/keys_spec.rb b/spec/lib/json_api_kit/request/family/sort/keys_spec.rb
new file mode 100644
index 00000000000..7f3d4ac7aa3
--- /dev/null
+++ b/spec/lib/json_api_kit/request/family/sort/keys_spec.rb
@@ -0,0 +1,66 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Request::Family::Sort::Keys do
+ subject(:keys) { described_class.parse(value, path) }
+
+ let(:value) { "postedDate,-title" }
+ let(:path) { ["sort"] }
+ let(:declared_names) do
+ { "postedDate" => "posted_at", "postedTime" => "posted_at", "title" => "title" }
+ end
+
+ describe ".parse" do
+ subject(:declared_sort) { keys.declare { it.name } }
+
+ it "returns the keys of a list with their directions" do
+ expect(declared_sort).to eq("postedDate" => :asc, "title" => :desc)
+ end
+
+ context "when the sort is a hash" do
+ let(:value) { { "postedDate" => "asc" } }
+
+ it "returns the keys with the directions as they came" do
+ expect(declared_sort).to eq("postedDate" => "asc")
+ end
+ end
+
+ context "when the sort is an array" do
+ let(:value) { %w[postedDate] }
+
+ it "returns nothing" do
+ expect(keys).to be_nil
+ end
+ end
+ end
+
+ describe "#declare" do
+ subject(:declared_sort) { keys.declare { declared_names.fetch(it.name) } }
+
+ it "returns the declared names with their directions" do
+ expect(declared_sort).to eq("posted_at" => :asc, "title" => :desc)
+ end
+
+ context "when two keys declare one name" do
+ let(:value) { "postedDate,postedTime" }
+
+ it "returns that name once" do
+ expect(declared_sort).to eq("posted_at" => :asc)
+ end
+
+ context "when their directions differ" do
+ let(:value) { "postedDate,-postedTime" }
+
+ it "raises two directions on the sort" do
+ expect { declared_sort }.to raise_error(
+ JsonApiKit::Request::Family::Sort::TwoDirections,
+ /postedDate and postedTime/,
+ )
+ end
+
+ it "points at the sort parameter" do
+ expect { declared_sort }.to raise_error(having_attributes(source: { parameter: "sort" }))
+ end
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/request/fieldsets_spec.rb b/spec/lib/json_api_kit/request/fieldsets_spec.rb
new file mode 100644
index 00000000000..bdd1a2a7165
--- /dev/null
+++ b/spec/lib/json_api_kit/request/fieldsets_spec.rb
@@ -0,0 +1,64 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Request::Fieldsets do
+ subject(:fieldsets) { described_class.parse(raw) }
+
+ let(:raw) { { "topics" => "title,postedDate" } }
+ let(:attributes) { { "title" => "A", "postedDate" => "2026-08-01", "postedTime" => "00:00:00" } }
+
+ describe ".parse" do
+ subject(:kept_attributes) { fieldsets.keep("topics", attributes) }
+
+ it "returns fieldsets that keep the attributes a list holds" do
+ expect(kept_attributes).to eq("title" => "A", "postedDate" => "2026-08-01")
+ end
+
+ context "when a fieldset is an array" do
+ let(:raw) { { "topics" => %w[postedDate] } }
+
+ it "returns fieldsets that keep the attributes it holds" do
+ expect(kept_attributes).to eq("postedDate" => "2026-08-01")
+ end
+ end
+
+ context "when a fieldset is empty" do
+ let(:raw) { { "topics" => "" } }
+
+ it "returns fieldsets that keep no attribute" do
+ expect(kept_attributes).to be_empty
+ end
+ end
+
+ context "without fieldsets" do
+ let(:raw) { nil }
+
+ it "returns fieldsets that keep every attribute" do
+ expect(kept_attributes).to eq(attributes)
+ end
+ end
+ end
+
+ describe "#keep" do
+ subject(:kept_attributes) { fieldsets.keep(type, attributes) }
+
+ let(:type) { "topics" }
+
+ it "returns the attributes the fieldset of that type holds" do
+ expect(kept_attributes).to eq("title" => "A", "postedDate" => "2026-08-01")
+ end
+
+ it "keeps the order of the attributes" do
+ expect(
+ described_class.parse("topics" => "postedDate,title").keep(type, attributes).keys,
+ ).to eq(%w[title postedDate])
+ end
+
+ context "when no fieldset holds the type" do
+ let(:type) { "users" }
+
+ it "returns every attribute" do
+ expect(kept_attributes).to eq(attributes)
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/request/parameters_spec.rb b/spec/lib/json_api_kit/request/parameters_spec.rb
index 4e60e3225d0..a7e984bc8f6 100644
--- a/spec/lib/json_api_kit/request/parameters_spec.rb
+++ b/spec/lib/json_api_kit/request/parameters_spec.rb
@@ -18,6 +18,18 @@ module JsonApiKitSpec
end
end
+ class ParametersMergeChange < JsonApiKit::VersionChange
+ version "2026-09-15"
+ description "The `posted_date` and `posted_time` attributes of the topics resource become `posted_at`."
+
+ resource :topics do
+ merged_attributes from: %i[posted_date posted_time],
+ to: :posted_at,
+ up: ->(date, time) { "#{date} #{time}" },
+ down: ->(posted_at) { posted_at.to_s.split(" ") }
+ end
+ end
+
class ParametersShapeChange < JsonApiKit::VersionChange
version "2026-09-15"
description "The `words` attribute of the topics resource becomes `title`, one string."
@@ -32,15 +44,40 @@ module JsonApiKitSpec
end
RSpec.describe JsonApiKit::Request::Parameters do
- subject(:declared_parameters) do
- described_class.new(parameters, glossary:, resource: JsonApiKitSpec::ParametersResource).to_h
- end
+ subject(:declared_parameters) { request_parameters.to_h }
+ let(:request_parameters) do
+ described_class.new(parameters, glossary:, resource: JsonApiKitSpec::ParametersResource)
+ end
let(:glossary) { JsonApiKit::Glossary.kit }
let(:parameters) { { "sort" => "-createdAt" } }
- it "converts the sort names" do
- expect(declared_parameters).to eq("sort" => "-created_at")
+ it "converts the sort into declared names and directions" do
+ expect(declared_parameters).to eq("sort" => { "created_at" => :desc })
+ end
+
+ context "when the sort holds several names" do
+ let(:parameters) { { "sort" => "-createdAt,title" } }
+
+ it "converts every one of them" do
+ expect(declared_parameters).to eq("sort" => { "created_at" => :desc, "title" => :asc })
+ end
+ end
+
+ context "when a sort name has a hyphen" do
+ let(:parameters) { { "sort" => "last-posted-at" } }
+
+ it "keeps the hyphen" do
+ expect(declared_parameters).to eq("sort" => { "last-posted-at" => :asc })
+ end
+ end
+
+ context "when the sort is an array" do
+ let(:parameters) { { "sort" => %w[createdAt] } }
+
+ it "leaves it to the contract" do
+ expect(declared_parameters).to eq("sort" => %w[createdAt])
+ end
end
context "when the sort is a hash" do
@@ -62,8 +99,32 @@ RSpec.describe JsonApiKit::Request::Parameters do
context "when the parameters have a fieldset" do
let(:parameters) { { "fields" => { "solved-statuses" => "answeredAt" } } }
- it "converts the field names only" do
- expect(declared_parameters).to eq("fields" => { "solved-statuses" => "answered_at" })
+ it "converts the fieldset into its declared names" do
+ expect(declared_parameters).to eq("fields" => { "solved-statuses" => %w[answered_at] })
+ end
+
+ context "when the fieldset is empty" do
+ let(:parameters) { { "fields" => { "solved-statuses" => "" } } }
+
+ it "returns no name for it" do
+ expect(declared_parameters).to eq("fields" => { "solved-statuses" => [] })
+ end
+ end
+
+ context "when the fieldset is an array" do
+ let(:parameters) { { "fields" => { "solved-statuses" => %w[answeredAt] } } }
+
+ it "converts every name" do
+ expect(declared_parameters).to eq("fields" => { "solved-statuses" => %w[answered_at] })
+ end
+ end
+
+ context "when the fieldset is neither a list nor an array" do
+ let(:parameters) { { "fields" => { "solved-statuses" => 42 } } }
+
+ it "leaves it to the contract" do
+ expect(declared_parameters).to eq("fields" => { "solved-statuses" => 42 })
+ end
end
end
@@ -115,7 +176,7 @@ RSpec.describe JsonApiKit::Request::Parameters do
let(:parameters) { { "fields" => { "topics" => "postedAt" } } }
it "converts the field to its current name" do
- expect(declared_parameters).to eq("fields" => { "topics" => "created_at" })
+ expect(declared_parameters).to eq("fields" => { "topics" => %w[created_at] })
end
end
@@ -123,7 +184,7 @@ RSpec.describe JsonApiKit::Request::Parameters do
let(:parameters) { { "fields" => { "users" => "handle" } } }
it "converts the field with the names of that type" do
- expect(declared_parameters).to eq("fields" => { "users" => "username" })
+ expect(declared_parameters).to eq("fields" => { "users" => %w[username] })
end
end
@@ -131,7 +192,7 @@ RSpec.describe JsonApiKit::Request::Parameters do
let(:parameters) { { "sort" => "-postedAt" } }
it "converts the field to its current name" do
- expect(declared_parameters).to eq("sort" => "-created_at")
+ expect(declared_parameters).to eq("sort" => { "created_at" => :desc })
end
end
@@ -139,7 +200,36 @@ RSpec.describe JsonApiKit::Request::Parameters do
let(:parameters) { { "sort" => "-postedAt,title" } }
it "converts every field" do
- expect(declared_parameters).to eq("sort" => "-created_at,title")
+ expect(declared_parameters).to eq("sort" => { "created_at" => :desc, "title" => :asc })
+ end
+ end
+
+ context "when the sort has two fields that merge into one" do
+ let(:change) { JsonApiKitSpec::ParametersMergeChange.new(__FILE__) }
+ let(:parameters) { { "sort" => "postedDate,postedTime" } }
+
+ it "converts both to the one field" do
+ expect(declared_parameters).to eq("sort" => { "posted_at" => :asc })
+ end
+
+ context "when their directions differ" do
+ let(:parameters) { { "sort" => "postedDate,-postedTime" } }
+
+ it "raises with the parameter that holds them" do
+ expect { declared_parameters }.to raise_error(
+ having_attributes(source: { parameter: "sort" }),
+ )
+ end
+ end
+
+ context "when the sort is a hash and their directions differ" do
+ let(:parameters) { { "sort" => { "postedDate" => "asc", "postedTime" => "desc" } } }
+
+ it "raises with the parameter that holds them" do
+ expect { declared_parameters }.to raise_error(
+ having_attributes(source: { parameter: "sort" }),
+ )
+ end
end
end
@@ -147,7 +237,7 @@ RSpec.describe JsonApiKit::Request::Parameters do
let(:parameters) { { "fields" => { "topics" => "title,postedAt" } } }
it "converts every field" do
- expect(declared_parameters).to eq("fields" => { "topics" => "title,created_at" })
+ expect(declared_parameters).to eq("fields" => { "topics" => %w[title created_at] })
end
end
@@ -193,7 +283,7 @@ RSpec.describe JsonApiKit::Request::Parameters do
let(:parameters) { { "sort" => "createdAt\n" } }
it "converts the case and keeps the newline for the contract" do
- expect(declared_parameters).to eq("sort" => "created_at\n")
+ expect(declared_parameters).to eq("sort" => { "created_at\n" => :asc })
end
end
@@ -228,4 +318,16 @@ RSpec.describe JsonApiKit::Request::Parameters do
expect(declared_parameters).to eq("page" => { "anchor" => "without_replies" })
end
end
+
+ describe "#fieldsets" do
+ subject(:fieldsets) { request_parameters.fieldsets }
+
+ let(:parameters) { { "fields" => { "topics" => "postedDate" } } }
+
+ it "returns the fieldsets under the names the client sent" do
+ expect(fieldsets.keep("topics", "postedDate" => "2026-08-01", "title" => "A")).to eq(
+ "postedDate" => "2026-08-01",
+ )
+ end
+ end
end
diff --git a/spec/lib/json_api_kit/resource_spec.rb b/spec/lib/json_api_kit/resource_spec.rb
index d87a8868879..6d9d6a19fce 100644
--- a/spec/lib/json_api_kit/resource_spec.rb
+++ b/spec/lib/json_api_kit/resource_spec.rb
@@ -25,6 +25,8 @@ module SpecBlog
end
end
+RSpec::Matchers.alias_matcher :accept_anchor, :be_anchor_accepts
+
RSpec.describe JsonApiKit::Resource do
subject(:resource) { SpecBlog::PostResource }
@@ -530,6 +532,20 @@ RSpec.describe JsonApiKit::Resource do
end
end
+ describe ".anchor_accepts?" do
+ subject(:resource) do
+ Class.new(topic_resource) do
+ anchor :created_at
+ anchor(:mine) { |topics, _guardian| topics }
+ end
+ end
+
+ it { is_expected.to accept_anchor(JsonApiKit::Anchoring.for(created_at: "2026-08-01")) }
+ it { is_expected.not_to accept_anchor(JsonApiKit::Anchoring.for(created_at: nil)) }
+ it { is_expected.to accept_anchor(JsonApiKit::Anchoring.for(:mine)) }
+ it { is_expected.not_to accept_anchor(JsonApiKit::Anchoring.for(:secrets)) }
+ end
+
describe ".scope_for" do
subject(:exposed_scope) { topic_resource.scope_for(guardian) }
@@ -569,7 +585,6 @@ RSpec.describe JsonApiKit::Resource do
describe ".paged_from?" do
fab!(:topic) { Fabricate(:topic, title: "A page read from a cursor") }
-
let(:ordering) { { "created_at" => :asc } }
let(:cursor) { topic_resource.order(ordering).first.position_of(topic).to_cursor }
diff --git a/spec/lib/json_api_kit/version_change/converter_spec.rb b/spec/lib/json_api_kit/version_change/converter_spec.rb
new file mode 100644
index 00000000000..76c1a3a88eb
--- /dev/null
+++ b/spec/lib/json_api_kit/version_change/converter_spec.rb
@@ -0,0 +1,54 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::VersionChange::Converter do
+ subject(:converter) { described_class.new(:up, callable, names) }
+
+ let(:callable) { ->(date, time) { "#{date} #{time}" } }
+ let(:names) { [date_name, time_name] }
+ let(:date_name) { JsonApiKit::Name::Field.new(value: "posted_date", type: "topics") }
+ let(:time_name) { JsonApiKit::Name::Field.new(value: "posted_time", type: "topics") }
+
+ describe ".new" do
+ context "when the callable does not respond to call" do
+ let(:callable) { nil }
+
+ it { expect { converter }.to raise_error(ArgumentError, /up: must respond to call/) }
+ end
+
+ context "when the callable takes another count of values" do
+ let(:callable) { ->(date) { date } }
+
+ it { expect { converter }.to raise_error(ArgumentError, /up: must take 2 values/) }
+ end
+
+ context "when the callable takes any count of values" do
+ let(:callable) { ->(*values) { values.join(" ") } }
+
+ it { expect { converter }.not_to raise_error }
+ end
+
+ context "when the callable is an object with a call method" do
+ let(:callable) { Class.new { def call(date, time) = "#{date} #{time}" }.new }
+
+ it { expect { converter }.not_to raise_error }
+ end
+ end
+
+ describe "#call" do
+ subject(:conversion) { converter.call("2026-08-01", "00:00:00") }
+
+ it "returns the value the callable builds" do
+ expect(conversion).to eq("2026-08-01 00:00:00")
+ end
+
+ context "when the callable raises" do
+ subject(:conversion) { converter.call("2026-13-45", "00:00:00") }
+
+ let(:callable) { ->(date, _time) { Time.zone.parse(date) } }
+
+ it "raises a failure with the names of the values" do
+ expect { conversion }.to raise_error(described_class::Failure, /posted_date, posted_time/)
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/version_change/declaration/merged_attributes_spec.rb b/spec/lib/json_api_kit/version_change/declaration/merged_attributes_spec.rb
new file mode 100644
index 00000000000..395e157621d
--- /dev/null
+++ b/spec/lib/json_api_kit/version_change/declaration/merged_attributes_spec.rb
@@ -0,0 +1,72 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::VersionChange::Declaration::MergedAttributes do
+ subject(:declaration) { described_class.new("things", from:, to: :posted_at, up:, down:) }
+
+ let(:from) { %i[posted_date posted_time] }
+ let(:up) { ->(date, time) { "#{date} #{time}" } }
+ let(:down) { ->(posted_at) { posted_at.to_s.split(" ") } }
+
+ describe "#transformations" do
+ subject(:transformations) { declaration.transformations }
+
+ it "returns a merge for the field, the sort and the anchor" do
+ expect(transformations.map(&:to)).to eq(
+ [
+ JsonApiKit::Name::Field.new(value: "posted_at", type: "things"),
+ JsonApiKit::Name::Sort.new(value: "posted_at", type: "things"),
+ JsonApiKit::Name::Anchor.new(value: "posted_at", type: "things"),
+ ],
+ )
+ end
+
+ it "gives each merge the old names in the order of the declaration" do
+ expect(transformations.first.from).to eq(
+ [
+ JsonApiKit::Name::Field.new(value: "posted_date", type: "things"),
+ JsonApiKit::Name::Field.new(value: "posted_time", type: "things"),
+ ],
+ )
+ end
+
+ it "gives each merge the converters" do
+ expect(transformations.map { it.up.call("2026-08-01", "00:00:00") }).to all(
+ eq("2026-08-01 00:00:00"),
+ )
+ end
+
+ context "when the declaration holds one name" do
+ let(:from) { :posted_date }
+
+ it "raises a fault with the count of names it needs" do
+ expect { transformations }.to raise_error(
+ described_class::Fault,
+ "Declare at least two names, to change posted_date into posted_at.",
+ )
+ end
+ end
+
+ context "when a converter does not respond to call" do
+ let(:up) { nil }
+ let(:down) { nil }
+
+ it "raises a fault with the converter" do
+ expect { transformations }.to raise_error(
+ described_class::Fault,
+ "up: must respond to call, to change posted_date, posted_time into posted_at.",
+ )
+ end
+ end
+
+ context "when the converter takes another count of values" do
+ let(:up) { ->(date) { date } }
+
+ it "raises a fault with the count it must take" do
+ expect { transformations }.to raise_error(
+ described_class::Fault,
+ "up: must take 2 values, to change posted_date, posted_time into posted_at.",
+ )
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/version_change/declaration/renamed_attribute_spec.rb b/spec/lib/json_api_kit/version_change/declaration/renamed_attribute_spec.rb
new file mode 100644
index 00000000000..c92b283498b
--- /dev/null
+++ b/spec/lib/json_api_kit/version_change/declaration/renamed_attribute_spec.rb
@@ -0,0 +1,70 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::VersionChange::Declaration::RenamedAttribute do
+ subject(:declaration) { described_class.new("things", from: :label, to: :name, up:, down:) }
+
+ let(:up) { described_class::NO_CONVERSION }
+ let(:down) { described_class::NO_CONVERSION }
+
+ describe "#transformations" do
+ subject(:transformations) { declaration.transformations }
+
+ it "returns a rename for the field, the sort and the anchor" do
+ expect(transformations.map(&:from)).to eq(
+ [
+ JsonApiKit::Name::Field.new(value: "label", type: "things"),
+ JsonApiKit::Name::Sort.new(value: "label", type: "things"),
+ JsonApiKit::Name::Anchor.new(value: "label", type: "things"),
+ ],
+ )
+ end
+
+ it "gives each rename the new name" do
+ expect(transformations.map { it.to.value }).to all(eq("name"))
+ end
+
+ context "when the declaration converts the value" do
+ let(:up) { ->(label) { label.upcase } }
+ let(:down) { ->(name) { name.downcase } }
+
+ it "gives each rename the converters" do
+ expect(transformations.map { it.up.call("a") }).to all(eq("A"))
+ end
+ end
+
+ context "when the declaration holds one converter only" do
+ let(:down) { ->(name) { name } }
+
+ it "raises a fault with the change" do
+ expect { transformations }.to raise_error(
+ described_class::Fault,
+ "Declare both up: and down:, to change label into name.",
+ )
+ end
+ end
+
+ context "when a converter does not respond to call" do
+ let(:up) { nil }
+ let(:down) { nil }
+
+ it "raises a fault with the converter" do
+ expect { transformations }.to raise_error(
+ described_class::Fault,
+ "up: must respond to call, to change label into name.",
+ )
+ end
+ end
+
+ context "when a converter takes another count of values" do
+ let(:up) { ->(label) { label } }
+ let(:down) { ->(name, other) { [name, other] } }
+
+ it "raises a fault with the count it must take" do
+ expect { transformations }.to raise_error(
+ described_class::Fault,
+ "down: must take 1 value, to change label into name.",
+ )
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/version_change/merge_spec.rb b/spec/lib/json_api_kit/version_change/merge_spec.rb
new file mode 100644
index 00000000000..e15f0fff307
--- /dev/null
+++ b/spec/lib/json_api_kit/version_change/merge_spec.rb
@@ -0,0 +1,65 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::VersionChange::Merge do
+ subject(:merge) { described_class.new(from: [date_name, time_name], to: new_name, up:, down:) }
+
+ let(:up) { ->(date, time) { "#{date} #{time}" } }
+ let(:down) { ->(posted_at) { posted_at.to_s.split(" ") } }
+ let(:date_name) { JsonApiKit::Name::Field.new(value: "posted_date", type: "topics") }
+ let(:time_name) { JsonApiKit::Name::Field.new(value: "posted_time", type: "topics") }
+ let(:new_name) { JsonApiKit::Name::Field.new(value: "posted_at", type: "topics") }
+
+ describe "#current" do
+ it "returns the new name" do
+ expect(merge.current).to eq(new_name)
+ end
+ end
+
+ describe "#current_pairs" do
+ subject(:current_pairs) { merge.current_pairs(attributes) }
+
+ let(:attributes) { { date_name => "2026-08-01", time_name => "00:00:00" } }
+
+ it "returns one pair, the new name with the value the converter builds" do
+ expect(current_pairs).to eq([[new_name, "2026-08-01 00:00:00"]])
+ end
+
+ context "when an old value is missing" do
+ let(:attributes) { { date_name => "2026-08-01" } }
+
+ it "gives the converter a null value in its place" do
+ expect(current_pairs).to eq([[new_name, "2026-08-01 "]])
+ end
+ end
+ end
+
+ describe "#previous_names" do
+ it "returns the old names in the order of the declaration" do
+ expect(merge.previous_names).to eq([date_name, time_name])
+ end
+ end
+
+ describe "#previous_pairs" do
+ subject(:previous_pairs) { merge.previous_pairs("2026-08-01 00:00:00") }
+
+ it "returns one pair per old name, in the order of the declaration" do
+ expect(previous_pairs).to eq([[date_name, "2026-08-01"], [time_name, "00:00:00"]])
+ end
+
+ context "when the converter answers another count of values" do
+ let(:down) { ->(posted_at) { [posted_at] } }
+
+ it "raises with the two counts" do
+ expect { previous_pairs }.to raise_error(ArgumentError, /1 value for 2 names/)
+ end
+ end
+
+ context "when the converter answers one value and not an array" do
+ let(:down) { ->(posted_at) { posted_at } }
+
+ it "raises with the two counts" do
+ expect { previous_pairs }.to raise_error(ArgumentError, /1 value for 2 names/)
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/version_change/pass_through_spec.rb b/spec/lib/json_api_kit/version_change/pass_through_spec.rb
index 3514e5d31a9..2b452f886a0 100644
--- a/spec/lib/json_api_kit/version_change/pass_through_spec.rb
+++ b/spec/lib/json_api_kit/version_change/pass_through_spec.rb
@@ -12,14 +12,14 @@ RSpec.describe JsonApiKit::VersionChange::PassThrough do
end
describe "#current_pairs" do
- it "returns the name with the value" do
- expect(pass_through.current_pairs("A")).to eq([[name, "A"]])
+ it "returns the name with its value" do
+ expect(pass_through.current_pairs(name => "A")).to eq([[name, "A"]])
end
end
- describe "#previous" do
+ describe "#previous_names" do
it "returns the name" do
- expect(pass_through.previous).to eq(name)
+ expect(pass_through.previous_names).to eq([name])
end
end
diff --git a/spec/lib/json_api_kit/version_change/rename_spec.rb b/spec/lib/json_api_kit/version_change/rename_spec.rb
index 4cb9aff6289..c2c6bf06f31 100644
--- a/spec/lib/json_api_kit/version_change/rename_spec.rb
+++ b/spec/lib/json_api_kit/version_change/rename_spec.rb
@@ -3,8 +3,8 @@
RSpec.describe JsonApiKit::VersionChange::Rename do
subject(:rename) { described_class.new(from: old_name, to: new_name, up:, down:) }
- let(:up) { JsonApiKit::VersionChange::Declarations::NO_CONVERSION }
- let(:down) { JsonApiKit::VersionChange::Declarations::NO_CONVERSION }
+ let(:up) { JsonApiKit::VersionChange::Declaration::RenamedAttribute::NO_CONVERSION }
+ let(:down) { JsonApiKit::VersionChange::Declaration::RenamedAttribute::NO_CONVERSION }
let(:old_name) { JsonApiKit::Name::Field.new(value: "posted_at", type: "topics") }
let(:new_name) { JsonApiKit::Name::Field.new(value: "created_at", type: "topics") }
@@ -15,7 +15,7 @@ RSpec.describe JsonApiKit::VersionChange::Rename do
end
describe "#current_pairs" do
- subject(:current_pairs) { rename.current_pairs(value) }
+ subject(:current_pairs) { rename.current_pairs(old_name => value) }
let(:value) { "2026/08/01" }
@@ -41,9 +41,9 @@ RSpec.describe JsonApiKit::VersionChange::Rename do
end
end
- describe "#previous" do
+ describe "#previous_names" do
it "returns the old name" do
- expect(rename.previous).to eq(old_name)
+ expect(rename.previous_names).to eq([old_name])
end
end
diff --git a/spec/lib/json_api_kit/version_change_spec.rb b/spec/lib/json_api_kit/version_change_spec.rb
index 2b2fe40d968..ea6a3f0e153 100644
--- a/spec/lib/json_api_kit/version_change_spec.rb
+++ b/spec/lib/json_api_kit/version_change_spec.rb
@@ -22,6 +22,18 @@ module JsonApiKitSpec
end
end
+ class MergeThingsDateAndTimeIntoPostedAt < JsonApiKit::VersionChange
+ version "2026-09-20"
+ description "The `posted_date` and `posted_time` attributes of the things resource become `posted_at`."
+
+ resource :things do
+ merged_attributes from: %i[posted_date posted_time],
+ to: :posted_at,
+ up: ->(date, time) { "#{date} #{time}" },
+ down: ->(posted_at) { posted_at.to_s.split(" ") }
+ end
+ end
+
class RenameThingsAndPeople < JsonApiKit::VersionChange
version "2026-10-01"
description "Two resources change their names."
@@ -105,13 +117,13 @@ RSpec.describe JsonApiKit::VersionChange do
context "when a change renames one name twice" do
let(:directory) { "api_changes_with_two_renames_from_one_name" }
- it { expect { changes }.to raise_error(ArgumentError, /renames label twice/) }
+ it { expect { changes }.to raise_error(ArgumentError, /changes label twice/) }
end
context "when a change renames two names to one name" do
let(:directory) { "api_changes_with_two_renames_to_one_name" }
- it { expect { changes }.to raise_error(ArgumentError, /renames two names to title/) }
+ it { expect { changes }.to raise_error(ArgumentError, /changes two names into title/) }
end
end
@@ -137,28 +149,18 @@ RSpec.describe JsonApiKit::VersionChange do
end
describe ".resource" do
- context "when a rename declares one converter only" do
- subject(:declaration) do
- Class.new(described_class) do
- version "2026-09-15"
- description "Half a shape change."
- resource(:things) { renamed_attribute from: :a, to: :b, down: ->(value) { value } }
- end
- end
+ subject(:transformations) { change_class.transformations }
- it { expect { declaration }.to raise_error(ArgumentError, /both up: and down:/) }
+ it "collects a rename for each name the attribute derives" do
+ expect(transformations).to all(be_a(JsonApiKit::VersionChange::Rename))
end
- context "when a converter is not callable" do
- subject(:declaration) do
- Class.new(described_class) do
- version "2026-09-15"
- description "A converter that is not one."
- resource(:things) { renamed_attribute from: :a, to: :b, up: nil, down: nil }
- end
- end
+ context "when the resource merges attributes" do
+ let(:change_class) { JsonApiKitSpec::MergeThingsDateAndTimeIntoPostedAt }
- it { expect { declaration }.to raise_error(ArgumentError, /must respond to call/) }
+ it "collects a merge for each name the attribute derives" do
+ expect(transformations).to all(be_a(JsonApiKit::VersionChange::Merge))
+ end
end
end
@@ -207,9 +209,17 @@ RSpec.describe JsonApiKit::VersionChange do
end
end
- context "with several resources" do
- subject(:change) { JsonApiKitSpec::RenameThingsAndPeople.new(__FILE__) }
+ context "when the change merges the name into another" do
+ let(:change_class) { JsonApiKitSpec::MergeThingsDateAndTimeIntoPostedAt }
+ let(:name) { JsonApiKit::Name::Field.new(value: "posted_time", type: "things") }
+ it "returns the name it merges into" do
+ expect(current_name).to eq(name.with(value: "posted_at"))
+ end
+ end
+
+ context "with several resources" do
+ let(:change_class) { JsonApiKitSpec::RenameThingsAndPeople }
let(:other_name) { JsonApiKit::Name::Field.new(value: "handle", type: "people") }
it "renames the names of every resource" do
@@ -234,6 +244,17 @@ RSpec.describe JsonApiKit::VersionChange do
expect(current_attributes).to include(other_name => "B")
end
+ context "when the change merges two attributes" do
+ let(:change_class) { JsonApiKitSpec::MergeThingsDateAndTimeIntoPostedAt }
+ let(:attributes) { { name => "2026-08-01", other_name => "00:00:00" } }
+ let(:name) { JsonApiKit::Name::Field.new(value: "posted_date", type: "things") }
+ let(:other_name) { JsonApiKit::Name::Field.new(value: "posted_time", type: "things") }
+
+ it "returns one attribute under the name they merge into" do
+ expect(current_attributes).to eq(name.with(value: "posted_at") => "2026-08-01 00:00:00")
+ end
+ end
+
context "when the change reshapes the value" do
let(:change_class) { JsonApiKitSpec::ReshapeThingsWordsToTitle }
let(:attributes) { { name => %w[Bands of a listing] } }
@@ -261,6 +282,36 @@ RSpec.describe JsonApiKit::VersionChange do
it "returns the name before the change" do
expect(previous_name).to eq(name.with(value: "label"))
end
+
+ context "when the change merges several names into the name" do
+ let(:change_class) { JsonApiKitSpec::MergeThingsDateAndTimeIntoPostedAt }
+ let(:name) { JsonApiKit::Name::Field.new(value: "posted_at", type: "things") }
+
+ it "returns the first of them" do
+ expect(previous_name).to eq(name.with(value: "posted_date"))
+ end
+ end
+ end
+
+ describe "#previous_names" do
+ subject(:previous_names) { change.previous_names(name) }
+
+ let(:name) { JsonApiKit::Name::Field.new(value: "name", type: "things") }
+
+ it "returns the name before the change" do
+ expect(previous_names).to eq([name.with(value: "label")])
+ end
+
+ context "when the change merges several names into the name" do
+ let(:change_class) { JsonApiKitSpec::MergeThingsDateAndTimeIntoPostedAt }
+ let(:name) { JsonApiKit::Name::Field.new(value: "posted_at", type: "things") }
+
+ it "returns every one of them" do
+ expect(previous_names).to eq(
+ [name.with(value: "posted_date"), name.with(value: "posted_time")],
+ )
+ end
+ end
end
describe "#previous_attributes" do
@@ -278,6 +329,19 @@ RSpec.describe JsonApiKit::VersionChange do
expect(previous_attributes).to include(other_name => "B")
end
+ context "when the change merges two attributes" do
+ let(:change_class) { JsonApiKitSpec::MergeThingsDateAndTimeIntoPostedAt }
+ let(:attributes) { { name => "2026-08-01 00:00:00" } }
+ let(:name) { JsonApiKit::Name::Field.new(value: "posted_at", type: "things") }
+
+ it "returns the two attributes under their names before the change" do
+ expect(previous_attributes).to eq(
+ name.with(value: "posted_date") => "2026-08-01",
+ name.with(value: "posted_time") => "00:00:00",
+ )
+ end
+ end
+
context "when the change reshapes the value" do
let(:change_class) { JsonApiKitSpec::ReshapeThingsWordsToTitle }
let(:attributes) { { name => "Bands of a listing" } }