• Stars
    star
    64
  • Rank 462,303 (Top 10 %)
  • Language
    Elixir
  • Created over 8 years ago
  • Updated about 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Enumerable type in Elixir

exnumerator

Enum type in Elixir known from Java or C#.

Build Status

Either in Java or in C# there is enum type available. It is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week. You should use enum types any time you need to represent a fixed set of constants. That includes natural enum types such as the planets in our solar system and data sets where you know all possible values at compile time—for example, the choices on a menu, command line flags, and so on.

See more:

Rationale

Imagine a question that can be either "pending”, "answered, or "flagged”. Or a phone number that’s a "home”, "office”, "mobile”, or "fax” (if it’s 1982).

Some models call for this kind of data. An attribute that can have only one of a few different values. And that set of values almost never changes. It’s a situation where, if it were plain Elixir, you’d just use an atom.

When it comes to a database though, you could create a PhoneNumberType or QuestionStatus table and a belongs_to relationship to hold these values, but that doesn’t seem worth it. You can use Ecto.Type behaviour for implementing custom types, but it expects 4 functions to be implemented, and it all becomes an overhead when you need to have many of custom enumerated types.

Here exnumerator steps in to give you a handy way to define enumerable types that can be used together with your database. They are kept as string type under the hood so whatever database you use (if not postgres for some reason) you can get full benefits from this library.

Installation

The package can be installed as:

def deps do
  [
    {:exnumerator, "~> 1.6"},
    # ...
  ]
end

Usage

This project is helpful if you have both ecto and postgrex in your project. It makes no sense to use it without a database.

Custom type

# VALUES as STRINGS
defmodule MyProject.Message.StatusAsString do
  use Exnumerator,
    values: ["sent", "read", "received", "delivered"]
end

# VALUES as ATOMS
defmodule MyProject.Message.StatusAsAtom do
  use Exnumerator,
    values: [:sent, :read, :received, :delivered]
end

# VALUES as KEYWORD
defmodule MyProject.Message.StatusAsKeyword do
  use Exnumerator,
    values: [sent: "S", read: "R", received: "RE", delivered: "D"]
end

Database migration

defmodule MyProject.Repo.Migrations.CreateMessage do
  use Ecto.Migration

  def change do
    create table(:messages) do
      add :status, :string
    end
  end
end

Database schema

defmodule MyProject.Message do
  use MyProject.Web, :schema

  schema "messages" do
    field :status, MyProject.Message.StatusAsString
  end
end

Operations

You can see all available values:

iex(1)> MyProject.Message.StatusAsString.values()
["sent", "read", "received", "delivered"]
iex(1)> MyProject.Message.StatusAsAtom.values()
[:sent, :read, :received, :delivered]
iex(1)> MyProject.Message.StatusAsKeyword.values()
[sent: "S", read: "R", received: "RE", delivered: "D"]

When you try to insert a record with some value that is not defined, you will get the following error:

# Status should be a String or an Atom, depending of what you use.

iex(1)> %MyProject.Message{status: "invalid"} |> MyProject.Repo.insert!()
** (Ecto.ChangeError) value `"invalid"` for `MyProject.Message.status`
   in `insert` does not match type MyProject.Message.status

You can also pick a random value from the predefined set:

iex(1)> MyProject.Message.StatusAsString.sample()
"delivered"

iex(1)> MyProject.Message.StatusAsAtom.sample()
:delivered

iex(1)> MyProject.Message.StatusAsKeyword.sample()
{:delivered, "D"}

You can pick the first value from the predefined set too:

iex(1)> MyProject.Message.StatusAsString.first()
"sent"

iex(1)> MyProject.Message.StatusAsAtom.first()
:sent

iex(1)> MyProject.Message.StatusAsKeyword.first()
{:sent, "S"}

Testing

To test this project you need to run:

mix test

More Repositories

1

yaml-elixir

Yaml parser for Elixir based on native Erlang implementation
Elixir
164
star
2

elixir-http-json-api

Minimal Elixir HTTP server with RESTful JSON API endpoint
Elixir
58
star
3

