Class: CsvObject

Inherits:
Object
  • Object
show all
Defined in:
lib/csv_object.rb,
lib/csv_object/version.rb

Constant Summary collapse

VERSION =
"0.1.1"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(content) ⇒ CsvObject

Returns a new instance of CsvObject.



41
42
43
# File 'lib/csv_object.rb', line 41

def initialize(content)
  @csv = CSV.parse(CsvObject.wrap(content), headers: true)
end

Class Method Details

.generate(array_of_hashes) ⇒ Object

class Error < StandardError; end



7
8
9
10
11
12
13
14
# File 'lib/csv_object.rb', line 7

def self.generate(array_of_hashes)
  CSV.generate do |csv|
    csv << array_of_hashes.first.keys
    array_of_hashes.each do |hash|
      csv << hash.values
    end
  end
end

.wrap(content) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/csv_object.rb', line 16

def self.wrap(content)
  case content
  when CSV::Table
    content
  when String
    if content =~ /\n/
      content
    elsif FileTest.exist?(content)
      wrap(Pathname.new(content))
    else
      content
    end
  when Pathname
    IO.read(content)
  when Array # array of hashes
    CsvObject.generate(content)
  when Paperclip::Attachment
    Paperclip.io_adapters.for(content).read  # https://stackoverflow.com/questions/6555468
  when CsvObject
    content.to_csv
  else
    raise ArgumentError, "unexpected object class '#{content.class}'"
  end
end

Instance Method Details

#headersObject



57
58
59
# File 'lib/csv_object.rb', line 57

def headers
  @headers ||= @csv.headers
end

#sizeObject



93
94
95
# File 'lib/csv_object.rb', line 93

def size
  to_h.size
end

#sort(&block) ⇒ Object



49
50
51
# File 'lib/csv_object.rb', line 49

def sort(&block)
  to_hash @csv.sort(&block)
end

#subset(ids, id_column_name) ⇒ Object



69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/csv_object.rb', line 69

def subset(ids, id_column_name)
  id_column_index = headers.index(id_column_name)

  tmp = CSV.generate(headers: true) do |row|
    row << headers

    to_a.each do |hash|
      id_value = hash[id_column_index]
      row << hash if ids.include?(id_value)
    end
  end

  CsvObject.new(tmp)
end

#to_aObject



45
46
47
# File 'lib/csv_object.rb', line 45

def to_a
  @csv
end

#to_csvObject



61
62
63
# File 'lib/csv_object.rb', line 61

def to_csv
  @csv.to_csv
end

#to_file(path) ⇒ Object



84
85
86
87
88
89
90
91
# File 'lib/csv_object.rb', line 84

def to_file(path)
  CSV.open(path, 'wb') do |file|
    file << headers
    to_h.each do |hash|
      file << hash.values_at(*headers)
    end
  end
end

#to_hObject



53
54
55
# File 'lib/csv_object.rb', line 53

def to_h
  to_hash @csv
end

#to_sObject



65
66
67
# File 'lib/csv_object.rb', line 65

def to_s
  to_csv
end