Combo.URLParam protocol (combo v0.10.0)
View SourceA protocol that converts data structures into URL parameters.
This protocol is mainly used by router helpers. For example, when you write:
alias MyApp.Web.Router.Helpers, as: Routes
Routes.user_path(conn, :show, @user)It knows how to convert @user to a string thanks to this protocol.
By default, Combo implements this protocol for integers, binaries, atoms,
and structs. For structs, a key :id is assumed, but you may provide a
specific implementation.
The term nil cannot be converted to URL parameter.
Custom implementation
In order to customize the parameter for any struct, one can simply implement
this protocol. For example for a Date struct:
defimpl Combo.URLParam, for: Date do
def to_param(date) do
Date.to_string(date)
end
endHowever, for convenience, this protocol can also be derivable. For example:
defmodule User do
@derive Combo.URLParam
defstruct [:id, :username]
endBy default, the derived implementation will use the :id key. In case the
user does not contain an :id key, the key can be specified with an option:
defmodule User do
@derive {Combo.URLParam, key: :username}
defstruct [:username]
endThen, it will use :username in URLs.
When using Ecto, you must call @derive before the schema call:
@derive {Combo.URLParam, key: :username}
schema "users" do
Summary
Types
@type t() :: term()
All the types that implement this protocol.