garrison

garrison

Global constants and pattern matching

A library I’m working on has a lot of functionality related to string prefixes (technically binaries, but they’re mostly strings). I have to add prefixes to keys a lot, and I have to pattern match them back off a lot.

Like:

defp prefix(key), do: "foo/" <> key
defp is_foo("foo/" <> key), do: true
defp is_foo(_key), do: false

And so on. But a lot of this functionality is embedded in application code, in anonymous functions, in Enum.maps, variable assignments, and so on. It’s everywhere.

I want to standardize these prefixes across the codebase going forward. They are already standardized, of course, but I have module attributes scattered across a couple dozen modules when I want them to be in one place.

There is, essentially, a lot of code like this, with the attributes duplicated across many modules:

@prefix "foo"
defp something(@prefix <> rest), do: rest

The docs recommend using public functions as constants instead of attributes, but this doesn’t work because I also need to use them for pattern matching everywhere.

I can think of two approaches off the top of my head:

First, use a module with a __using__ macro to inject the same set of attributes into every module. This would be acceptable for my use case, but it seems kinda cursed.

Second, replace the attributes with macros that inject the constants into the expressions. Essentially, the function-as-constant approach but with a macro instead. This sounds more sane to me, and is what I’ll probably do, but I figured I should seek some guidance in case I’ve overlooked something. This approach is conspicuously absent from the docs I linked.

Most Liked

cmo

cmo

I don’t hate the __using__ method for those cases that are truly global and/or want to be used in function heads.

It is a little less discoverable but it doesn’t take me too long to see the use MyModuleAttrubuteConstants at the top of the module and remember what I’ve done.

mudasobwa

mudasobwa

Creator of Cure

Use global public macros as constants then.

defmodule Prefixes do
  defmacro prefix(prefix \\ "foo", rest) do
    case __CALLER__.context do
      :match -> 
        quote generated: true, do: unquote(prefix) <> unquote(rest)
    end
  end
end

defmodule Usage do
  import Prefixes, only: [prefix: 1]

  def something(prefix(key)), do: key
end

Resulting in:

iex(2)> Usage.something "ggg"
** (FunctionClauseError) no function clause matching in Usage.something/1    
    
    The following arguments were given to Usage.something/1:
    
        # 1
        "ggg"
    
    iex:6: Usage.something/1
    iex:5: (file)
iex(5)> Usage.something "fooggg"
"ggg"
mudasobwa

mudasobwa

Creator of Cure

Well, Elixir macros are being expanded during compile-time and the AST they return is being directly injected into a resulting beam code. That said, the runtime would have zero impact compared to something("foo" <> rest) because _this is exactly the code the VM machine would see.

Duting the compilation time, yeah, it’ll gorge a couple of processor ticks, but you’d never notice this.

dimitarvp

dimitarvp

Then I would go for the __using__ approach but would not hard-code the values there; I’d make them part of the application’s config and just use Application.compile_env in the code that’s injected via the macro. That would help with the single source of truth problem.

garrison

garrison

This is contextual enough that I would not expect you to understand, but in this particular case the values are “implementation details” in such a way that using config seems like the wrong choice. It would be like defining magic numbers for a file format using config options - not quite right. These values are not going to change.

Anyway, I don’t love the __using__ approach because I feel like it’s less discoverable. At some point someone is going to read my code and wonder where @prefix came from, and it’s not going to be defined. I don’t like that.

If I use individual macros at least they will have a clear definition somewhere discoverable.

Where Next?

Popular in Questions Top

vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
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
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
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
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
Codball
Mix format works fine if run from the cmd. I’ve followed this to facilitate the implementation into VSC which involves downloading an ext...
New

Other popular topics Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
977 41022 311
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
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
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
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
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New

We're in Beta

About us Mission Statement