thojanssens1
Dynamic operator in argument of macro function?
I have an operator in a variable, for example:
guard = &Kernel.>=/2
How can I use that variable as argument to a macro, e.g. for Ecto.Query.where/3?
Ecto.Query.where(query, [..., r], field(r, ^field) >= ^value)
I want to replace the operator hard-coded above by the one dynamically defined in the variable guard.
Marked As Solved
ityonemo
Looking at the code it seems like that’s not something you can do. A macro transforms AST at compile time, and you’re trying to gate it on something that exists only at runtime.
Also Liked
NobbZ
How exactly you have to use variables in a macro depends on the Macro. You already see it in ecto where the names are used to build the query, except when you pin (^), then you use the variables value in the query.
Though, passing in the operator like that is not possible. I think you’ll have to limit yourt choices to a handfull of operators and branch on them, eg:
case op do
:">=" -> Ecto.Query.where(query, [..., r], field(r, ^field) >= ^value)
:"<" -> Ecto.Query.where(query, [..., r], field(r, ^field) < ^value)
end
Popular in Questions
Other popular topics
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
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance








