Skip to content

Instantly share code, notes, and snippets.

@dudo
Last active February 5, 2020 03:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dudo/743dd63e1b836458bb5d851819d3cee9 to your computer and use it in GitHub Desktop.
Save dudo/743dd63e1b836458bb5d851819d3cee9 to your computer and use it in GitHub Desktop.
require 'csv'
require 'activerecord-import'
module ActsAsCsv
extend ActiveSupport::Concern
class_methods do
def filename
if const_defined? :CSV_FILENAME
self::CSV_FILENAME
else
name.underscore.pluralize
end
end
def headers
if const_defined? :CSV_HEADERS
self::CSV_HEADERS
else
attribute_names - %w[id created_at updated_at]
end
end
def export_csv
CSV.open("#{filename}.csv", 'w', write_headers: true, headers: headers) do |csv|
all.each { |row| csv << row.attributes.values_at(*headers) }
end
end
def import_csv(csv_file)
values = CSV.open("#{csv_file}.csv", headers: true).each_with_object([]) do |row, o|
o << row.to_h
end
import values, validate: true, on_duplicate_key_ignore: true
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment