concept Metex in category elixir

appears as: Metex, Metex
The Little Elixir & OTP Guidebook

This is an excerpt from Manning's book The Little Elixir & OTP Guidebook.

It’s important to realize that requests don’t depend on each other. In other words, you can package each call to Metex.Worker.temperature_of/1 into a process. Let’s teach the worker how to respond to messages. First, add the loop/0 function to lib/worker.ex in the next listing.

Once you understand the core principles of OTP, you’ll learn about one of the most important and common OTP behaviors: GenServer. Short for Generic Server, the GenServer behavior is an abstraction of client/server functionality. You’ll take Metex, the temperature-reporting application that you built in chapter 3, and turn it into a GenServer. By then, you’ll have a firm grasp of how to implement your own GenServers.

Let’s fill in the missing pieces to get Metex.Worker.get_temperature/2 to work in the next listing.

Listing 4.6. Implementing the helper functions
defmodule Metex.Worker do
  use GenServer

  ## Client API and Server API

  ## previously implemented code

  ## Helper Functions


  defp temperature_of(location) do
    url_for(location) |> HTTPoison.get |> parse_response
  end

  defp url_for(location) do
    "http://api.openweathermbap.org/data/2.5/weather?q=#{location}&APPID=
#{apikey}"
  end

  defp parse_response({:ok, %HTTPoison.Response{body: body, status_code:
200}}) do
    body |> JSON.decode! |> compute_temperature
  end

  defp parse_response(_) do
    :error
  end

  defp compute_temperature(json) do
    try do
      temp = (json["main"]["temp"] - 273.15) |> Float.round(1)
      {:ok, temp}
    rescue
      _ -> :error
    end
  end
  def apikey do
    "APIKEY-GOES-HERE"
  end

  defp update_stats(old_stats, location) do
    case Map.has_key?(old_stats, location) do
      true ->
        Map.update!(old_stats, location, &(&1 + 1))
      false ->
        Map.put_new(old_stats, location, 1)
    end
  end

end

Most of the implementation is the same as in chapter 3, except for minor changes to Metex.Worker.temperature_of/1 and Metex.Worker.update_stats/2, which are new. The implementation of Metex.Worker.update_stats/2 is simple. See the following listing.

In case you need a refresher, Metex reports the temperature in degrees Celsius, given a location such as the name of a city. This is done through a HTTP call to a third-party weather service. You’ll add other bells and whistles to illustrate various GenServer concepts such as keeping state and process registration. For example, you’ll track the frequency of valid locations requested.