Skip to content

Commit

Permalink
Allow relationship links to be declared as object method (#2)
Browse files Browse the repository at this point in the history
* Allow relationship links to be declared as object method

* Relationship links note added to readme
  • Loading branch information
jopotts authored and kpheasey committed Oct 4, 2019
1 parent f04abfd commit 83e99b2
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 2 deletions.
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 6 additions & 2 deletions lib/fast_jsonapi/relationship.rb
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,12 @@ def fetch_id(record, params)
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

Expand Down
23 changes: 23 additions & 0 deletions spec/lib/object_serializer_relationship_links_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -67,5 +67,28 @@ class LazyLoadingMovieSerializer < MovieSerializer
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

0 comments on commit 83e99b2

Please sign in to comment.