Last active
February 5, 2020 03:16
-
-
Save dudo/743dd63e1b836458bb5d851819d3cee9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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