Pattern matching deeply nested arguments in Elixir
I've just taken a whack at cleaning up my original code after a few days.

edit: Now including refactor suggestions from alxndr.



Set everything in motion

  def run(job) do
    HTTPStatusCheck.run(job)
    |&gt; update_db
    |&gt; send_alerts
  end


(The new run method seen here handles what was previously done by query and parse.)

The new HTTPStatusCheck.run/1 method:

  def run(job) do
    method = :head
    url = job.url
    body = ""
    headers = [@user_agent]
    options = @http_options

    HTTPoison.request(method, url, body, headers, options)
    |&gt; parse
  end


(You can see it calls parse internally now, as I cannot find a reason anything else would ever need to work with the unparsed results object.)



The new HTTPStatusCheck.parse/1 definitions:

  defp parse({:ok, %Response{status_code: c}} = resp) do
    %HTTPCheckResult{}
    |&gt; add_http_code(c)
    |&gt; add_http_response(resp)
  end

  defp parse({:error, %HTTPoison.Error{reason: reason}} = resp) do
    %HTTPCheckResult{}
    |&gt; add_http_response(resp)
    |&gt; add_error(reason)
  end

  defp parse(_) do
    %HTTPCheckResult{}
    |&gt; add_error("unknown")
  end


(I feel these are much better, as the method signature and definition code are now much shorter and more readable. The suggestions from alxndr were implemented here and in the next section of helper methods.)

Helper methods for HTTPStatusCheck.parse/1:

  defp add_result(result, val), do: %{result | result: val}
  defp add_http_response(result, response), do: %{result | http_response: response}

  defp add_http_code(result, code) do
    %{result | code: code}
    |&gt; handle_http_code(code)
  end

  defp handle_http_code(result, code) when code in @up do
    result
    |&gt; add_result(:up)
  end
  defp handle_http_code(result, code) when code in @down do
    result
    |&gt; add_result(:down)
  end
  defp handle_http_code(result, code) do
    result
    |&gt; add_error("unhandled http code #{c}")
  end

  defp add_error(result, error) do
    %{result | error: error}
    |&gt; add_result(:error)
  end




%HTTPCheckResult{} is improved too:

There is no longer the need to indicate parsed: false or parsed: true on this struct.