Skip to content

Commit

Permalink
Merge pull request #27 from mylanconnolly/main
Browse files Browse the repository at this point in the history
Allow slugs to handle Ash.CiString values
  • Loading branch information
rhblind authored Nov 18, 2024
2 parents d1efacd + a374c29 commit 21813fd
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 2 deletions.
9 changes: 8 additions & 1 deletion lib/ash_slug/changes/slugify.ex
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ defmodule AshSlug.Changes.Slugify do
Ash.Changeset.before_action(changeset, fn changeset ->
with {attribute, opts} <- Keyword.pop(opts, :attribute),
{into, opts} <- Keyword.pop(opts, :into, attribute),
{:ok, value} when is_binary(value) <- Ash.Changeset.fetch_argument_or_change(changeset, attribute),
{:ok, value} when is_binary(value) <- get_attribute(changeset, attribute),
slug <- Slug.slugify(value, opts) do
changeset
|> Ash.Changeset.force_change_attribute(into, slug)
Expand All @@ -61,6 +61,13 @@ defmodule AshSlug.Changes.Slugify do
end)
end

defp get_attribute(changeset, attribute) do
case Ash.Changeset.fetch_argument_or_change(changeset, attribute) do
{:ok, %Ash.CiString{} = value} -> {:ok, Ash.CiString.value(value)}
res -> res
end
end

@spec replace_lowercase_opts(Keyword.t()) :: Keyword.t()
defp replace_lowercase_opts(opts) do
Keyword.pop(opts, :lowercase?)
Expand Down
10 changes: 10 additions & 0 deletions test/ash_slug_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,16 @@ defmodule AshSlugTest do
assert resource.text1 == "Hello-World"
end

test "ensure Ash.CiString value is slugified" do
resource =
AshSlugTest.Resource
|> Ash.Changeset.for_create(:create, %{text3: Ash.CiString.new("Hello, World!")})
|> Ash.Changeset.set_context(%{foo: :bar})
|> Ash.create!()

assert resource.text3_slug == "hello-world"
end

test "ensure value is slugified into another attribute" do
resource =
AshSlugTest.Resource
Expand Down
5 changes: 4 additions & 1 deletion test/support/resource.ex
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,18 @@ defmodule AshSlugTest.Resource do
attribute(:text1, :string, public?: true)
attribute(:text2, :string, public?: true)
attribute(:text2_slug, :string)
attribute(:text3, :ci_string, public?: true)
attribute(:text3_slug, :string)
attribute(:bool, :boolean, public?: true)
end

actions do
create :create do
accept([:text1, :text2, :bool])
accept([:text1, :text2, :text3, :bool])

change(slugify(:text1, lowercase?: false))
change(slugify(:text2, into: :text2_slug))
change(slugify(:text3, into: :text3_slug))
change(slugify(:bool))
end
end
Expand Down

0 comments on commit 21813fd

Please sign in to comment.