create link class
This commit is contained in:
parent
f86a8926f5
commit
699630d812
29
lib/fast_jsonapi/link.rb
Normal file
29
lib/fast_jsonapi/link.rb
Normal file
@ -0,0 +1,29 @@
|
||||
module FastJsonapi
|
||||
class Link
|
||||
attr_reader :key, :method, :conditional_proc
|
||||
|
||||
def initialize(key:, method:, options: {})
|
||||
@key = key
|
||||
@method = method
|
||||
@conditional_proc = options[:if]
|
||||
end
|
||||
|
||||
def serialize(record, serialization_params, output_hash)
|
||||
if include_link?(record, serialization_params)
|
||||
output_hash[key] = if method.is_a?(Proc)
|
||||
method.arity == 1 ? method.call(record) : method.call(record, serialization_params)
|
||||
else
|
||||
record.public_send(method)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def include_link?(record, serialization_params)
|
||||
if conditional_proc.present?
|
||||
conditional_proc.call(record, serialization_params)
|
||||
else
|
||||
true
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
@ -5,6 +5,7 @@ require 'active_support/concern'
|
||||
require 'active_support/inflector'
|
||||
require 'fast_jsonapi/attribute'
|
||||
require 'fast_jsonapi/relationship'
|
||||
require 'fast_jsonapi/link'
|
||||
require 'fast_jsonapi/serialization_core'
|
||||
|
||||
module FastJsonapi
|
||||
@ -238,11 +239,16 @@ module FastJsonapi
|
||||
{}
|
||||
end
|
||||
|
||||
def link(link_name, link_method_name = nil, &block)
|
||||
def link(link_name, link_method_name = nil, options = {}, &block)
|
||||
self.data_links = {} if self.data_links.nil?
|
||||
link_method_name = link_name if link_method_name.nil?
|
||||
key = run_key_transform(link_name)
|
||||
self.data_links[key] = block || link_method_name
|
||||
|
||||
self.data_links[key] = Link.new(
|
||||
key: key,
|
||||
method: block || link_method_name,
|
||||
options: options
|
||||
)
|
||||
end
|
||||
|
||||
def validate_includes!(includes)
|
||||
|
@ -35,18 +35,14 @@ module FastJsonapi
|
||||
end
|
||||
|
||||
def links_hash(record, params = {})
|
||||
data_links.each_with_object({}) do |(key, method), link_hash|
|
||||
link_hash[key] = if method.is_a?(Proc)
|
||||
method.arity == 1 ? method.call(record) : method.call(record, params)
|
||||
else
|
||||
record.public_send(method)
|
||||
end
|
||||
data_links.each_with_object({}) do |(_k, link), hash|
|
||||
link.serialize(record, params, hash)
|
||||
end
|
||||
end
|
||||
|
||||
def attributes_hash(record, params = {})
|
||||
attributes_to_serialize.each_with_object({}) do |(key, attribute), attr_hash|
|
||||
attribute.serialize(record, params, attr_hash)
|
||||
attributes_to_serialize.each_with_object({}) do |(_k, attribute), hash|
|
||||
attribute.serialize(record, params, hash)
|
||||
end
|
||||
end
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user