From 34ce5b70b6920abdc5074822e2c1c4d07d252a79 Mon Sep 17 00:00:00 2001 From: Justin Coyne Date: Mon, 12 Jan 2015 21:54:46 -0600 Subject: [PATCH] Extract new method initialize_field for easier overrides --- app/forms/hydra_editor/form.rb | 19 +++++----- spec/forms/hydra_editor_form_spec.rb | 52 ++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+), 8 deletions(-) create mode 100644 spec/forms/hydra_editor_form_spec.rb diff --git a/app/forms/hydra_editor/form.rb b/app/forms/hydra_editor/form.rb index eae8e15..3cfcc4b 100644 --- a/app/forms/hydra_editor/form.rb +++ b/app/forms/hydra_editor/form.rb @@ -55,16 +55,19 @@ def build_permitted_params end protected - # override this method if you need to initialize more complex RDF assertions (b-nodes) def initialize_fields + # we're making a local copy of the attributes that we can modify. @attributes = model.attributes - terms.select { |key| self[key].blank? }.each do |key| - # if value is empty, we create an one element array to loop over for output - if self.class.multiple?(key) - self[key] = [''] - else - self[key] = '' - end + terms.select { |key| self[key].blank? }.each { |key| initialize_field(key) } + end + + # override this method if you need to initialize more complex RDF assertions (b-nodes) + def initialize_field(key) + # if value is empty, we create an one element array to loop over for output + if self.class.multiple?(key) + self[key] = [''] + else + self[key] = '' end end end diff --git a/spec/forms/hydra_editor_form_spec.rb b/spec/forms/hydra_editor_form_spec.rb new file mode 100644 index 0000000..07064db --- /dev/null +++ b/spec/forms/hydra_editor_form_spec.rb @@ -0,0 +1,52 @@ +require 'spec_helper' + +describe HydraEditor::Form do + class TestModel < ActiveFedora::Base + property :title, predicate: ::RDF::DC.title + property :creator, predicate: ::RDF::DC.creator, multiple: false + end + + class TestForm + include HydraEditor::Form + self.model_class = TestModel + # Terms is the list of fields displayed by app/views/records/_form.html.erb + self.terms = [:title, :creator] + end + + describe "class methods" do + subject { TestForm.model_name } + it { is_expected.to eq 'TestModel' } + end + + let(:object) { TestModel.new(title: ['foo', 'bar'], creator: 'baz') } + let(:form) { TestForm.new(object) } + + describe "#terms" do + subject { form.terms } + it { is_expected.to eq [:title, :creator] } + end + + describe "the term accessors" do + it "should have the accessors" do + expect(form.title).to eq ['foo', 'bar'] + expect(form.creator).to eq 'baz' + end + + it "should have the hash accessors" do + expect(form[:title]).to eq ['foo', 'bar'] + expect(form[:creator]).to eq 'baz' + end + end + + describe "#initialize_field" do + before do + form[:title] = nil + end + + it "should put an empty element in the value" do + expect { form.send(:initialize_field, :title) }.to change { form[:title] }. + from(nil).to(['']) + end + end + +end