Skip to content

Commit

Permalink
Implemented asiniy#20
Browse files Browse the repository at this point in the history
  • Loading branch information
h4cc committed Nov 28, 2016
1 parent 9065a2e commit 4c461be
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 2 deletions.
4 changes: 2 additions & 2 deletions lib/ecto_state_machine.ex
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,15 @@ defmodule EctoStateMachine do
model
|> Changeset.change(%{ unquote(column) => "#{unquote(event[:to])}" })
|> unquote(event[:callback]).()
|> validate_state_transition(unquote(event), model)
|> unquote(:"validate_state_transition_#{column}")(unquote(event), model)
end

def unquote(:"can_#{event[:name]}?")(model) do
:"#{Map.get(model, unquote(column))}" in unquote(event[:from])
end
end)

defp validate_state_transition(changeset, event, model) do
defp unquote(:"validate_state_transition_#{column}")(changeset, event, model) do
change = Map.get(model, unquote(column))

if :"#{change}" in event[:from] do
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ defmodule Dummy.Repo.Migrations.CreateUser do
def change do
create table(:users) do
add :rules, :string, null: false
add :level, :string, null: false
add :confirmed_at, :datetime
end
end
Expand Down
16 changes: 16 additions & 0 deletions test/dummy/web/models/user.ex
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,23 @@ defmodule Dummy.User do
]
]

use EctoStateMachine,
column: :level,
states: [:beginner, :advanced, :expert],
events: [
[
name: :ascend_advanced,
from: [:beginner],
to: :advanced
], [
name: :ascend_expert,
from: [:advanced],
to: :expert
],
]

schema "users" do
field :rules, :string
field :level, :string, default: "beginner"
end
end

0 comments on commit 4c461be

Please sign in to comment.