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



12
13
14
15
16
17
# File 'lib/alba/type.rb', line 12

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.



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

def auto_convert=(value)
  @auto_convert = value
end

#nameObject (readonly)

Returns the value of attribute name.



4
5
6
# File 'lib/alba/type.rb', line 4

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



38
39
40
41
# File 'lib/alba/type.rb', line 38

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



23
24
25
# File 'lib/alba/type.rb', line 23

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



32
33
34
# File 'lib/alba/type.rb', line 32

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