From 45d0950956ab14cea191979a4930074c51e74edc Mon Sep 17 00:00:00 2001 From: Weston Ganger Date: Thu, 27 Jun 2019 10:01:37 -0700 Subject: [PATCH] Fix with_scope for Section Blocks --- lib/locomotive/steam/liquid/drops/section.rb | 22 +++++++++- spec/unit/liquid/drops/section_spec.rb | 43 ++++++++++++++++++-- 2 files changed, 60 insertions(+), 5 deletions(-) diff --git a/lib/locomotive/steam/liquid/drops/section.rb b/lib/locomotive/steam/liquid/drops/section.rb index 428ce3e2..f20cad61 100644 --- a/lib/locomotive/steam/liquid/drops/section.rb +++ b/lib/locomotive/steam/liquid/drops/section.rb @@ -43,7 +43,7 @@ def anchor end def blocks - (@content['blocks'] || []).each_with_index.map do |block, index| + scoped_blocks.each_with_index.map do |block, index| SectionBlock.new(@section, block, index) end end @@ -52,6 +52,26 @@ def editor_setting_data SectionEditorSettingData.new(@section) end + private + + def scoped_blocks + val = (@content['blocks'] || []) + + if @context['with_scope'] + @context['with_scope_content_type'] ||= 'blocks' + + if @context['with_scope_content_type'] == 'blocks' + conditions = @context['with_scope'] || {} + + val = val.select do |block| + conditions.all?{|k,v| block[k] == v} + end + end + end + + val + end + end end diff --git a/spec/unit/liquid/drops/section_spec.rb b/spec/unit/liquid/drops/section_spec.rb index 1dc4d930..69f383c0 100644 --- a/spec/unit/liquid/drops/section_spec.rb +++ b/spec/unit/liquid/drops/section_spec.rb @@ -2,10 +2,25 @@ describe Locomotive::Steam::Liquid::Drops::Section do - let(:context) { ::Liquid::Context.new({}, {}, { locale: 'en' }) } - let(:settings) { [] } - let(:definition) { instance_double('SectionDefinition', definition: { 'settings' => settings }) } - let(:drop) { described_class.new(definition, content).tap { |d| d.context = context } } + let(:context) { ::Liquid::Context.new({}, {}, { locale: 'en' }) } + let(:settings) { [] } + let(:definition) { + instance_double('SectionDefinition', definition: { + 'settings' => settings, + 'blocks' => [{type: :foo}, {type: :bar}], + }) + } + let(:content) { + { + 'settings' => {}, + 'blocks' => [ + {'type' => 'foo'}, + {'type' => 'bar'}, + {'type' => 'foo'}, + ] + } + } + let(:drop) { described_class.new(definition, content).tap { |d| d.context = context } } describe 'text type setting' do @@ -23,4 +38,24 @@ end + describe '#blocks' do + subject { drop.send(:blocks).count } + + before { context['with_scope'] = {'type' => 'foo'} } + + it { is_expected.to eq 2 } + + context 'the with_scope has been used before by another and different content type' do + before { context['with_scope_content_type'] = 'articles' } + it { is_expected.to eq 3 } + end + + context 'the with_scope has been used before by the same content type' do + before { context['with_scope_content_type'] = 'blocks' } + it { is_expected.to eq 2 } + end + + end + + end