Where should I define helper method in Phoenix project?
I want to define helper method like Rails. But I am wondering where should I define helper method.
the method is used in template, view, model and controller. I defined the methods in model like following and import in web.ex. Is it right? Or should I define these in views?
# web/models/session.ex defmodule UserAuthenticator.Session do alias UserAuthenticator.User @doc """ return current user logged in """ def current_user(conn) do id = Plug.Conn.get_session(conn, :current_user) if id, do: UserAuthenticator.Repo.get(User, id) end @doc """ check whether user login in """ def logged_in?(conn) do !!current_user(conn) end end
There is no “you should define helpers there” in the first place. Elixir functions are just functions.
But importing the whole model into somewhere else does not sound as a good idea. If you need to have a bundle of functions to be available in the set of other modules, the most common approach would be to declare a helpers module as:
defmodule Helpers do
defmacro __using__(_opts) do
quote do
def func1, do: func2()
def func2, do: IO.puts 'yay'
end
end
end
and use Helpers
everywhere you need these functions:
defmodule A do
use Helpers
def check, do: func1()
end
A.check #⇒ 'yay'
More on Kernel.use/2
(check Best practices.)
If, on the other hand, you just want to have helpers declared in some dedicated place and different modules are supposed to need different functions, use Kernel.SpecialForms.import/2
with explicit only
parameter to prevent name clash:
defmodule Helper do
def func1, do: IO.puts '1'
def func2, do: IO.puts '2'
end
defmodule M1 do
import Helper, only: [:func1]
end
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