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.

First Post!

dimitarvp

dimitarvp

Just to make sure: those prefixes are not changing during runtime, correct?

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.

Where Next?

Popular in Questions 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
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
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
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New

Other popular topics Top

KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 36689 110
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
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
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
sergio
Kind of like when jquery came out, it was super necessary. Existing drag and drop libraries have a bunch of baggage to support old browse...
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