Skip to content

Commit

Permalink
feature: Add Worksheet#rows monkeypatch
Browse files Browse the repository at this point in the history
The monkeypatch intention is to use #rows for numeric_values
  • Loading branch information
Drowze committed Jul 21, 2020
1 parent 63cfba8 commit 202bc5b
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 2 deletions.
2 changes: 2 additions & 0 deletions lib/aspire_budget.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# frozen_string_literal: true

require 'core_extensions'

require 'configuration'

require 'worksheets/backend_data'
Expand Down
20 changes: 20 additions & 0 deletions lib/core_extensions.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# frozen_string_literal: true

require 'google_drive'

module AspireBudget
module CoreExtensions
module Worksheet
def rows(skip = 0, cell_method: :[])
nc = num_cols
result = ((1 + skip)..num_rows).map do |row|
(1..nc).map { |col| send(cell_method, row, col) }.freeze
end
result.freeze
end
end
end
end

# https://github.com/gimite/google-drive-ruby/issues/378
GoogleDrive::Worksheet.prepend AspireBudget::CoreExtensions::Worksheet
30 changes: 28 additions & 2 deletions spec/support/google_drive_mock.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# frozen_string_literal: true

require 'date'

class GoogleDriveMock
def self.from_config(_)
Session.new
Expand Down Expand Up @@ -36,15 +38,28 @@ def worksheets
end

class Worksheet
CURRENCY_REGEX = /^[$̂€]?([0-9]{1,3},([0-9]{3},)*[0-9]{3}|[0-9]+)(.[0-9][0-9])?$/.freeze
LOTUS_DAY_ONE = Date.new(1899, 12, 30).freeze
DATE_FORMAT = '%d/%m/%y'

attr_reader :title

def initialize(title, rows)
@title = title
@rows = rows
end

def rows(skip = 0)
@rows.drop(skip)
def rows(skip = 0, cell_method: :[])
case cell_method
when :[]
@rows.drop(skip)
when :numeric_value
@rows.map.with_index do |r, i|
r.map.with_index do |_c, j|
numeric_value(i + 1, j + 1)
end
end
end
end

def synchronize
Expand Down Expand Up @@ -94,6 +109,17 @@ def []=(row, col, value) # rubocop:disable Metrics/MethodLength
@rows[row - 1][col - 1] = value
end

# assumes that "," is not a decimal separator
# assumes date format as defined above
def numeric_value(*args)
value = self[*args]
if value.match?(CURRENCY_REGEX)
value.gsub(/[€$,]/, '').to_f
elsif value.match?(%r{\d+/\d+/\d+})
Float(Date.strptime(value, DATE_FORMAT) - LOTUS_DAY_ONE)
end
end

def update_cells(starting_row, starting_col, matrix)
matrix.each_with_index do |row, i|
row.each_with_index do |cell, j|
Expand Down

0 comments on commit 202bc5b

Please sign in to comment.