Skip to content

Commit

Permalink
Merge pull request #208 from tpltn/fix-field-exclusion
Browse files Browse the repository at this point in the history
fix field exclusion for views

Resolves #207
  • Loading branch information
philipqnguyen authored Apr 7, 2020
2 parents 87fe9e9 + 9ac260d commit 9dc6743
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 10 deletions.
24 changes: 14 additions & 10 deletions lib/blueprinter/view_collection.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,10 @@ def has_view?(view_name)
def fields_for(view_name)
return identifier_fields if view_name == :identifier

fields_hash = sortable_fields(view_name)
sorted_fields = sort_by_definition ? sort_by_def(view_name, fields_hash) : fields_hash.values.sort_by(&:name)
identifier_fields + sorted_fields
fields, excluded_fields = sortable_fields(view_name)
sorted_fields = sort_by_definition ? sort_by_def(view_name, fields) : fields.values.sort_by(&:name)

(identifier_fields + sorted_fields).reject { |field| excluded_fields.include?(field.name) }
end

def transformers(view_name)
Expand All @@ -42,20 +43,23 @@ def identifier_fields
views[:identifier].fields.values
end

# @param [String] view_name
# @return [Array<(Hash, Hash<String, NilClass>)>] fields, excluded_fields
def sortable_fields(view_name)
excluded_fields = {}
fields = views[:default].fields
fields = merge_fields(fields, views[view_name].fields)
views[view_name].included_view_names.each do |included_view_name|
if view_name != included_view_name
fields = merge_fields(fields, sortable_fields(included_view_name))
end
end
next if view_name == included_view_name

views[view_name].excluded_field_names.each do |name|
fields.delete(name)
view_fields, view_excluded_fields = sortable_fields(included_view_name)
fields = merge_fields(fields, view_fields)
excluded_fields.merge!(view_excluded_fields)
end

fields
views[view_name].excluded_field_names.each { |name| excluded_fields[name] = nil }

[fields, excluded_fields]
end

# select and order members of fields according to traversal of the definition_orders
Expand Down
27 changes: 27 additions & 0 deletions spec/integrations/shared/base_render_examples.rb
Original file line number Diff line number Diff line change
Expand Up @@ -672,4 +672,31 @@ def transform(result_hash, object, options={})

end

context 'field exclusion' do
let(:view) do
Class.new(Blueprinter::Base) do
view :exclude_first_name do
exclude :first_name
end

identifier :id
field :first_name
field :last_name

view :excluded do
field :middle_name
exclude :id
include_view :exclude_first_name
end
end
end
let(:excluded_view_keys) { %i[last_name middle_name] }
let(:blueprint) { view }

subject { blueprint.render_as_hash(object_with_attributes, view: :excluded).keys }

it 'excludes fields' do
should(eq(excluded_view_keys))
end
end
end

0 comments on commit 9dc6743

Please sign in to comment.