Router: Add missing Web to docs (#2532)

Router: Add missing Web to docs (#2532)

defmodule Phoenix.Router do
  defmodule NoRouteError do
    @moduledoc """
    Exception raised when no route is found.
    """
    defexception plug_status: 404, message: "no route found", conn: nil, router: nil

    def exception(opts) do
      conn   = Keyword.fetch!(opts, :conn)
      router = Keyword.fetch!(opts, :router)
      path   = "/" <> Enum.join(conn.path_info, "/")

      %NoRouteError{message: "no route found for #{conn.method} #{path} (#{inspect router})",
                    conn: conn, router: router}
    end
  end

  @moduledoc """
  Defines a Phoenix router.

  The router provides a set of macros for generating routes
  that dispatch to specific controllers and actions. Those
  macros are named after HTTP verbs. For example:

      defmodule MyAppWeb.Router do
        use Phoenix.Router

        get "/pages/:page", PageController, :show
      end

  The `get/3` macro above accepts a request of format `"/pages/VALUE"` and
  dispatches it to the show action in the `PageController`.

  Routes can also match glob-like patterns, routing any path with a common
  base to the same controller. For example:

      get "/dynamic*anything", DynamicController, :show

  Phoenix's router is extremely efficient, as it relies on Elixir
  pattern matching for matching routes and serving requests.

  ## Helpers

  Phoenix automatically generates a module `Helpers` inside your router
  which contains named helpers to help developers generate and keep
  their routes up to date.

  Helpers are automatically generated based on the controller name.
  For example, the route:

      get "/pages/:page", PageController, :show

  will generate the following named helper:

      MyAppWeb.Router.Helpers.page_path(conn_or_endpoint, :show, "hello")
      "/pages/hello"

      MyAppWeb.Router.Helpers.page_path(conn_or_endpoint, :show, "hello", some: "query")
      "/pages/hello?some=query"

      MyAppWeb.Router.Helpers.page_url(conn_or_endpoint, :show, "hello")
      "http://example.com/pages/hello"

      MyAppWeb.Router.Helpers.page_url(conn_or_endpoint, :show, "hello", some: "query")
      "http://example.com/pages/hello?some=query"

  If the route contains glob-like patterns, parameters for those have to be given as
  list:

      MyAppWeb.Router.Helpers.dynamic_path(conn_or_endpoint, :show, ["dynamic", "something"])
      "/dynamic/something"

  The URL generated in the named URL helpers is based on the configuration for
  `:url`, `:http` and `:https`. However, if for some reason you need to manually
  control the URL generation, the url helpers also allow you to pass in a `URI`
  struct:

      uri = %URI{scheme: "https", host: "other.example.com"}
      MyAppWeb.Router.Helpers.page_url(uri, :show, "hello")
      "https://other.example.com/pages/hello"

  The named helper can also be customized with the `:as` option. Given
  the route:

      get "/pages/:page", PageController, :show, as: :special_page

  the named helper will be:

      MyAppWeb.Router.Helpers.special_page_path(conn, :show, "hello")
      "/pages/hello"

  ## Scopes and Resources

  It is very common in Phoenix applications to namespace all of your
  routes under the application scope:

      scope "/", MyAppWeb do
        get "/pages/:id", PageController, :show
      end

  The route above will dispatch to `MyAppWeb.PageController`. This syntax
  is not only convenient for developers, since we don't have to repeat
  the `MyAppWeb.` prefix on all routes, but it also allows Phoenix to put
  less pressure in the Elixir compiler. If instead we had written:

      get "/pages/:id", MyAppWeb.PageController, :show

  The Elixir compiler would infer that the router depends directly on
  `MyAppWeb.PageController`, which is not true. By using scopes, Phoenix
  can properly hint to the Elixir compiler the controller is not an
  actual dependency of the router. This provides more efficient
  compilation times.

  Scopes allow us to scope on any path or even on the helper name:

      scope "/api/v1", MyAppWeb, as: :api_v1 do
        get "/pages/:id", PageController, :show
      end

  For example, the route above will match on the path `"/api/v1/pages/:id"`
  and the named route will be `api_v1_page_path`, as expected from the
  values given to `scope/2` option.

  Phoenix also provides a `resources/4` macro that allows developers
  to generate "RESTful" routes to a given resource:

      defmodule MyAppWeb.Router do
        use Phoenix.Router

        resources "/pages", PageController, only: [:show]
        resources "/users", UserController, except: [:delete]
      end

  Finally, Phoenix ships with a `mix phx.routes` task that nicely
  formats all routes in a given router. We can use it to verify all
  routes included in the router above:

      $ mix phx.routes
      page_path  GET    /pages/:id       PageController.show/2
      user_path  GET    /users           UserController.index/2
      user_path  GET    /users/:id/edit  UserController.edit/2
      user_path  GET    /users/new       UserController.new/2
      user_path  GET    /users/:id       UserController.show/2
      user_path  POST   /users           UserController.create/2
      user_path  PATCH  /users/:id       UserController.update/2
                 PUT    /users/:id       UserController.update/2

  One can also pass a router explicitly as an argument to the task:

      $ mix phx.routes MyAppWeb.Router

  Check `scope/2` and `resources/4` for more information.

  ## Pipelines and plugs

  Once a request arrives at the Phoenix router, it performs
  a series of transformations through pipelines until the
  request is dispatched to a desired end-point.

  Such transformations are defined via plugs, as defined
  in the [Plug](http://github.com/elixir-lang/plug) specification.
  Once a pipeline is defined, it can be piped through per scope.

  For example:

      defmodule MyAppWeb.Router do
        use Phoenix.Router

        pipeline :browser do
          plug :fetch_session
          plug :accepts, ["html"]
        end

        scope "/" do
          pipe_through :browser

          # browser related routes and resources
        end
      end

  `Phoenix.Router` imports functions from both `Plug.Conn` and `Phoenix.Controller`
  to help define plugs. In the example above, `fetch_session/2`
  comes from `Plug.Conn` while `accepts/2` comes from `Phoenix.Controller`.

  Note that router pipelines are only invoked after a route is found.
  No plug is invoked in case no matches were found.
  """

  alias Phoenix.Router.Resource
  alias Phoenix.Router.Scope
  alias Phoenix.Router.Route
  alias Phoenix.Router.Helpers

  @http_methods [:get, :post, :put, :patch, :delete, :options, :connect, :trace, :head]

  @doc false
  defmacro __using__(_) do
    quote do
      unquote(prelude())
      unquote(defs())
      unquote(match_dispatch())
    end
  end

  defp prelude() do
    quote do
      Module.register_attribute __MODULE__, :phoenix_routes, accumulate: true
      @phoenix_forwards %{}

      import Phoenix.Router

      # TODO v2: No longer automatically import dependencies
      import Plug.Conn
      import Phoenix.Controller

      # Set up initial scope
      @phoenix_pipeline nil
      Phoenix.Router.Scope.init(__MODULE__)
      @before_compile unquote(__MODULE__)
    end
  end

  # Because those macros are executed multiple times,
  # we end-up generating a huge scope that drastically
  # affects compilation. We work around it by defining
  # those functions only once and calling it over and
  # over again.
  defp defs() do
    quote unquote: false do
      var!(add_resources, Phoenix.Router) = fn resource ->
        path = resource.path
        ctrl = resource.controller
        opts = resource.route

        if resource.singleton do
          Enum.each resource.actions, fn
            :show    -> get    path,            ctrl, :show, opts
            :new     -> get    path <> "/new",  ctrl, :new, opts
            :edit    -> get    path <> "/edit", ctrl, :edit, opts
            :create  -> post   path,            ctrl, :create, opts
            :delete  -> delete path,            ctrl, :delete, opts
            :update  ->
              patch path, ctrl, :update, opts
              put   path, ctrl, :update, Keyword.put(opts, :as, nil)
          end
        else
          param = resource.param

          Enum.each resource.actions, fn
            :index   -> get    path,                             ctrl, :index, opts
            :show    -> get    path <> "/:" <> param,            ctrl, :show, opts
            :new     -> get    path <> "/new",                   ctrl, :new, opts
            :edit    -> get    path <> "/:" <> param <> "/edit", ctrl, :edit, opts
            :create  -> post   path,                             ctrl, :create, opts
            :delete  -> delete path <> "/:" <> param,            ctrl, :delete, opts
            :update  ->
              patch path <> "/:" <> param, ctrl, :update, opts
              put   path <> "/:" <> param, ctrl, :update, Keyword.put(opts, :as, nil)
          end
        end
      end
    end
  end

  @doc false
  def __call__({%Plug.Conn{private: %{phoenix_router: router, phoenix_bypass: {router, pipes}}} = conn, _pipeline, _dispatch}) do
    Enum.reduce(pipes, conn, fn pipe, acc -> apply(router, pipe, [acc, []]) end)
  end
  def __call__({%Plug.Conn{private: %{phoenix_bypass: :all}} = conn, _pipeline, _dispatch}) do
    conn
  end
  def __call__({conn, pipeline, dispatch}) do
    case pipeline.(conn) do
      %Plug.Conn{halted: true} = halted_conn ->
        halted_conn
      %Plug.Conn{} = piped_conn ->
        try do
          dispatch.(piped_conn)
        catch
          :error, reason -> Plug.Conn.WrapperError.reraise(piped_conn, :error, reason)
        end
    end
  end

  defp match_dispatch() do
    quote location: :keep do
      @behaviour Plug

      @doc """
      Callback required by Plug that initializes the router
      for serving web requests.
      """
      def init(opts) do
        opts
      end

      @doc """
      Callback invoked by Plug on every request.
      """
      def call(conn, _opts) do
        conn
        |> prepare()
        |> __match_route__(conn.method, Enum.map(conn.path_info, &URI.decode/1), conn.host)
        |> Phoenix.Router.__call__()
      end

      defoverridable [init: 1, call: 2]
    end
  end

  @anno (if :erlang.system_info(:otp_release) >= '19' do
    [generated: true]
  else
    [line: -1]
  end)

  @doc false
  defmacro __before_compile__(env) do
    routes = env.module |> Module.get_attribute(:phoenix_routes) |> Enum.reverse
    routes_with_exprs = Enum.map(routes, &{&1, Route.exprs(&1)})

    Helpers.define(env, routes_with_exprs)
    matches = Enum.map(routes_with_exprs, &build_match/1)

    # @anno is used here to avoid warnings if forwarding to root path
    match_404 =
      quote @anno do
        def __match_route__(conn, _method, _path_info, _host) do
          raise NoRouteError, conn: conn, router: __MODULE__
        end
      end

    quote do
      @doc false
      def __routes__,  do: unquote(Macro.escape(routes))

      @doc false
      def __helpers__, do: __MODULE__.Helpers

      defp prepare(conn) do
        update_in conn.private,
          &(&1 |> Map.put(:phoenix_pipelines, [])
          |> Map.put(:phoenix_router, __MODULE__)
          |> Map.put(__MODULE__, {conn.script_name, @phoenix_forwards}))
      end

      unquote(matches)
      unquote(match_404)
    end
  end

  defp build_match({_route, exprs}) do
    {conn_block, pipelines, dispatch} = exprs.route_match

    quote do
      @doc false
      def __match_route__(var!(conn), unquote(exprs.verb_match), unquote(exprs.path),
                 unquote(exprs.host)) do

        unquote(conn_block)
        {var!(conn), unquote(pipelines), unquote(dispatch)}
      end
    end
  end

  @doc """
  Generates a route match based on an arbitrary HTTP method.

  Useful for defining routes not included in the builtin macros:

  #{Enum.map_join(@http_methods, ", ", &"`#{&1}`")}

  The catch-all verb, `:*`, may also be used to match all HTTP methods.

  ## Examples

      match(:move, "/events/:id", EventController, :move)

      match(:*, "/any", SomeController, :any)
  """
  defmacro match(verb, path, plug, plug_opts, options \\ []) do
    add_route(:match, verb, path, plug, plug_opts, options)
  end

  for verb <- @http_methods do
    @doc """
    Generates a route to handle a #{verb} request to the given path.
    """
    defmacro unquote(verb)(path, plug, plug_opts, options \\ []) do
      verb = unquote(verb)
      quote bind_quoted: binding() do
        match(verb, path, plug, plug_opts, options)
      end
    end
  end

  defp add_route(kind, verb, path, plug, plug_opts, options) do
    quote do
      @phoenix_routes Scope.route(__MODULE__, unquote(kind), unquote(verb), unquote(path),
                                  unquote(plug), unquote(plug_opts), unquote(options))
    end
  end

  @doc """
  Defines a plug pipeline.

  Pipelines are defined at the router root and can be used
  from any scope.

  ## Examples

      pipeline :api do
        plug :token_authentication
        plug :dispatch
      end

  A scope may then use this pipeline as:

      scope "/" do
        pipe_through :api
      end

  Every time `pipe_through/1` is called, the new pipelines
  are appended to the ones previously given.
  """
  defmacro pipeline(plug, do: block) do
    block =
      quote do
        plug = unquote(plug)
        @phoenix_pipeline []
        unquote(block)
      end

    compiler =
      quote unquote: false do
        Scope.pipeline(__MODULE__, plug)
        {conn, body} = Plug.Builder.compile(__ENV__, @phoenix_pipeline, [])
        def unquote(plug)(unquote(conn), _) do
          try do
            unquote(body)
          catch
            :error, reason ->
              Plug.Conn.WrapperError.reraise(unquote(conn), :error, reason)
          end
        end
        @phoenix_pipeline nil
      end

    quote do
      try do
        unquote(block)
        unquote(compiler)
      after
        :ok
      end
    end
  end

  @doc """
  Defines a plug inside a pipeline.

  See `pipeline/2` for more information.
  """
  defmacro plug(plug, opts \\ []) do
    quote do
      if pipeline = @phoenix_pipeline do
        @phoenix_pipeline [{unquote(plug), unquote(opts), true}|pipeline]
      else
        raise "cannot define plug at the router level, plug must be defined inside a pipeline"
      end
    end
  end

  @doc """
  Defines a pipeline to send the connection through.

  See `pipeline/2` for more information.
  """
  defmacro pipe_through(pipes) do
    quote do
      if pipeline = @phoenix_pipeline do
        raise "cannot pipe_through inside a pipeline"
      else
        Scope.pipe_through(__MODULE__, unquote(pipes))
      end
    end
  end

  @doc """
  Defines "RESTful" routes for a resource.

  The given definition:

      resources "/users", UserController

  will include routes to the following actions:

    * `GET /users` => `:index`
    * `GET /users/new` => `:new`
    * `POST /users` => `:create`
    * `GET /users/:id` => `:show`
    * `GET /users/:id/edit` => `:edit`
    * `PATCH /users/:id` => `:update`
    * `PUT /users/:id` => `:update`
    * `DELETE /users/:id` => `:delete`

  ## Options

  This macro accepts a set of options:

    * `:only` - a list of actions to generate routes for, for example: `[:show, :edit]`
    * `:except` - a list of actions to exclude generated routes from, for example: `[:delete]`
    * `:param` - the name of the parameter for this resource, defaults to `"id"`
    * `:name` - the prefix for this resource. This is used for the named helper
      and as the prefix for the parameter in nested resources. The default value
      is automatically derived from the controller name, i.e. `UserController` will
      have name `"user"`
    * `:as` - configures the named helper exclusively
    * `:singleton` - defines routes for a singleton resource that is looked up by
      the client without referencing an ID. Read below for more information

  ## Singleton resources

  When a resource needs to be looked up without referencing an ID, because
  it contains only a single entry in the given context, the `:singleton`
  option can be used to generate a set of routes that are specific to
  such single resource:

    * `GET /user` => `:show`
    * `GET /user/new` => `:new`
    * `POST /user` => `:create`
    * `GET /user/edit` => `:edit`
    * `PATCH /user` => `:update`
    * `PUT /user` => `:update`
    * `DELETE /user` => `:delete`

  Usage example:

      resources "/account", AccountController, only: [:show], singleton: true

  ## Nested Resources

  This macro also supports passing a nested block of route definitions.
  This is helpful for nesting children resources within their parents to
  generate nested routes.

  The given definition:

      resources "/users", UserController do
        resources "/posts", PostController
      end

  will include the following routes:

      user_post_path  GET     /users/:user_id/posts           PostController :index
      user_post_path  GET     /users/:user_id/posts/:id/edit  PostController :edit
      user_post_path  GET     /users/:user_id/posts/new       PostController :new
      user_post_path  GET     /users/:user_id/posts/:id       PostController :show
      user_post_path  POST    /users/:user_id/posts           PostController :create
      user_post_path  PATCH   /users/:user_id/posts/:id       PostController :update
                      PUT     /users/:user_id/posts/:id       PostController :update
      user_post_path  DELETE  /users/:user_id/posts/:id       PostController :delete

  """
  defmacro resources(path, controller, opts, do: nested_context) do
    add_resources path, controller, opts, do: nested_context
  end

  @doc """
  See `resources/4`.
  """
  defmacro resources(path, controller, do: nested_context) do
    add_resources path, controller, [], do: nested_context
  end

  @doc """
  See `resources/4`.
  """
  defmacro resources(path, controller, opts) do
    add_resources path, controller, opts, do: nil
  end

  @doc """
  See `resources/4`.
  """
  defmacro resources(path, controller) do
    add_resources path, controller, [], do: nil
  end

  defp add_resources(path, controller, options, do: context) do
    scope =
      if context do
        quote do
          scope resource.member, do: unquote(context)
        end
      end

    quote do
      resource = Resource.build(unquote(path), unquote(controller), unquote(options))
      var!(add_resources, Phoenix.Router).(resource)
      unquote(scope)
    end
  end

  @doc """
  Defines a scope in which routes can be nested.

  ## Examples

      scope path: "/api/v1", as: :api_v1, alias: API.V1 do
        get "/pages/:id", PageController, :show
      end

  The generated route above will match on the path `"/api/v1/pages/:id"`
  and will dispatch to `:show` action in `API.V1.PageController`. A named
  helper `api_v1_page_path` will also be generated.

  ## Options

  The supported options are:

    * `:path` - a string containing the path scope
    * `:as` - a string or atom containing the named helper scope
    * `:alias` - an alias (atom) containing the controller scope
    * `:host` - a string containing the host scope, or prefix host scope,
      ie `"foo.bar.com"`, `"foo."`
    * `:private` - a map of private data to merge into the connection when a route matches
    * `:assigns` - a map of data to merge into the connection when a route matches

  """
  defmacro scope(options, do: context) do
    do_scope(options, context)
  end

  @doc """
  Define a scope with the given path.

  This function is a shortcut for:

      scope path: path do
        ...
      end

  ## Examples

      scope "/api/v1", as: :api_v1, alias: API.V1 do
        get "/pages/:id", PageController, :show
      end

  """
  defmacro scope(path, options, do: context) do
    options = quote do
      path = unquote(path)
      case unquote(options) do
        alias when is_atom(alias) -> [path: path, alias: alias]
        options when is_list(options) -> Keyword.put(options, :path, path)
      end
    end
    do_scope(options, context)
  end

  @doc """
  Defines a scope with the given path and alias.

  This function is a shortcut for:

      scope path: path, alias: alias do
        ...
      end

  ## Examples

      scope "/api/v1", API.V1, as: :api_v1 do
        get "/pages/:id", PageController, :show
      end

  """
  defmacro scope(path, alias, options, do: context) do
    options = quote do
      unquote(options)
      |> Keyword.put(:path, unquote(path))
      |> Keyword.put(:alias, unquote(alias))
    end
    do_scope(options, context)
  end

  defp do_scope(options, context) do
    quote do
      Scope.push(__MODULE__, unquote(options))
      try do
        unquote(context)
      after
        Scope.pop(__MODULE__)
      end
    end
  end

  @doc """
  Forwards a request at the given path to a plug.

  All paths that match the forwarded prefix will be sent to
  the forwarded plug. This is useful for sharing a router between
  applications or even breaking a big router into smaller ones.
  The router pipelines will be invoked prior to forwarding the
  connection.

  The forwarded plug will be initialized at compile time.

  Note, however, that we don't advise forwarding to another
  endpoint. The reason is that plugs defined by your app
  and the forwarded endpoint would be invoked twice, which
  may lead to errors.

  ## Examples

      scope "/", MyApp do
        pipe_through [:browser, :admin]

        forward "/admin", SomeLib.AdminDashboard
        forward "/api", ApiRouter
      end

  """
  defmacro forward(path, plug, plug_opts \\ [], router_opts \\ []) do
    router_opts = Keyword.put(router_opts, :as, nil)

    quote unquote: true, bind_quoted: [path: path, plug: plug] do
      path_segments = Route.forward_path_segments(path, plug, @phoenix_forwards)
      @phoenix_forwards Map.put(@phoenix_forwards, plug, path_segments)
      unquote(add_route(:forward, :*, path, plug, plug_opts, router_opts))
    end
  end
end

defmodule Phoenix.Router do
  defmodule NoRouteError do
    @moduledoc """
    Exception raised when no route is found.
    """
    defexception plug_status: 404, message: "no route found", conn: nil, router: nil

    def exception(opts) do
      conn   = Keyword.fetch!(opts, :conn)
      router = Keyword.fetch!(opts, :router)
      path   = "/" <> Enum.join(conn.path_info, "/")

      %NoRouteError{message: "no route found for #{conn.method} #{path} (#{inspect router})",
                    conn: conn, router: router}
    end
  end

  @moduledoc """
  Defines a Phoenix router.

  The router provides a set of macros for generating routes
  that dispatch to specific controllers and actions. Those
  macros are named after HTTP verbs. For example:

      defmodule MyAppWeb.Router do
        use Phoenix.Router

        get "/pages/:page", PageController, :show
      end

  The `get/3` macro above accepts a request of format `"/pages/VALUE"` and
  dispatches it to the show action in the `PageController`.

  Routes can also match glob-like patterns, routing any path with a common
  base to the same controller. For example:

      get "/dynamic*anything", DynamicController, :show

  Phoenix's router is extremely efficient, as it relies on Elixir
  pattern matching for matching routes and serving requests.

  ## Helpers

  Phoenix automatically generates a module `Helpers` inside your router
  which contains named helpers to help developers generate and keep
  their routes up to date.

  Helpers are automatically generated based on the controller name.
  For example, the route:

      get "/pages/:page", PageController, :show

  will generate the following named helper:

      MyAppWeb.Router.Helpers.page_path(conn_or_endpoint, :show, "hello")
      "/pages/hello"

      MyAppWeb.Router.Helpers.page_path(conn_or_endpoint, :show, "hello", some: "query")
      "/pages/hello?some=query"

      MyAppWeb.Router.Helpers.page_url(conn_or_endpoint, :show, "hello")
      "http://example.com/pages/hello"

      MyAppWeb.Router.Helpers.page_url(conn_or_endpoint, :show, "hello", some: "query")
      "http://example.com/pages/hello?some=query"

  If the route contains glob-like patterns, parameters for those have to be given as
  list:

      MyAppWeb.Router.Helpers.dynamic_path(conn_or_endpoint, :show, ["dynamic", "something"])
      "/dynamic/something"

  The URL generated in the named URL helpers is based on the configuration for
  `:url`, `:http` and `:https`. However, if for some reason you need to manually
  control the URL generation, the url helpers also allow you to pass in a `URI`
  struct:

      uri = %URI{scheme: "https", host: "other.example.com"}
      MyAppWeb.Router.Helpers.page_url(uri, :show, "hello")
      "https://other.example.com/pages/hello"

  The named helper can also be customized with the `:as` option. Given
  the route:

      get "/pages/:page", PageController, :show, as: :special_page

  the named helper will be:

      MyAppWeb.Router.Helpers.special_page_path(conn, :show, "hello")
      "/pages/hello"

  ## Scopes and Resources

  It is very common in Phoenix applications to namespace all of your
  routes under the application scope:

      scope "/", MyAppWeb do
        get "/pages/:id", PageController, :show
      end

  The route above will dispatch to `MyApp.PageController`. This syntax
  is not only convenient for developers, since we don't have to repeat
  the `MyApp.` prefix on all routes, but it also allows Phoenix to put
  less pressure in the Elixir compiler. If instead we had written:

      get "/pages/:id", MyAppWeb.PageController, :show

  The Elixir compiler would infer that the router depends directly on
  `MyApp.PageController`, which is not true. By using scopes, Phoenix
  can properly hint to the Elixir compiler the controller is not an
  actual dependency of the router. This provides more efficient
  compilation times.

  Scopes allow us to scope on any path or even on the helper name:

      scope "/api/v1", MyAppWeb, as: :api_v1 do
        get "/pages/:id", PageController, :show
      end

  For example, the route above will match on the path `"/api/v1/pages/:id"`
  and the named route will be `api_v1_page_path`, as expected from the
  values given to `scope/2` option.

  Phoenix also provides a `resources/4` macro that allows developers
  to generate "RESTful" routes to a given resource:

      defmodule MyAppWeb.Router do
        use Phoenix.Router

        resources "/pages", PageController, only: [:show]
        resources "/users", UserController, except: [:delete]
      end

  Finally, Phoenix ships with a `mix phx.routes` task that nicely
  formats all routes in a given router. We can use it to verify all
  routes included in the router above:

      $ mix phx.routes
      page_path  GET    /pages/:id       PageController.show/2
      user_path  GET    /users           UserController.index/2
      user_path  GET    /users/:id/edit  UserController.edit/2
      user_path  GET    /users/new       UserController.new/2
      user_path  GET    /users/:id       UserController.show/2
      user_path  POST   /users           UserController.create/2
      user_path  PATCH  /users/:id       UserController.update/2
                 PUT    /users/:id       UserController.update/2

  One can also pass a router explicitly as an argument to the task:

      $ mix phx.routes MyAppWeb.Router

  Check `scope/2` and `resources/4` for more information.

  ## Pipelines and plugs

  Once a request arrives at the Phoenix router, it performs
  a series of transformations through pipelines until the
  request is dispatched to a desired end-point.

  Such transformations are defined via plugs, as defined
  in the [Plug](http://github.com/elixir-lang/plug) specification.
  Once a pipeline is defined, it can be piped through per scope.

  For example:

      defmodule MyAppWeb.Router do
        use Phoenix.Router

        pipeline :browser do
          plug :fetch_session
          plug :accepts, ["html"]
        end

        scope "/" do
          pipe_through :browser

          # browser related routes and resources
        end
      end

  `Phoenix.Router` imports functions from both `Plug.Conn` and `Phoenix.Controller`
  to help define plugs. In the example above, `fetch_session/2`
  comes from `Plug.Conn` while `accepts/2` comes from `Phoenix.Controller`.

  Note that router pipelines are only invoked after a route is found.
  No plug is invoked in case no matches were found.
  """

  alias Phoenix.Router.Resource
  alias Phoenix.Router.Scope
  alias Phoenix.Router.Route
  alias Phoenix.Router.Helpers

  @http_methods [:get, :post, :put, :patch, :delete, :options, :connect, :trace, :head]

  @doc false
  defmacro __using__(_) do
    quote do
      unquote(prelude())
      unquote(defs())
      unquote(match_dispatch())
    end
  end

  defp prelude() do
    quote do
      Module.register_attribute __MODULE__, :phoenix_routes, accumulate: true
      @phoenix_forwards %{}

      import Phoenix.Router

      # TODO v2: No longer automatically import dependencies
      import Plug.Conn
      import Phoenix.Controller

      # Set up initial scope
      @phoenix_pipeline nil
      Phoenix.Router.Scope.init(__MODULE__)
      @before_compile unquote(__MODULE__)
    end
  end

  # Because those macros are executed multiple times,
  # we end-up generating a huge scope that drastically
  # affects compilation. We work around it by defining
  # those functions only once and calling it over and
  # over again.
  defp defs() do
    quote unquote: false do
      var!(add_resources, Phoenix.Router) = fn resource ->
        path = resource.path
        ctrl = resource.controller
        opts = resource.route

        if resource.singleton do
          Enum.each resource.actions, fn
            :show    -> get    path,            ctrl, :show, opts
            :new     -> get    path <> "/new",  ctrl, :new, opts
            :edit    -> get    path <> "/edit", ctrl, :edit, opts
            :create  -> post   path,            ctrl, :create, opts
            :delete  -> delete path,            ctrl, :delete, opts
            :update  ->
              patch path, ctrl, :update, opts
              put   path, ctrl, :update, Keyword.put(opts, :as, nil)
          end
        else
          param = resource.param

          Enum.each resource.actions, fn
            :index   -> get    path,                             ctrl, :index, opts
            :show    -> get    path <> "/:" <> param,            ctrl, :show, opts
            :new     -> get    path <> "/new",                   ctrl, :new, opts
            :edit    -> get    path <> "/:" <> param <> "/edit", ctrl, :edit, opts
            :create  -> post   path,                             ctrl, :create, opts
            :delete  -> delete path <> "/:" <> param,            ctrl, :delete, opts
            :update  ->
              patch path <> "/:" <> param, ctrl, :update, opts
              put   path <> "/:" <> param, ctrl, :update, Keyword.put(opts, :as, nil)
          end
        end
      end
    end
  end

  @doc false
  def __call__({%Plug.Conn{private: %{phoenix_router: router, phoenix_bypass: {router, pipes}}} = conn, _pipeline, _dispatch}) do
    Enum.reduce(pipes, conn, fn pipe, acc -> apply(router, pipe, [acc, []]) end)
  end
  def __call__({%Plug.Conn{private: %{phoenix_bypass: :all}} = conn, _pipeline, _dispatch}) do
    conn
  end
  def __call__({conn, pipeline, dispatch}) do
    case pipeline.(conn) do
      %Plug.Conn{halted: true} = halted_conn ->
        halted_conn
      %Plug.Conn{} = piped_conn ->
        try do
          dispatch.(piped_conn)
        catch
          :error, reason -> Plug.Conn.WrapperError.reraise(piped_conn, :error, reason)
        end
    end
  end

  defp match_dispatch() do
    quote location: :keep do
      @behaviour Plug

      @doc """
      Callback required by Plug that initializes the router
      for serving web requests.
      """
      def init(opts) do
        opts
      end

      @doc """
      Callback invoked by Plug on every request.
      """
      def call(conn, _opts) do
        conn
        |> prepare()
        |> __match_route__(conn.method, Enum.map(conn.path_info, &URI.decode/1), conn.host)
        |> Phoenix.Router.__call__()
      end

      defoverridable [init: 1, call: 2]
    end
  end

  @anno (if :erlang.system_info(:otp_release) >= '19' do
    [generated: true]
  else
    [line: -1]
  end)

  @doc false
  defmacro __before_compile__(env) do
    routes = env.module |> Module.get_attribute(:phoenix_routes) |> Enum.reverse
    routes_with_exprs = Enum.map(routes, &{&1, Route.exprs(&1)})

    Helpers.define(env, routes_with_exprs)
    matches = Enum.map(routes_with_exprs, &build_match/1)

    # @anno is used here to avoid warnings if forwarding to root path
    match_404 =
      quote @anno do
        def __match_route__(conn, _method, _path_info, _host) do
          raise NoRouteError, conn: conn, router: __MODULE__
        end
      end

    quote do
      @doc false
      def __routes__,  do: unquote(Macro.escape(routes))

      @doc false
      def __helpers__, do: __MODULE__.Helpers

      defp prepare(conn) do
        update_in conn.private,
          &(&1 |> Map.put(:phoenix_pipelines, [])
          |> Map.put(:phoenix_router, __MODULE__)
          |> Map.put(__MODULE__, {conn.script_name, @phoenix_forwards}))
      end

      unquote(matches)
      unquote(match_404)
    end
  end

  defp build_match({_route, exprs}) do
    {conn_block, pipelines, dispatch} = exprs.route_match

    quote do
      @doc false
      def __match_route__(var!(conn), unquote(exprs.verb_match), unquote(exprs.path),
                 unquote(exprs.host)) do

        unquote(conn_block)
        {var!(conn), unquote(pipelines), unquote(dispatch)}
      end
    end
  end

  @doc """
  Generates a route match based on an arbitrary HTTP method.

  Useful for defining routes not included in the builtin macros:

  #{Enum.map_join(@http_methods, ", ", &"`#{&1}`")}

  The catch-all verb, `:*`, may also be used to match all HTTP methods.

  ## Examples

      match(:move, "/events/:id", EventController, :move)

      match(:*, "/any", SomeController, :any)
  """
  defmacro match(verb, path, plug, plug_opts, options \\ []) do
    add_route(:match, verb, path, plug, plug_opts, options)
  end

  for verb <- @http_methods do
    @doc """
    Generates a route to handle a #{verb} request to the given path.
    """
    defmacro unquote(verb)(path, plug, plug_opts, options \\ []) do
      verb = unquote(verb)
      quote bind_quoted: binding() do
        match(verb, path, plug, plug_opts, options)
      end
    end
  end

  defp add_route(kind, verb, path, plug, plug_opts, options) do
    quote do
      @phoenix_routes Scope.route(__MODULE__, unquote(kind), unquote(verb), unquote(path),
                                  unquote(plug), unquote(plug_opts), unquote(options))
    end
  end

  @doc """
  Defines a plug pipeline.

  Pipelines are defined at the router root and can be used
  from any scope.

  ## Examples

      pipeline :api do
        plug :token_authentication
        plug :dispatch
      end

  A scope may then use this pipeline as:

      scope "/" do
        pipe_through :api
      end

  Every time `pipe_through/1` is called, the new pipelines
  are appended to the ones previously given.
  """
  defmacro pipeline(plug, do: block) do
    block =
      quote do
        plug = unquote(plug)
        @phoenix_pipeline []
        unquote(block)
      end

    compiler =
      quote unquote: false do
        Scope.pipeline(__MODULE__, plug)
        {conn, body} = Plug.Builder.compile(__ENV__, @phoenix_pipeline, [])
        def unquote(plug)(unquote(conn), _) do
          try do
            unquote(body)
          catch
            :error, reason ->
              Plug.Conn.WrapperError.reraise(unquote(conn), :error, reason)
          end
        end
        @phoenix_pipeline nil
      end

    quote do
      try do
        unquote(block)
        unquote(compiler)
      after
        :ok
      end
    end
  end

  @doc """
  Defines a plug inside a pipeline.

  See `pipeline/2` for more information.
  """
  defmacro plug(plug, opts \\ []) do
    quote do
      if pipeline = @phoenix_pipeline do
        @phoenix_pipeline [{unquote(plug), unquote(opts), true}|pipeline]
      else
        raise "cannot define plug at the router level, plug must be defined inside a pipeline"
      end
    end
  end

  @doc """
  Defines a pipeline to send the connection through.

  See `pipeline/2` for more information.
  """
  defmacro pipe_through(pipes) do
    quote do
      if pipeline = @phoenix_pipeline do
        raise "cannot pipe_through inside a pipeline"
      else
        Scope.pipe_through(__MODULE__, unquote(pipes))
      end
    end
  end

  @doc """
  Defines "RESTful" routes for a resource.

  The given definition:

      resources "/users", UserController

  will include routes to the following actions:

    * `GET /users` => `:index`
    * `GET /users/new` => `:new`
    * `POST /users` => `:create`
    * `GET /users/:id` => `:show`
    * `GET /users/:id/edit` => `:edit`
    * `PATCH /users/:id` => `:update`
    * `PUT /users/:id` => `:update`
    * `DELETE /users/:id` => `:delete`

  ## Options

  This macro accepts a set of options:

    * `:only` - a list of actions to generate routes for, for example: `[:show, :edit]`
    * `:except` - a list of actions to exclude generated routes from, for example: `[:delete]`
    * `:param` - the name of the parameter for this resource, defaults to `"id"`
    * `:name` - the prefix for this resource. This is used for the named helper
      and as the prefix for the parameter in nested resources. The default value
      is automatically derived from the controller name, i.e. `UserController` will
      have name `"user"`
    * `:as` - configures the named helper exclusively
    * `:singleton` - defines routes for a singleton resource that is looked up by
      the client without referencing an ID. Read below for more information

  ## Singleton resources

  When a resource needs to be looked up without referencing an ID, because
  it contains only a single entry in the given context, the `:singleton`
  option can be used to generate a set of routes that are specific to
  such single resource:

    * `GET /user` => `:show`
    * `GET /user/new` => `:new`
    * `POST /user` => `:create`
    * `GET /user/edit` => `:edit`
    * `PATCH /user` => `:update`
    * `PUT /user` => `:update`
    * `DELETE /user` => `:delete`

  Usage example:

      resources "/account", AccountController, only: [:show], singleton: true

  ## Nested Resources

  This macro also supports passing a nested block of route definitions.
  This is helpful for nesting children resources within their parents to
  generate nested routes.

  The given definition:

      resources "/users", UserController do
        resources "/posts", PostController
      end

  will include the following routes:

      user_post_path  GET     /users/:user_id/posts           PostController :index
      user_post_path  GET     /users/:user_id/posts/:id/edit  PostController :edit
      user_post_path  GET     /users/:user_id/posts/new       PostController :new
      user_post_path  GET     /users/:user_id/posts/:id       PostController :show
      user_post_path  POST    /users/:user_id/posts           PostController :create
      user_post_path  PATCH   /users/:user_id/posts/:id       PostController :update
                      PUT     /users/:user_id/posts/:id       PostController :update
      user_post_path  DELETE  /users/:user_id/posts/:id       PostController :delete

  """
  defmacro resources(path, controller, opts, do: nested_context) do
    add_resources path, controller, opts, do: nested_context
  end

  @doc """
  See `resources/4`.
  """
  defmacro resources(path, controller, do: nested_context) do
    add_resources path, controller, [], do: nested_context
  end

  @doc """
  See `resources/4`.
  """
  defmacro resources(path, controller, opts) do
    add_resources path, controller, opts, do: nil
  end

  @doc """
  See `resources/4`.
  """
  defmacro resources(path, controller) do
    add_resources path, controller, [], do: nil
  end

  defp add_resources(path, controller, options, do: context) do
    scope =
      if context do
        quote do
          scope resource.member, do: unquote(context)
        end
      end

    quote do
      resource = Resource.build(unquote(path), unquote(controller), unquote(options))
      var!(add_resources, Phoenix.Router).(resource)
      unquote(scope)
    end
  end

  @doc """
  Defines a scope in which routes can be nested.

  ## Examples

      scope path: "/api/v1", as: :api_v1, alias: API.V1 do
        get "/pages/:id", PageController, :show
      end

  The generated route above will match on the path `"/api/v1/pages/:id"`
  and will dispatch to `:show` action in `API.V1.PageController`. A named
  helper `api_v1_page_path` will also be generated.

  ## Options

  The supported options are:

    * `:path` - a string containing the path scope
    * `:as` - a string or atom containing the named helper scope
    * `:alias` - an alias (atom) containing the controller scope
    * `:host` - a string containing the host scope, or prefix host scope,
      ie `"foo.bar.com"`, `"foo."`
    * `:private` - a map of private data to merge into the connection when a route matches
    * `:assigns` - a map of data to merge into the connection when a route matches

  """
  defmacro scope(options, do: context) do
    do_scope(options, context)
  end

  @doc """
  Define a scope with the given path.

  This function is a shortcut for:

      scope path: path do
        ...
      end

  ## Examples

      scope "/api/v1", as: :api_v1, alias: API.V1 do
        get "/pages/:id", PageController, :show
      end

  """
  defmacro scope(path, options, do: context) do
    options = quote do
      path = unquote(path)
      case unquote(options) do
        alias when is_atom(alias) -> [path: path, alias: alias]
        options when is_list(options) -> Keyword.put(options, :path, path)
      end
    end
    do_scope(options, context)
  end

  @doc """
  Defines a scope with the given path and alias.

  This function is a shortcut for:

      scope path: path, alias: alias do
        ...
      end

  ## Examples

      scope "/api/v1", API.V1, as: :api_v1 do
        get "/pages/:id", PageController, :show
      end

  """
  defmacro scope(path, alias, options, do: context) do
    options = quote do
      unquote(options)
      |> Keyword.put(:path, unquote(path))
      |> Keyword.put(:alias, unquote(alias))
    end
    do_scope(options, context)
  end

  defp do_scope(options, context) do
    quote do
      Scope.push(__MODULE__, unquote(options))
      try do
        unquote(context)
      after
        Scope.pop(__MODULE__)
      end
    end
  end

  @doc """
  Forwards a request at the given path to a plug.

  All paths that match the forwarded prefix will be sent to
  the forwarded plug. This is useful for sharing a router between
  applications or even breaking a big router into smaller ones.
  The router pipelines will be invoked prior to forwarding the
  connection.

  The forwarded plug will be initialized at compile time.

  Note, however, that we don't advise forwarding to another
  endpoint. The reason is that plugs defined by your app
  and the forwarded endpoint would be invoked twice, which
  may lead to errors.

  ## Examples

      scope "/", MyApp do
        pipe_through [:browser, :admin]

        forward "/admin", SomeLib.AdminDashboard
        forward "/api", ApiRouter
      end

  """
  defmacro forward(path, plug, plug_opts \\ [], router_opts \\ []) do
    router_opts = Keyword.put(router_opts, :as, nil)

    quote unquote: true, bind_quoted: [path: path, plug: plug] do
      path_segments = Route.forward_path_segments(path, plug, @phoenix_forwards)
      @phoenix_forwards Map.put(@phoenix_forwards, plug, path_segments)
      unquote(add_route(:forward, :*, path, plug, plug_opts, router_opts))
    end
  end
end


Don't assign unused attributed in monitoring

defmodule Annon.Plugins.Monitoring do
  @moduledoc """
  This plugin measures or receives performance metrics from other parts of Annon and sends them to StatsD server.

  It is enabled by default and can not be disabled without rebuilding Annon container.

  It can be used with [DataDog agent](http://datadoghq.com).
  """
  use Annon.Plugin, plugin_name: :monitoring
  alias Plug.Conn
  alias Annon.Monitoring.MetricsCollector
  alias Annon.Monitoring.Latencies

  def validate_settings(changeset),
    do: changeset

  def settings_validation_schema,
    do: %{}

  def execute(%Conn{} = conn, %{api: api, start_time: request_start_time}, _settings) do
    content_length = get_content_length(conn, nil)

    sample_rate =
      :annon_api
      |> Application.get_env(:metrics_collector)
      |> Keyword.get(:sample_rate, 1)
      |> Confex.process_env()

    collector_opts = [
      tags: tags(conn, api),
      sample_rate: sample_rate
    ]

    request_id = get_request_id(conn, nil)

    MetricsCollector.track_request(request_id, content_length, collector_opts)

    conn
    |> Conn.register_before_send(&track_latencies(&1, request_id, request_start_time, collector_opts))
  end

  defp track_latencies(conn, request_id, request_start_time, collector_opts) do
    request_end_time = System.monotonic_time()
    latencies_client = System.convert_time_unit(request_end_time - request_start_time, :native, :micro_seconds)
    latencies_upstream = Map.get(conn.assigns, :latencies_upstream, 0)
    latencies_gateway = latencies_client - latencies_upstream

    latencies = %Latencies{
      client_request: latencies_client,
      upstream: latencies_upstream,
      gateway: latencies_gateway
    }

    status = conn |> get_conn_status(0) |> Integer.to_string()

    MetricsCollector.track_response(request_id, latencies, [
      tags: ["http.status:#{status}"] ++ collector_opts[:tags],
      sample_rate: collector_opts[:sample_rate]
    ])

    Conn.assign(conn, :latencies, latencies)
  end

  defp tags(%Conn{host: host, method: method, port: port} = conn, nil) do
    port = Integer.to_string(port)
    request_id = get_request_id(conn, "unknown")

    ["http.host:#{host}", "http.method:#{method}", "http.port:#{port}",
     "api.name:unknown", "api.id:unknown", "request.id:#{request_id}"]
  end
  defp tags(%Conn{host: host, method: method, port: port} = conn, api) do
    port = Integer.to_string(port)
    request_id = get_request_id(conn, "unknown")
    %{id: api_id, name: api_name} = api

    ["http.host:#{host}", "http.method:#{method}", "http.port:#{port}",
     "api.name:#{api_name}", "api.id:#{api_id}", "request.id:#{request_id}"]
  end

  defp get_request_id(conn, default) do
    case Conn.get_resp_header(conn, "x-request-id") do
      [] -> default
      [id | _] -> id
    end
  end

  defp get_content_length(conn, default) do
    case Conn.get_resp_header(conn, "content-length") do
      [] -> default
      [id | _] -> id
    end
  end

  def get_conn_status(%{status: nil}, default),
    do: default
  def get_conn_status(%{status: status}, _default),
    do: status
end

defmodule Annon.Plugins.Monitoring do
  @moduledoc """
  This plugin measures or receives performance metrics from other parts of Annon and sends them to StatsD server.

  It is enabled by default and can not be disabled without rebuilding Annon container.

  It can be used with [DataDog agent](http://datadoghq.com).
  """
  use Annon.Plugin, plugin_name: :monitoring
  alias Plug.Conn
  alias Annon.Monitoring.MetricsCollector
  alias Annon.Monitoring.Latencies

  def validate_settings(changeset),
    do: changeset

  def settings_validation_schema,
    do: %{}

  def execute(%Conn{} = conn, %{api: api, start_time: request_start_time}, _settings) do
    content_length = get_content_length(conn, nil)

    sample_rate =
      :annon_api
      |> Application.get_env(:metrics_collector)
      |> Keyword.get(:sample_rate, 1)
      |> Confex.process_env()

    collector_opts = [
      tags: tags(conn, api),
      sample_rate: sample_rate
    ]

    request_id = get_request_id(conn, nil)

    MetricsCollector.track_request(request_id, content_length, collector_opts)

    conn
    |> Conn.register_before_send(&track_latencies(&1, request_id, request_start_time, collector_opts))
  end

  defp track_latencies(conn, request_id, request_start_time, collector_opts) do
    request_end_time = System.monotonic_time()
    latencies_client = System.convert_time_unit(request_end_time - request_start_time, :native, :micro_seconds)
    latencies_upstream = Map.get(conn.assigns, :latencies_upstream, 0)
    latencies_gateway = latencies_client - latencies_upstream

    latencies = %Latencies{
      client_request: latencies_client,
      upstream: latencies_upstream,
      gateway: latencies_gateway
    }

    status = conn |> get_conn_status(0) |> Integer.to_string()

    MetricsCollector.track_response(request_id, latencies, [
      tags: ["http.status:#{status}"] ++ collector_opts[:tags],
      sample_rate: collector_opts[:sample_rate]
    ])

    conn
    |> Conn.assign(:latencies_gateway, latencies_gateway)
    |> Conn.assign(:latencies_client, latencies_client)
    |> Conn.assign(:latencies, latencies)
  end

  defp tags(%Conn{host: host, method: method, port: port} = conn, nil) do
    port = Integer.to_string(port)
    request_id = get_request_id(conn, "unknown")

    ["http.host:#{host}", "http.method:#{method}", "http.port:#{port}",
     "api.name:unknown", "api.id:unknown", "request.id:#{request_id}"]
  end
  defp tags(%Conn{host: host, method: method, port: port} = conn, api) do
    port = Integer.to_string(port)
    request_id = get_request_id(conn, "unknown")
    %{id: api_id, name: api_name} = api

    ["http.host:#{host}", "http.method:#{method}", "http.port:#{port}",
     "api.name:#{api_name}", "api.id:#{api_id}", "request.id:#{request_id}"]
  end

  defp get_request_id(conn, default) do
    case Conn.get_resp_header(conn, "x-request-id") do
      [] -> default
      [id | _] -> id
    end
  end

  defp get_content_length(conn, default) do
    case Conn.get_resp_header(conn, "content-length") do
      [] -> default
      [id | _] -> id
    end
  end

  def get_conn_status(%{status: nil}, default),
    do: default
  def get_conn_status(%{status: status}, _default),
    do: status
end


Fix bug (#110)

Fix bug (#110)

defmodule Xee.HostController do
  use Xee.Web, :controller
  require Logger
  plug Xee.AuthenticationPlug

  def index(conn, _params) do
    user = conn.assigns[:host]
    experiment = Xee.HostServer.get(user.id)
    if experiment do
      experiment = Enum.filter_map(experiment,
       &(Xee.ExperimentServer.has?(&1)),
       &(Xee.ExperimentServer.get_info(&1)))
    end
    render conn, "index.html", csrf_token: get_csrf_token(), experiment: experiment
  end

  def remove(conn, %{"xid" => xid}) do
    user = conn.assigns[:host]

    if Xee.ExperimentServer.has?(xid) do
      %{x_token: token} = Xee.ExperimentServer.get_info(xid)
      pid = Xee.ExperimentServer.get(xid)
      Xee.ExperimentServer.remove(xid)
      Xee.TokenServer.drop(token)
      Xee.HostServer.drop(user.id, xid)
      Xee.Experiment.stop(pid)
    end
    conn
    |> redirect(to: "/host")
    |> halt
  end

  def experiment(conn, params) do
    user = conn.assigns[:host]
    themes = Xee.ThemeServer.get_all
              |> Map.to_list
              |> Enum.map(fn {_key, value} -> value end)
              |> Enum.filter(fn theme -> Xee.Theme.granted?(theme, user.name) end)
    if length(themes) == 0 do
      conn
      |> put_flash(:error, "There are no themes")
      |> redirect(to: "/host")
      |> halt
    else
      theme_id = Map.get(params, "theme_id", nil) || hd(themes).id
      render conn, "experiment.html", csrf_token: get_csrf_token(), experiment_name: "", theme_id: theme_id, themes: themes, x_token: Xee.TokenServer.generate_id
    end
  end

  def create(conn, %{"experiment_name" => name, "theme" => theme_id, "x_token" => x_token}) do
    if (String.length(name) == 0 || String.length(x_token) == 0) do
      conn
      |> put_flash(:error, "All fields are required")
      |> redirect(to: "/host/experiment?theme_id=#{theme_id}")
      |> halt
    else
      user = conn.assigns[:host]
      unless (Xee.TokenServer.has?(x_token)) do
        xid = Xee.TokenGenerator.generate
        themes = Xee.ThemeServer.get_all
                  |> Map.to_list
                  |> Enum.map(fn {_key, value} -> value end)
                  |> Enum.filter(fn theme -> Xee.Theme.granted?(theme, user.name) end)
        xtheme = Xee.ThemeServer.get(theme_id)
        true = Xee.Theme.granted?(xtheme, user.name)
        Xee.TokenServer.register(x_token, xid)
        Xee.ExperimentServer.create(xid, xtheme.experiment, %{name: name, experiment: xtheme.experiment, theme: xtheme.name, x_token: x_token, xid: xid})
        Xee.HostServer.register(user.id, xid)
        conn
        |> redirect(to: "/experiment/" <> xid <> "/host")
        |> halt
      else
        themes = Xee.ThemeServer.get_all
                  |> Map.to_list
                  |> Enum.map(fn {_key, value} -> value end)
                  |> Enum.filter(fn theme -> Xee.Theme.granted?(theme, user.name) end)
        conn
        |> put_flash(:error, "This ExperimentID is already being used.")
        |> render("experiment.html", csrf_token: get_csrf_token(), experiment_name: name, theme_id: theme_id, themes: themes, x_token: Xee.TokenServer.generate_id)
      end
    end
  end
end

defmodule Xee.HostController do
  use Xee.Web, :controller
  require Logger
  plug Xee.AuthenticationPlug

  def index(conn, _params) do
    user = conn.assigns[:host]
    experiment = Xee.HostServer.get(user.id)
    if experiment do
      experiment = Enum.map(experiment, fn(x) -> Xee.ExperimentServer.get_info(x) end)
    end
    render conn, "index.html", csrf_token: get_csrf_token(), experiment: experiment
  end

  def remove(conn, %{"xid" => xid}) do
    user = conn.assigns[:host]
    %{x_token: token} = Xee.ExperimentServer.get_info(xid)
    pid = Xee.ExperimentServer.get(xid)
    Xee.ExperimentServer.remove(xid)
    Xee.TokenServer.drop(token)
    Xee.HostServer.drop(user.id, xid)
    Xee.Experiment.stop(pid)
    conn
    |> redirect(to: "/host")
    |> halt
  end

  def experiment(conn, params) do
    user = conn.assigns[:host]
    themes = Xee.ThemeServer.get_all
              |> Map.to_list
              |> Enum.map(fn {_key, value} -> value end)
              |> Enum.filter(fn theme -> Xee.Theme.granted?(theme, user.name) end)
    if length(themes) == 0 do
      conn
      |> put_flash(:error, "There are no themes")
      |> redirect(to: "/host")
      |> halt
    else
      theme_id = Map.get(params, "theme_id", nil) || hd(themes).id
      render conn, "experiment.html", csrf_token: get_csrf_token(), experiment_name: "", theme_id: theme_id, themes: themes, x_token: Xee.TokenServer.generate_id
    end
  end

  def create(conn, %{"experiment_name" => name, "theme" => theme_id, "x_token" => x_token}) do
    if (String.length(name) == 0 || String.length(x_token) == 0) do
      conn
      |> put_flash(:error, "All fields are required")
      |> redirect(to: "/host/experiment?theme_id=#{theme_id}")
      |> halt
    else
      user = conn.assigns[:host]
      unless (Xee.TokenServer.has?(x_token)) do
        xid = Xee.TokenGenerator.generate
        themes = Xee.ThemeServer.get_all
                  |> Map.to_list
                  |> Enum.map(fn {_key, value} -> value end)
                  |> Enum.filter(fn theme -> Xee.Theme.granted?(theme, user.name) end)
        xtheme = Xee.ThemeServer.get(theme_id)
        true = Xee.Theme.granted?(xtheme, user.name)
        Xee.TokenServer.register(x_token, xid)
        Xee.ExperimentServer.create(xid, xtheme.experiment, %{name: name, experiment: xtheme.experiment, theme: xtheme.name, x_token: x_token, xid: xid})
        Xee.HostServer.register(user.id, xid)
        conn
        |> redirect(to: "/experiment/" <> xid <> "/host")
        |> halt
      else
        themes = Xee.ThemeServer.get_all
                  |> Map.to_list
                  |> Enum.map(fn {_key, value} -> value end)
                  |> Enum.filter(fn theme -> Xee.Theme.granted?(theme, user.name) end)
        conn
        |> put_flash(:error, "This ExperimentID is already being used.")
        |> render("experiment.html", csrf_token: get_csrf_token(), experiment_name: name, theme_id: theme_id, themes: themes, x_token: Xee.TokenServer.generate_id)
      end
    end
  end
end


Add manual stop

Add manual stop

# Copyright 2014 LKC Technologies, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

defmodule WpaSupplicant do
  use GenServer
  require Logger

  defstruct port: nil,
            manager: nil,
            requests: []

  @doc """
  Start and link a WpaSupplicant process that uses the specified
  control socket. A GenEvent will be spawned for managing wpa_supplicant
  events. Call event_manager/1 to get the GenEvent pid.
  """
  def start_link(control_socket_path) do
    { :ok, manager } = GenEvent.start_link
    start_link(control_socket_path, manager)
  end

  @doc """
  Start and link a WpaSupplicant that uses the specified control
  socket and GenEvent event manager.
  """
  def start_link(control_socket_path, event_manager) do
    GenServer.start_link(__MODULE__, {control_socket_path, event_manager})
  end

  @doc """
  Stop the WpaSupplicant control interface
  """
  def stop(pid) do
    GenServer.stop(pid)
  end

  @doc """
  Send a request to the wpa_supplicant.

  ## Examples

      iex> WpaSupplicant.request(pid, :PING)
      :PONG
  """
  def request(pid, command) do
    GenServer.call(pid, {:request, command})
  end

  @doc """
  Get a reference to the GenEvent event manager in use by this
  supplicant.
  """
  def event_manager(pid) do
    GenServer.call(pid, :event_manager)
  end

  @doc """
  Return the current status of the wpa_supplicant. It wraps the
  STATUS command.
  """
  def status(pid) do
    request(pid, :STATUS)
  end

  @doc """
  Tell the wpa_supplicant to connect to the specified network. Invoke
  like this:

      iex> WpaSupplicant.set_network(pid, ssid: "MyNetworkSsid", key_mgmt: :WPA_PSK, psk: "secret")

  or like this:

      iex> WpaSupplicant.set_network(pid, %{ssid: "MyNetworkSsid", key_mgmt: :WPA_PSK, psk: "secret"})

  Many options are supported, but it is likely that `ssid` and `psk` are
  the most useful. The full list can be found in the wpa_supplicant
  documentation. Here's a list of some common ones:

  Option                | Description
  ----------------------|------------
  :ssid                 | Network name. This is mandatory.
  :key_mgmt             | The security in use. This is mandatory. Set to :NONE, :WPA_PSK
  :proto                | Protocol use use. E.g., :WPA2
  :psk                  | WPA preshared key. 8-63 chars or the 64 char one as processed by `wpa_passphrase`
  :bssid                | Optional BSSID. If set, only associate with the AP with a matching BSSID
  :mode                 | Mode: 0 = infrastructure (default), 1 = ad-hoc, 2 = AP
  :frequency            | Channel frequency. e.g., 2412 for 802.11b/g channel 1
  :wep_key0..3          | Static WEP key
  :wep_tx_keyidx        | Default WEP key index (0 to 3)

  Note that this is a helper function that wraps several low level calls and
  is limited to specifying only one network at a time. If you'd
  like to register multiple networks with the supplicant, send the
  ADD_NETWORK, SET_NETWORK, SELECT_NETWORK messages manually.
  """
  def set_network(pid, options) do
    # Don't worry if the following fails. We just need to
    # make sure that no other networks registered with the
    # wpa_supplicant take priority over ours
    request(pid, {:REMOVE_NETWORK, :all})

    netid = request(pid, :ADD_NETWORK)
    Enum.each(options, fn({key, value}) ->
        :ok = request(pid, {:SET_NETWORK, netid, key, value})
      end)

    :ok = request(pid, {:SELECT_NETWORK, netid})
  end

  @doc """
  This is a helper function that will initiate a scan, wait for the
  scan to complete and return a list of all of the available access
  points. This can take a while if the wpa_supplicant hasn't scanned
  for access points recently.
  """
  def scan(pid) do
    stream = pid |> event_manager |> GenEvent.stream(timeout: 60000)
    case request(pid, :SCAN) do
      :ok -> :ok

      # If the wpa_supplicant is already scanning, FAIL-BUSY is
      # returned.
      "FAIL-BUSY" -> :ok
    end

    # Wait for the scan results
    Enum.take_while(stream, fn(x) -> x == {:wpa_supplicant, pid, :"CTRL-EVENT-SCAN-RESULTS"} end)

    # Collect all BSSs
    all_bss(pid, 0, [])
  end

  defp all_bss(pid, count, acc) do
    result = request(pid, {:BSS, count})
    if result do
      all_bss(pid, count + 1, [result | acc])
    else
      acc
    end
  end

  def init({control_socket_path, event_manager}) do
    executable = :code.priv_dir(:wpa_supplicant) ++ '/wpa_ex'
    port = Port.open({:spawn_executable, executable},
                     [{:args, [control_socket_path]},
                      {:packet, 2},
                      :binary,
                      :exit_status])
    { :ok, %WpaSupplicant{port: port, manager: event_manager} }
  end

  def handle_call({:request, command}, from, state) do
    payload = WpaSupplicant.Encode.encode(command)
    Logger.info("WpaSupplicant: sending '#{payload}'")
    send state.port, {self, {:command, payload}}
    state = %{state | :requests => state.requests ++ [{from, command}]}
    {:noreply, state}
  end
  def handle_call(:event_manager, _from, state) do
    {:reply, state.manager, state}
  end

  def handle_info({_, {:data, message}}, state) do
    handle_wpa(message, state)
  end
  def handle_info({_, {:exit_status, _}}, state) do
    {:stop, :unexpected_exit, state}
  end

  defp handle_wpa(<< "<", _priority::utf8, ">", notification::binary>>, state) do
    decoded_notif = WpaSupplicant.Decode.notif(notification)
    GenEvent.notify(state.manager, {:wpa_supplicant, self, decoded_notif})
    {:noreply, state}
  end
  defp handle_wpa(response, state) do
    [{client, command} | next_ones] = state.requests
    state = %{state | :requests => next_ones}

    decoded_response = WpaSupplicant.Decode.resp(command, response)
    GenServer.reply client, decoded_response
    {:noreply, state}
  end
end

# Copyright 2014 LKC Technologies, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

defmodule WpaSupplicant do
  use GenServer
  require Logger

  defstruct port: nil,
            manager: nil,
            requests: []

  @doc """
  Start and link a WpaSupplicant process that uses the specified
  control socket. A GenEvent will be spawned for managing wpa_supplicant
  events. Call event_manager/1 to get the GenEvent pid.
  """
  def start_link(control_socket_path) do
    { :ok, manager } = GenEvent.start_link
    start_link(control_socket_path, manager)
  end

  @doc """
  Start and link a WpaSupplicant that uses the specified control
  socket and GenEvent event manager.
  """
  def start_link(control_socket_path, event_manager) do
    GenServer.start_link(__MODULE__, {control_socket_path, event_manager})
  end

  @doc """
  Send a request to the wpa_supplicant.

  ## Examples

      iex> WpaSupplicant.request(pid, :PING)
      :PONG
  """
  def request(pid, command) do
    GenServer.call(pid, {:request, command})
  end

  @doc """
  Get a reference to the GenEvent event manager in use by this
  supplicant.
  """
  def event_manager(pid) do
    GenServer.call(pid, :event_manager)
  end

  @doc """
  Return the current status of the wpa_supplicant. It wraps the
  STATUS command.
  """
  def status(pid) do
    request(pid, :STATUS)
  end

  @doc """
  Tell the wpa_supplicant to connect to the specified network. Invoke
  like this:

      iex> WpaSupplicant.set_network(pid, ssid: "MyNetworkSsid", key_mgmt: :WPA_PSK, psk: "secret")

  or like this:

      iex> WpaSupplicant.set_network(pid, %{ssid: "MyNetworkSsid", key_mgmt: :WPA_PSK, psk: "secret"})

  Many options are supported, but it is likely that `ssid` and `psk` are
  the most useful. The full list can be found in the wpa_supplicant
  documentation. Here's a list of some common ones:

  Option                | Description
  ----------------------|------------
  :ssid                 | Network name. This is mandatory.
  :key_mgmt             | The security in use. This is mandatory. Set to :NONE, :WPA_PSK
  :proto                | Protocol use use. E.g., :WPA2
  :psk                  | WPA preshared key. 8-63 chars or the 64 char one as processed by `wpa_passphrase`
  :bssid                | Optional BSSID. If set, only associate with the AP with a matching BSSID
  :mode                 | Mode: 0 = infrastructure (default), 1 = ad-hoc, 2 = AP
  :frequency            | Channel frequency. e.g., 2412 for 802.11b/g channel 1
  :wep_key0..3          | Static WEP key
  :wep_tx_keyidx        | Default WEP key index (0 to 3)

  Note that this is a helper function that wraps several low level calls and
  is limited to specifying only one network at a time. If you'd
  like to register multiple networks with the supplicant, send the
  ADD_NETWORK, SET_NETWORK, SELECT_NETWORK messages manually.
  """
  def set_network(pid, options) do
    # Don't worry if the following fails. We just need to
    # make sure that no other networks registered with the
    # wpa_supplicant take priority over ours
    request(pid, {:REMOVE_NETWORK, :all})

    netid = request(pid, :ADD_NETWORK)
    Enum.each(options, fn({key, value}) ->
        :ok = request(pid, {:SET_NETWORK, netid, key, value})
      end)

    :ok = request(pid, {:SELECT_NETWORK, netid})
  end

  @doc """
  This is a helper function that will initiate a scan, wait for the
  scan to complete and return a list of all of the available access
  points. This can take a while if the wpa_supplicant hasn't scanned
  for access points recently.
  """
  def scan(pid) do
    stream = pid |> event_manager |> GenEvent.stream(timeout: 60000)
    case request(pid, :SCAN) do
      :ok -> :ok

      # If the wpa_supplicant is already scanning, FAIL-BUSY is
      # returned.
      "FAIL-BUSY" -> :ok
    end

    # Wait for the scan results
    Enum.take_while(stream, fn(x) -> x == {:wpa_supplicant, pid, :"CTRL-EVENT-SCAN-RESULTS"} end)

    # Collect all BSSs
    all_bss(pid, 0, [])
  end

  defp all_bss(pid, count, acc) do
    result = request(pid, {:BSS, count})
    if result do
      all_bss(pid, count + 1, [result | acc])
    else
      acc
    end
  end

  def init({control_socket_path, event_manager}) do
    executable = :code.priv_dir(:wpa_supplicant) ++ '/wpa_ex'
    port = Port.open({:spawn_executable, executable},
                     [{:args, [control_socket_path]},
                      {:packet, 2},
                      :binary,
                      :exit_status])
    { :ok, %WpaSupplicant{port: port, manager: event_manager} }
  end

  def handle_call({:request, command}, from, state) do
    payload = WpaSupplicant.Encode.encode(command)
    Logger.info("WpaSupplicant: sending '#{payload}'")
    send state.port, {self, {:command, payload}}
    state = %{state | :requests => state.requests ++ [{from, command}]}
    {:noreply, state}
  end
  def handle_call(:event_manager, _from, state) do
    {:reply, state.manager, state}
  end

  def handle_info({_, {:data, message}}, state) do
    handle_wpa(message, state)
  end
  def handle_info({_, {:exit_status, _}}, state) do
    {:stop, :unexpected_exit, state}
  end

  defp handle_wpa(<< "<", _priority::utf8, ">", notification::binary>>, state) do
    decoded_notif = WpaSupplicant.Decode.notif(notification)
    GenEvent.notify(state.manager, {:wpa_supplicant, self, decoded_notif})
    {:noreply, state}
  end
  defp handle_wpa(response, state) do
    [{client, command} | next_ones] = state.requests
    state = %{state | :requests => next_ones}

    decoded_response = WpaSupplicant.Decode.resp(command, response)
    GenServer.reply client, decoded_response
    {:noreply, state}
  end
end


Rename users to chats

Rename users to chats

defmodule Server.Components.Chats do
  use GenServer

  def start_link do
    GenServer.start_link(__MODULE__, :ok, name: __MODULE__)
  end

  def register_user(user) do
    GenServer.call(__MODULE__, {:register_user, user})
  end

  def list_users do
    GenServer.call(__MODULE__, :list_users)
  end

  def init(_) do
    # TODO: create User and ChatHistory models
    chats = %{}
    {:ok, chats}
  end

  def handle_call({:register_user, user}, _from, chats) do
    case Map.has_key?(chats, user) do
      true -> {:reply, {:error, :already_taken}, chats}
      false -> {:reply, :ok, Map.put(chats, user, %{})}
    end
  end

  def handle_call(:list_users, _from, chats) do
    {:reply, {:ok, Map.keys chats}, chats}
  end
end

defmodule Server.Components.Chats do
  use GenServer

  def start_link do
    GenServer.start_link(__MODULE__, :ok, name: __MODULE__)
  end

  def register_user(user) do
    GenServer.call(__MODULE__, {:register_user, user})
  end

  def list_users do
    GenServer.call(__MODULE__, :list_users)
  end

  def init(_) do
    # TODO: create User and ChatHistory models
    users = %{}
    {:ok, users}
  end

  def handle_call({:register_user, user}, _from, state) do
    case Map.has_key?(state, user) do
      true -> {:reply, {:error, :already_taken}, state}
      false -> {:reply, :ok, Map.put(state, user, %{})}
    end
  end

  def handle_call(:list_users, _from, state) do
    {:reply, {:ok, Map.keys state}, state}
  end
end


Code cleanup, some comment clarifications

# numbers to words

defmodule NumbersToWords do

  @places ~w[ thousand million billion trillion quadrillion quintillion sextillion septillion octillion nonillion decillion ]

  # the default entry point, when the argument is an int and not a binary string
  def parse(int) when is_integer(int) do
    parse(Integer.to_string(int)) |> String.replace("  ", " ") |> String.rstrip
  end

  # nought case
  def parse(""), do: ""

  # negative integer case
  def parse(<<?-, the_rest::binary>>), do: "negative " <> parse(the_rest)

  # ones
  def parse("0"), do: "zero"
  def parse("1"), do: "one"
  def parse("2"), do: "two"
  def parse("3"), do: "three"
  def parse("4"), do: "four"
  def parse("5"), do: "five"
  def parse("6"), do: "six"
  def parse("7"), do: "seven"
  def parse("8"), do: "eight"
  def parse("9"), do: "nine"

  # tens
  def parse("00"), do: ""
  def parse("10"), do: "ten"
  def parse("11"), do: "eleven"
  def parse("12"), do: "twelve"
  def parse("13"), do: "thirteen"
  def parse("14"), do: "fourteen"
  def parse("15"), do: "fifteen"
  def parse("16"), do: "sixteen"
  def parse("17"), do: "seventeen"
  def parse("18"), do: "eighteen"
  def parse("19"), do: "nineteen"
  def parse("20"), do: "twenty"

  # tens, finally with a pattern
  def parse(<<?2, n::utf8>>), do: "twenty #{parse(<<n>>)}"
  def parse("30"), do: "thirty"
  def parse(<<?3, n::utf8>>), do: "thirty #{parse(<<n>>)}"
  def parse("40"), do: "forty"
  def parse(<<?4, n::utf8>>), do: "forty #{parse(<<n>>)}"
  def parse("50"), do: "fifty"
  def parse(<<?5, n::utf8>>), do: "fifty #{parse(<<n>>)}"
  def parse("60"), do: "sixty"
  def parse(<<?6, n::utf8>>), do: "sixty #{parse(<<n>>)}"
  def parse("70"), do: "seventy"
  def parse(<<?7, n::utf8>>), do: "seventy #{parse(<<n>>)}"
  def parse("80"), do: "eighty"
  def parse(<<?8, n::utf8>>), do: "eighty #{parse(<<n>>)}"
  def parse("90"), do: "ninety"
  def parse(<<?9, n::utf8>>), do: "ninety #{parse(<<n>>)}"

  # tens with a leading zero... drop it
  def parse(<<?0, n::utf8>>), do: parse(<<n>>)

  # hundreds with a leading zero... drop it
  def parse(<<?0, tens::utf8, ones::utf8>>), do: parse(<<tens, ones>>)

  # regular hundreds
  def parse(<<hundreds::utf8, tens::utf8, ones::utf8>>), do: "#{parse(<<hundreds>>)} hundred #{parse(<<tens, ones>>)}"

  #### Thousands and up. now we get fancy ####

  # General case for splitting up digits 4 or longer, start an "every third digit" state and pass back
  # Since all binaries fall through to here that also haven't already matched, we have to validate too
  def parse(<<long_binary::binary>>) when is_binary(long_binary) do
    if validate?(long_binary) do
      parse(<<long_binary::binary>>, @places)
    else
      raise ArgumentError, message: "Unknown digit(s): #{long_binary}"
    end
  end

  # End case where we run out of words. Oops.
  def parse(_, []) do
    raise ArgumentError, message: "Dude. That number is too long. I don't know how to say it."
  end

  # End cases (length is 3 or less). no more to parse, drop "every third digit" state, fallback to digit-trio parsing
  def parse(<<ones::utf8>>, _), do: parse(<<ones::utf8>>)
  def parse(<<tens::utf8, ones::utf8>>, _), do: parse(<<tens::utf8, ones::utf8>>)
  def parse(<<hundreds::utf8, tens::utf8, ones::utf8>>, _), do: parse(<<hundreds::utf8, tens::utf8, ones::utf8>>)

  # thousands and up here... recursive call... this is most of the magic
  def parse(<<long_binary::binary>>, [illion | rest]) do
    { further_digits, these_digits } = String.split_at(long_binary, -3)
    if String.match?(further_digits, ~r/0{3}$/) do
      # we have to skip the trio join word if the next trio of parseable digits to the left is all zeroes, basically
      # Otherwise you'd get stuff like "six trillion billion million thousand"
      parse(<<further_digits::binary>>, rest) <> parse(<<these_digits::binary>>)
    else
      parse(<<further_digits::binary>>, rest) <> " #{illion} " <> parse(<<these_digits::binary>>)
    end
  end

  # numeric string validation
  defp validate?(str) do
    String.match?(str, ~r/^-?[0-9]+$/)
  end

end

# run this inline suite with "elixir #{__ENV__.file} test"
if System.argv |> List.first == "test" do
  ExUnit.start
  defmodule NumbersToWordsTest do
    use ExUnit.Case, async: true

    test "single digits to words" do
      %{zero: 0, one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9}
      |>
      Enum.each(fn {word, num} ->
        assert to_string(word) == NumbersToWords.parse(num)
      end)
    end

    test "negative" do
      assert "negative one thousand one" == NumbersToWords.parse(-1001)
    end

    test "tens digits to words" do
      assert "twelve" == NumbersToWords.parse(12)
      assert "eighteen" == NumbersToWords.parse(18)
      assert "twenty three" == NumbersToWords.parse(23)
      assert "fifty six" == NumbersToWords.parse(56)
      assert "sixty nine" == NumbersToWords.parse(69)
      assert "ninety five" == NumbersToWords.parse(95)
    end

    test "hundreds numbers to words" do
      assert "one hundred three" == NumbersToWords.parse(103)
      assert "five hundred twelve" == NumbersToWords.parse(512)
      assert "three hundred" == NumbersToWords.parse(300)
    end

    test "thousands numbers to words" do
      assert "four thousand twenty three" == NumbersToWords.parse(4023)
    end

    test "hundred thousand numbers to words" do
      assert "three hundred thousand four" == NumbersToWords.parse(300004)
    end

    test "three zeroes" do
      assert "" == NumbersToWords.parse("000")
    end

    test "quadrillion baby" do
      assert "three quadrillion" == NumbersToWords.parse(3000000000000000)
      assert "three quadrillion one" == NumbersToWords.parse(3000000000000001)
    end

    # showoff...
    test "negative quintillion with interspersed digits" do
      assert "negative sixty nine quintillion one billion six hundred ninety million one" == NumbersToWords.parse(-69000000001690000001)
    end

    test "running out of available words raises" do
      assert_raise ArgumentError, "Dude. That number is too long. I don't know how to say it.", fn ->
        NumbersToWords.parse(100000000000000000000000000000000000000000000000000)
      end
    end

    test "unknown characters raise" do
      assert_raise ArgumentError, "Unknown digit(s): r", fn -> NumbersToWords.parse("r") end
      assert_raise ArgumentError, "Unknown digit(s): r5", fn -> NumbersToWords.parse("1r5") end
    end

  end
end

# numbers to words

defmodule NumbersToWords do

  @places ~w[ thousand million billion trillion quadrillion quintillion sextillion septillion octillion nonillion decillion ]

  # the default entry point, when the argument is an int and not a binary string
  def parse(int) when is_integer(int) do
    parse(Integer.to_string(int)) |> String.replace("  ", " ") |> String.rstrip
  end

  # nought case
  def parse(""), do: ""

  # negative case
  def parse(<<?-, the_rest::binary>>), do: "negative " <> parse(the_rest)

  # ones
  def parse("0"), do: "zero"
  def parse("1"), do: "one"
  def parse("2"), do: "two"
  def parse("3"), do: "three"
  def parse("4"), do: "four"
  def parse("5"), do: "five"
  def parse("6"), do: "six"
  def parse("7"), do: "seven"
  def parse("8"), do: "eight"
  def parse("9"), do: "nine"

  # fallthrough case for any binary strings that haven't matched yet
  def parse(<<unknown::utf8>>) when is_binary(unknown) do
    IO.puts "parsing #{unknown}"
    raise ArgumentError, message: "Unknown digit(s): #{unknown}"
  end

  # tens
  def parse("00"), do: ""
  def parse("10"), do: "ten"
  def parse("11"), do: "eleven"
  def parse("12"), do: "twelve"
  def parse("13"), do: "thirteen"
  def parse("14"), do: "fourteen"
  def parse("15"), do: "fifteen"
  def parse("16"), do: "sixteen"
  def parse("17"), do: "seventeen"
  def parse("18"), do: "eighteen"
  def parse("19"), do: "nineteen"
  def parse("20"), do: "twenty"
  def parse(<<?2, n::utf8>>), do: "twenty #{parse(<<n>>)}"
  def parse("30"), do: "thirty"
  def parse(<<?3, n::utf8>>), do: "thirty #{parse(<<n>>)}"
  def parse("40"), do: "forty"
  def parse(<<?4, n::utf8>>), do: "forty #{parse(<<n>>)}"
  def parse("50"), do: "fifty"
  def parse(<<?5, n::utf8>>), do: "fifty #{parse(<<n>>)}"
  def parse("60"), do: "sixty"
  def parse(<<?6, n::utf8>>), do: "sixty #{parse(<<n>>)}"
  def parse("70"), do: "seventy"
  def parse(<<?7, n::utf8>>), do: "seventy #{parse(<<n>>)}"
  def parse("80"), do: "eighty"
  def parse(<<?8, n::utf8>>), do: "eighty #{parse(<<n>>)}"
  def parse("90"), do: "ninety"
  def parse(<<?9, n::utf8>>), do: "ninety #{parse(<<n>>)}"

  # tens with a leading zero... drop it
  def parse(<<?0, n::utf8>>), do: parse(<<n>>)

  # hundreds with a leading zero
  def parse(<<?0, tens::utf8, ones::utf8>>), do: parse(<<tens, ones>>)

  # regular hundreds
  def parse(<<hundreds::utf8, tens::utf8, ones::utf8>>), do: "#{parse(<<hundreds>>)} hundred #{parse(<<tens, ones>>)}"

  #### thousands and up. now we get fancy ####

  # General case for splitting up digits 4 or longer, start an "every third digit" state and pass back
  # Since all binaries fall through to here that also haven't already matched, we have to validate too
  def parse(<<long_binary::binary>>) when is_binary(long_binary) do
    if validate?(long_binary) do
      parse(<<long_binary::binary>>, @places)
    else
      raise ArgumentError, message: "Unknown digit(s): #{long_binary}"
    end
  end

  defp validate?(str) do
    String.match?(str, ~r/^-?[0-9]+$/)
  end

  # End case where we run out of words. Oops.
  def parse(_, []) do
    raise ArgumentError, message: "Dude. That number is too long. I don't know how to say it."
  end

  # End cases (length is 3 or less). no more to parse, drop "every third digit" state, fallback to digit-trio parsing
  def parse(<<ones::utf8>>, _), do: parse(<<ones::utf8>>)
  def parse(<<tens::utf8, ones::utf8>>, _), do: parse(<<tens::utf8, ones::utf8>>)
  def parse(<<hundreds::utf8, tens::utf8, ones::utf8>>, _), do: parse(<<hundreds::utf8, tens::utf8, ones::utf8>>)

  # thousands and up here... recursive call... this is most of the magic
  def parse(<<long_binary::binary>>, [next | rest]) do
    { further_digits, these_digits } = String.split_at(long_binary, -3)
    if String.match?(further_digits, ~r/0{3}$/) do
      # we have to skip the trio join word if the next trio of parseable digits to the left is all zeroes basically
      parse(<<further_digits::binary>>, rest) <> parse(<<these_digits::binary>>)
    else
      parse(<<further_digits::binary>>, rest) <> " #{next} " <> parse(<<these_digits::binary>>)
    end
  end

end

# run this inline suite with "elixir #{__ENV__.file} test"
if System.argv |> List.first == "test" do
  ExUnit.start
  defmodule NumbersToWordsTest do
    use ExUnit.Case, async: true

    test "single digits to words" do
      %{zero: 0, one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9}
      |>
      Enum.each(fn {word, num} ->
        assert to_string(word) == NumbersToWords.parse(num)
      end)
    end

    test "negative" do
      assert "negative one thousand one" == NumbersToWords.parse(-1001)
    end

    test "tens digits to words" do
      assert "twelve" == NumbersToWords.parse(12)
      assert "eighteen" == NumbersToWords.parse(18)
      assert "twenty three" == NumbersToWords.parse(23)
      assert "fifty six" == NumbersToWords.parse(56)
      assert "sixty nine" == NumbersToWords.parse(69)
      assert "ninety five" == NumbersToWords.parse(95)
    end

    test "hundreds numbers to words" do
      assert "one hundred three" == NumbersToWords.parse(103)
      assert "five hundred twelve" == NumbersToWords.parse(512)
      assert "three hundred" == NumbersToWords.parse(300)
    end

    test "thousands numbers to words" do
      assert "four thousand twenty three" == NumbersToWords.parse(4023)
    end

    test "hundred thousand numbers to words" do
      assert "three hundred thousand four" == NumbersToWords.parse(300004)
    end

    test "three zeroes" do
      assert "" == NumbersToWords.parse("000")
    end

    test "quadrillion baby" do
      assert "three quadrillion" == NumbersToWords.parse(3000000000000000)
      assert "three quadrillion one" == NumbersToWords.parse(3000000000000001)
    end

    # showoff...
    test "negative quintillion with interspersed digits" do
      assert "negative sixty nine quintillion one billion six hundred ninety million one" == NumbersToWords.parse(-69000000001690000001)
    end

    test "running out of available words raises" do
      assert_raise ArgumentError, "Dude. That number is too long. I don't know how to say it.", fn ->
        NumbersToWords.parse(100000000000000000000000000000000000000000000000000)
      end
    end

    test "unknown characters raise" do
      assert_raise ArgumentError, "Unknown digit(s): r", fn -> NumbersToWords.parse("r") end
      assert_raise ArgumentError, "Unknown digit(s): r5", fn -> NumbersToWords.parse("1r5") end
    end

  end
end


integration level test

integration level test

defmodule BencheeTest do
  use ExUnit.Case
  import ExUnit.CaptureLog
  doctest Benchee

  test "integration" do
    capture_log fn ->
      result =
        Benchee.init(%{time: 0.1})
        |> Benchee.benchmark("Sleeps", fn -> :timer.sleep(10) end)
        |> Benchee.Statistics.statistics
        |> Benchee.Formatters.String.format

      [header, benchmark_stats] = result
      assert Regex.match?(~r/Name.+ips.+average.+deviation/, header)

      assert Regex.match?(~r/Sleeps/, benchmark_stats)
    end
  end
end

defmodule BencheeTest do
  use ExUnit.Case
  doctest Benchee
end