Permalink
Browse files

Tables support row/column access by negative indices

You can now use syntax like table.row(0..-2), which selects all but the
last row of your table.

Closes #144.
  • Loading branch information...
1 parent fa9e689 commit 91d6efa7ad4d4bd64b5eb33336a2e6fd4d496a9b @bradediger bradediger committed Aug 18, 2010
Showing with 40 additions and 2 deletions.
  1. +22 −2 lib/prawn/table/cells.rb
  2. +18 −0 spec/table_spec.rb
View
@@ -54,6 +54,7 @@ class Cells < Array
#
def rows(row_spec)
index_cells unless @indexed
+ row_spec = transform_spec(row_spec, @row_count)
Cells.new(@rows[row_spec] ||= select{ |c| row_spec === c.row })
end
alias_method :row, :rows
@@ -65,9 +66,10 @@ def rows(row_spec)
# table.column(0) # selects first column
# table.columns(3..4) # selects columns four and five
#
- def columns(row_spec)
+ def columns(col_spec)
index_cells unless @indexed
- Cells.new(@columns[row_spec] ||= select{ |c| row_spec === c.column })
+ col_spec = transform_spec(col_spec, @column_count)
+ Cells.new(@columns[col_spec] ||= select{ |c| col_spec === c.column })
end
alias_method :column, :columns
@@ -182,8 +184,26 @@ def index_cells
@columns[cell.column] << cell
end
+ @row_count = @rows.size
+ @column_count = @columns.size
+
@indexed = true
end
+
+ # Transforms +spec+, a column / row specification, into an object that
+ # can be compared against a row or column number using ===. Normalizes
+ # negative indices to be positive, given a total size of +total+.
+ #
+ def transform_spec(spec, total)
+ case spec
+ when Range
+ transform_spec(spec.begin, total)..transform_spec(spec.end, total)
+ when Integer
+ spec < 0 ? (total + spec) : spec
+ else
+ raise ArgumentError, "invalid row/column specification #{spec.inspect}"
+ end
+ end
end
end
end
View
@@ -99,13 +99,31 @@
Set.new(%w[R0C0 R0C1 R1C0 R1C1])
end
+ it "should allow negative row selectors" do
+ Set.new(@table.row(-1).map { |c| c.content }).should ==
+ Set.new(%w[R1C0 R1C1])
+ Set.new(@table.rows(-2..-1).map { |c| c.content }).should ==
+ Set.new(%w[R0C0 R0C1 R1C0 R1C1])
+ Set.new(@table.rows(0..-1).map { |c| c.content }).should ==
+ Set.new(%w[R0C0 R0C1 R1C0 R1C1])
+ end
+
it "should select columns by number or range" do
Set.new(@table.column(0).map { |c| c.content }).should ==
Set.new(%w[R0C0 R1C0])
Set.new(@table.columns(0..1).map { |c| c.content }).should ==
Set.new(%w[R0C0 R0C1 R1C0 R1C1])
end
+ it "should allow negative column selectors" do
+ Set.new(@table.column(-1).map { |c| c.content }).should ==
+ Set.new(%w[R0C1 R1C1])
+ Set.new(@table.columns(-2..-1).map { |c| c.content }).should ==
+ Set.new(%w[R0C0 R0C1 R1C0 R1C1])
+ Set.new(@table.columns(0..-1).map { |c| c.content }).should ==
+ Set.new(%w[R0C0 R0C1 R1C0 R1C1])
+ end
+
it "should allow rows and columns to be combined" do
@table.row(0).column(1).map { |c| c.content }.should == ["R0C1"]
end

0 comments on commit 91d6efa

Please sign in to comment.