Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Starting mix task process dependencies

Tags:

elixir

New to Elixir but loving it so far :)

A lot of my mix tasks depend on HTTPotion.

My mix.exs file is declared as such

  def application do
    [
      applications: [:logger, :cowboy, :plug, :httpotion, :poison],
      mod: {BiddingAgent, []}
    ]
  end

So HTTPotion.start is called automatically. However, when I run a task like mix campaign.list which needs to call an http request, I have to manually call HTTPotion.start.

What is the idiomatic way to make sure the right processes are started for my mix tasks?

Thanks!

like image 379
Venkat D. Avatar asked Feb 29 '16 18:02

Venkat D.


1 Answers

You're right, when starting the app outside of the startup script you do need to start the dependencies manually.

I prefer to call the Application module instead of each dependency directly.

Add the following code to the run function inside your task module.

{:ok, _started} = Application.ensure_all_started(:httpotion)

If you have any doubt you can take a look at the documentation

Edit: The practice described is being used in Ecto

  • https://github.com/elixir-lang/ecto/blob/master/lib/mix/ecto.ex#L73

  • https://github.com/elixir-lang/ecto/blob/df13b1c64f8edd128cec1316336b20f3153eafa3/lib/mix/tasks/ecto.migrate.ex#L67

A module is included in a the mix tasks which provides an ensure_started method.

like image 74
josemrb Avatar answered Nov 18 '22 15:11

josemrb