Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access current module in Elixir

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?

like image 564
NoDisplayName Avatar asked Aug 29 '15 04:08

NoDisplayName


People also ask

What is __ module __ In elixir?

__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.

What are module attributes elixir?

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.

What is macro elixir?

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.


2 Answers

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.

like image 156
José Valim Avatar answered Oct 29 '22 06:10

José Valim


You can use __MODULE__, which will be replaced with the name of the enclosing module at compile time.

like image 28
Patrick Oscity Avatar answered Oct 29 '22 06:10

Patrick Oscity