2

I am trying to do initialize a module attribute like this

  response = HTTPoison.get! url
  {:ok, response} = Poison.decode(response.body)
  @attr response

I have done it before with a file, something like this:

  @external_resource file = Path.join([__DIR__, "file.txt"])
  Module.register_attribute __MODULE__, :attr, accumulate: true

  for line <- File.stream!(file, [], :line) do
    @attr line
    ...

Is not possible to do the same with HTTPoison and fetching the response of an API? I am receiving this error:

== Compilation error in file lib/module.ex ==
** (ArgumentError) argument error
    (stdlib) :ets.lookup_element(:hackney_config, :mod_metrics, 2)
    /project/deps/hackney/src/hackney_metrics.erl:27: :hackney_metrics.get_engine/0
    /project/deps/hackney/src/hackney_connect.erl:69: :hackney_connect.create_connection/5
    /project/deps/hackney/src/hackney_connect.erl:37: :hackney_connect.connect/5
    /project/deps/hackney/src/hackney.erl:316: :hackney.request/5
    lib/httpoison/base.ex:630: HTTPoison.Base.request/9
    lib/httpoison.ex:66: HTTPoison.request!/5
    lib/module.ex:4: (module)
lapinkoira
  • 8,320
  • 9
  • 51
  • 94

1 Answers1

5

The dependent applications are not started automatically at compile time. You need to explicitly start HTTPoison before using it:

HTTPoison.start()
response = HTTPoison.get! url
{:ok, response} = Poison.decode(response.body)
@attr response
Dogbert
  • 212,659
  • 41
  • 396
  • 397
  • Could HTTPoison.start() be added on the mix.exs file instead in the module? – lapinkoira Jun 20 '18 at 14:58
  • I mean, I added it to applications: [:httpoison] and tried also with extra_applications but didnt work, is to avoid having to explicitly call it on the module – lapinkoira Jun 21 '18 at 07:41
  • I don't think there is. I see you posted a new question about that. Let's see if someone else can give a definitive answer. – Dogbert Jun 21 '18 at 13:27
  • 1
    I am afraid is not possible, from elixir forum: "Applications listed in extra_applications are still started at start up time, not at compile-time. If you need to use HTTPoison at compile-time, you need to start it at compile time manually." – lapinkoira Jun 21 '18 at 13:41