Module: Cosm::Parsers::CSV::FeedDefaults

Included in:
Feed
Defined in:
lib/cosm-rb/parsers/csv/feed_defaults.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.detect_version(rows, version = nil) ⇒ Object



10
11
12
13
14
15
# File 'lib/cosm-rb/parsers/csv/feed_defaults.rb', line 10

def detect_version(rows, version = nil)
  return version if version
  return :v2 if rows.size >= 2
  return :v1 if rows.size == 1 && rows.first.size != 2
  raise UnknownVersionError, "CSV Version could not be detected"
end

Instance Method Details

#from_csv(csv, csv_version = nil) ⇒ Object

Raises:



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/cosm-rb/parsers/csv/feed_defaults.rb', line 18

def from_csv(csv, csv_version = nil)
  begin
    rows = Cosm::CSV.parse(csv.strip)
  rescue Exception => e
    # this might be a FasterCSV or CSV exception depending on whether
    # we are running under 1.8.x or 1.9.x
    raise InvalidCSVError, e.message
  end

  version = FeedDefaults.detect_version(rows, csv_version)

  hash = Hash.new

  raise InvalidCSVError, "Submitted CSV is empty." if rows.empty?

  if version == :v2
    hash["datastreams"] = extract_datastreams(rows)
  elsif version == :v1
    raise InvalidCSVError, "CSV is invalid. Currently we can only accept CSV for your most recent set of values. You have submitted #{rows.size} rows of data." if rows.size > 1
    hash["datastreams"] = []
    rows.first.each_with_index do |current_value, stream_id|
      hash["datastreams"] << { "id" => stream_id.to_s.strip, "current_value" => current_value.to_s.strip }
    end
  end
  hash["csv_version"] = version
  hash
end