Class: CommaSplice::CommaCalculator

Inherits:
Object
  • Object
show all
Defined in:
lib/comma_splice/helpers/comma_calculator.rb

Overview

provide an array of CSV headers and and array of CSV values and this will figure out the best correction and prompt you if it can’t find out

Instance Method Summary collapse

Constructor Details

#initialize(headers, values, separator = ',') ⇒ CommaCalculator

Returns a new instance of CommaCalculator.



9
10
11
12
13
14
15
16
17
18
19
# File 'lib/comma_splice/helpers/comma_calculator.rb', line 9

def initialize(headers, values, separator = ',')
  if headers.size > 10 && values.size > 10
    raise StandardError,
          "Determining all the possibilities to fit #{values.size} values into the #{headers.size} headers #{headers.inspect} is computationally expensive. Please specify the columns where commas might be."
  end

  @separator      = separator
  @headers        = headers
  @values         = values
  @longest_header = @headers.max_by(&:length)
end

Instance Method Details

#best_optionsObject



57
58
59
60
# File 'lib/comma_splice/helpers/comma_calculator.rb', line 57

def best_options
  max_score = ranked_options.collect { |o| o.score }.max
  ranked_options.select { |o| o.score == max_score }
end

#correctionObject



21
22
23
24
25
26
27
28
29
30
31
# File 'lib/comma_splice/helpers/comma_calculator.rb', line 21

def correction
  if @headers.size == @values.size
    @values
  elsif best_options.size == 1
    best_options.first.option
  elsif best_options.size > 1
    prompt_for_options(best_options)
  else
    prompt_for_options(ranked_options)
  end
end

#needs_correcting?Boolean

Returns:

  • (Boolean)


66
67
68
# File 'lib/comma_splice/helpers/comma_calculator.rb', line 66

def needs_correcting?
  @headers.size < @values.size
end

#needs_manual_input?Boolean

Returns:

  • (Boolean)


62
63
64
# File 'lib/comma_splice/helpers/comma_calculator.rb', line 62

def needs_manual_input?
  !best_options.one?
end


70
71
72
73
74
# File 'lib/comma_splice/helpers/comma_calculator.rb', line 70

def print_all_options
  ranked_options.each_with_index do |option, index|
    print_option(option, index)
  end
end

#ranked_optionsObject



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/comma_splice/helpers/comma_calculator.rb', line 33

def ranked_options
  @all_options ||= join_possibilities.collect do |joins|
    values = @values.dup
    joins.collect do |join_num|
      val = values.shift(join_num)
      if val.empty?
        nil
      elsif val.size == 1
        val.first
      else
        val.join(',')
      end
    end
  end

  @ranked_options ||= @all_options.collect do |option|
    OptionScorer.new(option, separator: @separator)
  end
end

#score_option(option) ⇒ Object



53
54
55
# File 'lib/comma_splice/helpers/comma_calculator.rb', line 53

def score_option(option)
  OptionScorer.new(option, separator: @separator).score
end