Class: CSV::FieldsConverter

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/csv/fields_converter.rb

Overview

Note: Don’t use this class directly. This is an internal class.

Constant Summary collapse

NO_QUOTED_FIELDS =

:nodoc:

[]

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ FieldsConverter

A CSV::FieldsConverter is a data structure for storing the fields converter properties to be passed as a parameter when parsing a new file (e.g. CSV::Parser.new(@io, parser_options))



20
21
22
23
24
25
26
27
28
# File 'lib/csv/fields_converter.rb', line 20

def initialize(options={})
  @converters = []
  @nil_value = options[:nil_value]
  @empty_value = options[:empty_value]
  @empty_value_is_empty_string = (@empty_value == "")
  @accept_nil = options[:accept_nil]
  @builtin_converters_name = options[:builtin_converters_name]
  @need_static_convert = need_static_convert?
end

Instance Method Details

#add_converter(name = nil, &converter) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/csv/fields_converter.rb', line 30

def add_converter(name=nil, &converter)
  if name.nil?  # custom converter
    @converters << converter
  else          # named converter
    combo = builtin_converters[name]
    case combo
    when Array  # combo converter
      combo.each do |sub_name|
        add_converter(sub_name)
      end
    else        # individual named converter
      @converters << combo
    end
  end
end

#convert(fields, headers, lineno, quoted_fields = NO_QUOTED_FIELDS) ⇒ Object



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
# File 'lib/csv/fields_converter.rb', line 54

def convert(fields, headers, lineno, quoted_fields=NO_QUOTED_FIELDS)
  return fields unless need_convert?

  fields.collect.with_index do |field, index|
    if field.nil?
      field = @nil_value
    elsif field.is_a?(String) and field.empty?
      field = @empty_value unless @empty_value_is_empty_string
    end
    @converters.each do |converter|
      break if field.nil? and @accept_nil
      if converter.arity == 1  # straight field converter
        field = converter[field]
      else                     # FieldInfo converter
        if headers
          header = headers[index]
        else
          header = nil
        end
        quoted = quoted_fields[index]
        field = converter[field, FieldInfo.new(index, lineno, header, quoted)]
      end
      break unless field.is_a?(String)  # short-circuit pipeline for speed
    end
    field  # final state of each field, converted or original
  end
end

#each(&block) ⇒ Object



46
47
48
# File 'lib/csv/fields_converter.rb', line 46

def each(&block)
  @converters.each(&block)
end

#empty?Boolean

Returns:

  • (Boolean)


50
51
52
# File 'lib/csv/fields_converter.rb', line 50

def empty?
  @converters.empty?
end