Class: Alba::TypedAttribute

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

Overview

Representing typed attributes to encapsulate logic about types

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name:, type:, converter:, &block) ⇒ 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, true, false, nil)


12
13
14
15
16
17
18
19
20
21
22
# File 'lib/alba/typed_attribute.rb', line 12

def initialize(name:, type:, converter:, &block)
  @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
  @block = block
end

Instance Attribute Details

#nameSymbol, String (readonly)

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:

  • (Symbol, String)


7
8
9
# File 'lib/alba/typed_attribute.rb', line 7

def name
  @name
end

Instance Method Details

#display_value_for(value) ⇒ 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.

Parameters:

  • value (Object)

Returns:

  • (String)


35
36
37
# File 'lib/alba/typed_attribute.rb', line 35

def display_value_for(value)
  value.nil? ? 'nil' : value.class.name
end

#value(object: nil) {|arg0| ... } ⇒ 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.

Yields:

Yield Parameters:

  • arg0 (Symbol, String)

Yield Returns:

  • (Object)

Returns:

  • (String, Integer, Boolean)

    type-checked or type-converted object



25
26
27
28
29
30
31
# File 'lib/alba/typed_attribute.rb', line 25

def value(object: nil)
  v = @block ? @block.call(object) : yield(@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