Sha256: dc330a9307b0a8b690cc710e1a5564821bf002524f9be624b56ab2855cf49216

Contents?: true

Size: 1.21 KB

Versions: 13

Compression:

Stored size: 1.21 KB

Contents

# frozen_string_literal: true

# Primer::FetchOrFallbackHelper
# A little helper to enable graceful fallbacks
#
# Use this helper to quietly ensure a value is
# one that you expect:
#
# allowed_values  - allowed options for *value*
# given_value     - input being coerced
# fallback        - returned if *given_value* is not included in *allowed_values*
#
# fetch_or_fallback([1,2,3], 5, 2) => 2
# fetch_or_fallback([1,2,3], 1, 2) => 1
# fetch_or_fallback([1,2,3], nil, 2) => 2
module Primer
  module FetchOrFallbackHelper
    mattr_accessor :fallback_raises, default: true

    InvalidValueError = Class.new(StandardError)

    def fetch_or_fallback(allowed_values, given_value, fallback = nil)
      if allowed_values.include?(given_value)
        given_value
      else
        if fallback_raises && ENV["RAILS_ENV"] != "production" && ENV["STORYBOOK"] != "true"
          raise InvalidValueError, <<~MSG
            fetch_or_fallback was called with an invalid value.

            Expected one of: #{allowed_values.inspect}
            Got: #{given_value.inspect}

            This will not raise in production, but will instead fallback to: #{fallback.inspect}
          MSG
        end

        fallback
      end
    end
  end
end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
primer_view_components-0.0.16 lib/primer/fetch_or_fallback_helper.rb
primer_view_components-0.0.15 lib/primer/fetch_or_fallback_helper.rb
primer_view_components-0.0.14 lib/primer/fetch_or_fallback_helper.rb
primer_view_components-0.0.13 lib/primer/fetch_or_fallback_helper.rb
primer_view_components-0.0.12 lib/primer/fetch_or_fallback_helper.rb
primer_view_components-0.0.11 lib/primer/fetch_or_fallback_helper.rb
primer_view_components-0.0.10 lib/primer/fetch_or_fallback_helper.rb
primer_view_components-0.0.9 lib/primer/fetch_or_fallback_helper.rb
primer_view_components-0.0.8 lib/primer/fetch_or_fallback_helper.rb
primer_view_components-0.0.7 lib/primer/fetch_or_fallback_helper.rb
primer_view_components-0.0.6 lib/primer/fetch_or_fallback_helper.rb
primer_view_components-0.0.5 lib/primer/fetch_or_fallback_helper.rb
primer_view_components-0.0.4 lib/primer/fetch_or_fallback_helper.rb