Skip to content

Commit

Permalink
Added support for nested arrays, fixes #1
Browse files Browse the repository at this point in the history
  • Loading branch information
fredwu committed Jul 3, 2012
1 parent f0cc9b4 commit aa6c853
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 15 deletions.
26 changes: 18 additions & 8 deletions lib/api_taster/form_builder.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,18 +20,21 @@ def html

def add_to_buffer(params, parent_labels = [])
params.each do |label, value|
if value.is_a?(Hash)
parent_labels << label
new_parent_labels = parent_labels.clone << label

@_buffer += render(
:partial => 'api_taster/routes/param_form_legend',
:locals => { :label => print_labels(parent_labels) }
)
if value.is_a?(Hash)
add_legend_to_buffer(parent_labels, label)

add_to_buffer(value, parent_labels)
add_to_buffer(value, new_parent_labels)
elsif value.is_a?(Array)
value.each do |v|
add_element_to_buffer(parent_labels, "[#{label}][]", v)
if v.is_a?(Hash)
add_legend_to_buffer(parent_labels, label)

add_to_buffer(v, new_parent_labels)
else
add_element_to_buffer(parent_labels, "[#{label}][]", v)
end
end
else
add_element_to_buffer(parent_labels, label, value)
Expand All @@ -50,6 +53,13 @@ def add_element_to_buffer(parent_labels, label, value)
)
end

def add_legend_to_buffer(parent_labels, label)
@_buffer += render(
:partial => 'api_taster/routes/param_form_legend',
:locals => { :label => print_labels(parent_labels.clone << label) }
)
end

def print_labels(parent_labels)
"[#{parent_labels * ']['}]"
end
Expand Down
28 changes: 21 additions & 7 deletions spec/form_builder_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,21 @@ module ApiTaster
let(:builder) do
FormBuilder.new({
:hello => 'world',
:nested => {
:foo => 'bar',
:integer => 1,
:array => [1, 2, 3]
}
:user => {
:name => 'Fred',
:comment => {
:title => [1, 2, 3]
}
},
:items => [
{ :name => 'flower', :price => '4.95' },
{ :name => 'pot', :price => '2.45' },
:nested_items => [
{ :name => 'apple' },
{ :name => 'orange'},
:nested_numbers => [3, 4, 5]
]
]
})
end

Expand All @@ -25,7 +35,7 @@ module ApiTaster
end

it "outputs html" do
builder.html.should match('bar')
builder.html.should match('world')
end

context "data types" do
Expand All @@ -38,7 +48,11 @@ module ApiTaster
end

it "does arrays" do
builder.html.should match(/name="\[nested\]\[array\]\[\]" value="2"/)
builder.html.should match(/name="\[user\]\[comment\]\[title\]\[\]" value="1"/)
end

it "does nested arrays" do
builder.html.should match(/name="\[items\]\[nested_items\]\[nested_numbers\]\[\]" value="5"/)
end
end
end
Expand Down

0 comments on commit aa6c853

Please sign in to comment.