From 2fb989a6c48162a74e7d8330ecda289cd1320b31 Mon Sep 17 00:00:00 2001 From: Alexis Montagne Date: Mon, 16 Nov 2026 10:26:24 -0800 Subject: [PATCH 01/14] lib/userializer: index sideloaded ids to deduplicate in constant time Deduplication scanned the whole sideloaded list for every entity, making serialization quadratic: 10k entities took ~1.9s. A Payload hash now keeps a set of ids per root key while to_hash keeps returning a plain Hash. --- lib/userializer/array_serializer.rb | 5 +- lib/userializer/base_serializer.rb | 15 ++-- lib/userializer/composite_serializer.rb | 5 +- lib/userializer/payload.rb | 28 +++++++ spec/userializer/sideloading_spec.rb | 98 +++++++++++++++++++++++++ 5 files changed, 137 insertions(+), 14 deletions(-) create mode 100644 lib/userializer/payload.rb create mode 100644 spec/userializer/sideloading_spec.rb diff --git a/lib/userializer/array_serializer.rb b/lib/userializer/array_serializer.rb index d192e30..e5fdfa5 100644 --- a/lib/userializer/array_serializer.rb +++ b/lib/userializer/array_serializer.rb @@ -1,4 +1,5 @@ require 'oj' +require 'userializer/payload' module USerializer class HeterogeneousArray < StandardError; end @@ -37,14 +38,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 diff --git a/lib/userializer/base_serializer.rb b/lib/userializer/base_serializer.rb index 95149f3..ed19026 100644 --- a/lib/userializer/base_serializer.rb +++ b/lib/userializer/base_serializer.rb @@ -3,6 +3,7 @@ require 'userializer/has_one' require 'userializer/has_many' require 'userializer/attribute' +require 'userializer/payload' module USerializer class BaseSerializer @@ -67,28 +68,22 @@ 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) } end def to_hash - res = {} + res = Payload.new merge_root(res, @root_key, true, @opts.slice(:scope)) res[:meta] = @meta if @meta - res + res.to_h end def to_json diff --git a/lib/userializer/composite_serializer.rb b/lib/userializer/composite_serializer.rb index 4010d09..fa4de2b 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) diff --git a/lib/userializer/payload.rb b/lib/userializer/payload.rb new file mode 100644 index 0000000..da000f7 --- /dev/null +++ b/lib/userializer/payload.rb @@ -0,0 +1,28 @@ +require 'set' + +module USerializer + class Payload < Hash + def []=(key, value) + @ids&.delete(key) + super + end + + def include_id?(key, id) + return false unless id + + ids(key).include?(id) + end + + def push(key, value) + (self[key] ||= []) << value + ids(key) << value[:id] + end + + private + + def ids(key) + @ids ||= {} + @ids[key] ||= Set.new((self[key] || []).map { |v| v[:id] }) + end + end +end diff --git a/spec/userializer/sideloading_spec.rb b/spec/userializer/sideloading_spec.rb new file mode 100644 index 0000000..d683405 --- /dev/null +++ b/spec/userializer/sideloading_spec.rb @@ -0,0 +1,98 @@ +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 +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 +end From cd728f9a01c20a0643466b56920d8cea5e5afa59 Mon Sep 17 00:00:00 2001 From: Alexis Montagne Date: Mon, 16 Nov 2026 10:26:45 -0800 Subject: [PATCH 02/14] lib/userializer: load each relation once per serializer has_many ran its scope twice per parent, once for the ids and once for the sideloaded entities, which doubles queries on ActiveRecord scopes. Relation values are now memoized on the serializer, and the if condition is checked before loading so a disabled relation is never fetched. --- lib/userializer/base_serializer.rb | 8 ++++++++ lib/userializer/has_many.rb | 13 ++++++++----- lib/userializer/has_one.rb | 12 +++++++++--- spec/userializer/sideloading_spec.rb | 29 ++++++++++++++++++++++++++++ 4 files changed, 54 insertions(+), 8 deletions(-) diff --git a/lib/userializer/base_serializer.rb b/lib/userializer/base_serializer.rb index ed19026..4c5c636 100644 --- a/lib/userializer/base_serializer.rb +++ b/lib/userializer/base_serializer.rb @@ -86,6 +86,14 @@ def to_hash res.to_h end + def relation_value(key) + @_relation_values ||= {} + + return @_relation_values[key] if @_relation_values.key?(key) + + @_relation_values[key] = yield + end + def to_json Oj.dump(to_hash, mode: :compat) end diff --git a/lib/userializer/has_many.rb b/lib/userializer/has_many.rb index 9125f70..6c487ea 100644 --- a/lib/userializer/has_many.rb +++ b/lib/userializer/has_many.rb @@ -16,23 +16,26 @@ def merge_attributes(res, ser, opts) return unless @conditional_block.call(ser.object, opts) res[@ids_key] = (entities(ser) || []).compact.map do |obj| - obj.nil? ? nil : obj.send(@embed_key) + obj.send(@embed_key) end.compact end def merge_root(res, ser, opts) + return unless @conditional_block.call(ser.object, 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.send(@key) || [] - obj.send(@opts[:scope]) + @opts[:scope] ? obj.send(@opts[:scope]) : obj + end end private diff --git a/lib/userializer/has_one.rb b/lib/userializer/has_one.rb index be7b069..77bec8a 100644 --- a/lib/userializer/has_one.rb +++ b/lib/userializer/has_one.rb @@ -23,18 +23,24 @@ def initialize(key, opts) def merge_attributes(res, ser, opts) return unless @conditional_block.call(ser.object, 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 @conditional_block.call(ser.object, opts) + + obj = entity(ser) - return if obj.nil? || !@conditional_block.call(ser.object, opts) + return if obj.nil? serializer(obj, opts).merge_root(res, root_key(obj), false, opts) end + def entity(ser) + ser.relation_value(@key) { ser.send(@key) } + end + private def serializer(obj, opts) diff --git a/spec/userializer/sideloading_spec.rb b/spec/userializer/sideloading_spec.rb index d683405..224433d 100644 --- a/spec/userializer/sideloading_spec.rb +++ b/spec/userializer/sideloading_spec.rb @@ -42,6 +42,11 @@ 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 @@ -95,4 +100,28 @@ def tags(*ids) ).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 From b43dfef1251295c927e4d5a95484d7ba304812f0 Mon Sep 17 00:00:00 2001 From: Alexis Montagne Date: Mon, 16 Nov 2026 10:27:00 -0800 Subject: [PATCH 03/14] lib/userializer/base_serializer.rb: compute root key lazily and skip empty filters Every serializer built its root key with underscore and two Sets for only/except, even sideloaded entities that never use them. Deferring the root key and iterating definitions directly removes most per-record allocations. --- lib/userializer/base_serializer.rb | 44 ++++++++++++-------- spec/userializer/basic_serialization_spec.rb | 24 +++++++++++ 2 files changed, 51 insertions(+), 17 deletions(-) diff --git a/lib/userializer/base_serializer.rb b/lib/userializer/base_serializer.rb index 4c5c636..99ae5ce 100644 --- a/lib/userializer/base_serializer.rb +++ b/lib/userializer/base_serializer.rb @@ -45,21 +45,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 @@ -73,13 +67,13 @@ def merge_root(res, key, single, opts) 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 = 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 @@ -102,20 +96,36 @@ def method_missing(mth); @obj.send(mth); end private + def _root_key + @_root_key ||= (@opts[:root] || ActiveSupport::Inflector.underscore( + @obj.class.name + ).split('/').last).to_sym + 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/spec/userializer/basic_serialization_spec.rb b/spec/userializer/basic_serialization_spec.rb index 4461c6f..787aa62 100644 --- a/spec/userializer/basic_serialization_spec.rb +++ b/spec/userializer/basic_serialization_spec.rb @@ -108,6 +108,30 @@ 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 'only && except' do it do expect(FooSerializer.new( From fa2c8f0c11681796d1f11b6953d9e00e8d2cabaf Mon Sep 17 00:00:00 2001 From: Alexis Montagne Date: Mon, 16 Nov 2026 10:27:05 -0800 Subject: [PATCH 04/14] lib/userializer.rb: try the full serializer constant before walking namespaces Walking each namespace segment allocated intermediate strings and arrays on every lookup. The full constant is now resolved directly when defined, falling back to the segment walk so namespaced models keep resolving to top level serializers. --- lib/userializer.rb | 8 ++- spec/userializer/serializer_inference_spec.rb | 58 +++++++++++++++++++ 2 files changed, 63 insertions(+), 3 deletions(-) create mode 100644 spec/userializer/serializer_inference_spec.rb diff --git a/lib/userializer.rb b/lib/userializer.rb index 99c9470..79d86f5 100644 --- a/lib/userializer.rb +++ b/lib/userializer.rb @@ -17,9 +17,11 @@ 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 end end 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 From 0197ba8cd2356ea24e477393bcc9876cd7d2c75a Mon Sep 17 00:00:00 2001 From: Alexis Montagne Date: Mon, 16 Nov 2026 10:27:12 -0800 Subject: [PATCH 05/14] lib/userializer/has_one.rb: cache sideload root key per class name The root key was pluralized and underscored for every related entity even though it only depends on the entity class. Keying the cache by name keeps it stable across Rails code reloading. --- lib/userializer/has_one.rb | 7 +++++-- spec/userializer/has_one_spec.rb | 17 +++++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/lib/userializer/has_one.rb b/lib/userializer/has_one.rb index 77bec8a..07c8474 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 + @root_keys = {} serializer = opts[:serializer] @@ -53,8 +54,10 @@ def serializer(obj, opts) def root_key(obj) return @root_key if @root_key - ActiveSupport::Inflector.pluralize( - ActiveSupport::Inflector.underscore(obj.class.name).split('/').last + name = obj.class.name + + @root_keys[name] ||= ActiveSupport::Inflector.pluralize( + ActiveSupport::Inflector.underscore(name).split('/').last ).to_sym end end 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 From f04a6c00c7f2dc75dd29e41be4b5d34267512dd8 Mon Sep 17 00:00:00 2001 From: Alexis Montagne Date: Mon, 16 Nov 2026 10:27:27 -0800 Subject: [PATCH 06/14] lib/userializer: skip the if condition call when none is given --- lib/userializer/attribute.rb | 10 ++++++++-- lib/userializer/has_many.rb | 10 +++++++--- lib/userializer/has_one.rb | 10 +++++++--- spec/userializer/basic_serialization_spec.rb | 18 ++++++++++++++++++ 4 files changed, 40 insertions(+), 8 deletions(-) diff --git a/lib/userializer/attribute.rb b/lib/userializer/attribute.rb index 33df0f7..f930202 100644 --- a/lib/userializer/attribute.rb +++ b/lib/userializer/attribute.rb @@ -8,11 +8,11 @@ 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) @@ -20,5 +20,11 @@ def merge_attributes(res, ser, opts) 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/has_many.rb b/lib/userializer/has_many.rb index 6c487ea..5fa3751 100644 --- a/lib/userializer/has_many.rb +++ b/lib/userializer/has_many.rb @@ -9,11 +9,11 @@ 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.send(@embed_key) @@ -21,7 +21,7 @@ def merge_attributes(res, ser, opts) end def merge_root(res, ser, opts) - return unless @conditional_block.call(ser.object, opts) + return unless allow?(ser, opts) objs = entities(ser) || [] @@ -40,6 +40,10 @@ def entities(ser) 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 07c8474..3713fa1 100644 --- a/lib/userializer/has_one.rb +++ b/lib/userializer/has_one.rb @@ -16,20 +16,20 @@ 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 = entity(ser) res[@id_key] = obj.nil? ? nil : obj.send(@embed_key) end def merge_root(res, ser, opts) - return unless @conditional_block.call(ser.object, opts) + return unless allow?(ser, opts) obj = entity(ser) @@ -44,6 +44,10 @@ def entity(ser) 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) diff --git a/spec/userializer/basic_serialization_spec.rb b/spec/userializer/basic_serialization_spec.rb index 787aa62..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 @@ -132,6 +136,20 @@ class AttributesRelationsSerializer < USerializer::BaseSerializer 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( From 6cee5a130fbdee8c87379b71d22e4ff90f87ea0f Mon Sep 17 00:00:00 2001 From: Alexis Montagne Date: Mon, 16 Nov 2026 10:33:00 -0800 Subject: [PATCH 07/14] lib/userializer: share a root key cache across sideloaded collections ArraySerializer is built for every has_many of every parent, so it pluralized and underscored the same class name over and over. The cache now lives at the module level, keyed by class name, and is shared with has_one. --- lib/userializer.rb | 10 ++++++++++ lib/userializer/array_serializer.rb | 4 +--- lib/userializer/has_one.rb | 9 +-------- 3 files changed, 12 insertions(+), 11 deletions(-) diff --git a/lib/userializer.rb b/lib/userializer.rb index 79d86f5..146790b 100644 --- a/lib/userializer.rb +++ b/lib/userializer.rb @@ -7,6 +7,8 @@ module USerializer NS_SEPARATOR = '::'.freeze + @root_keys = {} + class << self def serializer_for(obj) return nil if obj.nil? @@ -23,5 +25,13 @@ def infered_serializer_class(kls) name.split(NS_SEPARATOR).inject(Object) { |o, c| o.const_get(c) } 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 e5fdfa5..14c0567 100644 --- a/lib/userializer/array_serializer.rb +++ b/lib/userializer/array_serializer.rb @@ -17,9 +17,7 @@ def initialize(objs, opts = {}, embed_empty_array: false) raise HeterogeneousArray if clss.count > 1 @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] diff --git a/lib/userializer/has_one.rb b/lib/userializer/has_one.rb index 3713fa1..1319919 100644 --- a/lib/userializer/has_one.rb +++ b/lib/userializer/has_one.rb @@ -5,7 +5,6 @@ def initialize(key, opts) @opts = opts @id_key = opts[:id_key] || "#{key}_id".to_sym @root_key = opts[:root]&.to_sym - @root_keys = {} serializer = opts[:serializer] @@ -56,13 +55,7 @@ def serializer(obj, opts) end def root_key(obj) - return @root_key if @root_key - - name = obj.class.name - - @root_keys[name] ||= ActiveSupport::Inflector.pluralize( - ActiveSupport::Inflector.underscore(name).split('/').last - ).to_sym + @root_key || USerializer.infered_root_key(obj.class) end end end From 5a202e216823475cc1fbb1d89cac92f2fbdd3a31 Mon Sep 17 00:00:00 2001 From: Alexis Montagne Date: Mon, 16 Nov 2026 10:33:01 -0800 Subject: [PATCH 08/14] lib/userializer/array_serializer.rb: infer the serializer once per collection Collections are already required to be homogeneous, so the inferred serializer is the same for every entity and only needs to be resolved on first use. --- lib/userializer/array_serializer.rb | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/lib/userializer/array_serializer.rb b/lib/userializer/array_serializer.rb index 14c0567..830bb9e 100644 --- a/lib/userializer/array_serializer.rb +++ b/lib/userializer/array_serializer.rb @@ -58,7 +58,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 From c55f3eff25d0b9bfc788ce2cd97888b19b0f824d Mon Sep 17 00:00:00 2001 From: Alexis Montagne Date: Mon, 16 Nov 2026 10:50:50 -0800 Subject: [PATCH 09/14] lib/userializer/array_serializer.rb: read embed_empty_array from options Since embed_empty_array was added as a keyword argument, Ruby 3 parses braceless calls such as ArraySerializer.new(objs, root: 'x') as keywords and raises an ArgumentError. Without keyword arguments, braceless calls are collected into the options hash again. --- lib/userializer/array_serializer.rb | 4 +- lib/userializer/composite_serializer.rb | 2 +- spec/userializer/array_serializer_spec.rb | 62 +++++++++++++++++++++++ 3 files changed, 65 insertions(+), 3 deletions(-) create mode 100644 spec/userializer/array_serializer_spec.rb diff --git a/lib/userializer/array_serializer.rb b/lib/userializer/array_serializer.rb index 830bb9e..e196b66 100644 --- a/lib/userializer/array_serializer.rb +++ b/lib/userializer/array_serializer.rb @@ -5,11 +5,11 @@ 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 diff --git a/lib/userializer/composite_serializer.rb b/lib/userializer/composite_serializer.rb index fa4de2b..db5e760 100644 --- a/lib/userializer/composite_serializer.rb +++ b/lib/userializer/composite_serializer.rb @@ -65,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/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 From 4f96e2e66ddc1f5322de11f8345872c46710b844 Mon Sep 17 00:00:00 2001 From: Alexis Montagne Date: Mon, 16 Nov 2026 10:54:58 -0800 Subject: [PATCH 10/14] lib/userializer/payload.rb: track sideloaded ids in a plain hash Each to_hash builds a fresh index per sideloaded root key, and a Set wraps a Hash and rebuilt it through an intermediate map. This shows up when serializing records one at a time, as most endpoints do. --- lib/userializer/base_serializer.rb | 1 + lib/userializer/payload.rb | 10 +++++----- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/lib/userializer/base_serializer.rb b/lib/userializer/base_serializer.rb index 99ae5ce..057a746 100644 --- a/lib/userializer/base_serializer.rb +++ b/lib/userializer/base_serializer.rb @@ -1,3 +1,4 @@ +require 'set' require 'oj' require 'active_support/inflector/methods' require 'userializer/has_one' diff --git a/lib/userializer/payload.rb b/lib/userializer/payload.rb index da000f7..7cbef8d 100644 --- a/lib/userializer/payload.rb +++ b/lib/userializer/payload.rb @@ -1,5 +1,3 @@ -require 'set' - module USerializer class Payload < Hash def []=(key, value) @@ -10,19 +8,21 @@ def []=(key, value) def include_id?(key, id) return false unless id - ids(key).include?(id) + ids(key).key?(id) end def push(key, value) (self[key] ||= []) << value - ids(key) << value[:id] + ids(key)[value[:id]] = true end private def ids(key) @ids ||= {} - @ids[key] ||= Set.new((self[key] || []).map { |v| v[:id] }) + @ids[key] ||= (self[key] || []).each_with_object({}) do |v, acc| + acc[v[:id]] = true + end end end end From 436469f304240e53f96c4c6f70ea71ad02af7116 Mon Sep 17 00:00:00 2001 From: Alexis Montagne Date: Mon, 16 Nov 2026 10:55:05 -0800 Subject: [PATCH 11/14] lib/userializer: cache the root key of serialized objects per class name to_hash ran underscore on the class name for every serialized object. It now shares the module level cache approach of sideloaded root keys. --- lib/userializer.rb | 9 +++++++++ lib/userializer/base_serializer.rb | 8 +++++--- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/lib/userializer.rb b/lib/userializer.rb index 146790b..501ca64 100644 --- a/lib/userializer.rb +++ b/lib/userializer.rb @@ -8,6 +8,7 @@ module USerializer NS_SEPARATOR = '::'.freeze @root_keys = {} + @singular_root_keys = {} class << self def serializer_for(obj) @@ -26,6 +27,14 @@ def infered_serializer_class(kls) 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 diff --git a/lib/userializer/base_serializer.rb b/lib/userializer/base_serializer.rb index 057a746..b0fa097 100644 --- a/lib/userializer/base_serializer.rb +++ b/lib/userializer/base_serializer.rb @@ -98,9 +98,11 @@ def method_missing(mth); @obj.send(mth); end private def _root_key - @_root_key ||= (@opts[:root] || ActiveSupport::Inflector.underscore( - @obj.class.name - ).split('/').last).to_sym + @_root_key ||= if @opts[:root] + @opts[:root].to_sym + else + USerializer.infered_singular_root_key(@obj.class) + end end def _attributes From 6884fd9e2b5ce6d33203b6ee6336982714aab1f6 Mon Sep 17 00:00:00 2001 From: Alexis Montagne Date: Mon, 16 Nov 2026 10:55:06 -0800 Subject: [PATCH 12/14] lib/userializer/has_one.rb: cache the inferred serializer per class The serializer was resolved through const_defined? and const_get for every related entity. The cache lives on the relation, so it is rebuilt whenever the owning serializer is reloaded. --- lib/userializer/has_one.rb | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/lib/userializer/has_one.rb b/lib/userializer/has_one.rb index 1319919..febd583 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] @@ -51,7 +52,11 @@ 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 infered_serializer(kls) + @infered_serializers[kls] ||= USerializer.infered_serializer_class(kls) end def root_key(obj) From d3a02d4a2ae66233e08701040594b430972b0a56 Mon Sep 17 00:00:00 2001 From: Alexis Montagne Date: Mon, 16 Nov 2026 10:55:10 -0800 Subject: [PATCH 13/14] lib/userializer: avoid intermediate arrays in has_many and collections has_many ids went through compact, map and compact, and the homogeneity check mapped and deduplicated every class. Both now run in a single pass, which matters since a collection is built for every has_many of every parent. --- lib/userializer/array_serializer.rb | 5 ++--- lib/userializer/has_many.rb | 7 ++++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/lib/userializer/array_serializer.rb b/lib/userializer/array_serializer.rb index e196b66..e40c049 100644 --- a/lib/userializer/array_serializer.rb +++ b/lib/userializer/array_serializer.rb @@ -11,10 +11,9 @@ def initialize(objs, opts = {}) @meta = opts[:meta] @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 ||= USerializer.infered_root_key(obj_class) if obj_class diff --git a/lib/userializer/has_many.rb b/lib/userializer/has_many.rb index 5fa3751..1d5293d 100644 --- a/lib/userializer/has_many.rb +++ b/lib/userializer/has_many.rb @@ -15,9 +15,10 @@ def initialize(key, opts) def merge_attributes(res, ser, opts) return unless allow?(ser, opts) - res[@ids_key] = (entities(ser) || []).compact.map do |obj| - 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) From 9062f706b88deeb6dcc350653650b0ce87037afc Mon Sep 17 00:00:00 2001 From: Alexis Montagne Date: Mon, 16 Nov 2026 10:27:35 -0800 Subject: [PATCH 14/14] lib/userializer!: read attributes from the model unless the serializer defines them Attributes and relations were read with send on the serializer, so names like meta, opts, object, hash or format returned serializer internals or Kernel methods instead of the model value. Serializers now register the methods they define or include, and everything else is read from the model. Serializers relying on such names resolving to the serializer's own internals now get the model value instead. --- lib/userializer/attribute.rb | 2 +- lib/userializer/base_serializer.rb | 28 +++- lib/userializer/has_many.rb | 2 +- lib/userializer/has_one.rb | 2 +- spec/userializer/attribute_resolution_spec.rb | 156 ++++++++++++++++++ 5 files changed, 186 insertions(+), 4 deletions(-) create mode 100644 spec/userializer/attribute_resolution_spec.rb diff --git a/lib/userializer/attribute.rb b/lib/userializer/attribute.rb index f930202..55575dd 100644 --- a/lib/userializer/attribute.rb +++ b/lib/userializer/attribute.rb @@ -14,7 +14,7 @@ def initialize(key, opts, block) def merge_attributes(res, ser, 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 diff --git a/lib/userializer/base_serializer.rb b/lib/userializer/base_serializer.rb index b0fa097..41e0380 100644 --- a/lib/userializer/base_serializer.rb +++ b/lib/userializer/base_serializer.rb @@ -12,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) @@ -35,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 @@ -81,6 +101,12 @@ def to_hash 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 ||= {} diff --git a/lib/userializer/has_many.rb b/lib/userializer/has_many.rb index 1d5293d..c073a4a 100644 --- a/lib/userializer/has_many.rb +++ b/lib/userializer/has_many.rb @@ -33,7 +33,7 @@ def merge_root(res, ser, opts) def entities(ser) ser.relation_value(@key) do - obj = ser.send(@key) || [] + obj = ser.read_attribute(@key) || [] @opts[:scope] ? obj.send(@opts[:scope]) : obj end diff --git a/lib/userializer/has_one.rb b/lib/userializer/has_one.rb index febd583..6da4ba5 100644 --- a/lib/userializer/has_one.rb +++ b/lib/userializer/has_one.rb @@ -39,7 +39,7 @@ def merge_root(res, ser, opts) end def entity(ser) - ser.relation_value(@key) { ser.send(@key) } + ser.relation_value(@key) { ser.read_attribute(@key) } end private 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