class Bmg::Reader::Csv
Constants
- DEFAULT_OPTIONS
Public Class Methods
new(type, path_or_io, options = {})
click to toggle source
# File lib/bmg/reader/csv.rb, line 12 def initialize(type, path_or_io, options = {}) @type = type @path_or_io = path_or_io @options = DEFAULT_OPTIONS.merge(options) if @options[:smart] && !@path_or_io.is_a?(IO) @options[:col_sep] ||= infer_col_sep @options[:quote_char] ||= infer_quote_char end end
Public Instance Methods
each() { |tuple(row)| ... }
click to toggle source
# File lib/bmg/reader/csv.rb, line 22 def each return to_enum unless block_given? require 'csv' with_io do |io| ::CSV.new(io, **csv_options).each do |row| yield tuple(row) end end end
to_ast()
click to toggle source
# File lib/bmg/reader/csv.rb, line 32 def to_ast [ :csv, @path_or_io, @options ] end
to_s()
click to toggle source
# File lib/bmg/reader/csv.rb, line 36 def to_s "(csv #{@path_or_io})" end
Also aliased as: inspect
Private Instance Methods
csv_options()
click to toggle source
# File lib/bmg/reader/csv.rb, line 79 def csv_options @csv_options ||= @options.dup.tap{|opts| opts.delete(:smart) } end
infer_col_sep()
click to toggle source
# File lib/bmg/reader/csv.rb, line 47 def infer_col_sep sniff(text_portion, [",","\t",";"], ",") end
infer_quote_char()
click to toggle source
# File lib/bmg/reader/csv.rb, line 51 def infer_quote_char sniff(text_portion, ["'","\""], "\"") end
sniff(str, candidates, default)
click to toggle source
Finds the best candidate among `candidates` for a separator found in `str`. If none is found, returns `default`.
# File lib/bmg/reader/csv.rb, line 70 def sniff(str, candidates, default) snif = {} candidates.each {|delim| snif[delim] = str.count(delim) } snif = snif.sort {|a,b| b[1] <=> a[1] } snif.size > 0 ? snif[0][0] : default end
text_portion()
click to toggle source
# File lib/bmg/reader/csv.rb, line 55 def text_portion @text_portion ||= with_io{|io| io.readlines(10).join("\n") } end
tuple(row)
click to toggle source
# File lib/bmg/reader/csv.rb, line 43 def tuple(row) row.to_hash.each_with_object({}){|(k,v),h| h[k.to_sym] = v } end
with_io(&bl)
click to toggle source
# File lib/bmg/reader/csv.rb, line 59 def with_io(&bl) case @path_or_io when IO, StringIO bl.call(@path_or_io) else File.open(@path_or_io, "r", &bl) end end