notexactlyawe

notexactlyawe

Passing anonymous function as plug option

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?

Marked As Solved

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?

Also Liked

notexactlyawe

notexactlyawe

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.

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.

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.

Last Post!

budgie

budgie

Understood, thank you!

Where Next?

Popular in Questions Top

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
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
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
Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
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
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

Other popular topics Top

jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 31525 112
New
sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
AstonJ
Seen any cool LiveView demos, sample apps or examples? Please post them here! :003:
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
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

We're in Beta

About us Mission Statement