Sugar.Controller

Controllers facilitate some separation of concerns for your application’s logic.

All handler actions should have an arrity of 2, with the first argument being a Plug.Conn representing the current connection and the second argument being a Keyword list of any parameters captured in the route path.

Sugar.Controller imports Plug.Conn, the plug/1 and plug/2 macros from Plug.Builder, Sugar.Controller, and Sugar.Controller.Helpers for convenience when creating handlers for your applications

Example

defmodule Controllers.Pages do
  use Sugar.Controller

  @doc false
  def index(conn, []) do
    # Somehow get our content
    pages = Queries.Page.all
    render conn, pages
  end

  @doc false
  def show(conn, args) do
    result = case Integer.parse args["page_id"] do
        :error -> 
          %Error{ id: "no_page_id",
                  message: "A valid page_id is required." }
        {i, _} ->
          Queries.Page.get i
      end

    render conn, result
  end

  @doc false
  def create(conn, args) do
    render conn, Queries.Page.create args, status: :created
  end

  @doc false
  def update(conn, args) do
    result = case Integer.parse args["page_id"] do
        :error -> 
          %Error{ id: "no_page_id",
                  message: "A valid page_id is requried." }
        {i, _} ->
          Queries.Page.update i, args
      end

    render conn, result
  end
end
Source