Ash Calculations - Cond

neophen

Mykolas Mankevicius

Posted on March 7, 2024

Ash Calculations - Cond

I want to have resource examples of all Ash calculations

Here's the cond example:

calculations do
  calculate(:title, :string, expr(
      cond do
        type == "RCCB" -> current <> "A P" <> slots <> " " <> type
        type == "MCB" -> curve <> current <> " P" <> slots <> " " <> type
      end
  ))
end
Enter fullscreen mode Exit fullscreen mode

Here's an example resource with full code:

defmodule NoSpark.Builder.Module do
  use Ash.Resource,
    data_layer: AshSqlite.DataLayer

  sqlite do
    table "modules"
    repo NoSpark.Repo
  end

  attributes do
    uuid_primary_key :id

    attribute :current, :integer do
      allow_nil? false
      constraints min: 0
    end

    attribute :curve, :string do
      allow_nil? false
    end

    attribute :type, :string do
      allow_nil? false
    end
  end

calculations do
  calculate(:title, :string, expr(
      cond do
        type == "RCCB" -> current <> "A " <> type
        type == "MCB" -> curve <> current <> " " <> type
      end
  ))
end

  code_interface do
    define_for(NoSpark.Builder)
    define(:read)
  end

  actions do
    defaults [:create, :read, :update, :destroy]
  end
end
Enter fullscreen mode Exit fullscreen mode

Here's how you would load the calculation:

Builder.Module
|> Ash.Query.load([:title])
|> Builder.read!()

# or with the code interface

Builder.Module.read!(load: [:title])
Enter fullscreen mode Exit fullscreen mode

Hope this helps.

💖 💪 🙅 🚩
neophen
Mykolas Mankevicius

Posted on March 7, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Ash - Create with relationship
elixir Ash - Create with relationship

March 27, 2024

Ash Calculations - Cond
elixir Ash Calculations - Cond

March 7, 2024