Skip to content

Instantly share code, notes, and snippets.

@etozzato
Last active February 3, 2020 09:31
Show Gist options
  • Save etozzato/2d4999e8d3ad3be6a4244e3ab5302f2b to your computer and use it in GitHub Desktop.
Save etozzato/2d4999e8d3ad3be6a4244e3ab5302f2b to your computer and use it in GitHub Desktop.
Implement this: WithFallbackConcern
# frozen_string_literal: true
FactoryBot.define do
factory :sample do
identifier { SecureRandom.uuid }
traceability_sample { 'AA123456789' }
traceability_batch { nil }
end
end
# frozen_string_literal: true
require 'rails_helper'
describe Sample, type: :model do
let(:sample) { FactoryBot.build(:sample) }
context '#with_fallback' do
it 'has a functional with_fallback methods' do
expect(sample).to respond_to(:traceability_sample)
expect(sample.traceability_sample).to eq('AA123456789')
expect(sample).to respond_to(:traceability_batch)
expect(sample.traceability_batch).to be_nil
expect(sample).not_to respond_to(:traceability_license)
expect(
sample.with_fallback(
:traceability_license,
:traceability_batch,
:traceability_sample
)
).to eq('AA123456789')
end
end
end
# frozen_string_literal: true
#
# Implement #with_fallback to use this as
# obj.with_fallback(meth_1, meth_2, ...)
# where the first valid method that does not
# return nil is returned
# sample.traceability_sample => "AA123456789"
# sample.traceability_batch => nil
# sample.traceability_license => NoMethodError
# sample.with_fallback(:traceability_sample, :traceability_batch, :traceability_license) => "AA123456789"
#
module WithFallbackConcern
extend ActiveSupport::Concern
def with_fallback
raise StandardError, 'not implemented'
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment