Sha256: a073268448e47b09e3917bf429c841d49fa8879d47cb78590b4e5fd972f110e0
Contents?: true
Size: 1.08 KB
Versions: 3
Compression:
Stored size: 1.08 KB
Contents
# frozen_string_literal: true module Alba # Representing typed attributes to encapsulate logic about types # @api private class TypedAttribute # @param name [Symbol, String] # @param type [Symbol, Class] # @param converter [Proc] 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 # @param object [Object] target to check and convert type with # @return [String, Integer, Boolean] type-checked or type-converted object 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 private def display_value_for(value) value.nil? ? 'nil' : value.class.name end end end
Version data entries
3 entries across 3 versions & 1 rubygems
Version | Path |
---|---|
alba-3.3.2 | lib/alba/typed_attribute.rb |
alba-3.3.1 | lib/alba/typed_attribute.rb |
alba-3.3.0 | lib/alba/typed_attribute.rb |