Clear ORM
Search…
Converters
Any type from PostgreSQL can be converted using converter objects. By default, Clear converts already the main type of PostgreSQL.
However, custom type may not be supported yet. Clear offers you the possibility to add a custom converter.

Declare a new converter

The example below with a converter for a Color structure should be straight-forward:
1
require "./base"
2
3
struct MyApp::Color
4
property r : UInt8 = 0
5
property g : UInt8 = 0
6
property b : UInt8 = 0
7
property a : UInt8 = 0
8
9
def to_s
10
# ...
11
end
12
13
def self.from_string(x : String)
14
# ...
15
end
16
17
def self.from_slice(x : Slice(UInt8))
18
# ...
19
end
20
end
21
22
class MyApp::ColorConverter
23
def self.to_column(x) : MyApp::Color?
24
case x
25
when Nil
26
nil
27
when Slice(UInt8)
28
MyApp::Color.from_slice(x)
29
when String
30
MyApp::Color.from_string(x)
31
else
32
raise "Cannot convert from #{x.class} to MyApp::Color"
33
end
34
end
35
36
def self.to_db(x : MyApp::Color?)
37
x.to_s #< css style output, e.g. #12345400
38
end
39
end
40
41
Clear::Model::Converter.add_converter("MyApp::Color", MyApp::ColorConverter)
Copied!
Then you can use your mapped type in your model:
1
class MyApp::MyModel
2
include Clear::Model
3
#...
4
column color : Color #< Automatically get the converter
5
end
Copied!

converter option

Optionally, you may want to use a converter which is not related to the type itself. To do so, you can pass the converter name as optional argument in the column declaration:
1
class MyApp::MyModel
2
include Clear::Model
3
#...
4
column s : String, converter: "my_custom_converter"
5
end
Copied!
By convention, converters which map struct and class directly are named using CamelCase, while converters which are not automatic should be named using the underscore notation.
Last modified 10mo ago