Class: ViewComponentProps::Definition
- Inherits:
-
Object
- Object
- ViewComponentProps::Definition
- Defined in:
- lib/view_component_props/definition.rb
Constant Summary collapse
- OPTION_KEYS =
%i[ default fallback required cast enum validate description ].freeze
Instance Attribute Summary collapse
-
#description ⇒ Object
readonly
Returns the value of attribute description.
-
#key ⇒ Object
readonly
Returns the value of attribute key.
Instance Method Summary collapse
- #call(props, instance = nil) ⇒ Object
-
#initialize(key, options = {}, component:) ⇒ Definition
constructor
A new instance of Definition.
Constructor Details
#initialize(key, options = {}, component:) ⇒ Definition
Returns a new instance of Definition.
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/view_component_props/definition.rb', line 17 def initialize(key, = {}, component:) @key = key @options = @component = component cast = normalize_cast(@options[:cast]) @caster = build_caster(cast) @cast_label = describe_cast(cast) @required = @options[:required] || false @enum = @options[:enum] @validate = @options[:validate] @default = @options[:default] @fallback = @options[:fallback] @description = @options[:description] end |
Instance Attribute Details
#description ⇒ Object (readonly)
Returns the value of attribute description.
15 16 17 |
# File 'lib/view_component_props/definition.rb', line 15 def description @description end |
#key ⇒ Object (readonly)
Returns the value of attribute key.
15 16 17 |
# File 'lib/view_component_props/definition.rb', line 15 def key @key end |
Instance Method Details
#call(props, instance = nil) ⇒ Object
35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/view_component_props/definition.rb', line 35 def call(props, instance = nil) value = evaluate(props, instance) casted_value = cast_value(value) raise RequiredPropError, "Required prop :#{@key} for #{@component} cannot be nil" if casted_value.nil? && @required return casted_value if casted_value.nil? raise InvalidEnumValueError, "Prop :#{@key} for #{@component} must be one of #{@enum.inspect}, got #{casted_value.inspect}" if @enum && !@enum.include?(casted_value) raise ValidationFailedError, "Prop :#{@key} for #{@component} failed validation, got #{casted_value.inspect}" if @validate && !@validate.call(casted_value) casted_value end |