Class: Parceira::Reader
- Inherits:
-
Object
- Object
- Parceira::Reader
- Defined in:
- lib/parceira/reader.rb
Constant Summary collapse
- DEFAULT_OPTIONS =
{ # CSV options col_sep: ',', row_sep: $/, quote_char: '"', # Header headers: true, headers_included: true, key_mapping: nil, file_encoding: nil, # Values reject_blank: true, reject_nil: false, reject_zero: false, reject_matching: nil, convert_to_numeric: true, }
Instance Attribute Summary collapse
-
#options ⇒ Object
readonly
Returns the value of attribute options.
Instance Method Summary collapse
-
#initialize(input, options) ⇒ Reader
constructor
A new instance of Reader.
- #process! ⇒ Object
Constructor Details
#initialize(input, options) ⇒ Reader
Returns a new instance of Reader.
24 25 26 27 |
# File 'lib/parceira/reader.rb', line 24 def initialize(input, ) @input = input @options = DEFAULT_OPTIONS.merge() end |
Instance Attribute Details
#options ⇒ Object (readonly)
Returns the value of attribute options.
21 22 23 |
# File 'lib/parceira/reader.rb', line 21 def @options end |
Instance Method Details
#process! ⇒ Object
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
# File 'lib/parceira/reader.rb', line 30 def process! if input_file.nil? && @input.is_a?(String) data = CSV.parse(@input, ) # content is already in memory. Process with CSV header_data = data.shift if [:headers_included] # Remove header row header_keys = \ if [:headers] == true self.parse_header( header_data ) elsif [:headers].is_a?(Array) [:headers] end data.map do |arr| values = parse_values(arr) if header_keys convert_to_hash(header_keys, values) else values end end elsif input_file.is_a?(File) output = [] begin $/ = [:row_sep] # Build header header_data = input_file.readline.to_s.chomp([:row_sep]) if [:headers_included] # Remove header row header_keys = \ if [:headers] == true begin data = CSV.parse(header_data, self.) self.parse_header( data ) rescue CSV::MalformedCSVError end elsif [:headers].is_a?(Array) [:headers] end # now on to processing all the rest of the lines in the CSV file: while !input_file.eof? # we can't use f.readlines() here, because this would read the whole file into memory at once, and eof => true values = begin parse_values( CSV.parse(input_file.readline.chomp, ) ) rescue CSV::MalformedCSVError end if header_keys output << convert_to_hash(header_keys, values) else output << values end if values end ensure $/ = $/ end output end end |