Skip to content

Instantly share code, notes, and snippets.

@gausby
Created August 12, 2015 20:39
Show Gist options
  • Save gausby/da2a4a06ae68458fb91e to your computer and use it in GitHub Desktop.
Save gausby/da2a4a06ae68458fb91e to your computer and use it in GitHub Desktop.
Collectable, Copenhagen Elixir, August 2015
defmodule Validator.Result do
defstruct errors: [], warnings: [], runs: 0, passes: 0
end
defmodule Validator do
alias Validator.Result
def run do
tests = [
&file_should_exist/0,
&file_should_have_a_title/0,
&this_one_should_be_ok/0,
&this_should_warn/0
]
for test <- tests, into: %Result{} do
apply(test, [])
end
end
defp file_should_exist do
{:error, "The file did not exist"}
end
defp file_should_have_a_title do
{:error, "The file did not have a title"}
end
defp this_should_warn do
{:warning, "This is not that bad"}
end
defp this_one_should_be_ok do
:ok
end
end
defimpl Collectable, for: Validator.Result do
def into(original) do
{original, fn
state, {:cont, {:error, reason}} ->
%Validator.Result{state|errors: [reason|state.errors],
runs: state.runs + 1}
state, {:cont, {:warning, reason}} ->
%Validator.Result{state|warnings: [reason|state.warnings],
runs: state.runs + 1,
passes: state.passes + 1}
state, {:cont, :ok} ->
%Validator.Result{state|runs: state.runs + 1,
passes: state.passes + 1}
state, :done ->
state
_, :halt ->
:ok
end}
end
end
defmodule SomeProject do
alias Validator.Result
def validate do
Validator.run
|> handle_results
end
defp handle_results(%Result{passes: x, runs: x}) do
"everythings beautiful!"
end
defp handle_results(%Result{errors: errors}) do
"""
Please fix the following issues:
* #{Enum.join(errors, "\n * ")}
"""
end
end
# for this example we just output to the terminal like so:
IO.puts SomeProject.validate
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment