I'm using Elixir + Phoenix 1.3 and have defined an Accounts
context. I wanted to use the accounts.ex
file as an index to require in other modules to prevent it from becoming too big but I'm having trouble importing the functions from the other modules I created.
The structure of my files is as follows:
lib
|- Project
|- Accounts
|- accounts.ex
|- user_api.ex
This is how my accounts.ex
file looks:
# accounts.ex
defmodule Project.Accounts do
@moduledoc """
The Accounts context.
"""
import Ev2Web
import Ecto.Query, warn: false
alias Project.{Accounts}
use Accounts.UserAPI
end
And this is the module that I'm trying to import:
# user_api.ex
defmodule Project.Accounts.UserAPI do
alias Project.{Repo}
alias Project.{Accounts.User}
def list_users do
Repo.all(User)
end
end
I want to be able to import my Project.Accounts.UserAPI
module so that I can reference Project.Accounts.list_users()
in my controller but the modules aren't being imported. I get the error function Project.Accounts.UserAPI.__using__/1 is undefined or private
.
My controller looks like this:
defmodule ProjectWeb.UserController do
use ProjectWeb, :controller
alias Project.Accounts
def index(conn, _params) do
users = Accounts.list_users()
render(conn, "index.html", users: users)
end
end
Does anyone know how to import all of the functions from one module into another so that they are available for use? Thanks in advance!
The simplest way of enumerating through a list in Elixir is to use the Enum.each/2function. Remember that the /2here means that the function takes two arguments. Those two arguments are:
Joy of Elixir is an absolute beginners guide to Elixir. Built-in functions: lists, maps and more - Joy of Elixir Joy of Elixir « Previous chapterNext chapter »
We then made Elixir run this function using this syntax: iex> greeting.("World") "Hello, World!" What we're doing different here with our puts = &IO.puts/1is that we're using an inbuilt function rather than constructing one of our own. We can do this with any inbuilt function we please.
You have to include the __using__
macro and put all the code that should be compiled into the using module in there. Like this:
defmodule Project.Accounts.UserAPI do
defmacro __using__(_) do
quote do
alias Project.{Repo}
alias Project.{Accounts.User}
def list_users do
Repo.all(User)
end
end
end
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