Manuel Albarran

A random notes about Elixir

SimpleController

12 Feb 2017 » elixir, macros
# https://thepugautomatic.com/2015/10/understanding-elixir-macros/
# https://thepugautomatic.com/2015/11/elixir-scoping/
# http://yos.io/2016/04/24/mixins-in-elixir/
# https://thepugautomatic.com/2015/12/elixir-block-keywords/
# http://elixir-lang.org/getting-started/meta/macros.html#our-first-macro

defmodule Router do
  use Plug.Router

  plug :fetch_query_params
  plug :match
  plug :dispatch

  match "/echo", to: EchoController
  match _, do: send_resp(conn, 404, "oops")
end

defmodule SimpleController do
  defmacro __using__(_) do
    quote location: :keep do
      require EEx
      import Plug.Conn

      def init(opts), do: opts

      def call(conn, _opts) do
        method_name = conn.method |> String.downcase |> String.to_atom
        apply(__MODULE__, method_name, [conn, conn.query_params])
      end

      def redirect(conn, to: url), do: conn|> put_resp_header("Location", url) |> send_resp(302, "")
      
      def render(conn, filename, vars \\ []) do
        send_resp(conn, 200, EEx.eval_string(File.read!("views/#{filename}.html.eex"), assigns: vars))
      end
    end
  end
end

defmodule EchoController do
  use SimpleController

  def get(conn, qs) do
    conn
    |> put_resp_content_type("text/plain")
    |> send_resp(200, "#{inspect(qs, width: 2, pretty: true)}")
  end
end