diff --git a/lib/userializer.rb b/lib/userializer.rb index 99c9470..501ca64 100644 --- a/lib/userializer.rb +++ b/lib/userializer.rb @@ -7,6 +7,9 @@ module USerializer NS_SEPARATOR = '::'.freeze + @root_keys = {} + @singular_root_keys = {} + class << self def serializer_for(obj) return nil if obj.nil? @@ -17,9 +20,27 @@ def serializer_for(obj) def infered_serializer_class(kls) return nil if kls.nil? - (kls.name + 'Serializer').split(NS_SEPARATOR).inject(Object) do |o, c| - o.const_get(c) - end + name = "#{kls.name}Serializer" + + return Object.const_get(name) if Object.const_defined?(name) + + name.split(NS_SEPARATOR).inject(Object) { |o, c| o.const_get(c) } + end + + def infered_singular_root_key(kls) + name = kls.name + + @singular_root_keys[name] ||= ActiveSupport::Inflector.underscore( + name + ).split('/').last.to_sym + end + + def infered_root_key(kls) + name = kls.name + + @root_keys[name] ||= ActiveSupport::Inflector.pluralize( + ActiveSupport::Inflector.underscore(name).split('/').last + ).to_sym end end end diff --git a/lib/userializer/array_serializer.rb b/lib/userializer/array_serializer.rb index d192e30..e40c049 100644 --- a/lib/userializer/array_serializer.rb +++ b/lib/userializer/array_serializer.rb @@ -1,24 +1,22 @@ require 'oj' +require 'userializer/payload' module USerializer class HeterogeneousArray < StandardError; end class ArraySerializer - def initialize(objs, opts = {}, embed_empty_array: false) + def initialize(objs, opts = {}) @objs = objs.compact @opts = opts @meta = opts[:meta] - @embed_empty_array = embed_empty_array + @embed_empty_array = opts[:embed_empty_array] || false - clss = @objs.map(&:class).uniq - obj_class = clss.first + obj_class = @objs.first&.class - raise HeterogeneousArray if clss.count > 1 + raise HeterogeneousArray if @objs.any? { |o| !o.instance_of?(obj_class) } @root_key = opts[:root]&.to_sym - @root_key ||= ActiveSupport::Inflector.pluralize( - ActiveSupport::Inflector.underscore(obj_class.name).split('/').last - ).to_sym if obj_class + @root_key ||= USerializer.infered_root_key(obj_class) if obj_class serializer = opts[:each_serializer] @@ -37,14 +35,14 @@ def merge_root(res, opts) end def to_hash - res = {} + res = Payload.new res[@root_key] = [] if @root_key merge_root(res, @opts) res[:meta] = @meta if @meta - res + res.to_h end def to_json @@ -59,7 +57,13 @@ def serializer(obj, opts) return @serializer.call(obj, opts).new(obj, @opts) if @serializer return obj.serialize if obj.respond_to?(:serialize) - USerializer.infered_serializer_class(obj.class).new(obj, @opts) + infered_serializer.new(obj, @opts) + end + + def infered_serializer + @infered_serializer ||= USerializer.infered_serializer_class( + @objs.first.class + ) end end end diff --git a/lib/userializer/attribute.rb b/lib/userializer/attribute.rb index 33df0f7..55575dd 100644 --- a/lib/userializer/attribute.rb +++ b/lib/userializer/attribute.rb @@ -8,17 +8,23 @@ def initialize(key, opts, block) @block = block @skip_nil = opts[:skip_nil] || false - @conditional_block = opts[:if] || proc { true } + @conditional_block = opts[:if] end def merge_attributes(res, ser, opts) - return unless @conditional_block.call(ser.object, opts) + return unless allow?(ser, opts) - value = @block ? @block.call(ser.object, opts) : ser.send(@key) + value = @block ? @block.call(ser.object, opts) : ser.read_attribute(@key) return if value.nil? && @skip_nil res[@key] = value end + + private + + def allow?(ser, opts) + @conditional_block.nil? || @conditional_block.call(ser.object, opts) + end end end diff --git a/lib/userializer/base_serializer.rb b/lib/userializer/base_serializer.rb index 95149f3..41e0380 100644 --- a/lib/userializer/base_serializer.rb +++ b/lib/userializer/base_serializer.rb @@ -1,8 +1,10 @@ +require 'set' require 'oj' require 'active_support/inflector/methods' require 'userializer/has_one' require 'userializer/has_many' require 'userializer/attribute' +require 'userializer/payload' module USerializer class BaseSerializer @@ -10,6 +12,26 @@ class << self def inherited(subclass) subclass.attrs = self.attrs.dup || { id: Attribute.new(:id, {}, nil) } subclass.relations = self.relations.dup || {} + subclass.serializer_methods = self.serializer_methods.dup || Set.new + end + + # BaseSerializer itself has no registry, so its own methods are never + # treated as serializer methods. + def method_added(name) + super + serializer_methods&.add(name) + end + + def include(*mods) + super + + mods.each do |mod| + serializer_methods&.merge( + mod.instance_methods + mod.private_instance_methods + ) + end + + self end def attributes(*attrs, &block) @@ -33,7 +55,7 @@ def has_many(*attrs) attrs.each { |attr| @relations[attr] = HasMany.new(attr, opts) } end - attr_accessor :attrs, :relations + attr_accessor :attrs, :relations, :serializer_methods end attr_reader :obj, :meta, :opts @@ -44,21 +66,15 @@ def initialize(obj, opts = {}) @obj = obj @opts = opts @meta = opts[:meta] - @except = Set.new([opts[:except]].flatten.compact) - @only = Set.new([opts[:only]].flatten.compact) - - @root_key = (opts[:root] || ActiveSupport::Inflector.underscore( - obj.class.name - ).split('/').last).to_sym + @except = key_filter(opts[:except]) + @only = key_filter(opts[:only]) end def serializable_hash(opts) res = {} - _attributes.each { |attr| attr.merge_attributes(res, self, opts) } - _relations.each do |rel| - rel.merge_attributes(res, self, opts) - end + _attributes { |attr| attr.merge_attributes(res, self, opts) } + _relations { |rel| rel.merge_attributes(res, self, opts) } res end @@ -67,28 +83,36 @@ def merge_root(res, key, single, opts) if single res[key] = serializable_hash(opts) else - res[key] ||= [] + return if res.include_id?(key, @obj.id) - id = @obj.id - - if res[key].detect { |v| id && v[:id] == id } - return - else - res[key] << serializable_hash(opts) - end + res.push(key, serializable_hash(opts)) end - _relations.each { |rel| rel.merge_root(res, self, opts) } + _relations { |rel| rel.merge_root(res, self, opts) } end def to_hash - res = {} + res = Payload.new - merge_root(res, @root_key, true, @opts.slice(:scope)) + merge_root(res, _root_key, true, @opts.slice(:scope)) res[:meta] = @meta if @meta - res + res.to_h + end + + def read_attribute(key) + return send(key) if self.class.serializer_methods.include?(key) + + @obj.send(key) + end + + def relation_value(key) + @_relation_values ||= {} + + return @_relation_values[key] if @_relation_values.key?(key) + + @_relation_values[key] = yield end def to_json @@ -99,20 +123,38 @@ def method_missing(mth); @obj.send(mth); end private + def _root_key + @_root_key ||= if @opts[:root] + @opts[:root].to_sym + else + USerializer.infered_singular_root_key(@obj.class) + end + end + def _attributes - @_attributes ||= (self.class.attrs || {}).values.select do |attr| - allow?(attr.key) + (self.class.attrs || {}).each_value do |attr| + yield attr if allow?(attr.key) end end def _relations - @_relations ||= (self.class.relations || {}).values.select do |rel| - allow?(rel.key) + (self.class.relations || {}).each_value do |rel| + yield rel if allow?(rel.key) end end + def key_filter(keys) + return if keys.nil? + + keys = [keys].flatten.compact + + Set.new(keys) unless keys.empty? + end + def allow?(key) - return @only.include?(key) if @only.any? + return @only.include?(key) if @only + return true unless @except + !@except.include?(key) end end diff --git a/lib/userializer/composite_serializer.rb b/lib/userializer/composite_serializer.rb index 4010d09..db5e760 100644 --- a/lib/userializer/composite_serializer.rb +++ b/lib/userializer/composite_serializer.rb @@ -1,4 +1,5 @@ require 'oj' +require 'userializer/payload' module USerializer class CompositeObject @@ -41,10 +42,10 @@ def merge_root(res, opts) end def to_hash - res = {} + res = Payload.new merge_root(res, @opts) - res + res.to_h end def serialize(*_args) @@ -64,7 +65,7 @@ def compose_objs(objs) if obj.is_a?(Hash) || !obj.is_a?(Enumerable) CompositeObject.new(obj, opts) else - ArraySerializer.new(obj, opts, embed_empty_array: true) + ArraySerializer.new(obj, opts.merge(embed_empty_array: true)) end end end diff --git a/lib/userializer/has_many.rb b/lib/userializer/has_many.rb index 9125f70..c073a4a 100644 --- a/lib/userializer/has_many.rb +++ b/lib/userializer/has_many.rb @@ -9,34 +9,42 @@ def initialize(key, opts) @ids_key = opts[:ids_key] || build_ids_key(key) @embed_key = opts[:embed_key] || :id - @conditional_block = opts[:if] || proc { true } + @conditional_block = opts[:if] end def merge_attributes(res, ser, opts) - return unless @conditional_block.call(ser.object, opts) + return unless allow?(ser, opts) - res[@ids_key] = (entities(ser) || []).compact.map do |obj| - obj.nil? ? nil : obj.send(@embed_key) - end.compact + res[@ids_key] = (entities(ser) || []).each_with_object([]) do |obj, ids| + id = obj&.send(@embed_key) + ids << id unless id.nil? + end end def merge_root(res, ser, opts) + return unless allow?(ser, opts) + objs = entities(ser) || [] - return if objs.empty? || !@conditional_block.call(ser.object, opts) + return if objs.empty? ArraySerializer.new(objs, @opts).merge_root(res, opts) end def entities(ser) - obj = ser.send(@key) || [] - return obj unless @opts[:scope] + ser.relation_value(@key) do + obj = ser.read_attribute(@key) || [] - obj.send(@opts[:scope]) + @opts[:scope] ? obj.send(@opts[:scope]) : obj + end end private + def allow?(ser, opts) + @conditional_block.nil? || @conditional_block.call(ser.object, opts) + end + def build_ids_key(key) "#{ActiveSupport::Inflector.singularize(key)}_ids".to_sym end diff --git a/lib/userializer/has_one.rb b/lib/userializer/has_one.rb index be7b069..6da4ba5 100644 --- a/lib/userializer/has_one.rb +++ b/lib/userializer/has_one.rb @@ -5,6 +5,7 @@ def initialize(key, opts) @opts = opts @id_key = opts[:id_key] || "#{key}_id".to_sym @root_key = opts[:root]&.to_sym + @infered_serializers = {} serializer = opts[:serializer] @@ -15,41 +16,51 @@ def initialize(key, opts) end @embed_key = opts[:embed_key] || :id - @conditional_block = opts[:if] || proc { true } + @conditional_block = opts[:if] end attr_reader :id_key, :key def merge_attributes(res, ser, opts) - return unless @conditional_block.call(ser.object, opts) + return unless allow?(ser, opts) - obj = ser.send(@key) + obj = entity(ser) res[@id_key] = obj.nil? ? nil : obj.send(@embed_key) end def merge_root(res, ser, opts) - obj = ser.send(@key) + return unless allow?(ser, opts) - return if obj.nil? || !@conditional_block.call(ser.object, opts) + obj = entity(ser) + + return if obj.nil? serializer(obj, opts).merge_root(res, root_key(obj), false, opts) end + def entity(ser) + ser.relation_value(@key) { ser.read_attribute(@key) } + end + private + def allow?(ser, opts) + @conditional_block.nil? || @conditional_block.call(ser.object, opts) + end + def serializer(obj, opts) return @serializer.call(obj, opts).new(obj, @opts) if @serializer return obj.serialize if obj.respond_to?(:serialize) - USerializer.infered_serializer_class(obj.class).new(obj, @opts) + infered_serializer(obj.class).new(obj, @opts) end - def root_key(obj) - return @root_key if @root_key + def infered_serializer(kls) + @infered_serializers[kls] ||= USerializer.infered_serializer_class(kls) + end - ActiveSupport::Inflector.pluralize( - ActiveSupport::Inflector.underscore(obj.class.name).split('/').last - ).to_sym + def root_key(obj) + @root_key || USerializer.infered_root_key(obj.class) end end end diff --git a/lib/userializer/payload.rb b/lib/userializer/payload.rb new file mode 100644 index 0000000..7cbef8d --- /dev/null +++ b/lib/userializer/payload.rb @@ -0,0 +1,28 @@ +module USerializer + class Payload < Hash + def []=(key, value) + @ids&.delete(key) + super + end + + def include_id?(key, id) + return false unless id + + ids(key).key?(id) + end + + def push(key, value) + (self[key] ||= []) << value + ids(key)[value[:id]] = true + end + + private + + def ids(key) + @ids ||= {} + @ids[key] ||= (self[key] || []).each_with_object({}) do |v, acc| + acc[v[:id]] = true + end + end + end +end diff --git a/spec/userializer/array_serializer_spec.rb b/spec/userializer/array_serializer_spec.rb new file mode 100644 index 0000000..331a6f8 --- /dev/null +++ b/spec/userializer/array_serializer_spec.rb @@ -0,0 +1,62 @@ +require 'spec_helper' + +module ArraySerializerTesting + class Foo + attr_accessor :id, :bar + + def initialize(id, bar) + @id = id + @bar = bar + end + end + + class FooSerializer < USerializer::BaseSerializer + attributes :bar + end + + class FooCustomSerializer < USerializer::BaseSerializer + attributes :bar do |object, _| + "custom #{object.bar}" + end + end +end + +RSpec.describe USerializer::ArraySerializer do + let(:foos) { [ArraySerializerTesting::Foo.new(1, 'bar')] } + + context 'options as a hash' do + it do + expect( + USerializer::ArraySerializer.new( + foos, + { root: :items, meta: { total: 1 } } + ).to_hash + ).to eq(items: [{ id: 1, bar: 'bar' }], meta: { total: 1 }) + end + end + + context 'options as keywords' do + it do + expect( + USerializer::ArraySerializer.new( + foos, + root: 'items', + meta: { total: 1 }, + each_serializer: ArraySerializerTesting::FooCustomSerializer + ).to_hash + ).to eq(items: [{ id: 1, bar: 'custom bar' }], meta: { total: 1 }) + end + end + + context 'embeds an empty array' do + it do + res = {} + + USerializer::ArraySerializer.new( + [], root: :items, embed_empty_array: true + ).merge_root(res, {}) + + expect(res).to eq(items: []) + end + end +end diff --git a/spec/userializer/attribute_resolution_spec.rb b/spec/userializer/attribute_resolution_spec.rb new file mode 100644 index 0000000..3da61f8 --- /dev/null +++ b/spec/userializer/attribute_resolution_spec.rb @@ -0,0 +1,156 @@ +require 'spec_helper' + +module AttributeResolutionTesting + class Post + attr_accessor :id, :meta, :opts, :obj, :object, :hash, :format, :title, + :author + + def initialize(opts = {}) + opts.each { |k, v| send("#{k}=", v) } + end + end + + class Author + attr_accessor :id + end + + class AuthorSerializer < USerializer::BaseSerializer + end + + class PostSerializer < USerializer::BaseSerializer + attributes :meta, :opts, :obj, :object, :hash, :format + end + + module Titleize + def title + object.title.upcase + end + end + + class PostTitleSerializer < USerializer::BaseSerializer + include Titleize + + attributes :title + end + + class PostTitleChildSerializer < PostTitleSerializer + end + + module NestedTitleize + include Titleize + end + + class PostNestedModuleSerializer < USerializer::BaseSerializer + include NestedTitleize + + attributes :title + end + + class PostDefineMethodSerializer < USerializer::BaseSerializer + attributes :title + + define_method(:title) { "defined #{object.title}" } + end + + class PostPrivateSerializer < USerializer::BaseSerializer + attributes :title + + private + + def title + "private #{object.title}" + end + end + + class PostRelationSerializer < USerializer::BaseSerializer + has_one :meta, serializer: AuthorSerializer, root: :authors + end +end + +RSpec.describe USerializer::BaseSerializer do + let(:post) do + AttributeResolutionTesting::Post.new( + id: 1, + meta: 'post meta', + opts: 'post opts', + obj: 'post obj', + object: 'post object', + hash: 'post hash', + format: 'post format', + title: 'title' + ) + end + + context 'attribute named like a serializer or Kernel method' do + it do + expect( + AttributeResolutionTesting::PostSerializer.new( + post, meta: { page: 1 } + ).to_hash + ).to eq( + post: { + id: 1, + meta: 'post meta', + opts: 'post opts', + obj: 'post obj', + object: 'post object', + hash: 'post hash', + format: 'post format' + }, + meta: { page: 1 } + ) + end + end + + context 'method defined in an included module' do + it do + expect( + AttributeResolutionTesting::PostTitleSerializer.new(post).to_hash + ).to eq(post: { id: 1, title: 'TITLE' }) + end + end + + context 'method defined in a parent serializer' do + it do + expect( + AttributeResolutionTesting::PostTitleChildSerializer.new(post).to_hash + ).to eq(post: { id: 1, title: 'TITLE' }) + end + end + + context 'method defined in a nested included module' do + it do + expect( + AttributeResolutionTesting::PostNestedModuleSerializer.new(post).to_hash + ).to eq(post: { id: 1, title: 'TITLE' }) + end + end + + context 'method defined with define_method' do + it do + expect( + AttributeResolutionTesting::PostDefineMethodSerializer.new(post).to_hash + ).to eq(post: { id: 1, title: 'defined title' }) + end + end + + context 'private serializer method' do + it do + expect( + AttributeResolutionTesting::PostPrivateSerializer.new(post).to_hash + ).to eq(post: { id: 1, title: 'private title' }) + end + end + + context 'relation named like a serializer method' do + it do + author = AttributeResolutionTesting::Author.new + author.id = 7 + post.meta = author + + expect( + AttributeResolutionTesting::PostRelationSerializer.new(post).to_hash + ).to eq(post: { id: 1, meta_id: 7 }, authors: [{ id: 7 }]) + end + end +end diff --git a/spec/userializer/basic_serialization_spec.rb b/spec/userializer/basic_serialization_spec.rb index 4461c6f..27a71ed 100644 --- a/spec/userializer/basic_serialization_spec.rb +++ b/spec/userializer/basic_serialization_spec.rb @@ -29,6 +29,10 @@ class FooSkipNilSerializer < USerializer::BaseSerializer attributes :bar, skip_nil: true end +class FooConditionalSerializer < USerializer::BaseSerializer + attributes :bar, if: proc { |_, opts| opts[:scope] == :admin } +end + class AttributesRelations attr_accessor :id, :relations, :attributes end @@ -108,6 +112,44 @@ class AttributesRelationsSerializer < USerializer::BaseSerializer end end + context 'only with a single key' do + it do + expect(FooSerializer.new(f, only: :bar).to_hash).to eq( + foo: { bar: 'bar' } + ) + end + end + + context 'only with nested keys' do + it do + expect(FooSerializer.new(f, only: [:id, [:buz]]).to_hash).to eq( + foo: { id: 1, buz: 'biz' } + ) + end + end + + context 'empty only && except' do + it do + expect(FooSerializer.new(f, only: [], except: []).to_hash).to eq( + foo: { id: 1, bar: 'bar', buz: 'biz' } + ) + end + end + + context 'conditional attribute' do + it do + expect(FooConditionalSerializer.new(f, scope: :admin).to_hash).to eq( + foo: { id: 1, bar: 'bar' } + ) + end + + it do + expect(FooConditionalSerializer.new(f, scope: :user).to_hash).to eq( + foo: { id: 1 } + ) + end + end + context 'only && except' do it do expect(FooSerializer.new( diff --git a/spec/userializer/has_one_spec.rb b/spec/userializer/has_one_spec.rb index 42f6e95..eec6b84 100644 --- a/spec/userializer/has_one_spec.rb +++ b/spec/userializer/has_one_spec.rb @@ -142,6 +142,23 @@ def zaz end end + context 'polymorphic relation' do + it do + biz = HasOneTesting::Biz.new + biz.id = 27 + + other = HasOneTesting::Bar.new + other.id = 3 + other.foo = biz + + expect(USerializer::ArraySerializer.new([b, other]).to_hash).to eq( + bars: [{ id: 2, foo_id: 1 }, { id: 3, foo_id: 27 }], + foos: [{ id: 1, bar: 'bar' }], + bizs: [{ id: 27, zaz: 'zaz' }] + ) + end + end + context 'nested' do let(:n) do n = HasOneTesting::Bar.new diff --git a/spec/userializer/serializer_inference_spec.rb b/spec/userializer/serializer_inference_spec.rb new file mode 100644 index 0000000..f06ff8e --- /dev/null +++ b/spec/userializer/serializer_inference_spec.rb @@ -0,0 +1,58 @@ +require 'spec_helper' + +module SerializerInferenceTesting + class Widget + attr_accessor :id + end + + class Gadget + attr_accessor :id + end + + class GadgetSerializer < USerializer::BaseSerializer + attributes :namespaced do + true + end + end +end + +class WidgetSerializer < USerializer::BaseSerializer + attributes :top_level do + true + end +end + +class GadgetSerializer < USerializer::BaseSerializer + attributes :top_level do + true + end +end + +RSpec.describe USerializer do + context 'serializer in the model namespace' do + it do + expect( + USerializer.infered_serializer_class(SerializerInferenceTesting::Gadget) + ).to eq(SerializerInferenceTesting::GadgetSerializer) + end + end + + context 'serializer at the top level' do + it do + expect( + USerializer.infered_serializer_class(SerializerInferenceTesting::Widget) + ).to eq(WidgetSerializer) + end + end + + context 'sideloads with a top level serializer' do + it do + widget = SerializerInferenceTesting::Widget.new + widget.id = 1 + + expect(USerializer::ArraySerializer.new([widget]).to_hash).to eq( + widgets: [{ id: 1, top_level: true }] + ) + end + end +end diff --git a/spec/userializer/sideloading_spec.rb b/spec/userializer/sideloading_spec.rb new file mode 100644 index 0000000..224433d --- /dev/null +++ b/spec/userializer/sideloading_spec.rb @@ -0,0 +1,127 @@ +require 'spec_helper' + +module SideloadingTesting + class Collection < Array + attr_reader :scope_calls + + def initialize(*) + super + @scope_calls = 0 + end + + def available + @scope_calls += 1 + self + end + end + + class Tag + attr_accessor :id, :name + + def initialize(id, name = nil) + @id = id + @name = name + end + end + + class TagSerializer < USerializer::BaseSerializer + attributes :name + end + + class Post + attr_accessor :id, :tags, :main_tag + + def initialize(id, tags, main_tag = nil) + @id = id + @tags = tags + @main_tag = main_tag + end + end + + class PostSerializer < USerializer::BaseSerializer + has_many :tags, scope: :available + has_one :main_tag, root: :tags + end + + class PostConditionalSerializer < USerializer::BaseSerializer + has_many :tags, if: proc { false } + has_one :main_tag, if: proc { false } + end +end + +RSpec.describe USerializer::BaseSerializer do + def tags(*ids) + SideloadingTesting::Collection.new( + ids.map { |id| SideloadingTesting::Tag.new(id, "tag #{id}") } + ) + end + + context 'deduplicates sideloaded entities across parents' do + it do + posts = [ + SideloadingTesting::Post.new(1, tags(1, 2), tags(2).first), + SideloadingTesting::Post.new(2, tags(2, 3), tags(4).first) + ] + + expect(USerializer::ArraySerializer.new(posts).to_hash).to eq( + posts: [ + { id: 1, tag_ids: [1, 2], main_tag_id: 2 }, + { id: 2, tag_ids: [2, 3], main_tag_id: 4 } + ], + tags: [ + { id: 1, name: 'tag 1' }, + { id: 2, name: 'tag 2' }, + { id: 3, name: 'tag 3' }, + { id: 4, name: 'tag 4' } + ] + ) + end + end + + context 'does not deduplicate entities without id' do + it do + objs = [ + SideloadingTesting::Tag.new(nil, 'a'), + SideloadingTesting::Tag.new(nil, 'b') + ] + + expect(USerializer::ArraySerializer.new(objs).to_hash).to eq( + tags: [{ id: nil, name: 'a' }, { id: nil, name: 'b' }] + ) + end + end + + context 'returns a plain hash' do + it do + post = SideloadingTesting::Post.new(1, tags(1)) + + expect( + SideloadingTesting::PostSerializer.new(post).to_hash.class + ).to eq(Hash) + end + end + + context 'evaluates the has_many scope once' do + it do + collection = tags(1, 2) + post = SideloadingTesting::Post.new(1, collection) + + SideloadingTesting::PostSerializer.new(post).to_hash + + expect(collection.scope_calls).to eq(1) + end + end + + context 'does not load relations when the condition is false' do + it do + post = SideloadingTesting::Post.new(1, nil) + + allow(post).to receive(:tags).and_raise('tags loaded') + allow(post).to receive(:main_tag).and_raise('main_tag loaded') + + expect( + SideloadingTesting::PostConditionalSerializer.new(post).to_hash + ).to eq(post: { id: 1 }) + end + end +end