Class: Alba::TypedAttribute Private

Inherits:
Object
  • Object
show all
Defined in:
lib/alba/typed_attribute.rb

Overview

This class is part of a private API. You should avoid using this class if possible, as it may be removed or be changed in the future.

Representing typed attributes to encapsulate logic about types

Instance Method Summary collapse

Constructor Details

#initialize(name:, type:, converter:) ⇒ TypedAttribute

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns a new instance of TypedAttribute.

Parameters:

  • name (Symbol, String)
  • type (Symbol, Class)
  • converter (Proc)


8
9
10
11
12
13
14
15
16
17
# File 'lib/alba/typed_attribute.rb', line 8

def initialize(name:, type:, converter:)
  @name = name
  t = Alba.find_type(type)
  @type = case converter
          when true then t.dup.tap { _1.auto_convert = true }
          when false, nil then t
          else
            t.dup.tap { _1.auto_convert_with(converter) }
          end
end

Instance Method Details

#value(object) ⇒ String, ...

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns type-checked or type-converted object.

Parameters:

  • object (Object)

    target to check and convert type with

Returns:

  • (String, Integer, Boolean)

    type-checked or type-converted object



21
22
23
24
25
26
27
# File 'lib/alba/typed_attribute.rb', line 21

def value(object)
  v = object.__send__(@name)
  result = @type.check(v)
  result ? v : @type.convert(v)
rescue TypeError
  raise TypeError, "Attribute #{@name} is expected to be #{@type.name} but actually #{display_value_for(v)}."
end