Skip to content

Commit

Permalink
Merge pull request #152 from hugopeixoto/feature/add-association-extr…
Browse files Browse the repository at this point in the history
…actor-as-an-option

Add :extractor option to ::association
  • Loading branch information
philipqnguyen authored May 23, 2019
2 parents 4df6de7 + ee7d608 commit da0ebb0
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
5 changes: 4 additions & 1 deletion lib/blueprinter/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,10 @@ def self.association(method, options = {}, &block)

field(
method,
options.merge(association: true, extractor: AssociationExtractor.new),
options.merge(
association: true,
extractor: options.fetch(:extractor) { AssociationExtractor.new },
),
&block
)
end
Expand Down
19 changes: 19 additions & 0 deletions spec/integrations/base_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,25 @@ def blueprint
end
it { expect{subject}.to raise_error(Blueprinter::BlueprinterError) }
end

context 'Given an association :extractor option' do
let(:result) { '{"id":' + obj_id + ',"vehicles":[{"make":"SUPER CAR"}]}' }
let(:blueprint) do
extractor = Class.new(Blueprinter::Extractor) do
def extract(association_name, object, _local_options, _options={})
object.send(association_name).map { |vehicle| { make: vehicle.make.upcase } }
end
end

vehicle_blueprint = Class.new(Blueprinter::Base) { fields :make }

Class.new(Blueprinter::Base) do
field :id
association :vehicles, blueprint: vehicle_blueprint, extractor: extractor
end
end
it('returns json derived from a custom extractor') { should eq(result) }
end
end

context "Given association is nil" do
Expand Down

0 comments on commit da0ebb0

Please sign in to comment.