ex_wallet

A Bitcoin Wallet implementation in Elixir
Elixir
47
star
4

active_nothing

Ruby gem for emulating Smalltalk’s Conditionals in Ruby
Ruby
24
star
5

postgres-pubsub-elixir

PostgreSQL async notification via the LISTEN and NOTIFY in Elixir.
Elixir
21
star
6

healthchex

A set of Plugs to be used for Kubernetes healthchecks.
Elixir
19
star
7

k8s-gcp-terraform

Provisioning GKE with Terraform
HCL
18
star
8

circleci-cli

CLI for CircleCI REST API in Elixir lang
Elixir
15
star
9

ruby-tuples

Ruby implementation for tuples known from functional programming
Ruby
12
star
10

recurring_events

Recurring Events in Elixir
Elixir
10
star
11

Ansible-Ruby-DirectoryStatus

Ruby library for Ansible that checks given directory status
Ruby
10
star
12

figaro-elixir

Environmental variables manager based on Figaro for Elixir projects
Elixir
10
star
13

elixir-islands-engine

A simple game written in Elixir
Elixir
8
star
14

postgres-visualizer

PostgreSQL database visualizer with LucidChart
Shell
5
star
15

czy-i--na-wyk-ad

Algorytm decyzyjny pomagający zdecydować studentowi czy danego dnia należy pójść na wykład.
HTML
4
star
16

ansible-with-clojure

An example of Ansible module in Clojure
Shell
4
star
17

ex_postmark

Postmark adapter for sending template emails in Elixir
Elixir
4
star
18

cqs-in-elixir

An example of using CQS in Elixir
Elixir
4
star
19

ruby-motion-facebook

RubyMotion Facebook application
Ruby
4
star
20

ansible-playground

An example setup for Ansible automation
Nginx
4
star
21

ex_cors

An Elixir Plug-based CORS middleware for Phoenix Framework.
Elixir
3
star
22

elixir-api

Elixir API for frontend/mobile client
Elixir
3
star
23

ex_watcher

An Elixir file change watcher
Elixir
3
star
24

scala-vs-ruby

Comparison of Scala and Ruby examples
Scala
3
star
25

elixir_data_dog

A simple library for sending metrics to DataDog
Elixir
2
star
26

rabbit-elixir-ruby

A proof of concept - connecting Ruby with Elixir via RabbitMQ
Elixir
2
star
27

crystal-twitter-client

An example of Twitter client written in Crystal Language
Crystal
2
star
28

MS-RCPSP

Modeling Sheduling Problem in Constraint Programming
Scala
2
star
29

grpc-with-go

An example implementation of gRPC in Go
Go
2
star
30

ansible-dokku

Ansible infrastructure for Dokku installation
Vim Script
2
star
31

phoenix-skeleton

A reusable Phoenix framework application bootstrap
Elixir
1
star
32

rails-new-way

A new approach to designing Rails application
Ruby
1
star
33

Hexagonal-BasicAuth

BasicAuth using Hexagonal Architecture
JavaScript
1
star
34

Hexagonal-oAuth

oAuth using Hexagonal Architecture
JavaScript
1
star
35

CookiesOrStorage

Persistency library for saving Cookies with LocalStorage fallback
CoffeeScript
1
star
36

ex_luminati

An Elixir client for https://luminati.io/.
Elixir
1
star
37

crystal-examples

Examples for Crystal Language
Crystal
1
star
38

plug-validation

An example of validation in Elixir Plug layer.
Elixir
1
star
39

elixir-graphql-blog

A blog engine with Elixir & GraphQL API
Elixir
1
star
40

squid3-cache-proxies

Configuring squid3 with Ansible on Vagrant VMs
1
star
41

brunch-coffee-sass-chai-mocha-karma

Brunch.io with coffeescript and sass for development and karma with chai and mocha for tests.
CoffeeScript
1
star
42

StorageOrCookies

Persistency library for saving LocalStorage with Cookies fallback
CoffeeScript
1
star