Created
December 21, 2020 15:38
-
-
Save BrianSigafoos/8bb5d619ad4c8a7735c117a4cd6b348b to your computer and use it in GitHub Desktop.
Fetch or fallback for Rails ViewComponent
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Source: https://www.youtube.com/watch?v=YVYRus_2KZM&t=302s