Skip to content

Commit

Permalink
Add virtual fields to create/update
Browse files Browse the repository at this point in the history
  • Loading branch information
paulcsmith committed May 25, 2018
1 parent 3199435 commit 9a867ee
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 0 deletions.
15 changes: 15 additions & 0 deletions spec/virtual_form_spec.cr
Expand Up @@ -9,7 +9,22 @@ private class TestVirtualForm < LuckyRecord::VirtualForm
end
end

private class UserWithVirtual < User::BaseForm
virtual password : String
end

describe LuckyRecord::VirtualForm do
it "has create/update args for virtual fields" do
UserWithVirtual.create(password: "p@ssword") do |form, _user|
form.password.value = "p@ssword"
end

user = UserBox.create
UserWithVirtual.update(user, password: "p@ssword") do |form, _user|
form.password.value = "p@ssword"
end
end

it "sets a form_name" do
TestVirtualForm.new.form_name.should eq "test_virtual"
TestVirtualForm.form_name.should eq "test_virtual"
Expand Down
6 changes: 6 additions & 0 deletions src/lucky_record/needy_initializer_and_save_methods.cr
Expand Up @@ -73,6 +73,9 @@ module LuckyRecord::NeedyInitializerAndSaveMethods
{{ field[:name] }} : {{ field[:type] }} | Nothing{% if field[:nilable] %} | Nil{% end %} = Nothing.new,
{% end %}
{% end %}
{% for field in VIRTUAL_FIELDS %}
{{ field.var }} : {{ field.type }} | Nothing = Nothing.new,
{% end %}
)
form = new(
{% if with_params %}params,{% end %}
Expand Down Expand Up @@ -116,6 +119,9 @@ module LuckyRecord::NeedyInitializerAndSaveMethods
{{ field[:name] }} : {{ field[:type] }} | Nothing{% if field[:nilable] %} | Nil{% end %} = Nothing.new,
{% end %}
{% end %}
{% for field in VIRTUAL_FIELDS %}
{{ field.var }} : {{ field.type }} | Nothing = Nothing.new,
{% end %}
)
form = new(
record,
Expand Down
6 changes: 6 additions & 0 deletions src/lucky_record/virtual.cr
Expand Up @@ -7,6 +7,10 @@ module LuckyRecord::Virtual
{% end %}
end

macro included
VIRTUAL_FIELDS = [] of Nil
end

ensure_base_virtual_fields_method_is_present

macro allow_virtual(*args, **named_args)
Expand All @@ -18,6 +22,8 @@ module LuckyRecord::Virtual
{% raise "virtual must use just one type" %}
{% end %}

{% VIRTUAL_FIELDS << type_declaration %}

{% type = type_declaration.type %}
{% name = type_declaration.var %}
@_{{ name }} : LuckyRecord::Field({{ type }}?)?
Expand Down

0 comments on commit 9a867ee

Please sign in to comment.