Skip to content

Commit

Permalink
rename @__struct__ to @___struct___ to use with typespec
Browse files Browse the repository at this point in the history
  • Loading branch information
namjae committed Apr 8, 2023
1 parent c37d41c commit 0b77c2d
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 9 deletions.
18 changes: 9 additions & 9 deletions lib/machinist.ex
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ defmodule Machinist do
@doc false
defmacro __using__(_) do
quote do
@__attr__ :state
@___attr___ :state

@behaviour Machinist.Transition

Expand All @@ -34,7 +34,7 @@ defmodule Machinist do
"""
defmacro transitions(do: block) do
quote do
@__struct__ __MODULE__
@___struct___ __MODULE__

unquote(block)
end
Expand Down Expand Up @@ -84,16 +84,16 @@ defmodule Machinist do

defmacro transitions([attr: attr], do: block) do
quote do
@__attr__ unquote(attr)
@__struct__ __MODULE__
@___attr___ unquote(attr)
@___struct___ __MODULE__

unquote(block)
end
end

defmacro transitions(struct, do: block) do
quote do
@__struct__ unquote(struct)
@___struct___ unquote(struct)

unquote(block)
end
Expand All @@ -109,8 +109,8 @@ defmodule Machinist do
"""
defmacro transitions(struct, [attr: attr], do: block) do
quote do
@__attr__ unquote(attr)
@__struct__ unquote(struct)
@___attr___ unquote(attr)
@___struct___ unquote(struct)

unquote(block)
end
Expand Down Expand Up @@ -226,10 +226,10 @@ defmodule Machinist do
defp define_transition(state, to: new_state, event: event) do
quote do
@impl true
def transit(%@__struct__{@__attr__ => unquote(state)} = resource, event: unquote(event)) do
def transit(%@___struct___{@___attr___ => unquote(state)} = resource, event: unquote(event)) do
case __set_new_state__(resource, unquote(new_state)) do
{:error, _msg} = term -> term
new_state -> {:ok, Map.put(resource, @__attr__, new_state)}
new_state -> {:ok, Map.put(resource, @___attr___, new_state)}
end
end
end
Expand Down
25 changes: 25 additions & 0 deletions test/machinist_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -356,4 +356,29 @@ defmodule MachinistTest do
end
end
end

describe "an example w/ typespec" do
defmodule Example11 do
defstruct state: 1

@type t :: %__MODULE__{
state: integer()
}

use Machinist

transitions do
from 1, to: 2, event: "next"
from 2, to: 3, event: "next"
end
end

test "all transitions" do
assert {:ok, %Example11{state: 2} = step_2} = Example11.transit(%Example11{}, event: "next")
assert {:ok, %Example11{state: 3} = step_3} = Example11.transit(step_2, event: "next")

assert {:error, :not_allowed} = Example11.transit(step_3, event: "next")
end
end

end

0 comments on commit 0b77c2d

Please sign in to comment.