notexactlyawe

notexactlyawe

I can’t seem to pass an anonymous function as an option to a Plug. I am using plug_hmouse which from the documentation takes an option digest that is a function to be called on a string. The example is provided below:

plug PlugHMouse,
  ... # other options
  digest: fn string -> Base.encode16(string) end

However when I try this in my router.ex, I get the following error:

router.ex

plug PlugHMouse,
  validate: {"x-hub-signature", webhook_secret},
  hash_algo: :sha,
  split_digest: true,
  digest: fn string -> Base.encode16(string, :lower) end

error

== Compilation error in file lib/spellcanary_web/router.ex ==
** (ArgumentError) cannot escape #Function<0.85932033 in file:lib/spellcanary_web/router.ex>. The supported values are: lists, tuples, maps, atoms, numbers, bitstrings, PIDs and remote functions in the format &Mod.fun/arity
    (elixir) src/elixir_quote.erl:122: :elixir_quote.argument_error/1
    (elixir) src/elixir_quote.erl:259: :elixir_quote.do_quote/3
    (elixir) src/elixir_quote.erl:421: :elixir_quote.do_quote_splice/5
    (plug) lib/plug/builder.ex:312: Plug.Builder.init_module_plug/4
    (plug) lib/plug/builder.ex:286: anonymous fn/5 in Plug.Builder.compile/3
    (elixir) lib/enum.ex:1940: Enum."-reduce/3-lists^foldl/2-0-"/3
    (plug) lib/plug/builder.ex:284: Plug.Builder.compile/3
    lib/spellcanary_web/router.ex:17: (module)
    (stdlib) erl_eval.erl:680: :erl_eval.do_apply/6
    (elixir) lib/kernel/parallel_compiler.ex:208: anonymous fn/4 in Kernel.ParallelCompiler.spawn_workers/6

I don’t get this error when passing &Base.encode16/1 but I do get it when using an anonymous function or when defining a function in my router and passing that, eg.

def encode16lower(string) do
  Base.encode16(string, :lower)
end

...
plug PlugHMouse,
  validate: {"x-hub-signature", webhook_secret},
  hash_algo: :sha,
  split_digest: true,
  digest: &self().encode16lower/1

I need the anonymous function since I want to add an extra argument to the function I’m calling. How can I get around this error?

Showing Posts 1 to 9

NobbZ

NobbZ

Module attributes can not contain anonymous functions. They may only contain a very strict subset of values. Whereas &Mod.fun/arit is one of these.

&self().encode16lower/1

self() does not return a module name, but a PID. Probably you meant __MODULE__.encode16lower/1?

notexactlyawe

notexactlyawe OP

Thanks NobbZ, the __MODULE__ tip fixed the error! I didn’t realise that calling plug would create a module attribute. For anyone reading this thread in future, the docs on Module attributes actually have some info on this.

budgie

budgie

I don’t really understand this. Having this same issue, not sure how to go about solving it. I want to be able to dynamically define redirect behaviour. What do you mean about the module attributes?

I have this plug:

  @moduledoc """
  Redirects the path to one location or another depending on handler return value.
  """

  def init(default), do: default

  def call(conn, opts) do
    handler = Keyword.fetch!(opts, :handler)

    destination = handler.(conn)

    Phoenix.Controller.redirect(conn, to: destination)
  end

But I can’t use it like expected:

get "/work", Plugs.Redirect, handler: fn conn -> nil end

Because I get the error cannot escape #Function<0.92307874/1 in :elixir_compiler_158.__MODULE__/1>. The supported values are: lists, tuples, maps, atoms, numbers, bitstrings, PIDs and remote functions in the format &Mod.fun/arity. Not quite sure what this is telling me and how I can solve it. For such simple implementations I try to keep the definition as close to the usage as possible to facilitate understanding, but not sure how I can do that if I can’t use an anonymous function.

al2o3cr

al2o3cr

The issue is that Plug pre-compiles the stack of plugs, so the init function is called at compile time and its result is stored in the compiled module.

As the error message states, that place can’t store anonymous functions.

The “standard idiom” for this situation is to use a tuple to specify a function by name (you’ll see the term “MFA tuple” a lot). Something like:

# in the plug
  def call(conn, opts) do
    {mod, fun, args} = Keyword.fetch!(opts, :handler)

    destination = apply(mod, fun, [conn | args])

    Phoenix.Controller.redirect(conn, to: destination)
  end

# in the config
get "/work", Plugs.Redirect, handler: {SomeModule, some_fun, []}

# the function definition
defmodule SomeModule do
  def some_fun(conn) do
    ...etc...
  end
end

If some_fun expects more than one argument, you’d include it in the tuple’s third element.

budgie

budgie

Why can’t it store anonymous functions? Also, is ther a reason to prefer an MFA tuple over referencing the named function directly as in &SomeModule.some_fun/1?

jswanner

jswanner

The ability to include extra arguments

budgie

budgie

Can’t you already do that with the &SomeModule.other_fun(&1, other_arg) syntax for a function that accepts 2 arguments? Or are you meaning something else?

al2o3cr

al2o3cr

&SomeModule.other_fun(&1, other_arg) is a shorthand for fn x -> SomeModule.other_fun(x, other_arg) end and will trigger precisely the same problems as any other anonymous function.

Despite the similar notation, &SomeModule.other_fun/1 is represented differently internally.

budgie

budgie

Understood, thank you!

— All posts loaded —

Where Next? Top

Trending in Questions Top

axelson
One of my LiveView view’s has a very heavy javascript dependency so I want to avoid loading it for every page on the site, while still us...
New
yasoob
Hi all! I know that quite a few people use Phoenix LiveView but it is hard to get a more up-to-date list of folks/companies using it. I ...
New
Hellowman
Hello everyone! I am new to coding with Elixir/Erlang. And i am looking for some utilities for fuzzing testing like AFL++. Does anyone ...
New
yarrichar
I’m very new to Elixir, so sorry if this is a silly question: I am wondering what happens to the mailbox of a process when the machine i...
New
mandar1045
I load tested a plain Phoenix chat app backed by Postgres with 100 million messages in it, everything on default settings, to see what br...
New
caioaao
Hey, I know this has been discussed ad nauseum, but I couldn’t find a definitive answer or at least some consensus around this, so let me...
New
Liam_or
I don’t suppose you can lazy load a library depending on runtime data? For example if it’s a certain user they can lazy load ‘library A’ ...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
261 13183 112
New
mudasobwa
I fully migrated to my own harness from Anthropic/Gemini and I think it’s time to share it. Welcome DSH, the DeepSeek Harness, fully writ...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
charlenopires
Hi everyone :waving_hand: I’ve been working on PhiaUI, an open-source UI component library for Phoenix LiveView, and I wanted to share i...
New
PJUllrich
On November 23, 2026, an unauthorized third party exploited a vulnerability in hex.pm (CVE-2026-129514, CVSS 10.0) that let them run comm...
New
akoutmos
@hugobarauna, Dr. Dimitrios Koutmos (my brother) and I (Alex Koutmos) have been hard at work on writing a book on how you can use Elixir ...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews