2
votes

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

1
I used the method found here - worked out well: medium.com/@andreichernykh/…dstull

1 Answers

1
votes

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