Module: Polaris::FetchOrFallbackHelper

Included in:
Component
Defined in:
app/helpers/polaris/fetch_or_fallback_helper.rb

Overview

:nodoc:

Constant Summary collapse

InvalidValueError =
Class.new(StandardError)

Instance Method Summary collapse

Instance Method Details

#fetch_or_fallback(allowed_values, given_value, fallback = nil, deprecated_values: nil, allow_nil: false) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'app/helpers/polaris/fetch_or_fallback_helper.rb', line 28

def fetch_or_fallback(allowed_values, given_value, fallback = nil, deprecated_values: nil, allow_nil: false)
  return if allow_nil && given_value.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

#fetch_or_fallback_boolean(given_value, fallback = false) ⇒ Object



47
48
49
50
51
52
53
# File 'app/helpers/polaris/fetch_or_fallback_helper.rb', line 47

def fetch_or_fallback_boolean(given_value, fallback = false)
  if [true, false].include?(given_value)
    given_value
  else
    fallback
  end
end

#fetch_or_fallback_nested(allowed_keys, allowed_values, given_value) ⇒ Object



55
56
57
58
59
60
61
62
63
# File 'app/helpers/polaris/fetch_or_fallback_helper.rb', line 55

def fetch_or_fallback_nested(allowed_keys, allowed_values, given_value)
  if given_value.is_a?(Hash)
    given_value.each_with_object({}) do |(key, value), hash|
      hash[fetch_or_fallback(allowed_keys, key)] = fetch_or_fallback(allowed_values, value)
    end
  else
    fetch_or_fallback(allowed_values, given_value)
  end
end