DEV Community

Cover image for Ash Calculations - Cond
Mykolas Mankevicius
Mykolas Mankevicius

Posted on

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.

Top comments (0)