Skip to content

Commit

Permalink
Add support for dynamic string-links in JsonApi adapter.
Browse files Browse the repository at this point in the history
  • Loading branch information
beauby committed Jan 15, 2016
1 parent 316026e commit cb35d6d
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 18 deletions.
12 changes: 2 additions & 10 deletions lib/active_model/serializer/adapter/json_api.rb
Original file line number Diff line number Diff line change
Expand Up @@ -209,16 +209,8 @@ def add_included_resources_for(serializer, include_tree, primary_data, included)
end

def links_for(serializer)
serializer._links.each_with_object({}) do |(name, value), hash|
hash[name] =
if value.respond_to?(:call)
link = Link.new(serializer)
link.instance_eval(&value)

link.to_hash
else
value
end
serializer.links.each_with_object({}) do |(name, value), hash|
hash[name] = Link.new(serializer, value).as_json
end
end

Expand Down
24 changes: 17 additions & 7 deletions lib/active_model/serializer/adapter/json_api/link.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,29 +3,39 @@ class Serializer
module Adapter
class JsonApi
class Link
def initialize(serializer)
def initialize(serializer, value)
@object = serializer.object
@scope = serializer.scope

# Use the return value of the block unless it is nil.
if value.respond_to?(:call)
@value = instance_eval(&value)
else
@value = value
end
end

def href(value)
self._href = value
@href = value
nil
end

def meta(value)
self._meta = value
@meta = value
nil
end

def to_hash
hash = { href: _href }
hash.merge!(meta: _meta) if _meta
def as_json
return @value if @value

hash = { href: @href }
hash.merge!(meta: @meta) if @meta

hash
end

protected

attr_accessor :_href, :_meta
attr_reader :object, :scope
end
end
Expand Down
7 changes: 6 additions & 1 deletion test/adapter/json_api/links_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ class LinkAuthorSerializer < ActiveModel::Serializer
end

link :other, '//example.com/resource'

link :yet_another do
"//example.com/resource/#{object.id}"
end
end

def setup
Expand Down Expand Up @@ -52,7 +56,8 @@ def test_resource_links
stuff: 'value'
}
},
other: '//example.com/resource'
other: '//example.com/resource',
yet_another: '//example.com/resource/1337'
}
assert_equal(expected, hash[:data][:links])
end
Expand Down

0 comments on commit cb35d6d

Please sign in to comment.