mruoss
Hi community!
What is the correct way to implement the __using__ macro with an option that changes the way generated functions behave? Or is that a no-go by itself?
An example:
defmodule UsedModule do
defmacro __using__(opts) do
quote do
if Keyword.get(unquote(opts), :with_extra, false) do
def extra(), do: "with extra"
else
def extra(), do: "no extra"
end
end
end
end
defmodule UsingModuleWithExtra, do: use UsedModule, with_extra: true
defmodule UsingModuleNoExtra, do: use UsedModule
iex> UsingModuleWithExtra.extra()
"with extra"
iex> UsingModuleNoExtra.extra()
"no extra"
My question: Is this the way to go inside the __using__ macro? Or would you define the extra function once and do the if inside like this?
def extra() do
if Keyword.get(unquote(opts), :with_extra, false),
do: "with extra",
else: "no extra"
end
Or is there a cleaner way I’m not seeing?
Thanks!
Trending in Questions
Hello!
Suppose you are building workflow (order / task / payment) processing system with the following requirements:
Each workflow con...
New
Hi all,
I’m working on a Phoenix project where I need to make external HTTP requests and I’m trying to choose between Req and HTTPoison....
New
How do I tell Hologram not to escape HTML when substituting into templates?
{Textile.render(@product.long_description)}
escapes the HTM...
New
I’d like to create a file with 600 permissions (rw-------), but there’s a race condition if I create it and then change the permissions. ...
New
Hi,
we run different LLM models across a cluster, with each node loading a configurable subset. Model-specific queues let nodes consume ...
New
When I use Mix.install with a git dependency, using git@github.com:... how do I change the SSH identity used?
I’ve got two Github accoun...
New
Hello all. I have a question as to best practices for code organization when implementing a liveview with a lot of responsibilities.
Sup...
New
Other Trending Topics
Hey there,
I haven’t seen a list of useful Elixir specific skills for the popular AI tools yet so I’m starting one here with my first.
...
New
Hi everyone :waving_hand:
I wanted to share something I’ve been building — NowBlind, a random chat app designed to help people discover ...
New
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
Hey. Is there anyone here who creates agents in their apps? Not talking about using agents, but creating them. I’m finding it pretty diff...
New
(I just needed to vent somewhere and LinkedIn is full of hope, or hype, I’m not sure which exactly)
AI dream has many faces, but general...
New
Localize is the next generation localisation library for Elixir. Think of it as ex_cldr version 3.0. The first version will be released ...
New
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #library
- #deployment
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #code-sync
- #discussion
- #podcasts
- #javascript
- #onsite
- #dialyzer
- #docker
- #authentication
- #ai
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #blog-post
- #elixirconf-us
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #elixirconf-eu
- #processes
- #security
- #api
- #forms
- #performance










Showing Posts 1 to 7- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
Eiji
In case you have a static output like in this example then you can simply call
unquote(string)and outsidequoteblock setstringvariable based on option.In other case I would recommend to simply move
ifcondition outsidequoteblock and simply use 2quotecalls.Note: If
opts[:with_extra]does not exists then you gotnilwhich is falsy value and therefore we do not need aKeyword.get/3call here.mruoss
Thanks for your answer. I mean to remember heaving read @josevalim mentioning somewhere that there should be no code (or as little as possible?) outside the quote block. But it might be applicable only in that context which obviously I don’t remember.
Anyway this helps, thanks. Also for the note!
Eiji
Yeah, I can say that it may depend on case. For example there is a big difference working on raw data passed to macro and variables passed to macro even if their declaration was static one line above …
unquoteinsidequoteblock solves the problem. However in some cases you may expect some value to be passedrawinstead.Here since the value is known “outside” the half of code we generate would never be used.
A simple example shows how important it may be:
Look that if we would have only 1/10 features enabled then we would generate only one
quoteblock.However if we would write it like this:
then said module with one enabled feature would have generated extra loop with 9/10 skipped elements. Also in example above
apply_feature/1is a public macro for absolutely no reason (comparing to previous example).Also it would be nice to provide a link for mentioned text as José could talk about other case or just more complex example. It would be good for others to see all sides of this coin.
mruoss
If I ever find that text again, I will definitely add a link to it here.
But your example with the 10 features only works because a quoted list of atoms is still a list of atoms, right? If for some stupid reason I decide to pass
enabled_features: [String.to_atom("my_frature")], it would not work?Eiji
If it’s stupid, but it works then it’s no stupid!
I have used
atomas it’s best for what I calledfeature_nameas those inapply_feature/1are known at compile-time. You can use strings, integers and every other data that you can write pattern-matching for.Also take a look at example below:
If you want to call
String.to_atom/1inside macro then:Enum.map(list, &String.to_atom/1)as long as you require list of atoms passed as raw list or sigil (see above example)String.to_atom/1call needs to be passed insideunquote/1call.moduleandfunctionblock you can useString.to_atom/1call as well insideunquote/1call as outsideunquote/1call.Hope that helps.
mruoss
Not maps. Or structs. You can’t expand those to their original value either. You’d have to call
Code.eval_quoted()which is discouraged inside macros, no?I’d like come back to my original question. I have changed the example to take a map. It does not make much sense like this and could be done better, but it is a simple example to show the case with a map as option value:
See the passed option is expected to be a map. Which cannot be expanded to its original value. You have to unquote them inside a quote block (right?). So my question was, if you would - in this case where the argument requires unquoting - implement the macro like I did above or rather put the if condition inside the generated function like this:
Eiji
You can’t expand them, because unlike
sigilthey arespecial forms. However if you still expect to pass rawmapthen you can solve that in few ways depends on use case …If you do not want to mix your code with handling special forms then all you need to do is write something like: