Class: ViewComponentProps::Definition

Inherits:
Object
  • Object
show all
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

Instance Method Summary collapse

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, options = {}, component:)
  @key = key
  @options = options
  @component = component

  validate_options!

  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

#descriptionObject (readonly)

Returns the value of attribute description.



15
16
17
# File 'lib/view_component_props/definition.rb', line 15

def description
  @description
end

#keyObject (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

Raises:



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