Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to put helper module on Phoenix Framework

I want to add a helper module to do a get request using

http://hexdocs.pm/httpoison/HTTPoison.Base.html

But when I put the defmodule in

/lib/Shopper/CallApi.ex

and use in

/web.ex

def controller do
quote do
  use Phoenix.Controller

  alias Shopper.Repo
  import Ecto.Model
  import Ecto.Query, only: [from: 1, from: 2]

  import Shopper.Router.Helpers

  use Shopper.CallApi
end

end

the compiler failed with

== Compilation error on file web/controllers/page_controller.ex ==
** (UndefinedFunctionError) undefined function: Shopper.CallApi.__using__/1
    Shopper.CallApi.__using__([])
    web/controllers/page_controller.ex:2: (module)

So... Where to define CallApi.ex and where I should declare it?

like image 289
ardhitama Avatar asked Sep 21 '15 10:09

ardhitama


1 Answers

When you call use Shopper.CallApi, __using__/1 macro is called - this is specific to meta-programming. If you want to use functions defined in Shopper.CallApi in your module then use alias Shopper.CallApi instead.

The differences between alias, require and import are documented in Alias, Require and Import and using is documented in Domain Specific Languages.

As an aside, normally in elixir projects, files are named in snake_case - call_api.ex instead of CallApi.ex.

like image 152
Gazler Avatar answered Oct 14 '22 03:10

Gazler