Skip to content

Commit 83e99b2

Browse files
jopottskpheasey
authored andcommitted
Allow relationship links to be declared as object method (Netflix#2)
* Allow relationship links to be declared as object method * Relationship links note added to readme
1 parent f04abfd commit 83e99b2

File tree

3 files changed

+35
-2
lines changed

3 files changed

+35
-2
lines changed

README.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -278,6 +278,12 @@ class MovieSerializer
278278
end
279279
```
280280

281+
Relationship links can also be configured to be defined as a method on the object.
282+
283+
```ruby
284+
has_many :actors, links: :actor_relationship_links
285+
```
286+
281287
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:
282288

283289
```ruby

lib/fast_jsonapi/relationship.rb

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -104,8 +104,12 @@ def fetch_id(record, params)
104104
end
105105

106106
def add_links_hash(record, params, output_hash)
107-
output_hash[key][:links] = links.each_with_object({}) do |(key, method), hash|
108-
Link.new(key: key, method: method).serialize(record, params, hash)\
107+
if links.is_a?(Symbol)
108+
output_hash[key][:links] = record.public_send(links)
109+
else
110+
output_hash[key][:links] = links.each_with_object({}) do |(key, method), hash|
111+
Link.new(key: key, method: method).serialize(record, params, hash)\
112+
end
109113
end
110114
end
111115

spec/lib/object_serializer_relationship_links_spec.rb

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,5 +67,28 @@ class LazyLoadingMovieSerializer < MovieSerializer
6767
expect(actor_hash).not_to have_key(:data)
6868
end
6969
end
70+
71+
context "relationship links defined by a method on the object" do
72+
before(:context) do
73+
class Movie
74+
def relationship_links
75+
{ self: "http://movies.com/#{id}/relationships/actors" }
76+
end
77+
end
78+
79+
class LinksPassingMovieSerializer < MovieSerializer
80+
has_many :actors, links: :relationship_links
81+
end
82+
end
83+
84+
let(:serializer) { LinksPassingMovieSerializer.new(movie) }
85+
let(:links) { hash[:data][:relationships][:actors][:links] }
86+
let(:relationship_url) { "http://movies.com/#{movie.id}/relationships/actors" }
87+
88+
it "generates relationship links in the object" do
89+
expect(links).to be_present
90+
expect(links[:self]).to eq(relationship_url)
91+
end
92+
end
7093
end
7194
end

0 commit comments

Comments
 (0)