Sha256: b272eed831cbeac5d0c039236d57a2c1c5733cc20b5e2a525a5e5a236a8d88e2
Contents?: true
Size: 1.88 KB
Versions: 1
Compression:
Stored size: 1.88 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* # deprecated_values - deprecated options for *value*. Will warn of deprecation if not in production # # 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 # # With deprecations: # fetch_or_fallback([1,2], 3, 2, deprecated_values: [3]) => 3 # fetch_or_fallback([1,2], nil, 2, deprecated_values: [3]) => 2 module Primer # :nodoc: module FetchOrFallbackHelper mattr_accessor :fallback_raises, default: true InvalidValueError = Class.new(StandardError) def fetch_or_fallback(allowed_values, given_value, fallback = nil, deprecated_values: []) if allowed_values.include?(given_value) given_value elsif deprecated_values.include?(given_value) ActiveSupport::Deprecation.warn("#{given_value} is deprecated and will be removed in a future version.") unless Rails.env.production? 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 def fetch_or_fallback_boolean(given_value, fallback = false) if [true, false].include?(given_value) given_value else fallback end end end end
Version data entries
1 entries across 1 versions & 1 rubygems
Version | Path |
---|---|
primer_view_components-0.0.28 | app/lib/primer/fetch_or_fallback_helper.rb |