From 83e99b2923081b343ca80fe32506c0f60ed320f3 Mon Sep 17 00:00:00 2001 From: Jo Potts Date: Fri, 4 Oct 2019 17:39:34 +0100 Subject: [PATCH] Allow relationship links to be declared as object method (#2) * Allow relationship links to be declared as object method * Relationship links note added to readme --- README.md | 6 +++++ lib/fast_jsonapi/relationship.rb | 8 +++++-- ...ject_serializer_relationship_links_spec.rb | 23 +++++++++++++++++++ 3 files changed, 35 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 461cf2b..b18d055 100644 --- a/README.md +++ b/README.md @@ -278,6 +278,12 @@ class MovieSerializer end ``` +Relationship links can also be configured to be defined as a method on the object. + +```ruby + has_many :actors, links: :actor_relationship_links +``` + This will create a `self` reference for the relationship, and a `related` link for loading the actors relationship later. NB: This will not automatically disable loading the data in the relationship, you'll need to do that using the `lazy_load_data` option: ```ruby diff --git a/lib/fast_jsonapi/relationship.rb b/lib/fast_jsonapi/relationship.rb index 7a038de..f8a9bfd 100644 --- a/lib/fast_jsonapi/relationship.rb +++ b/lib/fast_jsonapi/relationship.rb @@ -104,8 +104,12 @@ module FastJsonapi end def add_links_hash(record, params, output_hash) - output_hash[key][:links] = links.each_with_object({}) do |(key, method), hash| - Link.new(key: key, method: method).serialize(record, params, hash)\ + if links.is_a?(Symbol) + output_hash[key][:links] = record.public_send(links) + else + output_hash[key][:links] = links.each_with_object({}) do |(key, method), hash| + Link.new(key: key, method: method).serialize(record, params, hash)\ + end end end diff --git a/spec/lib/object_serializer_relationship_links_spec.rb b/spec/lib/object_serializer_relationship_links_spec.rb index 8c2f272..e0d4848 100644 --- a/spec/lib/object_serializer_relationship_links_spec.rb +++ b/spec/lib/object_serializer_relationship_links_spec.rb @@ -67,5 +67,28 @@ describe FastJsonapi::ObjectSerializer do expect(actor_hash).not_to have_key(:data) end end + + context "relationship links defined by a method on the object" do + before(:context) do + class Movie + def relationship_links + { self: "http://movies.com/#{id}/relationships/actors" } + end + end + + class LinksPassingMovieSerializer < MovieSerializer + has_many :actors, links: :relationship_links + end + end + + let(:serializer) { LinksPassingMovieSerializer.new(movie) } + let(:links) { hash[:data][:relationships][:actors][:links] } + let(:relationship_url) { "http://movies.com/#{movie.id}/relationships/actors" } + + it "generates relationship links in the object" do + expect(links).to be_present + expect(links[:self]).to eq(relationship_url) + end + end end end