vrod
Adding more to __using__?
Is there a way to put more functions into __using__ block? It gets very long and hard to read. I cannot figure out how to split up the quote do into multiple functions. Is there a trick?
Most Liked
benwilson512
Yea I agree with @eksperimental here, this use of macros generally causes more trouble than it’s worth.
If you find yourself with functions that take too many arguments, consider creating a struct and then passing on that struct. For example:
defmodule SomeModule do
defstruct [shared1: "a", shared2: "b", foo: nil, bar: nil]
end
Then you construct a %SomeModule{} struct and it will take on the relevant defaults, and also provide a place to store other values you want to set. Then you can pass this to your various functions, and add extra arguments as appropriate.
benwilson512
@vrod I’ll start by saying: If this is a problem you’re running into, you are 100% putting too much inside of a __using__ block. Code inside of a using block should generally look like this:
defmodule SomeThing do
defmacro __using__(opts) do
quote do
def foo(arg) do
SomeThing.foo(__MODULE__, arg)
end
end
end
def foo(module, arg) do
# complex multi-line implementation here
end
end
NOT
defmodule SomeThing do
defmacro __using__(opts) do
quote do
def foo(arg) do
# complex multi-line implementation here
end
end
end
end
Doing it the first way will improve compile times, debugging ability, and avoid the problem you are running into.
BUT, to actually answer your question, you can do this;
defmacro __using__(opts) do
[
first_part_stuff(opts),
second_part_stuff(opts),
]
end
defp first_part_stuff(opts) do
quote do
# things here
end
end
defp second_part_stuff(opts) do
quote do
# things here
end
end
Basically, return a list of quote do blocks.
benwilson512
You can @doc false those functions if you want to make it clear that they aren’t supposed to be used.
kip
If the only purpose of the __using__ macro is to define functions that have no dependency on macro arguments then I think just import MyModule is far clearer in intent and easier to maintain. I can’t tell if your use case fits this description though.
Otherwise, as @benwilson512 says, the quoted code should do as little as possible and delegate to normal functions early for the same reasons as clear intent and maintainability.
eksperimental
I would recommend against that. Be explicit and avoid magic.
Later you will loose understanding of what’ s going on with your code.








