Skip to content

Instantly share code, notes, and snippets.

@totaltrash
Last active April 26, 2022 05:29
Show Gist options
  • Save totaltrash/1480b1fbcf96142c27df773edab515b6 to your computer and use it in GitHub Desktop.
Save totaltrash/1480b1fbcf96142c27df773edab515b6 to your computer and use it in GitHub Desktop.

A taste of Ash

Install deps

Mix.install([
  {:ash, "~> 1.51.2"},
  {:kino, "~> 0.5.2"}
])

Define some resources

defmodule MyApp.Tweet do
  use Ash.Resource, data_layer: Ash.DataLayer.Ets

  attributes do
    uuid_primary_key(:id)

    attribute :body, :string do
      allow_nil?(false)
      constraints(max_length: 255)
    end

    attribute(:public, :boolean, allow_nil?: false, default: false)

    create_timestamp(:inserted_at)
    update_timestamp(:updated_at)
  end
end

defmodule MyApp.User do
  use Ash.Resource, data_layer: Ash.DataLayer.Ets

  attributes do
    attribute(:email, :string,
      allow_nil?: false,
      constraints: [
        match: ~r/^[\w.!#$%&’*+\-\/=?\^`{|}~]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*$/i
      ]
    )

    uuid_primary_key(:id)
  end
end

Set up the API and registry

defmodule MyApp.Api do
  use Ash.Api

  resources do
    registry(MyApp.Registry)
  end
end

defmodule MyApp.Registry do
  use Ash.Registry,
    extensions: [Ash.Registry.ResourceValidations]

  entries do
    entry(MyApp.User)
    entry(MyApp.Tweet)
  end
end

Time to play

MyApp.User
|> Ash.Changeset.new(%{email: "[email protected]"})
|> MyApp.Api.create!()
users = MyApp.Api.read!(MyApp.User)
Kino.DataTable.new(users)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment