class CsvObject

Constants

VERSION

Public Class Methods

generate(array_of_hashes) click to toggle source

class Error < StandardError; end

# 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
new(content) click to toggle source
# File lib/csv_object.rb, line 41
def initialize(content)
  @csv = CSV.parse(CsvObject.wrap(content), headers: true)
end
wrap(content) click to toggle source
# 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

Public Instance Methods

headers() click to toggle source
# File lib/csv_object.rb, line 57
def headers
  @headers ||= @csv.headers
end
size() click to toggle source
# File lib/csv_object.rb, line 93
def size
  to_h.size
end
sort(&block) click to toggle source
# File lib/csv_object.rb, line 49
def sort(&block)
  to_hash @csv.sort(&block)
end
subset(ids, id_column_name) click to toggle source
# 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_a() click to toggle source
# File lib/csv_object.rb, line 45
def to_a
  @csv
end
to_csv() click to toggle source
# File lib/csv_object.rb, line 61
def to_csv
  @csv.to_csv
end
to_file(path) click to toggle source
# 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_h() click to toggle source
# File lib/csv_object.rb, line 53
def to_h
  to_hash @csv
end
to_s() click to toggle source
# File lib/csv_object.rb, line 65
def to_s
  to_csv
end

Private Instance Methods

to_hash(collection) click to toggle source
# File lib/csv_object.rb, line 99
def to_hash(collection)
  hash = collection.map(&:to_hash)
  defined?(ActiveSupport) ? hash.map(&:with_indifferent_access) : hash
end