class FileSniffers::ColSepSniffer

stackoverflow.com/questions/14693929/ruby-how-can-i-detect-intelligently-guess-the-delimiter-used-in-a-csv-file

Constants

COMMON_DELIMITERS
EmptyFile
NoColumnSeparatorFound

Public Class Methods

call(first) click to toggle source
# File lib/file_sniffers.rb, line 17
def self.call(first)
  new(first).find
end
new(first) click to toggle source
# File lib/file_sniffers.rb, line 13
def initialize(first)
  @first = first
end

Public Instance Methods

find() click to toggle source
# File lib/file_sniffers.rb, line 21
def find
  fail EmptyFile unless first

  if valid?
    delimiters[0][0][1]
  else
    fail NoColumnSeparatorFound
  end
end

Private Instance Methods

count() click to toggle source
# File lib/file_sniffers.rb, line 49
def count
  ->(hash, delimiter) { hash[delimiter] = first.count(delimiter); hash }
end
delimiters() click to toggle source

delimiters #=> [[“"|"”, 54], [“","”, 0], [“";"”, 0]] delimiters #=> [“";"”, 54] delimiters[0] #=> “","” delimiters[0] #=> “;”

# File lib/file_sniffers.rb, line 41
def delimiters
  @delimiters ||= COMMON_DELIMITERS.inject({}, &count).sort(&most_found)
end
first() click to toggle source
# File lib/file_sniffers.rb, line 53
def first
  @first
end
most_found() click to toggle source
# File lib/file_sniffers.rb, line 45
def most_found
  ->(a, b) { b[1] <=> a[1] }
end
valid?() click to toggle source
# File lib/file_sniffers.rb, line 33
def valid?
  !delimiters.collect(&:last).reduce(:+).zero?
end