From 4f87c49c7dfaab16d8a8f74e51e5cc39f7a19c81 Mon Sep 17 00:00:00 2001 From: baash05 Date: Sun, 29 Apr 2018 01:27:23 +1000 Subject: [PATCH] [add lazy meta] Add the ability to run the meta in a lazy load this will let the user check if the meta should even be loaded --- lib/jsonapi/serializable/relationship.rb | 12 +++++++++++- lib/jsonapi/serializable/relationship/dsl.rb | 6 ++++-- spec/renderer/relationship_spec.rb | 14 ++++++++++++++ 3 files changed, 29 insertions(+), 3 deletions(-) diff --git a/lib/jsonapi/serializable/relationship.rb b/lib/jsonapi/serializable/relationship.rb index a5d9395..cb2ed28 100644 --- a/lib/jsonapi/serializable/relationship.rb +++ b/lib/jsonapi/serializable/relationship.rb @@ -15,14 +15,19 @@ def initialize(exposures = {}, options = {}, &block) end def as_jsonapi(included) + @_included = included {}.tap do |hash| hash[:links] = @_links if @_links.any? hash[:data] = linkage_data if included || @_include_linkage - hash[:meta] = @_meta unless @_meta.nil? + hash[:meta] = meta_data unless (@_meta_value.nil? && @_meta_block.nil?) hash[:meta] = { included: false } if hash.empty? end end + def included? + @_included + end + # @api private def related_resources @_related_resources ||= Array(resources) @@ -45,6 +50,11 @@ def linkage_data resources.respond_to?(:each) ? linkage_data : linkage_data.first end + + # @api private + def meta_data + @_meta_value || @_meta_block&.call + end end end end diff --git a/lib/jsonapi/serializable/relationship/dsl.rb b/lib/jsonapi/serializable/relationship/dsl.rb index 9332c55..67945c5 100644 --- a/lib/jsonapi/serializable/relationship/dsl.rb +++ b/lib/jsonapi/serializable/relationship/dsl.rb @@ -52,8 +52,10 @@ def linkage(always: false, &block) # meta do # { paginated: true } # end - def meta(value = nil) - @_meta = value || yield + def meta(value = nil, &block) + @_meta_value = value + # NOTE: Lazify computation since it might make decisions based on included? or eager loading + @_meta_block = block unless value end # Declare a link for this relationship. The properties of the link are set diff --git a/spec/renderer/relationship_spec.rb b/spec/renderer/relationship_spec.rb index 9e8a0bb..9ecf5cc 100644 --- a/spec/renderer/relationship_spec.rb +++ b/spec/renderer/relationship_spec.rb @@ -32,4 +32,18 @@ expect(hash).to eq(expected) end + + it 'can interigate included? in the meta block' do + klass = Class.new(JSONAPI::Serializable::Resource) do + type 'users' + + has_many(:posts) do + meta do + included? + end + end + end + expect_any_instance_of(JSONAPI::Serializable::Relationship).to receive(:included?) + subject.render(user, class: { User: klass, Post: SerializablePost }) + end end