Skip to content

Instantly share code, notes, and snippets.

@BrianSigafoos
Created December 21, 2020 15:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BrianSigafoos/8bb5d619ad4c8a7735c117a4cd6b348b to your computer and use it in GitHub Desktop.
Save BrianSigafoos/8bb5d619ad4c8a7735c117a4cd6b348b to your computer and use it in GitHub Desktop.
Fetch or fallback for Rails ViewComponent
# frozen_string_literal: true
class ApplicationComponent < ViewComponent::Base
private
# Reference: https://www.youtube.com/watch?v=YVYRus_2KZM&t=302s
def fetch_or_fallback(allowed_values, given_value, fallback)
if allowed_values.include?(given_value)
given_value
else
if Rails.env.development?
raise ArgumentError.new(
"Value '#{given_value}' for #{self.class.name} is not allowed. " \
"Allowed values include: #{allowed_values}"
)
end
fallback
end
end
end
@BrianSigafoos
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment