Skip to content

Commit

Permalink
implement saving of nested forms in Save. fixes #73 and #37.
Browse files Browse the repository at this point in the history
  • Loading branch information
apotonick committed Apr 30, 2014
1 parent 44e0ffb commit 36f2323
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 15 deletions.
26 changes: 23 additions & 3 deletions lib/reform/form/save.rb
Original file line number Diff line number Diff line change
@@ -1,14 +1,34 @@
class Reform::Form
module Save
module OnNested
def to_hash(*)
# process output from InputRepresenter {title: "Mint Car", hit: <Form>}
# and just call sync! on nested forms.
nested_forms do |attr|
attr.merge!(
:instance => lambda { |fragment, *| fragment },
:serialize => lambda { |object, *| object.save! },
)
end

super
end
end

def save
# DISCUSS: we should never hit @mapper here (which writes to the models) when a block is passed.
return yield self, to_nested_hash if block_given?

sync_models
save_models
sync_models # recursion
save!
end

def save!
save_model
mapper.new(self).extend(OnNested).to_hash # save! on all nested forms.
end

def save_models
def save_model
model.save # TODO: implement nested (that should really be done by Twin/AR).
end
end
Expand Down
12 changes: 0 additions & 12 deletions test/form_composition_test.rb
Original file line number Diff line number Diff line change
@@ -1,17 +1,5 @@
require 'test_helper'

MiniTest::Spec.class_eval do
module Saveable
def save
@saved = true
end

def saved?
@saved
end
end
end

class FormCompositionTest < MiniTest::Spec
Song = Struct.new(:id, :title)
Requester = Struct.new(:id, :name)
Expand Down
45 changes: 45 additions & 0 deletions test/save_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
require 'test_helper'

class SaveTest < BaseTest
describe "populated" do
let (:params) {
{
"title" => "Best Of",
"hit" => {"title" => "Roxanne"},
"songs" => [{"title" => "Fallout"}, {"title" => "Roxanne"}],
:band => {:label => {:name => "Polydor"}}
}
}

let (:album) { Album.new(nil, hit, [song1, song2], band) }
let (:hit) { Song.new }
let (:song1) { Song.new }
let (:song2) { Song.new }
let (:band) { Band.new(label) }
let (:label) { Label.new }

subject { ErrorsTest::AlbumForm.new(album) }

before do
[album, hit, song1, song2, band, label].each { |mdl| mdl.extend(Saveable) }

subject.validate(params)
subject.save
end

# synced?
it { album.title.must_equal "Best Of" }
it { hit.title.must_equal "Roxanne" }
it { song1.title.must_equal "Fallout" }
it { song2.title.must_equal "Roxanne" }
it { label.name.must_equal "Polydor" }

# saved?
it { album.saved?.must_equal true }
it { hit.saved?.must_equal true }
it { song1.saved?.must_equal true }
it { song1.saved?.must_equal true }
it { band.saved?.must_equal true }
it { label.saved?.must_equal true }
end
end

0 comments on commit 36f2323

Please sign in to comment.