Predefined Types

Predefined types are not shipped with enolib - they are provided as separate gems, for instance enotype.

There are two ways to use them:

Registering types globally

This is the preferred approach when you re-use types a lot - when you register a type it is made available through the native API.

require 'enolib'
require 'enotype'

loaders = Enotype.procs(:boolean, :color)
Enolib.register(loaders)

document = Enolib.parse('#b5b5b5: yes')

document.field('#b5b5b5').boolean_key # raises "A boolean is required - allowed values are 'true', 'false', 'yes' and 'no'."
document.field('#b5b5b5').color_key # returns '#b5b5b5'
document.field('#b5b5b5').required_boolean_value # returns true
document.field('#b5b5b5').required_color_value # raises "A color is required, for instance '#B6D918', '#fff' or '#01b'."

In this approach you take any of the content query methods in enolib and replace string with a type you have registered.

Supplying types with queries

This is essentially what's happening above as well, only under the hood. We'll see why this approach is sometimes preferable on the next page, when we define our own custom types.

require 'enolib'
require 'enotype'

loaders = Enotype.procs(:boolean, :color)
boolean = loaders[:boolean]
color = loaders[:color]

document = Enolib.parse('#b5b5b5: yes')

document.field('#b5b5b5').key(boolean) # raises "A boolean is required - allowed values are 'true', 'false', 'yes' and 'no'."
document.field('#b5b5b5').key(color) # returns '#b5b5b5'
document.field('#b5b5b5').required_value(boolean) # returns true
document.field('#b5b5b5').required_value(color) # raises "A color is required, for instance '#B6D918', '#fff' or '#01b'."

In this approach you remove string from any content query method and pass the type as a parameter instead.


Next page: Custom Types