Class: Alba::Type

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

Overview

Representing type itself, combined with TypedAttribute

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, check:, converter:, auto_convert: false) ⇒ Type

Returns a new instance of Type.

Parameters:

  • name (Symbol, String)

    name of the type

  • check (Proc, Boolean)

    proc to check type If false, type check is skipped

  • converter (Proc)

    proc to convert type

  • auto_convert (Boolean) (defaults to: false)

    whether to convert type automatically



14
15
16
17
18
19
# File 'lib/alba/type.rb', line 14

def initialize(name, check:, converter:, auto_convert: false)
  @name = name
  @check = check
  @converter = converter
  @auto_convert = auto_convert
end

Instance Attribute Details

#auto_convert=(value) ⇒ Object (writeonly)

Sets the attribute auto_convert

Parameters:

  • value

    the value to set the attribute auto_convert to.



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

def auto_convert=(value)
  @auto_convert = value
end

#nameObject (readonly)

Returns the value of attribute name.



6
7
8
# File 'lib/alba/type.rb', line 6

def name
  @name
end

Instance Method Details

#auto_convert_with(converter) ⇒ Object

Enable auto convert with given converter

Parameters:

  • converter (Proc)

    proc to convert type



40
41
42
43
# File 'lib/alba/type.rb', line 40

def auto_convert_with(converter)
  @converter = converter
  @auto_convert = true
end

#check(value) ⇒ Boolean

Type check

Parameters:

  • value (Object)

    value to check

Returns:

  • (Boolean)

    the result of type check



25
26
27
# File 'lib/alba/type.rb', line 25

def check(value)
  @check == false ? false : @check.call(value)
end

#convert(obj) ⇒ Object

Type convert If @auto_convert is true, @convert proc is called with obj Otherwise, it raises an exception that is caught by Alba::TypedAttribute

Parameters:

  • obj (Object)

    object to convert



34
35
36
# File 'lib/alba/type.rb', line 34

def convert(obj)
  @auto_convert ? @converter.call(obj) : raise(TypeError)
end