Clear ORM
Search…
Enums
Clear offers support of PG enum.
To define an enum, use the Clear.enum method:
1
# Define the enum
2
Clear.enum Gender, "male", "female"
Copied!
This will create a new record called MyApp::Gender, which contains the constants Male and Female.

Validation, assignation

You can use the new type directly in your model:
1
class User
2
include Clear::Model
3
#...
4
5
column gender : Gender
6
end
Copied!
Assignation cannot be made from string, but instead from constants:
1
u = User.new
2
u.gender = MyApp::Gender::Male
Copied!
List of helpers are present for validation and conversion from/to string:
1
MyApp::Gender.authorized_values # < return ["male", "female"]
2
MyApp::Gender.all # < return [MyApp::Gender::Male, MyApp::Gender::Female]
3
4
MyApp::Gender::Female.to_s # Return "female"
5
6
MyApp::Gender.from_string("male") # < return MyApp::Gender::Male
7
MyApp::Gender.from_string("unknown") # < throw Clear::IllegalEnumValueError
8
9
MyApp::Gender.valid?("female") #< Return true
10
MyApp::Gender.valid?("unknown") #< Return false
Copied!

Migration

1
class MyMigration1
2
include Clear::Migration
3
4
def change(dir)
5
create_enum("gender", %w(male female))
6
end
7
end
Copied!
Last modified 2yr ago