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

Last Post!

beamologist

beamologist

Thank you so much, good sir! I will shamelessly steal this, but mention your name for the glory :slight_smile:

Where Next?

Popular in Questions Top

nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" =&gt; #BSON.ObjectId&lt;58eb1a7a9ad169198c3dXXXX&gt;, "email" =&gt; ...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New

Other popular topics Top

vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
985 44608 311
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New

We're in Beta

About us Mission Statement