Class: Nebulous::Row

Inherits:
Array
  • Object
show all
Defined in:
lib/nebulous/row.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.headers(str, opts) ⇒ Object



3
4
5
6
7
8
9
# File 'lib/nebulous/row.rb', line 3

def self.headers(str, opts)
  headers = parse(str, opts).
    map(&:parameterize).
    map(&:underscore).
    map(&:to_sym)
  headers.zip(headers).to_h
end

.parse(str, opts) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/nebulous/row.rb', line 11

def self.parse(str, opts)
  str.gsub!(opts.comment_exp, '')
  str.chomp!

  begin
    args = opts.to_h.slice(:col_sep, :row_sep, :quote_char)
    data = CSV.parse_line str, args
  rescue CSV::MalformedCSVError
    exp = /(#{opts.col_sep})(?=(?:[^"]|"[^"]*")*$)/
    data = str.gsub(exp, "\0").split(/\0/)
  end

  data.map!(&:strip)
  new(data).to_numeric
end

Instance Method Details

#merge(keys) ⇒ Object



42
43
44
45
# File 'lib/nebulous/row.rb', line 42

def merge(keys)
  return self unless keys
  keys.values.zip(self).to_h
end

#to_numericObject



27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/nebulous/row.rb', line 27

def to_numeric
  arr = map do |val|
    case val
    when /^[+-]?\d+\.\d+$/
      val.to_i
    when /^[+-]?\d+$/
      val.to_i
    else
      val
    end
  end

  self.class.new(arr)
end