benperiton

benperiton

Shared module constants

Hi,

I’m porting an old PHP application over to Elixir and Phoenix, and I’m struggling to figure out the best way to transfer the constants that currently exist.

At the moment there are multiple files with various constants used throughout the app, for instance:

<?php
namespace Shared\Consts;

class System
{
    const AUDIT_ENTITY_REV_TYPE_DELETE = 301001;
    const AUDIT_ENTITY_REV_TYPE_INSERT = 301002;
    const AUDIT_ENTITY_REV_TYPE_UPDATE = 301003;
    const AUDIT_LOG_ACTION_CREATE = 301004;
    const AUDIT_LOG_ACTION_CUSTOM = 301005;
    const AUDIT_LOG_ACTION_DELETE = 301006;
    const AUDIT_LOG_ACTION_EDIT = 301007;
   
    const SOURCE_LVL1_API = 301023; 
    const SOURCE_LVL1_HTTP = 301024;
    const SOURCE_LVL1_EMAIL = 301025;
    const SOURCE_LVL1_SMS = 301026;
    const SOURCE_LVL1_UNKNOWN = 301027;

    const SOURCE_LVL2_STAFF_PANEL = 301028;
    const SOURCE_LVL2_STAFF_APP = 301029;
    const SOURCE_LVL2_RESELLER_PANEL = 301030;
    const SOURCE_LVL2_RESELLER_APP = 301031;
    const SOURCE_LVL2_AFFILIATE_PANEL = 301032;
    const SOURCE_LVL2_CUSTOMER_PANEL = 301033;
    const SOURCE_LVL2_CUSTOMER_APP = 301034;
    const SOURCE_LVL2_UNKNOWN = 301035;
}

Then in other files I can do:

<?php
use Shared\Const\System as SysConst;

if (SysConst::SOURCE_LVL1_API === $someOtherVariable)
{
    echo 'Starts at API';
}

Is there a way to do something similar in Elixir? Or is there a better way to store lots of constants that could be the same name, but relate to different areas?

Most Liked

smpallen99

smpallen99

I have a macro for reusing constants across multiple modules. The benefit being that they work in matches and in guards.

defmodule Constants do
  @moduledoc """
  An alternative to use @constant_name value approach to defined reusable 
  constants in elixir. 

  This module offers an approach to define these in a
  module that can be shared with other modules. They are implemented with 
  macros so they can be used in guards and matches

  ## Examples: 

  Create a module to define your shared constants

      defmodule MyConstants do
        use Constants

        define something,   10
        define another,     20
      end

  Use the constants

      defmodule MyModule do
        require MyConstants
        alias MyConstants, as: Const

        def myfunc(item) when item == Const.something, do: Const.something + 5
        def myfunc(item) when item == Const.another, do: Const.another
      end

  """
  
 defmacro __using__(_opts) do
    quote do
      import Constants
    end
  end

  @doc "Define a constant"
  defmacro constant(name, value) do
    quote do
      defmacro unquote(name), do: unquote(value)
    end
  end

  @doc "Define a constant. An alias for constant"
  defmacro define(name, value) do
    quote do
      constant unquote(name), unquote(value)
    end
  end
end
16
Post #6
sasajuric

sasajuric

Author of Elixir In Action

I would definitely go for the approach from @michalmuskala. One problem with maps is that it only supports one way conversion (converting a const into an integer). If you need to convert an integer into a const, you’ll have to build a reversal map. This can be easily done, even during compilation time, but then the code becomes as complex if not more than Michal’s version.

Moreover, I’m not completely sure whether this map is stored in the so called “constant pool”, and if it’s not, then the performance might suck. But even if this is not the case, my previous point stands, and I would personally go for Michal’s solution.

Using that approach, you could have something like:

defmodule Const do
  # Michal's snippet:
  values = [source_lvl1_api: 301023, ...]
  for {key, value} <- values do
    def encode(unquote(key)),   do: unquote(value)
    def decode(unquote(value)), do: unquote(key)
  end
end

And now you can do e.g. Const.encode(:source_lvl1_api), or Const.decode(301023) to perform atom ↔ integer conversions.

So what Michal is trying to tell you is that as soon as you take some input from say HTTP request, or the database, you invoke Const.decode to convert it into an atom. Then in the rest of your code, you just deal with atoms (e.g. :source_lvl1_api), so the code is ridden of magical numbers. Likewise, if you need to send a response to some client, or store to the database, you perform Const.encode to convert the atom into a corresponding integer.

michalmuskala

michalmuskala

The usual approach would be to use atoms inside the system, e.g. :source_lvl1_api and convert to/from integer encoding on the system boundary, if needed. This makes it easy for debugging and introspection since at runtime you have readable atoms, instead of opaque integer values flying around. You can generate the conversion functions easily with a sprinkle of macros:

values = [source_lvl1_api: 301023, ...]
for {key, value} <- values do
  def encode(unquote(key)),   do: unquote(value)
  def decode(unquote(value)), do: unquote(key)
end
OvermindDL1

OvermindDL1

You can also store it into a map that is returned from a function like this:

def Consts, do: %{
  AUDIT_ENTITY_REV_TYPE_DELETE: 301001,
  AUDIT_ENTITY_REV_TYPE_INSERT: 301002,
  ...
}

Being a constant object in the code with no variables it gets constructed fast, however usual things in Erlang/Elixir get optimized into the bytecode so no construction actually takes place and it gets shared easily, I’m not sure if maps do that however.

Overall @michalmuskala method is usually best, no construction time at all, however the lookup time can be linear in a match set like that so a map might be faster in lookup speed.

michalmuskala

michalmuskala

Using such macros has still the same issue - you have opaque integers passing around at runtime - this makes it really hard to debug issues, especially if dealing with large numbers.

As to when do conversions - I spoke about boundaries of the system. By that I mean every time we receive data from outside or send it out - this means params from requests, database responses, etc. For example, when using ecto, you can provide a custom type to do the conversions for you (assuming encode and decode functions as before):

defmodule Constant do
  @behaviour Ecto.Type

  def type, do: :integer

  def cast(int) when is_integer(int), do: {:ok, decode(value)}
  def cast(atom) when is_atom(atom), do: {:ok, atom)
  def cast(_), do: :error

  def load(int) when is_integer(int), do: {:ok, decode(value)}
  def load(_), do: :error

  def dump(atom) when is_atom(atom), do: {:ok, encode(value)}
  def dump(_), do: :error
end

Where Next?

Popular in Questions Top

minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
pgiesin
This should be a simple problem but I just can’t seem to figure it out. I have a standalone Elixir app that won’t find the database. Dep...
New
Kagamiiiii
Student &amp; New to elixir. Nice language. I want to convert a english character, e.g. “a”, which is stored in a variable, to it’s asci...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
makeitrein
Hey all, just started picking up Elixir last week and am writing a scraper as a learning project. Baby step #1 is extracting the number ...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
hpopp
To simplify some tasks at work, I wrote and published this package yesterday. It’s a simple macro that enables Access behaviour on struct...
New

Other popular topics Top

lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1140 51847 244
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
sergio
I couldn’t find any guides that worked well with Phoenix 1.6.0 and esbuild. I hope this helps people test the waters and eases you into t...
New
AstonJ
You’re a programmer, so you don’t need spoon feeding with the conventional drivel about “this is an integer.” No. You need to know what’s...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 35421 110
New
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New

We're in Beta

About us Mission Statement