How to add md5 sum of email to user

I’d like to display a gravatar avatar for a user (Creating the Hash – Gravatar Developer Docs) and need the md5 sum of the email address for that. What is the best way to do this within Ash? I can’t solve this with calculations or can I?

defmodule Animina.Accounts.User do
  @moduledoc """
  This is the User module.
  """

  use Ash.Resource,
    data_layer: AshPostgres.DataLayer,
    extensions: [AshAuthentication]

  attributes do
    uuid_primary_key :id
    attribute :email, :ci_string, allow_nil?: false
    attribute :hashed_password, :string, allow_nil?: false, sensitive?: true
    attribute :username, :string, allow_nil?: false
  end

You can definitely use calculations for that. You’d just want to use a module-backed calculation (or the shorthand anonymous function)

defmodule MyApp.Calculations.Md5 do
  use Ash.Calculation

  def load(_, opts, _), do: [opts[:field]]

  def calculate(records, opts, _) do
    Enum.map(records, fn record -> md5(Map.get(record, opts[:field])) end)
  end
end

calculations do
  calculate :gravatar_hash, :string, {MyApp.Calculations.Md5, field: :email}
end
3 Likes