Skip to content

Instantly share code, notes, and snippets.

@zachdaniel
Last active December 5, 2024 03:23
Show Gist options
  • Save zachdaniel/bb3fd191679774c3d3fb56e98accb4d3 to your computer and use it in GitHub Desktop.
Save zachdaniel/bb3fd191679774c3d3fb56e98accb4d3 to your computer and use it in GitHub Desktop.
Example of data-layer-less resources
defmodule Greeting do
use Ash.Resource
# This resource has no struct representation
# and simply contains the action.
# What makes this better than a function?
# https://hexdocs.pm/ash/generic-actions.html#why-use-generic-actions
actions do
action :say_hello, :string do
argument :to, :string, allow_nil?: false
run fn input, _ ->
{:ok, "Helo, #{input.arguments.to}"}
end
end
end
end
defmodule MyApp.Ticket do
use Ash.Resource
# This resource has a struct representation but no data layer
# In this case, it works with external data
actions do
create :create do
accept [:title, :priority]
manual fn changeset, _ ->
with {:ok, data} <- Ash.Changeset.apply_attributes(changeset),
{:ok, result} <- SomeExternalService.create(data.title, data.priority) do
{:ok, struct(__MODULE__, id: result.id, title: result.title, priority: result.priority)}
end
end
end
end
attributes do
integer_primary_key :id
attribute :title, :string, allow_nil?: false
attribute :priority, :integer, allow_nil?: false
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment