How to Autoload Calculations?

Is there a way to autoload calculations? Right now I can do Accounts.User.by_id!("123") |> Accounts.load(:gravatar_hash) but I’d like to be able to get the same result with just Accounts.User.by_id!("123")

  • Is that possible?
  • Is there a reason not to autoload? Other than performance.

The module

defmodule Animina.Accounts.User do
  # ...
  
  attributes do
    uuid_primary_key :id
    attribute :email, :ci_string, allow_nil?: false
    attribute :hashed_password, :string, allow_nil?: false, sensitive?: true
  end

  calculations do
    calculate :gravatar_hash, :string, {Animina.Calculations.Md5, field: :email}
  end

  # ...

  identities do
    identity :unique_email, [:email]
  end

  actions do
    defaults [:read]
  end

  code_interface do
    define_for Animina.Accounts
    define :read
    define :by_id, get_by: [:id], action: :read
  end
end
``

You can use the global preparations block to add a preparation to all read actions, and then you can use the build/1 preparation to add to the query.

prepare build(load: [:calc])

The only reason not to autoload would be performance :slight_smile:. I generally avoid it, but if its a simple calculation and you access it all the time, its not a big deal at all.

1 Like

For everybody who needs it spoon fed (like me) here’s the code solution:

  preparations do
    prepare build(load: [:gravatar_hash])
  end
2 Likes