Skip to content

Commit

Permalink
Merge pull request #60 from projecthydra-labs/extract_initialize_field
Browse files Browse the repository at this point in the history
Extract new method initialize_field for easier overrides
  • Loading branch information
Trey Terrell committed Jan 13, 2015
2 parents 81f2669 + 34ce5b7 commit 1cfd521
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 8 deletions.
19 changes: 11 additions & 8 deletions app/forms/hydra_editor/form.rb
Original file line number Diff line number Diff line change
Expand Up @@ -56,16 +56,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
Expand Down
52 changes: 52 additions & 0 deletions spec/forms/hydra_editor_form_spec.rb
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit 1cfd521

Please sign in to comment.