Skip to content

Commit cdcfb2b

Browse files
authored
Merge pull request #255 from kelostrada/bugfix/default-field-value-lazy-load
Lazy load default kaffy field value
2 parents 4636a84 + 519a11f commit cdcfb2b

File tree

3 files changed

+20
-4
lines changed

3 files changed

+20
-4
lines changed

lib/kaffy/resource_schema.ex

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,6 @@ defmodule Kaffy.ResourceSchema do
157157
end
158158

159159
def kaffy_field_value(conn, schema, {field, options}) do
160-
default_value = kaffy_field_value(schema, field)
161160
ft = Kaffy.ResourceSchema.field_type(schema.__struct__, field)
162161
value = Map.get(options || %{}, :value)
163162

@@ -184,7 +183,7 @@ defmodule Kaffy.ResourceSchema do
184183
value
185184

186185
true ->
187-
default_value
186+
kaffy_field_value(schema, field)
188187
end
189188
end
190189

test/kaffy_test.exs

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
defmodule KaffyTest do
22
use ExUnit.Case
33
doctest Kaffy
4-
alias KaffyTest.Schemas.{Person, Pet}
4+
alias KaffyTest.Schemas.{Company, Person, Pet}
55
# alias KaffyTest.Admin.PersonAdmin
66

77
test "greets the world" do
@@ -56,9 +56,16 @@ defmodule KaffyTest do
5656
assert "Abdullah" == ResourceSchema.kaffy_field_value(nil, person, field)
5757
end
5858

59+
test "kaffy_field_value/3 should handle preloaded structs with a custom function" do
60+
person = %Person{company: %Company{name: "Dashbit"}}
61+
62+
options = {:company, %{name: "Company", value: fn p -> p.company.name end}}
63+
assert "Dashbit" == ResourceSchema.kaffy_field_value(%{}, person, options)
64+
end
65+
5966
test "associations/1 must return all associations for the schema" do
6067
associations = ResourceSchema.associations(Person)
61-
assert [:pets] == associations
68+
assert [:pets, :company] == associations
6269
pet_assoc = ResourceSchema.associations(Pet)
6370
assert [:person] == pet_assoc
6471
end

test/test_helper.exs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ defmodule KaffyTest.Schemas.Person do
1111
field(:birth_date, :date)
1212
field(:address, :string)
1313
has_many(:pets, KaffyTest.Schemas.Pet)
14+
belongs_to(:company, KaffyTest.Schemas.Company)
1415
end
1516
end
1617

@@ -33,3 +34,12 @@ defmodule KaffyTest.Schemas.Pet do
3334
belongs_to(:person, KaffyTest.Schemas.Person)
3435
end
3536
end
37+
38+
defmodule KaffyTest.Schemas.Company do
39+
use Ecto.Schema
40+
41+
schema "companies" do
42+
field(:name, :string)
43+
has_many(:people, KaffyTest.Schemas.Person)
44+
end
45+
end

0 commit comments

Comments
 (0)