Skip to content

Commit

Permalink
Merge pull request #2 from bf4/dynamic-jsonapi-string-links
Browse files Browse the repository at this point in the history
Use return value of link block if any
  • Loading branch information
beauby committed Dec 31, 2015
2 parents 4ce77c5 + 013d71a commit 88e5e50
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 18 deletions.
10 changes: 1 addition & 9 deletions lib/active_model/serializer/adapter/json_api.rb
Original file line number Diff line number Diff line change
Expand Up @@ -209,15 +209,7 @@ def add_included_resources_for(serializer, include_tree, primary_data, included)

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(value)
end
end

Expand Down
27 changes: 19 additions & 8 deletions lib/active_model/serializer/adapter/json_api/link.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,29 +10,40 @@ def initialize(serializer)

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

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

def string(value)
self._string = value
def value(value)
if value.respond_to?(:call)
string instance_eval(&value)
_string || to_hash
else
value
end
end

def to_hash
return _string unless _string.nil?
protected

attr_accessor :_href, :_meta, :_string
attr_reader :object, :scope

private

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

hash
end

protected

attr_accessor :_href, :_meta, :_string
attr_reader :object, :scope
def string(value)
self._string = value
end
end
end
end
Expand Down
2 changes: 1 addition & 1 deletion test/adapter/json_api/links_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class LinkAuthorSerializer < ActiveModel::Serializer
link :other, '//example.com/resource'

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

Expand Down

0 comments on commit 88e5e50

Please sign in to comment.