From 20a9c18917b60120f1d244224a642df86672d4ae Mon Sep 17 00:00:00 2001 From: Pritilender Date: Fri, 19 Jan 2024 16:25:37 +0100 Subject: [PATCH] Prevent re-adding same transformers to the view all the time Signed-off-by: Pritilender --- lib/blueprinter/view_collection.rb | 7 ++++--- spec/benchmarks/ips_test.rb | 11 +++++++++++ spec/units/view_collection_spec.rb | 6 ++++++ 3 files changed, 21 insertions(+), 3 deletions(-) diff --git a/lib/blueprinter/view_collection.rb b/lib/blueprinter/view_collection.rb index 952aa5fd..e624a118 100644 --- a/lib/blueprinter/view_collection.rb +++ b/lib/blueprinter/view_collection.rb @@ -36,7 +36,7 @@ def fields_for(view_name) def transformers(view_name) included_transformers = gather_transformers_from_included_views(view_name).reverse - all_transformers = views[:default].view_transformers.concat(included_transformers).uniq + all_transformers = [*views[:default].view_transformers, *included_transformers].uniq all_transformers.empty? ? Blueprinter.configuration.default_transformers : all_transformers end @@ -94,11 +94,12 @@ def add_to_ordered_fields(ordered_fields, definition, fields, view_name_filter = def gather_transformers_from_included_views(view_name) current_view = views[view_name] - current_view.included_view_names.flat_map do |included_view_name| + already_included_transformers = current_view.included_view_names.flat_map do |included_view_name| next [] if view_name == included_view_name gather_transformers_from_included_views(included_view_name) - end.concat(current_view.view_transformers) + end + [*already_included_transformers, *current_view.view_transformers].uniq end end end diff --git a/spec/benchmarks/ips_test.rb b/spec/benchmarks/ips_test.rb index 00b00605..adcc5f22 100644 --- a/spec/benchmarks/ips_test.rb +++ b/spec/benchmarks/ips_test.rb @@ -9,8 +9,19 @@ class Blueprinter::IPSTest < Minitest::Test def setup @blueprinter = Class.new(Blueprinter::Base) do + transformer = Class.new(Blueprinter::Transformer) do + define_method :transform do |result_hash, _obj, _options| + { + foo: :bar, + **result_hash + } + end + end + field :id field :name + + transform transformer end @prepared_objects = 10.times.map {|i| OpenStruct.new(id: i, name: "obj #{i}")} end diff --git a/spec/units/view_collection_spec.rb b/spec/units/view_collection_spec.rb index 8ad5561c..cf86d74b 100644 --- a/spec/units/view_collection_spec.rb +++ b/spec/units/view_collection_spec.rb @@ -91,6 +91,12 @@ it 'should return both the view transformer and default transformers for the view' do expect(view_collection.transformers(:view)).to eq([default_transformer, transformer]) end + + it 'should not alter view transformers of the view on subsequent fetches' do + view_collection.transformers(:default) + expect { view_collection.transformers(:default) } + .not_to change(default_view.view_transformers, :count) + end end context 'include view transformer' do