Skip to content

Instantly share code, notes, and snippets.

@KamilLelonek
Created May 17, 2020 10:56
Show Gist options
  • Select an option

  • Save KamilLelonek/77fcdfeebd8f1b68f1e0cab570c3bd89 to your computer and use it in GitHub Desktop.

Select an option

Save KamilLelonek/77fcdfeebd8f1b68f1e0cab570c3bd89 to your computer and use it in GitHub Desktop.

Revisions

  1. KamilLelonek created this gist May 17, 2020.
    20 changes: 20 additions & 0 deletions download.ex
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,20 @@
    defmodule Download do
    use Pipe

    def start(api_key) do
    api_key
    ~> download()
    ~> parse()
    end

    defp download(123), do: {:ok, "valid result"}
    defp download(_), do: {:error, "invalid API key"}

    defp parse({:ok, message}), do: %{message: message, downloaded_at: Time.utc_now()}
    end

    Download.start(123)
    #=> %{downloaded_at: ~T[10:53:31.643047], message: "valid result"}

    Download.start("invalid") |> IO.inspect()
    #=> {:error, "invalid API key"}
    21 changes: 21 additions & 0 deletions pipe.ex
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,21 @@
    defmodule Pipe do
    defmacro __using__(_) do
    quote do
    require unquote(__MODULE__)

    import unquote(__MODULE__)
    end
    end

    defmacro left ~> right do
    quote do
    case unquote(left) do
    {:error, error} ->
    {:error, error}

    result ->
    result |> unquote(right)
    end
    end
    end
    end