diff --git a/lib/holdings.rb b/lib/holdings.rb index 8a4034652..5992884ea 100644 --- a/lib/holdings.rb +++ b/lib/holdings.rb @@ -19,10 +19,13 @@ def find_by_barcode(barcode) end end def preferred_callnumber - @preferred_callnumber ||= if @document[:preferred_barcode] - find_by_barcode(@document[:preferred_barcode]) - else - callnumbers.first + @preferred_callnumber ||= begin + if @document[:preferred_barcode] && + (found_callnumber = find_by_barcode(@document[:preferred_barcode])).present? + found_callnumber + else + callnumbers.first + end end end def present? diff --git a/spec/lib/holdings_spec.rb b/spec/lib/holdings_spec.rb index 15a167aca..bd1bb188c 100644 --- a/spec/lib/holdings_spec.rb +++ b/spec/lib/holdings_spec.rb @@ -106,6 +106,17 @@ ) ) } + let(:bad_preferred) { + Holdings.new( + SolrDocument.new( + preferred_barcode: 'does-not-exist', + item_display: [ + '54321 -|- GREEN -|- STACKS -|- -|- -|- -|- -|- -|- callnumber1 -|- 1', + '12345 -|- GREEN -|- STACKS -|- -|- -|- -|- -|- -|- callnumber2 -|- 2' + ] + ) + ) + } let(:no_preferred) { Holdings.new( SolrDocument.new( @@ -119,6 +130,9 @@ it 'should return the callnumber based on preferred barcode' do expect(preferred.preferred_callnumber.barcode).to eq '12345' end + it 'should return the first callnumber when the preferred barcode does not exist in the holdings' do + expect(bad_preferred.preferred_callnumber.barcode).to eq '54321' + end it 'should return the first callnumber if there is no preferred barcode available' do expect(no_preferred.preferred_callnumber.barcode).to eq '54321' end