Skip to content

Commit

Permalink
Merge pull request #6 from adamburmister/master
Browse files Browse the repository at this point in the history
Making parsing less fragile
  • Loading branch information
glebm committed Nov 8, 2012
2 parents a69728e + f0b4544 commit 0bb3548
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 15 deletions.
4 changes: 4 additions & 0 deletions README.textile
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
43 changes: 30 additions & 13 deletions lib/to_spreadsheet/xls.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
12 changes: 10 additions & 2 deletions spec/xls_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down

0 comments on commit 0bb3548

Please sign in to comment.