From ee7d6089741c8d59b3922e781a577e1a0596b2f8 Mon Sep 17 00:00:00 2001 From: Hugo Peixoto Date: Wed, 15 May 2019 10:05:00 +0100 Subject: [PATCH] Add :extractor option to ::association --- lib/blueprinter/base.rb | 5 ++++- spec/integrations/base_spec.rb | 19 +++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/lib/blueprinter/base.rb b/lib/blueprinter/base.rb index 0ccdfcb6..49fcfc6f 100644 --- a/lib/blueprinter/base.rb +++ b/lib/blueprinter/base.rb @@ -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 diff --git a/spec/integrations/base_spec.rb b/spec/integrations/base_spec.rb index 8a1d6255..247d6fd3 100644 --- a/spec/integrations/base_spec.rb +++ b/spec/integrations/base_spec.rb @@ -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