Let's say I have a module MyApp.User
and it has the following method:
def update_some_counter(user) do
from(u in MyApp.User , where: u.id == ^user.id)
|> Repo.update_all(inc: [some_counter: 1])
end
Is there a way to change MyApp.User
in the code above to some method that retrieves current module?
__MODULE__ is a compilation environment macros which is the current module name as an atom. Now you know alias __MODULE__ just defines an alias for our Elixir module. This is very useful when used with defstruct which we will talk about next.
Module attributes in Elixir serve three purposes: They serve to annotate the module, often with information to be used by the user or the VM . They work as constants. They work as a temporary module storage to be used during compilation.
Macros are compile-time constructs that receive Elixir's AST as input and return Elixir's AST as output. Many of the functions in this module exist precisely to work with Elixir AST, to traverse, query, and transform it.
Patrick's answer is correct: you can use __MODULE__
. However, I would advise all of your query functions in the model to receive the query as argument (see here: http://blog.drewolson.org/composable-queries-ecto/) and to not call the repository inside your model.
Leave the act of calling the repository, which is a side-effect, to the integration layer, like controllers and what not.
You can use __MODULE__
, which will be replaced with the name of the enclosing module at compile time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With