Class: Jsapi::Meta::Attributes::TypeCaster

Inherits:
Object
  • Object
show all
Defined in:
lib/jsapi/meta/attributes/type_caster.rb

Constant Summary collapse

STRING_CASTER =

:nodoc:

->(arg) { arg&.to_s }
SYMBOL_CASTER =

:nodoc:

->(arg) { # :nodoc:
  return if arg.nil?

  arg = arg.to_s unless arg.respond_to?(:to_sym)
  arg.to_sym
}

Instance Method Summary collapse

Constructor Details

#initialize(klass, name: 'value', values: nil) ⇒ TypeCaster

Creates a new type caster for klass.



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/jsapi/meta/attributes/type_caster.rb', line 17

def initialize(klass, name: 'value', values: nil)
  @caster =
    case klass.name
    when 'String'
      STRING_CASTER
    when 'Symbol'
      SYMBOL_CASTER
    else
      ->(arg) {
        return arg if arg.is_a?(klass)
        return klass.from(arg) if klass.respond_to?(:from)
        return klass.new if arg.nil?

        klass.new(arg)
      }
    end
  @values = values
  @name = name
end

Instance Method Details

#cast(value) ⇒ Object

Casts value. Raises an InvalidArgumentError if the (casted) value is invalid.



39
40
41
42
43
44
# File 'lib/jsapi/meta/attributes/type_caster.rb', line 39

def cast(value)
  casted_value = @caster.call(value)
  return casted_value unless @values&.exclude?(casted_value)

  raise InvalidArgumentError.new(@name, casted_value, @values)
end