I've recently started working with Elixir and am writing an app that queries various URLs and parses the response. I am having issues with my parse
method, which is included below. The code works just fine, but I am concerned that I may have taken pattern matching too far. The method signature looks like spaghetti.
This is the code that sets the whole thing in process. I think it's fine, but include it to give you some background:
def run(job) do
HTTPStatusCheck.query(job)
|> HTTPStatusCheck.parse
|> update_db
|> send_alerts
end
The query
method returns this "object":
%HTTPCheckResult{parsed: false, http_response: resp}
# resp is a %HTTPoison.Response{} "object"
Here is the parse
method I need help with:
def parse(%HTTPCheckResult{
parsed: false, http_response: {:ok, %Response{status_code: c}}} = result)
when c in @up do
%{result | parsed: true, code: c, result: :up}
end
def parse(%HTTPCheckResult{
parsed: false, http_response: {:ok, %Response{status_code: c}}} = result)
when c in @down do
%{result | parsed: true, code: c, result: :down}
end
def parse(%HTTPCheckResult{
parsed: false, http_response: {:ok, %Response{status_code: c}}} = result) do
%{result | parsed: true, result: :error, error: "http code #{c}"}
end
def parse(
%HTTPCheckResult{parsed: false, http_response: {:error, %HTTPoison.Error{reason: reason}}} = result) do
%{result | parsed: true, result: :error, error: reason}
end
def parse(%HTTPCheckResult{parsed: false} = result) do
%{result | result: :error, error: "unknown"}
end
My biggest objection is really the size of the parse
method signatures, which are three lines in some cases. The important parts also seem pretty deeply nested in there.
How can the parse
method can be improved?
parse
methods to make them easier to read and understand. \$\endgroup\$