Looker
Hash based enumerated types (ENUMS)
Quick Start
gem install looker
Looker.add roles: {
:admin => 1,
:reader => 2,
:writer => 3
}
# The name (first Hash key) & value is converted
# to an upcase named frozen constant on the Looker module
Looker::ROLES[:admin] # => 1
Looker::ROLES["admin"] # => 1
Looker::ROLES[1] # => :admin
Looker::ROLES[:reader] # => 2
Looker::ROLES["reader"] # => 2
Looker::ROLES[2] # => :reader
Looker::ROLES[:writer] # => 3
Looker::ROLES["writer"] # => 3
Looker::ROLES[3] # => :writer
Looker::ROLES.name # => "roles"
Looker::ROLES.constant_name # => "ROLES"
Looker::ROLES.to_h # => {:admin=>1, :reader=>2, :writer=>3}
Multiple Enumerated Types
It's possible to add multiple enumerated types with a single call to Looker#add
.
Looker.add(
roles: {
:admin => 1,
:reader => 2,
:writer => 3
},
colors: {
:red => "ff0000",
:yellow => "ffff00",
:blue => "0000ff"
}
)
Looker::ROLES[:admin] # => 1
Looker::ROLES[3] # => :writer
Looker::COLORS[:red] # => "ff0000"
Looker::COLORS["ffff00"] # => :yellow
Adding Enumerated Types from YAML
It can be useful to manage enumerated type definitions with a YAML file.
# /path/to/enums.yml
roles:
admin: 1
reader: 2
writer: 3
colors:
red: ff0000
yellow: ffff00
blue: 0000ff
Looker.add YAML.load(File.read("/path/to/enums.yml")
Looker::ROLES["reader"] # => 2
Looker::ROLES[1] # => "admin"
Looker::COLORS["yellow"] # => "ffff00"
Looker::COLORS["0000ff"] # => "blue"
ActiveRecord enums
You may find it useful to reuse Looker defined enumerated types as ActiveRecord enums.
Fortunately this is pretty simple— just use the to_h
method on the Looker constant.
Looker.add roles: {
:admin => 1,
:reader => 2,
:writer => 3
}
class User < ActiveRecord::Base
enum roles: Looker::ROLES.to_h
end