A Waffle definition module is created by using the Waffle.Definition module. This module defines how files are validated, transformed (e.g., resizing images), named, and where they are stored.
Key callbacks to implement:
@versions: A list of atoms representing the different versions of the file (e.g., [:original, :thumb]).@extensions: A list of allowed file extensions.validate/1: Validates the file (e.g., checking extensions). Returns :ok or {:error, reason}.transform/2: Defines image processing instructions for a specific version. Returns {:convert, command, extension}.filename/2: Determines the filename for a specific version.storage_dir/2: Determines the directory path where the file should be stored. This function can accept additional context (like a user record) passed during the store call.
defmodule Avatar do
use Waffle.Definition
@versions [:original, :thumb]
@extensions ~w(.jpg .jpeg .gif .png)
def validate({file, _}) do
file_extension = file.file_name |> Path.extname |> String.downcase
case Enum.member?(@extensions, file_extension) do
true -> :ok
false -> {:error, "file type is invalid"}
end
end
def transform(:thumb, _) do
{:convert, "-thumbnail 100x100^ -gravity center -extent 100x100 -format png", :png}
end
def filename(version, _) do
version
end
def storage_dir(_, {file, user}) do
"uploads/avatars/#{user.id}"
end
end