A platform for community discussion. Free, open, simple.
DEV: Support relationship renames in JSON:API versions (#43585)
Loïc Guitaut70ef4351bae7
diff --git a/lib/json_api_kit/declarations/relationships.rb b/lib/json_api_kit/declarations/relationships.rbindex 2043109891a..742ba57658c 100644--- a/lib/json_api_kit/declarations/relationships.rb+++ b/lib/json_api_kit/declarations/relationships.rb@@ -3,6 +3,8 @@module JsonApiKitmodule Declarationsclass Relationships+ delegate :fetch, to: :relationships+def initialize(relationships)@relationships = relationships.index_by(&:name)enddiff --git a/lib/json_api_kit/document/relationship_object.rb b/lib/json_api_kit/document/relationship_object.rbindex 952fe6f67c1..205e6877e28 100644--- a/lib/json_api_kit/document/relationship_object.rb+++ b/lib/json_api_kit/document/relationship_object.rb@@ -5,6 +5,7 @@ module JsonApiKitclass RelationshipObjectdelegate :pages, to: :linkage, private: truedelegate :urls, :glossary, to: :client, private: true+ delegate :member_type, to: :glossary, private: truedef initialize(linkage, client:, owner:, name:)@linkage = linkage@@ -22,7 +23,7 @@ module JsonApiKitdef data = linkage.collapse { identifier(it) }def identifier(record)- { type: glossary.member_type(record.type), id: record.id }+ { type: member_type(record.type), id: record.id }enddef links = { self: relationship_url.to_s, related: related_url.to_s }.merge(page_links)diff --git a/lib/json_api_kit/document/resource_object.rb b/lib/json_api_kit/document/resource_object.rbindex 2c62ff18c2d..2f600ddb119 100644--- a/lib/json_api_kit/document/resource_object.rb+++ b/lib/json_api_kit/document/resource_object.rb@@ -5,6 +5,7 @@ module JsonApiKitclass ResourceObjectdelegate :id, to: :record, private: truedelegate :glossary, :urls, to: :client, private: true+ delegate :member_type, :member_relationship, :member_attributes, to: :glossary, private: truedef initialize(record, client:, fieldsets:, meta: {})@record = record@@ -19,20 +20,18 @@ module JsonApiKitattr_reader :record, :client, :fieldsets, :meta- def type = glossary.member_type(record.type)-- def relationship(value) = Name::Relationship.new(value:, type: record.type)-- def member_value(name) = glossary.member_name(name).value+ def type = member_type(record.type)def attributes- fieldsets.keep(type, glossary.member_attributes(record.attributes).transform_keys(&:value))+ fieldsets.keep(type, member_attributes(record.attributes).transform_keys(&:value))enddef relationshipsrecord.relationships.to_h do |name, linkage|- member = member_value(relationship(name))- [member, RelationshipObject.new(linkage, client:, owner: record, name: member).to_h]+ [+ member_relationship(declared: name, type: record.type),+ RelationshipObject.new(linkage, client:, owner: record, name:).to_h,+ ]endenddiff --git a/lib/json_api_kit/glossary.rb b/lib/json_api_kit/glossary.rbindex 99a8165500f..947eb248020 100644--- a/lib/json_api_kit/glossary.rb+++ b/lib/json_api_kit/glossary.rb@@ -79,6 +79,18 @@ module JsonApiKitdef member_type(type) = member_name(Name::Type.new(value: type)).value+ def declared_relationship(member:, type:)+ declared_name(Name::Relationship.new(value: member, type: member_type(type))).value+ end++ def member_relationship(declared:, type:)+ member_name(Name::Relationship.new(value: declared, type:)).value+ end++ def unscoped_member(declared:)+ member_name(Name::Member.new(value: declared)).value+ end+def member_attributes(attributes)rules.reverse_each.reduce(attributes) { |result, rule| rule.member_attributes(result) }enddiff --git a/lib/json_api_kit/record_url.rb b/lib/json_api_kit/record_url.rbindex b27faf54bc5..cd5c77d3a2f 100644--- a/lib/json_api_kit/record_url.rb+++ b/lib/json_api_kit/record_url.rb@@ -9,14 +9,16 @@ module JsonApiKitdef to_s = address- def relationship(name) = Url.new("#{address}/relationships/#{name}")+ def relationship(name) = Url.new("#{address}/relationships/#{path_segment(name)}")- def related(name) = Url.new("#{address}/#{name}")+ def related(name) = Url.new("#{address}/#{path_segment(name)}")privateattr_reader :base, :record+ def path_segment(name) = name.dasherize+def address = [base, record.namespace, record.type, record.id].compact.join("/")endenddiff --git a/lib/json_api_kit/relationship_paths.rb b/lib/json_api_kit/relationship_paths.rbnew file mode 100644index 00000000000..04450f769fb--- /dev/null+++ b/lib/json_api_kit/relationship_paths.rb@@ -0,0 +1,54 @@+# frozen_string_literal: true++module JsonApiKit+ class RelationshipPaths+ class UnknownPath < BadParameter+ def initialize(path, parameter: nil)+ @path = path+ super("There is no relationship path named #{path}.", parameter:)+ end++ def title = "No such relationship path"++ private++ attr_reader :path++ def arguments = [path]+ end++ def initialize(resource:, glossary:)+ @resource = resource+ @glossary = glossary+ end++ def declared_path(path)+ translate(path_names(path)) { |position, name| position.advance_to_declared(member: name) }+ rescue UnknownPath+ raise UnknownPath.new(path.to_s)+ end++ def member_path(path)+ translate(path_names(path)) { |position, name| position.advance_to_member(declared: name) }+ end++ private++ attr_reader :resource, :glossary++ def translate(names, &)+ return "" if names.empty?+ steps(names.each, &).map(&:name).join(Path::SEPARATOR)+ end++ def steps(names, &advance)+ Enumerator.produce(advance.call(position, names.next)) do |step|+ advance.call(step.next_position, names.next)+ end+ end++ def path_names(path) = path.to_s.split(Path::SEPARATOR, -1)++ def position = Position.new(resource:, glossary:)+ end+enddiff --git a/lib/json_api_kit/relationship_paths/position.rb b/lib/json_api_kit/relationship_paths/position.rbnew file mode 100644index 00000000000..134ea6417a0--- /dev/null+++ b/lib/json_api_kit/relationship_paths/position.rb@@ -0,0 +1,30 @@+# frozen_string_literal: true++module JsonApiKit+ class RelationshipPaths+ Position =+ Data.define(:resource, :glossary) do+ delegate :declared_relationship, :member_relationship, to: :glossary, private: true++ def advance_to_declared(member:)+ step(declared_relationship(member:, type: resource.type))+ end++ def advance_to_member(declared:)+ step(declared, name: member_relationship(declared:, type: resource.type))+ rescue UnknownPath+ UnscopedPosition.new(glossary:).advance_to_member(declared:)+ end++ private++ def step(relationship_name, name: relationship_name)+ Step.new(name:, next_position: with(resource: relationship(relationship_name).resource))+ end++ def relationship(name)+ resource.relationships.fetch(name) { raise UnknownPath.new(name) }+ end+ end+ end+enddiff --git a/lib/json_api_kit/relationship_paths/step.rb b/lib/json_api_kit/relationship_paths/step.rbnew file mode 100644index 00000000000..0a81c427f3d--- /dev/null+++ b/lib/json_api_kit/relationship_paths/step.rb@@ -0,0 +1,7 @@+# frozen_string_literal: true++module JsonApiKit+ class RelationshipPaths+ Step = Data.define(:name, :next_position)+ end+enddiff --git a/lib/json_api_kit/relationship_paths/unscoped_position.rb b/lib/json_api_kit/relationship_paths/unscoped_position.rbnew file mode 100644index 00000000000..9e93aa0fcb0--- /dev/null+++ b/lib/json_api_kit/relationship_paths/unscoped_position.rb@@ -0,0 +1,14 @@+# frozen_string_literal: true++module JsonApiKit+ class RelationshipPaths+ UnscopedPosition =+ Data.define(:glossary) do+ delegate :unscoped_member, to: :glossary, private: true++ def advance_to_member(declared:)+ Step.new(name: unscoped_member(declared:), next_position: self)+ end+ end+ end+enddiff --git a/lib/json_api_kit/request/contract/error.rb b/lib/json_api_kit/request/contract/error.rbindex 07bdeb06ca0..f24087e8234 100644--- a/lib/json_api_kit/request/contract/error.rb+++ b/lib/json_api_kit/request/contract/error.rb@@ -35,6 +35,8 @@ module JsonApiKitdef resource_type = glossary.member_type(options[:type])+ def relationship_path = options[:path]+def member_parameter(member = name) = parameter.member(member)def window_parameters = base.page.window_names.map { page_parameter(it) }diff --git a/lib/json_api_kit/request/contract/including.rb b/lib/json_api_kit/request/contract/including.rbindex 6227d6ed43f..a24b256b205 100644--- a/lib/json_api_kit/request/contract/including.rb+++ b/lib/json_api_kit/request/contract/including.rb@@ -26,14 +26,20 @@ module JsonApiKitprivatedef check_include_paths- refuse_unknown(- :include,- Paths- .new(include)- .reject { resource.paths_include?(it) }- .map { Name::Member.new(value: it.to_s) },- )+ Paths+ .new(include)+ .reject { resource.paths_include?(it) }+ .each do |path|+ errors.add(+ :include,+ :no_such_name,+ path: relationship_paths.member_path(path),+ message: "no such name",+ )+ endend++ def relationship_paths = @relationship_paths ||= RelationshipPaths.new(resource:, glossary:)endendenddiff --git a/lib/json_api_kit/request/contract/mapper.rb b/lib/json_api_kit/request/contract/mapper.rbindex e772e4eaf4f..4c107f3cf73 100644--- a/lib/json_api_kit/request/contract/mapper.rb+++ b/lib/json_api_kit/request/contract/mapper.rb@@ -75,7 +75,7 @@ module JsonApiKit},%i[include no_such_name] => {title: "No such relationship path",- detail: ->(error) { "There is no relationship path named #{error.name}." },+ detail: ->(error) { "There is no relationship path named #{error.relationship_path}." },},%i[fields bad_shape] => {title: "Invalid fields parameter",diff --git a/lib/json_api_kit/request/family.rb b/lib/json_api_kit/request/family.rbindex 4a7e81bc857..26bfc56ee8c 100644--- a/lib/json_api_kit/request/family.rb+++ b/lib/json_api_kit/request/family.rb@@ -5,14 +5,16 @@ module JsonApiKitclass FamilyLIST_ITEM = /\A(?<direction>-?)(?<name>.*)\z/m- def initialize(glossary:, type:)+ def initialize(glossary:, resource:)@glossary = glossary- @type = type+ @resource = resourceendprivate- attr_reader :glossary, :type+ attr_reader :glossary, :resource++ def type = glossary.member_type(resource.type)def names(value, path, &name_for)case valuediff --git a/lib/json_api_kit/request/family/include.rb b/lib/json_api_kit/request/family/include.rbindex 3289b29ac2f..1e687cf239f 100644--- a/lib/json_api_kit/request/family/include.rb+++ b/lib/json_api_kit/request/family/include.rb@@ -4,7 +4,22 @@ module JsonApiKitclass Requestclass Familyclass Include < Family- def declared_value(value, path) = names(value, path) { Name::Member.new(value: it) }+ def declared_value(value, path)+ case value+ when Array+ value.map { declared_value(it, path) }+ when String, Symbol+ value.to_s.split(LIST, -1).map { relationship_paths.declared_path(it) }.join(LIST)+ else+ value+ end+ rescue Glossary::NotAMemberName, RelationshipPaths::UnknownPath => error+ raise error.at(ParameterName.new(*path).to_s)+ end++ private++ def relationship_paths = @relationship_paths ||= RelationshipPaths.new(resource:, glossary:)endendenddiff --git a/lib/json_api_kit/request/parameters.rb b/lib/json_api_kit/request/parameters.rbindex 380b9481f9a..3230ae1277e 100644--- a/lib/json_api_kit/request/parameters.rb+++ b/lib/json_api_kit/request/parameters.rb@@ -30,9 +30,7 @@ module JsonApiKitattr_reader :raw, :glossary, :resource- def family_for(key) = FAMILIES.fetch(key, Family::Other).new(glossary:, type: member_type)-- def member_type = glossary.member_type(resource.type)+ def family_for(key) = FAMILIES.fetch(key, Family::Other).new(glossary:, resource:)def declared_name(family)glossary.declared_name(Name::Member.new(value: family)).valuediff --git a/lib/json_api_kit/version_change/declarations.rb b/lib/json_api_kit/version_change/declarations.rbindex 397fb8aa33d..f427e722d35 100644--- a/lib/json_api_kit/version_change/declarations.rb+++ b/lib/json_api_kit/version_change/declarations.rb@@ -20,6 +20,10 @@ module JsonApiKitdeclare(Declaration::RenamedName.new(type, [Name::Filter], from:, to:))end+ def renamed_relationship(from:, to:)+ declare(Declaration::RenamedName.new(type, [Name::Relationship, Name::Field], from:, to:))+ end+def to_a = transformationsprivatediff --git a/spec/integration/json_api_kit/casing_spec.rb b/spec/integration/json_api_kit/casing_spec.rbindex 5612dabd3d3..4a556d1171f 100644--- a/spec/integration/json_api_kit/casing_spec.rb+++ b/spec/integration/json_api_kit/casing_spec.rb@@ -106,8 +106,8 @@ RSpec.describe "JSON:API member names", type: :request doexpect(relationship).to be_presentend- it "sends its links under that name" do- expect(relationship["links"]["related"]).to end_with("/orderedPosts")+ it "sends its links with kebab-case path segments" do+ expect(relationship["links"]["related"]).to end_with("/ordered-posts")endenddiff --git a/spec/integration/json_api_kit/renamed_relationships_spec.rb b/spec/integration/json_api_kit/renamed_relationships_spec.rbnew file mode 100644index 00000000000..07079ef1433--- /dev/null+++ b/spec/integration/json_api_kit/renamed_relationships_spec.rb@@ -0,0 +1,394 @@+# frozen_string_literal: true++require_relative "support"++module JsonApiKitSpec+ class RelationshipUser < ::User+ has_many :valid_groups, through: :group_users, source: :group+ end++ class RelationshipTopic < ::Topic+ belongs_to :writer, class_name: "JsonApiKitSpec::RelationshipUser", foreign_key: :user_id+ end++ class RelationshipGroupResource < JsonApiKit::Resource+ model Group+ type :groups+ attribute :name+ end++ class RelationshipUserResource < JsonApiKit::Resource+ model RelationshipUser+ type :users+ attribute :username+ has_many :valid_groups, resource: RelationshipGroupResource+ end++ RelationshipGroupResource.has_many(:users, resource: RelationshipUserResource)++ class RelationshipTopicResource < JsonApiKit::Resource+ model RelationshipTopic+ type :topics+ attribute :title+ sort :created_at+ sort "writer.username"+ default_sort created_at: :desc+ has_one :writer, resource: RelationshipUserResource+ has_one :category, resource: CategoryResource+ includes "writer.valid_groups"+ end++ class RelationshipTopicsController < JsonApiKit::BaseController+ resource RelationshipTopicResource++ def writer+ render_document(+ JsonApiKit::Document::Individual.for(+ topic.user_id,+ request.query_parameters,+ resource: RelationshipUserResource,+ client:,+ ),+ )+ end++ def writer_linkage+ render json: {+ data: {+ type: glossary.member_type("users"),+ id: topic.user_id.to_s,+ },+ },+ content_type: JsonApiKit::Pagination::Profile::MEDIA_TYPE+ end++ private++ def topic = RelationshipTopic.find(params[:id])+ end++ class RelationshipUsersController < JsonApiKit::BaseController+ resource RelationshipUserResource++ def valid_groups+ render_document(+ JsonApiKit::Document::Collection.for(+ request.query_parameters,+ resource: RelationshipGroupResource,+ client:,+ scoped_to: user.valid_groups,+ ),+ )+ end++ def valid_groups_linkage+ render json: {+ data: group_identifiers,+ },+ content_type: JsonApiKit::Pagination::Profile::MEDIA_TYPE+ end++ private++ def user = RelationshipUser.find(params[:id])++ def group_identifiers+ user.valid_groups.map { { type: glossary.member_type("groups"), id: it.id.to_s } }+ end+ end++ class RenameTopicAuthorToWriter < JsonApiKit::VersionChange+ version "2026-09-01"+ description "The author relationship becomes writer."++ resource :topics do+ renamed_relationship from: :author, to: :writer+ end+ end++ class RenameUserGroupsToValidGroups < JsonApiKit::VersionChange+ version "2026-09-02"+ description "The groups relationship becomes valid_groups."++ resource :users do+ renamed_relationship from: :groups, to: :valid_groups+ end+ end+end++RSpec.describe "JSON:API relationship renames", type: :request do+ include_context "with a listing of topics"++ let(:version) { JsonApiKit::Timeline::FIRST_RELEASE.to_s }+ let(:changes) do+ [+ JsonApiKitSpec::RenameTopicAuthorToWriter.new(__FILE__),+ JsonApiKitSpec::RenameUserGroupsToValidGroups.new(__FILE__),+ ]+ end+ let(:version_changes) { JsonApiKit::VersionChanges.new(changes) }+ let(:query) { { "include" => "author.groups" } }+ let(:body) { JSON.parse(response.body) }+ let(:primary_resource) { body.fetch("data").first }+ let(:author_resource) do+ body.fetch("included").detect { it["type"] == "users" && it["id"] == newest.user_id.to_s }+ end+ let(:error) { body.fetch("errors").sole }++ fab!(:group)++ before do+ group.add(newest.user)+ freeze_time(Date.new(2026, 9, 3))+ allow(JsonApiKit::VersionChanges).to receive(:core).and_return(version_changes)+ Rails.application.routes.disable_clear_and_finalize = true+ Rails.application.routes.draw do+ get "/api/topics" => "json_api_kit_spec/relationship_topics#index"+ get "/api/topics/:id/writer" => "json_api_kit_spec/relationship_topics#writer"+ get "/api/topics/:id/relationships/writer" =>+ "json_api_kit_spec/relationship_topics#writer_linkage"+ get "/api/users/:id/valid-groups" => "json_api_kit_spec/relationship_users#valid_groups"+ get "/api/users/:id/relationships/valid-groups" =>+ "json_api_kit_spec/relationship_users#valid_groups_linkage"+ end+ Rails.application.routes.disable_clear_and_finalize = false+ get "/api/topics", headers: { "HTTP_API_VERSION" => version }, params: query+ end++ after { Rails.application.reload_routes! }++ it "uses the historical name of the to-one relationship" do+ expect(primary_resource.fetch("relationships")).to include(+ "author" => a_hash_including("data" => { "type" => "users", "id" => newest.user_id.to_s }),+ )+ end++ it "uses the historical name of the to-many relationship" do+ expect(author_resource.dig("relationships", "groups", "data")).to include(+ "type" => "groups",+ "id" => group.id.to_s,+ )+ end++ it "includes the resources reached through both renamed segments" do+ expect(body.fetch("included")).to include(+ a_hash_including("type" => "users", "id" => newest.user_id.to_s),+ a_hash_including("type" => "groups", "id" => group.id.to_s),+ )+ end++ context "when the request selects renamed relationships in fieldsets" do+ let(:query) { super().merge("fields" => { "topics" => "author", "users" => "groups" }) }++ it "selects the historical to-one relationship" do+ expect(primary_resource.fetch("relationships").keys).to contain_exactly("author")+ end++ it "selects the historical to-many relationship" do+ expect(author_resource.fetch("relationships").keys).to contain_exactly("groups")+ end++ it "excludes unselected attributes" do+ expect(author_resource).not_to have_key("attributes")+ end+ end++ context "when the request includes an unrelated relationship" do+ let(:query) { super().merge("include" => "author.groups,category") }++ it "preserves the unrelated name" do+ expect(primary_resource.fetch("relationships").keys).to contain_exactly("author", "category")+ end+ end++ context "when the client follows the to-one related link" do+ before do+ get primary_resource.dig("relationships", "author", "links", "related"),+ headers: {+ "HTTP_API_VERSION" => version,+ }+ end++ it "serves the related resource through the current route" do+ expect(JSON.parse(response.body).fetch("data")).to include(+ "type" => "users",+ "id" => newest.user_id.to_s,+ )+ end+ end++ context "when the client follows the to-one linkage link" do+ before do+ get primary_resource.dig("relationships", "author", "links", "self"),+ headers: {+ "HTTP_API_VERSION" => version,+ }+ end++ it "serves linkage through the current route" do+ expect(JSON.parse(response.body).fetch("data")).to eq(+ "type" => "users",+ "id" => newest.user_id.to_s,+ )+ end+ end++ context "when the client follows the to-many related link" do+ before do+ get author_resource.dig("relationships", "groups", "links", "related"),+ headers: {+ "HTTP_API_VERSION" => version,+ }+ end++ it "serves the collection through the current kebab-case route" do+ expect(JSON.parse(response.body).fetch("data")).to include(+ a_hash_including("type" => "groups", "id" => group.id.to_s),+ )+ end+ end++ context "when the client follows the to-many linkage link" do+ before do+ get author_resource.dig("relationships", "groups", "links", "self"),+ headers: {+ "HTTP_API_VERSION" => version,+ }+ end++ it "serves linkage through the current kebab-case route" do+ expect(JSON.parse(response.body).fetch("data")).to include(+ "type" => "groups",+ "id" => group.id.to_s,+ )+ end+ end++ context "when the request uses a newer name in the first segment" do+ let(:query) { { "include" => "writer.groups" } }++ it "corrects that segment" do+ expect(error).to include(+ "detail" => "Use author, not writer.",+ "source" => {+ "parameter" => "include",+ },+ )+ end+ end++ context "when the request uses a newer name in the second segment" do+ let(:query) { { "include" => "author.validGroups" } }++ it "corrects the segment in the target resource's vocabulary" do+ expect(error).to include(+ "detail" => "Use groups, not validGroups.",+ "source" => {+ "parameter" => "include",+ },+ )+ end+ end++ context "when the request uses a newer relationship name in a fieldset" do+ let(:query) { super().merge("fields" => { "users" => "validGroups" }) }++ it "corrects the field name" do+ expect(error).to include(+ "detail" => "Use groups, not validGroups.",+ "source" => {+ "parameter" => "fields[users]",+ },+ )+ end+ end++ context "when a later segment does not exist" do+ let(:query) { { "include" => "author.unknownGroups" } }++ it "reports the original client path" do+ expect(error).to include(+ "detail" => "There is no relationship path named author.unknownGroups.",+ "source" => {+ "parameter" => "include",+ },+ )+ end+ end++ context "when the translated path exists but is not allowed" do+ let(:query) { { "include" => "author.groups.users" } }++ it "reports the disallowed path in the client's vocabulary" do+ expect(error).to include(+ "detail" => "There is no relationship path named author.groups.users.",+ "source" => {+ "parameter" => "include",+ },+ )+ end+ end++ context "when a long cyclic path is not allowed" do+ let(:query) { { "include" => "author.#{Array.new(1500, "groups.users").join(".")}" } }++ it "rejects the path without exhausting the stack" do+ expect(response).to have_http_status(:bad_request)+ end+ end++ context "when the request uses the historical relationship in a sort name" do+ let(:query) { super().merge("sort" => "author.username") }++ it "requires an explicit sort rename" do+ expect(error).to include("detail" => "There is no sort named author.username.")+ end+ end++ context "when the pin follows the first rename" do+ let(:version) { "2026-09-01" }+ let(:query) { { "include" => "writer.groups" } }++ it "uses the current first segment" do+ expect(primary_resource.fetch("relationships").keys).to contain_exactly("writer")+ end++ it "uses the historical second segment" do+ expect(author_resource.fetch("relationships").keys).to contain_exactly("groups")+ end+ end++ context "when the pin follows both renames" do+ let(:version) { "2026-09-02" }+ let(:query) { { "include" => "writer.validGroups" } }++ it "uses the current second segment with camel casing" do+ expect(author_resource.fetch("relationships").keys).to contain_exactly("validGroups")+ end+ end++ context "when the types also have historical names" do+ let(:changes) { [type_change, *super()] }+ let(:type_change) do+ Class+ .new(JsonApiKit::VersionChange) do+ version "2026-09-01"+ description "Discussion and member types use their current names."+ renamed_type from: :discussions, to: :topics+ renamed_type from: :members, to: :users+ end+ .new(__FILE__)+ end+ let(:query) { super().merge("fields" => { "discussions" => "author", "members" => "groups" }) }++ it "composes type and relationship renames at each segment" do+ expect(primary_resource).to include(+ "type" => "discussions",+ "relationships" => {+ "author" =>+ a_hash_including("data" => { "type" => "members", "id" => newest.user_id.to_s }),+ },+ )+ end+ end+enddiff --git a/spec/lib/json_api_kit/declarations/relationships_spec.rb b/spec/lib/json_api_kit/declarations/relationships_spec.rbindex 755d2b95339..211519a0d83 100644--- a/spec/lib/json_api_kit/declarations/relationships_spec.rb+++ b/spec/lib/json_api_kit/declarations/relationships_spec.rb@@ -22,6 +22,28 @@ RSpec.describe JsonApiKit::Declarations::Relationships doendlet(:declarations) { [user_relationship, tags_relationship] }+ describe "#fetch" do+ subject(:relationship) { relationships.fetch(name) }++ let(:name) { "user" }++ it "returns the declaration with that name" do+ expect(relationship).to equal(user_relationship)+ end++ context "when the name is not declared" do+ let(:name) { "author" }++ it "raises a lookup error" do+ expect { relationship }.to raise_error(KeyError)+ end++ it "uses a caller-supplied fallback" do+ expect(relationships.fetch(name) { :unknown }).to eq(:unknown)+ end+ end+ end+describe "#pick" doit "returns every one of them" doexpect(relationships.pick(%w[user tags])).to eq([user_relationship, tags_relationship])@@ -59,8 +81,6 @@ RSpec.describe JsonApiKit::Declarations::Relationships doenddescribe "#resolves?" do- subject { relationships }-let(:path) { JsonApiKit::Path.for("user") }it { is_expected.to resolve(path) }diff --git a/spec/lib/json_api_kit/document/relationship_object_spec.rb b/spec/lib/json_api_kit/document/relationship_object_spec.rbindex 7d65c7560cb..86bf0d1d577 100644--- a/spec/lib/json_api_kit/document/relationship_object_spec.rb+++ b/spec/lib/json_api_kit/document/relationship_object_spec.rb@@ -1,7 +1,7 @@# frozen_string_literal: trueRSpec.describe JsonApiKit::Document::RelationshipObject do- subject(:relationship_object) { described_class.new(linkage, client:, owner:, name: "posts") }+ subject(:relationship_object) { described_class.new(linkage, client:, owner:, name:) }fab!(:author, :user)fab!(:topic)@@ -41,11 +41,37 @@ RSpec.describe JsonApiKit::Document::RelationshipObject do)endlet(:namespace) { nil }+ let(:name) { "posts" }let(:linkage) { JsonApiKit::Linkage::ToOne.new([record]) }let(:relationship_url) { "https://example.com/api/topics/#{topic.id}/relationships/posts" }let(:related_url) { "https://example.com/api/topics/#{topic.id}/posts" }describe "#to_h" do+ context "when the current relationship name has several words" do+ let(:name) { "ordered_posts" }+ let(:glossary) { JsonApiKit::Glossary.resource(JsonApiKit::Timeline::FIRST_RELEASE) }+ let(:version_change) do+ Class+ .new(JsonApiKit::VersionChange) do+ resource :topics do+ renamed_relationship from: :archived_posts, to: :ordered_posts+ end+ end+ .new(__FILE__)+ end++ before do+ allow(JsonApiKit::VersionChanges.core).to receive(:after).and_return([version_change])+ end++ it "uses the current names with kebab casing in URLs" do+ expect(relationship_object.to_h[:links]).to eq(+ self: "https://example.com/api/topics/#{topic.id}/relationships/ordered-posts",+ related: "https://example.com/api/topics/#{topic.id}/ordered-posts",+ )+ end+ end+context "when the type has a historical name" dolet(:glossary) { JsonApiKit::Glossary.resource(JsonApiKit::Timeline::FIRST_RELEASE) }let(:version_change) dodiff --git a/spec/lib/json_api_kit/document/resource_object_spec.rb b/spec/lib/json_api_kit/document/resource_object_spec.rbindex d9a2b9811ba..afb22c42006 100644--- a/spec/lib/json_api_kit/document/resource_object_spec.rb+++ b/spec/lib/json_api_kit/document/resource_object_spec.rb@@ -102,6 +102,29 @@ RSpec.describe JsonApiKit::Document::ResourceObject dobefore { allow(JsonApiKit::Document::RelationshipObject).to receive(:new).and_call_original }+ context "when the relationship has a historical name" do+ let(:glossary) { JsonApiKit::Glossary.resource(JsonApiKit::Timeline::FIRST_RELEASE) }+ let(:version_change) do+ Class+ .new(JsonApiKit::VersionChange) do+ resource :topics do+ renamed_relationship from: :author, to: :user+ end+ end+ .new(__FILE__)+ end++ before do+ allow(JsonApiKit::VersionChanges.core).to receive(:after).and_return([version_change])+ end++ it "uses the current name in the relationship's URL" do+ expect(resource_object.to_h.dig(:relationships, "author", :links, :related)).to eq(+ "https://example.com/api/topics/#{topic.id}/user",+ )+ end+ end+it "renders the relationship under its own name" doexpect(resource_object.to_h[:relationships].keys).to eq(["user"])enddiff --git a/spec/lib/json_api_kit/glossary/relationship_names_spec.rb b/spec/lib/json_api_kit/glossary/relationship_names_spec.rbnew file mode 100644index 00000000000..31bfb9674a0--- /dev/null+++ b/spec/lib/json_api_kit/glossary/relationship_names_spec.rb@@ -0,0 +1,99 @@+# frozen_string_literal: true++RSpec.describe JsonApiKit::Glossary do+ subject(:glossary) { described_class.resource(JsonApiKit::Timeline::FIRST_RELEASE) }++ let(:type) { "discussion_threads" }+ let(:earlier_change) do+ Class+ .new(JsonApiKit::VersionChange) do+ resource :articles do+ renamed_relationship from: :original_author, to: :author+ end+ end+ .new(__FILE__)+ end+ let(:type_change) do+ Class+ .new(JsonApiKit::VersionChange) { renamed_type from: :articles, to: :discussion_threads }+ .new(__FILE__)+ end+ let(:later_change) do+ Class+ .new(JsonApiKit::VersionChange) do+ resource :discussion_threads do+ renamed_relationship from: :author, to: :writer+ end+ end+ .new(__FILE__)+ end++ before do+ allow(JsonApiKit::VersionChanges.core).to receive(:after).and_return(+ [earlier_change, type_change, later_change],+ )+ end++ describe "#declared_relationship" do+ subject(:declared_name) { glossary.declared_relationship(member:, type:) }++ let(:member) { "originalAuthor" }++ it "uses the historical type to translate the relationship" do+ expect(declared_name).to eq("writer")+ end++ context "when the client supplies a newer name" do+ let(:member) { "writer" }++ it "suggests the name from the client's version" do+ expect { declared_name }.to raise_error(+ described_class::NotAMemberName,+ "Use originalAuthor, not writer.",+ )+ end+ end++ context "when the glossary has no version changes" do+ let(:glossary) { described_class.kit }++ it "converts the member name into declared casing" do+ expect(declared_name).to eq("original_author")+ end+ end+ end++ describe "#member_relationship" do+ subject(:member_name) { glossary.member_relationship(declared: "writer", type:) }++ it "translates the relationship across field and type changes" do+ expect(member_name).to eq("originalAuthor")+ end++ context "when the relationship belongs to another type" do+ let(:type) { "users" }++ it "preserves the unrelated name" do+ expect(member_name).to eq("writer")+ end+ end+ end++ describe "#unscoped_member" do+ subject(:member_name) { glossary.unscoped_member(declared:) }++ let(:declared) { "writer" }++ it "preserves the name without applying resource renames" do+ expect(member_name).to eq("writer")+ end++ context "when the name has several words" do+ let(:declared) { "original_author" }++ it "converts the name to camel case" do+ expect(member_name).to eq("originalAuthor")+ end+ end+ end+enddiff --git a/spec/lib/json_api_kit/record_url_spec.rb b/spec/lib/json_api_kit/record_url_spec.rbindex 0f802a700b4..04062266c28 100644--- a/spec/lib/json_api_kit/record_url_spec.rb+++ b/spec/lib/json_api_kit/record_url_spec.rb@@ -20,14 +20,34 @@ RSpec.describe JsonApiKit::RecordUrl doenddescribe "#relationship" do- subject(:address) { url.relationship("posts").to_s }+ subject(:address) { url.relationship(name).to_s }++ let(:name) { "posts" }it { is_expected.to eq("https://example.com/api/topics/5/relationships/posts") }++ context "when the declared name has several words" do+ let(:name) { "valid_groups" }++ it "uses a kebab-case path segment" do+ expect(address).to eq("https://example.com/api/topics/5/relationships/valid-groups")+ end+ endenddescribe "#related" do- subject(:address) { url.related("posts").to_s }+ subject(:address) { url.related(name).to_s }++ let(:name) { "posts" }it { is_expected.to eq("https://example.com/api/topics/5/posts") }++ context "when the declared name has several words" do+ let(:name) { "valid_groups" }++ it "uses a kebab-case path segment" do+ expect(address).to eq("https://example.com/api/topics/5/valid-groups")+ end+ endendenddiff --git a/spec/lib/json_api_kit/relationship_paths/unscoped_position_spec.rb b/spec/lib/json_api_kit/relationship_paths/unscoped_position_spec.rbnew file mode 100644index 00000000000..19c6ccbf97e--- /dev/null+++ b/spec/lib/json_api_kit/relationship_paths/unscoped_position_spec.rb@@ -0,0 +1,30 @@+# frozen_string_literal: true++RSpec.describe JsonApiKit::RelationshipPaths::UnscopedPosition do+ subject(:position) { described_class.new(glossary:) }++ let(:glossary) { JsonApiKit::Glossary.resource(JsonApiKit::Timeline::FIRST_RELEASE) }+ let(:version_change) do+ Class+ .new(JsonApiKit::VersionChange) do+ resource :users do+ renamed_relationship from: :groups, to: :valid_groups+ end+ end+ .new(__FILE__)+ end++ before { allow(JsonApiKit::VersionChanges.core).to receive(:after).and_return([version_change]) }++ describe "#advance_to_member" do+ subject(:step) { position.advance_to_member(declared: "valid_groups") }++ it "applies casing without a resource rename" do+ expect(step.name).to eq("validGroups")+ end++ it "keeps the following position unscoped" do+ expect(step.next_position).to eq(position)+ end+ end+enddiff --git a/spec/lib/json_api_kit/relationship_paths_spec.rb b/spec/lib/json_api_kit/relationship_paths_spec.rbnew file mode 100644index 00000000000..6ceed94fb57--- /dev/null+++ b/spec/lib/json_api_kit/relationship_paths_spec.rb@@ -0,0 +1,279 @@+# frozen_string_literal: true++module JsonApiKitSpec+ class PathGroupsResource < JsonApiKit::Resource+ type :groups+ end++ class PathUsersResource < JsonApiKit::Resource+ type :users+ has_many :valid_groups, resource: PathGroupsResource+ end++ class PathTopicsResource < JsonApiKit::Resource+ type :topics+ has_one :writer, resource: PathUsersResource+ end++ PathGroupsResource.has_many(:members, resource: PathUsersResource)+end++RSpec.describe JsonApiKit::RelationshipPaths::Position do+ subject(:position) do+ described_class.new(resource: JsonApiKitSpec::PathTopicsResource, glossary:)+ end++ let(:glossary) { JsonApiKit::Glossary.resource(JsonApiKit::Timeline::FIRST_RELEASE) }+ let(:version_change) do+ Class+ .new(JsonApiKit::VersionChange) do+ resource :topics do+ renamed_relationship from: :author, to: :writer+ end+ resource :users do+ renamed_relationship from: :groups, to: :valid_groups+ end+ end+ .new(__FILE__)+ end++ before { allow(JsonApiKit::VersionChanges.core).to receive(:after).and_return([version_change]) }++ describe "#advance_to_declared" do+ subject(:step) { position.advance_to_declared(member:) }++ let(:member) { "author" }++ it "returns the declared name at the current resource" do+ expect(step.name).to eq("writer")+ end++ it "returns a new position at the target resource" do+ expect(step.next_position).to eq(+ described_class.new(resource: JsonApiKitSpec::PathUsersResource, glossary:),+ )+ end++ it "preserves the starting resource" do+ step+ expect(position.resource).to eq(JsonApiKitSpec::PathTopicsResource)+ end++ context "when the position follows the first relationship" do+ let(:member) { "groups" }+ let(:position) { super().advance_to_declared(member: "author").next_position }++ it "translates the next name in the target resource" do+ expect(step.name).to eq("valid_groups")+ end+ end+ end++ describe "#advance_to_member" do+ subject(:step) { position.advance_to_member(declared:) }++ let(:declared) { "writer" }++ it "translates the name using the owning resource" do+ expect(step.name).to eq("author")+ end++ it "returns a new position at the target resource" do+ expect(step.next_position).to eq(+ described_class.new(resource: JsonApiKitSpec::PathUsersResource, glossary:),+ )+ end++ it "preserves the starting resource" do+ step+ expect(position.resource).to eq(JsonApiKitSpec::PathTopicsResource)+ end++ context "when the position follows the first relationship" do+ let(:declared) { "valid_groups" }+ let(:position) { super().advance_to_member(declared: "writer").next_position }++ it "translates the next name in the target resource" do+ expect(step.name).to eq("groups")+ end+ end++ context "when the relationship cannot be resolved" do+ let(:declared) { "missing_groups" }++ it "formats the unresolved name as a member" do+ expect(step.name).to eq("missingGroups")+ end++ it "continues from an unscoped position" do+ expect(step.next_position).to eq(+ JsonApiKit::RelationshipPaths::UnscopedPosition.new(glossary:),+ )+ end+ end+ end+end++RSpec.describe JsonApiKit::RelationshipPaths do+ subject(:paths) { described_class.new(resource: JsonApiKitSpec::PathTopicsResource, glossary:) }++ let(:glossary) { JsonApiKit::Glossary.resource(JsonApiKit::Timeline::FIRST_RELEASE) }+ let(:version_change) do+ Class+ .new(JsonApiKit::VersionChange) do+ renamed_type from: :articles, to: :topics+ renamed_type from: :people, to: :users+ resource :topics do+ renamed_relationship from: :author, to: :writer+ end+ resource :users do+ renamed_relationship from: :groups, to: :valid_groups+ end+ end+ .new(__FILE__)+ end++ before { allow(JsonApiKit::VersionChanges.core).to receive(:after).and_return([version_change]) }++ describe "#declared_path" do+ subject(:declared_path) { paths.declared_path(path) }++ let(:path) { "author.groups" }++ it "translates each segment in its owning resource" do+ expect(declared_path).to eq("writer.valid_groups")+ end++ context "when the path is empty" do+ let(:path) { "" }++ it "returns an empty path" do+ expect(declared_path).to eq("")+ end+ end++ context "when the path returns to an earlier resource" do+ let(:path) { "author.groups.members.groups" }++ it "uses that resource's vocabulary again" do+ expect(declared_path).to eq("writer.valid_groups.members.valid_groups")+ end+ end++ context "when a cyclic path has many segments" do+ let(:path) { "author.#{Array.new(1500, "groups.members").join(".")}" }+ let(:expected_path) { "writer.#{Array.new(1500, "valid_groups.members").join(".")}" }++ it "translates the complete path without exhausting the stack" do+ expect(declared_path).to eq(expected_path)+ end+ end++ context "when the first segment does not exist" do+ let(:path) { "unknownAuthor.groups" }++ it "reports the original path" do+ expect { declared_path }.to raise_error(+ described_class::UnknownPath,+ /unknownAuthor.groups/,+ )+ end+ end++ context "when a later segment does not exist" do+ let(:path) { "author.unknownGroups.members" }++ it "preserves the client spelling of every segment" do+ expect { declared_path }.to raise_error(+ described_class::UnknownPath,+ "There is no relationship path named author.unknownGroups.members.",+ )+ end+ end++ context "when a segment belongs to another version" do+ let(:path) { "author.validGroups" }++ it "suggests the historical name of that segment" do+ expect { declared_path }.to raise_error(+ JsonApiKit::Glossary::NotAMemberName,+ "Use groups, not validGroups.",+ )+ end+ end++ context "when the path contains an empty segment" do+ let(:path) { "author..groups" }++ it "rejects the path" do+ expect { declared_path }.to raise_error(described_class::UnknownPath)+ end+ end++ context "when the path ends with a separator" do+ let(:path) { "author." }++ it "rejects the path" do+ expect { declared_path }.to raise_error(described_class::UnknownPath)+ end+ end+ end++ describe "#member_path" do+ subject(:member_path) { paths.member_path(path) }++ let(:path) { "writer.valid_groups" }++ it "translates the current path into the client's vocabulary" do+ expect(member_path).to eq("author.groups")+ end++ context "when the path is empty" do+ let(:path) { "" }++ it "returns an empty path" do+ expect(member_path).to eq("")+ end+ end++ context "when a cyclic path has many segments" do+ let(:path) { "writer.#{Array.new(1500, "valid_groups.members").join(".")}" }+ let(:expected_path) { "author.#{Array.new(1500, "groups.members").join(".")}" }++ it "translates the complete path without exhausting the stack" do+ expect(member_path).to eq(expected_path)+ end+ end++ context "when a segment cannot be resolved" do+ let(:path) { "writer.missing_groups.last_member" }++ before { allow(glossary).to receive(:unscoped_member).and_call_original }++ it "translates the known prefix and formats the unknown suffix" do+ expect(member_path).to eq("author.missingGroups.lastMember")+ end++ it "formats the last segment through the request glossary" do+ member_path+ expect(glossary).to have_received(:unscoped_member).with(declared: "last_member")+ end++ context "when a later segment matches a renamed relationship" do+ let(:path) { "writer.missing_groups.valid_groups" }++ it "formats the suffix without applying resource-specific renames" do+ expect(member_path).to eq("author.missingGroups.validGroups")+ end+ end+ end++ context "when the glossary has no version changes" do+ let(:glossary) { JsonApiKit::Glossary.kit }++ it "converts current names to camel case" do+ expect(member_path).to eq("writer.validGroups")+ end+ end+ end+enddiff --git a/spec/lib/json_api_kit/request/parameters_spec.rb b/spec/lib/json_api_kit/request/parameters_spec.rbindex 77900749d22..72d3d8f0c70 100644--- a/spec/lib/json_api_kit/request/parameters_spec.rb+++ b/spec/lib/json_api_kit/request/parameters_spec.rb@@ -1,8 +1,18 @@# frozen_string_literal: truemodule JsonApiKitSpec+ class ParametersAuthorResource < JsonApiKit::Resource+ type :users+ end++ class ParametersPostResource < JsonApiKit::Resource+ type :posts+ has_one :last_poster, resource: ParametersAuthorResource+ end+class ParametersResource < JsonApiKit::Resourcetype :topics+ has_many :ordered_posts, resource: ParametersPostResourceendclass ParametersChange < JsonApiKit::VersionChange@@ -94,6 +104,39 @@ RSpec.describe JsonApiKit::Request::Parameters doit "converts every segment of the path" doexpect(declared_parameters).to eq("include" => "ordered_posts.last_poster")end++ context "when both relationships have historical names" do+ let(:parameters) { { "include" => "olderPosts.author,olderPosts" } }+ let(:glossary) { JsonApiKit::Glossary.resource(JsonApiKit::Timeline::FIRST_RELEASE) }+ let(:version_change) do+ Class+ .new(JsonApiKit::VersionChange) do+ resource :topics do+ renamed_relationship from: :older_posts, to: :ordered_posts+ end+ resource :posts do+ renamed_relationship from: :author, to: :last_poster+ end+ end+ .new(__FILE__)+ end++ before do+ allow(JsonApiKit::VersionChanges.core).to receive(:after).and_return([version_change])+ end++ it "translates every path against the resource declarations" do+ expect(declared_parameters).to eq("include" => "ordered_posts.last_poster,ordered_posts")+ end++ context "when the paths are an array" do+ let(:parameters) { { "include" => ["olderPosts.author"] } }++ it "preserves the array while translating its paths" do+ expect(declared_parameters).to eq("include" => ["ordered_posts.last_poster"])+ end+ end+ endendcontext "when the parameters have a fieldset" dodiff --git a/spec/lib/json_api_kit/version_change/relationship_renames_spec.rb b/spec/lib/json_api_kit/version_change/relationship_renames_spec.rbnew file mode 100644index 00000000000..1e0d48fd3fb--- /dev/null+++ b/spec/lib/json_api_kit/version_change/relationship_renames_spec.rb@@ -0,0 +1,73 @@+# frozen_string_literal: true++RSpec.describe JsonApiKit::VersionChange do+ describe ".resource" do+ subject(:transformations) { change_class.transformations }++ let(:change_class) { Class.new(described_class).tap { it.resource(:topics, &declarations) } }+ let(:declarations) { proc { renamed_relationship from: :author, to: :writer } }+ let(:previous_names) { transformations.flat_map(&:previous_names) }++ it "registers the relationship and its fieldset name" do+ expect(previous_names).to contain_exactly(+ JsonApiKit::Name::Relationship.new(value: "author", type: "topics"),+ JsonApiKit::Name::Field.new(value: "author", type: "topics"),+ )+ end++ context "when the declaration supplies an up converter" do+ let(:declarations) do+ proc { renamed_relationship from: :author, to: :writer, up: ->(value) { value } }+ end++ it "rejects the converter" do+ expect { transformations }.to raise_error(ArgumentError, "unknown keyword: :up")+ end+ end++ context "when the declaration supplies a down converter" do+ let(:declarations) do+ proc { renamed_relationship from: :author, to: :writer, down: ->(value) { value } }+ end++ it "rejects the converter" do+ expect { transformations }.to raise_error(ArgumentError, "unknown keyword: :down")+ end+ end+ end++ describe "#verify!" do+ subject(:verify) { version_change.verify! }++ let(:version_change) { change_class.new("2026-09-01_rename_relationships.rb") }+ let(:change_class) do+ Class.new(described_class) do+ version "2026-09-01"+ description "The author relationship becomes writer."+ resource :topics do+ renamed_relationship from: :author, to: :writer+ end+ end+ end++ before { freeze_time(Date.new(2026, 9, 3)) }++ context "when an attribute uses the same source name" do+ before do+ change_class.resource(:topics) { renamed_attribute from: :author, to: :display_name }+ end++ it "rejects the ambiguous fieldset name" do+ expect { verify }.to raise_error(ArgumentError, /changes author twice/)+ end+ end++ context "when an attribute uses the same target name" do+ before { change_class.resource(:topics) { renamed_attribute from: :title, to: :writer } }++ it "rejects the conflicting fieldset target" do+ expect { verify }.to raise_error(ArgumentError, /changes two names into writer/)+ end+ end+ end+end