Add support for dynamic string-links in JsonApi adapter.

This commit is contained in:
Lucas Hosseini 2015-12-29 20:02:32 +01:00
parent 316026e9ce
commit 30d8414cce
4 changed files with 25 additions and 17 deletions

View File

@ -16,6 +16,7 @@ Breaking changes:
Features:
- [#1406](https://github.com/rails-api/active_model_serializers/pull/1406) Allow for custom dynamic values in JSON API links (@beauby)
- [#1270](https://github.com/rails-api/active_model_serializers/pull/1270) Adds `assert_response_schema` test helper (@maurogeorge)
- [#1099](https://github.com/rails-api/active_model_serializers/pull/1099) Adds `assert_serializer` test helper (@maurogeorge)
- [#1403](https://github.com/rails-api/active_model_serializers/pull/1403) Add support for if/unless on attributes/associations (@beauby)

View File

@ -210,15 +210,7 @@ module ActiveModel
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
hash[name] = Link.new(serializer, value).as_json
end
end

View File

@ -3,29 +3,39 @@ module ActiveModel
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

View File

@ -13,6 +13,10 @@ module ActiveModel
end
link :other, '//example.com/resource'
link :yet_another do
"//example.com/resource/#{object.id}"
end
end
def setup
@ -52,7 +56,8 @@ module ActiveModel
stuff: 'value'
}
},
other: '//example.com/resource'
other: '//example.com/resource',
yet_another: '//example.com/resource/1337'
}
assert_equal(expected, hash[:data][:links])
end