Skip to content

Commit

Permalink
Add generator support for groups.
Browse files Browse the repository at this point in the history
* Make sure we're reading out of groups in the data hash.
* Small bugfix in generator; Array() doesn't do what I thought with a hash.
  • Loading branch information
Timon Karnezos committed May 23, 2010
1 parent 37ec83f commit b3908ba
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 3 deletions.
3 changes: 2 additions & 1 deletion lib/fixed_width/generator.rb
Expand Up @@ -9,8 +9,9 @@ def generate(data)
@builder = []
@definition.sections.each do |section|
content = data[section.name]
arrayed_content = content.is_a?(Array) ? content : [content]
raise FixedWidth::RequiredSectionEmptyError.new("Required section '#{section.name}' was empty.") if (content.nil? || content.empty?) && !section.optional
Array(content).each {|row| @builder << section.format(row) }
arrayed_content.each {|row| @builder << section.format(row) }
end
@builder.join("\n")
end
Expand Down
5 changes: 4 additions & 1 deletion lib/fixed_width/section.rb
Expand Up @@ -43,7 +43,10 @@ def template(name)
end

def format(data)
@columns.map{|column| column.format(data[column.name]) }.join
@columns.map do |c|
hash = c.group ? data[c.group] : data
c.format(hash[c.name])
end.join
end

def parse(line)
Expand Down
8 changes: 7 additions & 1 deletion spec/generator_spec.rb
Expand Up @@ -20,7 +20,7 @@
end
end
@data = {
:header => [ {:type => "HEAD", :file_id => "1" }],
:header => [ {:type => "HEAD", :file_id => "1" } ],
:body => [
{:first => "Paul", :last => "Hewson" },
{:first => "Dave", :last => "Evans" }
Expand All @@ -39,4 +39,10 @@
expected = "HEAD 1\n Paul Hewson\n Dave Evans\nFOOT 1"
@generator.generate(@data).should == expected
end

it "should handle lazy data declaration (no array around single record for a section)" do
expected = "HEAD 1\n Paul Hewson\n Dave Evans\nFOOT 1"
@data[:header] = @data[:header].first
@generator.generate(@data).should == expected
end
end
7 changes: 7 additions & 0 deletions spec/section_spec.rb
Expand Up @@ -115,6 +115,13 @@
@section.column(:name, 10, :align => :left)
@section.format(@data).should == " 3Ryan "
end

it "should read from groups" do
@data = { :id => 3, :foo => { :name => "Ryan" } }
@section.column(:id, 5)
@section.column(:name, 10, :align => :left, :group => :foo)
@section.format(@data).should == " 3Ryan "
end
end

describe "when parsing a file" do
Expand Down

0 comments on commit b3908ba

Please sign in to comment.