From f0b45448f35384857e3ff9eccb5770756709b742 Mon Sep 17 00:00:00 2001 From: Adam Burmister Date: Thu, 8 Nov 2012 15:21:43 +0000 Subject: [PATCH] Allow default values via attributes on TDs. If there is a parse error return the val unparsed. --- README.textile | 4 ++++ lib/to_spreadsheet/xls.rb | 43 +++++++++++++++++++++++++++------------ spec/xls_spec.rb | 12 +++++++++-- 3 files changed, 44 insertions(+), 15 deletions(-) diff --git a/README.textile b/README.textile index ae78990..884c330 100644 --- a/README.textile +++ b/README.textile @@ -59,6 +59,10 @@ You can use class names on td/th for typed values. Here is the list of class to | date | Date | | time | Time | +h3. Default null values + +Add a `data-null="default value"` attribute to a cell to use the value as a default if the model value is nil. + h3. Worksheets Every table in the view will be converted to a separate sheet. diff --git a/lib/to_spreadsheet/xls.rb b/lib/to_spreadsheet/xls.rb index ef9182b..a4767df 100644 --- a/lib/to_spreadsheet/xls.rb +++ b/lib/to_spreadsheet/xls.rb @@ -22,21 +22,38 @@ def to_io(html) private def typed_node_val(node) + val = val_or_null_default(node) + + return '' if !val + + begin + case node[:class] + when /decimal|float/ + val.to_f + when /num|int/ + val.to_i + when /datetime/ + DateTime.parse(val) + when /date/ + Date.parse(val) + when /time/ + Time.parse(val) + else + val + end + rescue + val + end + end + + def val_or_null_default(node) val = node.inner_text - case node[:class] - when /decimal|float/ - val.to_f - when /num|int/ - val.to_i - when /datetime/ - DateTime.parse(val) - when /date/ - Date.parse(val) - when /time/ - Time.parse(val) - else - val + if val.blank? + node['data-null'] + else + val end end + end end diff --git a/spec/xls_spec.rb b/spec/xls_spec.rb index 8a5c342..207ac23 100644 --- a/spec/xls_spec.rb +++ b/spec/xls_spec.rb @@ -23,6 +23,14 @@ spreadsheet.worksheet(0)[1, 2].class.should be(Date) end + it 'parses null dates' do + spreadsheet.worksheet(0)[2, 2].class.should_not be(Date) + end + + it 'parses default values' do + spreadsheet.worksheet(0)[2, 1].should == 100 + end + # This is for final manual test # The test spreadsheet will be saved to /tmp/spreadsheet.xls it 'writes to disk' do @@ -49,8 +57,8 @@ %td.date 27/05/1991 %tr %td John - %td.num 21 - %td.date 01/05/1990 + %td.num{ data: { null: 100 } } + %td.date %table %caption Another worksheet