Skip to content

Commit

Permalink
Prevent re-adding same transformers to the view all the time
Browse files Browse the repository at this point in the history
Signed-off-by: Pritilender <[email protected]>
  • Loading branch information
Pritilender committed Jan 19, 2024
1 parent a82f204 commit 20a9c18
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 3 deletions.
7 changes: 4 additions & 3 deletions lib/blueprinter/view_collection.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
11 changes: 11 additions & 0 deletions spec/benchmarks/ips_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions spec/units/view_collection_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 20a9c18

Please sign in to comment.