Skip to content

Commit

Permalink
Fix skema default value when create new struct
Browse files Browse the repository at this point in the history
  • Loading branch information
bluzky committed Mar 23, 2024
1 parent 12bf549 commit 109528d
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 2 deletions.
13 changes: 12 additions & 1 deletion lib/schema.ex
Original file line number Diff line number Diff line change
Expand Up @@ -247,13 +247,24 @@ defmodule Skema.Schema do

unquote(block)

definitions = Enum.map(@ts_fields, fn {name, opts} ->
{name, Skema.Schema.__default_value__(opts[:default])}
end)

@enforce_keys @ts_enforce_keys
defstruct @ts_fields
defstruct definitions

Skema.Schema.__type__(@ts_types)
end
end

# expand default value, this only applied a single time at build time
def __default_value__(default) when is_function(default, 0) do
default.()
end

def __default_value__(default), do: default

@doc false
defmacro __type__(types) do
quote bind_quoted: [types: types] do
Expand Down
2 changes: 1 addition & 1 deletion mix.exs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ defmodule Skema.MixProject do
def project do
[
app: :skema,
version: "0.2.0",
version: "0.2.1",
elixir: "~> 1.10",
start_permanent: Mix.env() == :prod,
deps: deps(),
Expand Down
17 changes: 17 additions & 0 deletions test/defschema_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,23 @@ defmodule DefSchemaTest do
use ExUnit.Case
use Skema


describe "defschema module with default value" do
defschema User do
field(:name, :string, required: true)
field(:email, :string, length: [min: 5])
field(:age, :integer, default: 10)
end

test "new with default value" do
assert %User{age: 10, name: nil, email: nil} = User.new(%{})
end

test "new override default value" do
assert %User{age: 18, name: "Donkey", email: nil} = User.new(%{age: 18, name: "Donkey"})
end
end

describe "Skema.cast_and_validate" do
defschema UserModel do
field(:name, :string, required: true)
Expand Down

0 comments on commit 109528d

Please sign in to comment.