mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-22 22:06:50 +00:00
Merge pull request #1406 from beauby/dynamic-jsonapi-string-links
Add support for custom dynamic valued links in JsonApi adapter.
This commit is contained in:
commit
b9f4720cbd
@ -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)
|
||||
|
||||
@ -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
|
||||
|
||||
|
||||
@ -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
|
||||
|
||||
@ -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
|
||||
|
||||
Loading…
Reference in New Issue
Block a user