Skip to content

Commit

Permalink
started to implement :populate which allows you to create missing mod…
Browse files Browse the repository at this point in the history
…els when doing #validate. this addresses #33.
  • Loading branch information
apotonick committed Apr 19, 2014
1 parent 3dc6be1 commit 0bd3aab
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 2 deletions.
24 changes: 24 additions & 0 deletions lib/reform/form.rb
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@ def initialize(model)

module ValidateMethods # TODO: introduce Base module.
def validate(params)
populate!(params)
puts "after populate! #{self.inspect}"
# populate nested properties
# update attributes of forms (from_hash)
# run validate(errors) for all forms (no 1-level limitation anymore)
Expand All @@ -99,6 +101,10 @@ def validate_for(form, res, prefix=nil)
errors.merge!(form.errors, prefix)
false
end

def populate!(params)
mapper.new(self).extend(Validate::Populator).from_hash(params)
end
end
include ValidateMethods
require 'reform/form/multi_parameter_attributes'
Expand Down Expand Up @@ -237,6 +243,24 @@ def from_hash(*)
super
end
end

module Populator
def from_hash(params, *args)
populated_attrs = []

nested_forms do |attr|
next unless attr[:populator]

attr.merge!(
:parse_strategy => attr[:populator],
:representable => false
)
populated_attrs << attr.name.to_sym
end

super(params, {:include => populated_attrs})
end
end
end

### TODO: add ToHash with :prepare => lambda { |form, args| form },
Expand Down
33 changes: 31 additions & 2 deletions test/validate_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,7 @@ class ValidateTest < BaseTest

before { subject.validate(params) }

it("xxx") { subject.title.must_equal "Best Of" }

it { subject.title.must_equal "Best Of" }

it { subject.hit.must_be_kind_of Reform::Form }
it { subject.hit.title.must_equal "Roxanne" }
Expand All @@ -29,4 +28,34 @@ class ValidateTest < BaseTest
it { subject.songs[1].must_be_kind_of Reform::Form }
it { subject.songs[1].title.must_equal "Roxanne" }
end


describe "setup with populator" do
let (:form) {
Class.new(Reform::Form) do
property :hit, :populator => lambda { |fragment, args|
puts "******************* #{fragment}"

hit or self.hit = args.binding[:form].new(Song.new)
# TODO: wrap into form/Forms automatically in :instance.
# what happens with @model? we have to sync that as well.
} do
property :title
end
end
}

let (:params) {
{
"hit" => {"title" => "Roxanne"},
# "songs" => [{"title" => "Fallout"}, {"title" => "Roxanne"}]
}
}

subject { form.new(Album.new) }

before { subject.validate(params) }

it( "xxx") { subject.hit.title.must_equal "Roxanne" }
end
end

0 comments on commit 0bd3aab

Please sign in to comment.