Created
September 7, 2012 05:15
-
-
Save rwjblue/3663385 to your computer and use it in GitHub Desktop.
Use cellify method to allow overridable defaults per cell in Prawn.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'prawn' | |
def cellify(data, default_options = nil) | |
default_options ||= {:borders => []} | |
output = [] | |
row_options = default_options.delete(:rows) || Hash.new {|h,k| h[k] = {}} | |
column_options = default_options.delete(:columns) || Hash.new {|h,k| h[k] = {}} | |
current_row = -1 | |
data.each do |row| | |
current_row += 1 | |
current_column = -1 | |
output << [] | |
current_row_options = row_options[current_row] | |
row.each do |cell| | |
current_column += 1 | |
current_column_options = column_options[current_column] | |
cellable = case cell | |
when Prawn::Table::Cell, Prawn::Table | |
output.last << cell | |
next | |
when Hash | |
default_options.merge(current_row_options).merge(current_column_options).merge(cell) | |
else | |
default_options.merge(current_row_options).merge(current_column_options).merge(:content => cell.to_s) | |
end | |
output.last << cellable | |
end | |
end | |
output | |
end | |
Prawn::Document.generate('test.pdf') do |pdf| | |
pdf.text 'all borders are on by default' | |
data = [ | |
['these', 'cells','will'], | |
['have', 'all', 'borders'], | |
['by','default',''] | |
] | |
pdf.table(data) | |
pdf.move_down 20 | |
pdf.text 'respects values specified, but is way too verbose' | |
data = [ | |
[{:content => 'these', :borders => [:bottom]}, {:content => 'cells', :borders => [:bottom]},{:content => 'will', :borders => [:bottom]}], | |
[{:content => 'respect', :borders => []}, {:content => 'borders', :borders => []}, {:content => 'specified', :borders => []}], | |
] | |
pdf.table(data) | |
pdf.move_down 20 | |
pdf.text 'specifying default values for :cell_style ignores any values specified in the data definition' | |
data = [ | |
[{:content => 'these', :borders => [:bottom]}, {:content => 'cells', :borders => [:bottom]},{:content => 'won\'t', :borders => [:bottom]}], | |
[{:content => 'respect', :borders => []}, {:content => 'borders', :borders => []}, {:content => 'specified', :borders => []}], | |
] | |
pdf.table(data, :cell_style => {:borders => []}) | |
pdf.move_down 20 | |
pdf.text 'use cellify method below to set default options up for each cell that can still be overridden as needed' | |
data = [ | |
[{:content => 'these', :borders => [:bottom]}, {:content => 'cells', :borders => [:bottom]},{:content => 'will', :borders => [:bottom]}], | |
['respect', 'borders', 'specified'], | |
] | |
pdf.table(cellify(data, :borders => [])) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment