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
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
Hey guys,
I’ve got a huge CSV ( around 10 GB ) that needs to be processed hourly
Do you guys have any suggestions what is the best prac...
New
Kia ora,
We have been using elixir-google-api to connect to Google Drive. However, with the updates to Tesla due to CVEs this is now bro...
New
Hello!
Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app.
I creat...
New
I’ve followed the Phoenix LiveView file upload code here Uploads — Phoenix LiveView v1.0.0-rc.7 and so far everything works just fine wit...
New
Hello,
I’m developing a online persistent chat system (what’s app) like using elixir/dynamodb/aws for a mobile app(flutter).
The diffic...
New
Other Trending Topics
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
Hobbes is a low-level distributed database for the Elixir programming language.
Hobbes provides a simple, safe, and scalable storage lay...
New
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge & Solve.
They are GUI (Emerge) and State management (S...
New
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #blog-post
- #ai
- #phoenix_html
- #iex
- #elixirconf-us
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #hex
- #security
- #metaprogramming










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: