Last active
March 24, 2020 08:42
-
-
Save TsubasaKawajiri/bfe12d1955e4e1b33e9a229762e20c04 to your computer and use it in GitHub Desktop.
手軽な要件のcsvを手軽に生成する
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
class CSVCreator | |
class_attribute :directory | |
class_attribute :file_name | |
class_attribute :items | |
class_attribute :headers | |
class_attribute :options | |
class << self | |
def directory(directory) | |
self.directory = directory | |
end | |
def file_name(file_name) | |
self.file_name = file_name | |
end | |
def items(items) | |
self.items = items | |
end | |
def options(options) | |
self.options = options | |
end | |
end | |
def do | |
raise(NotImplementedError, "You must implement #{self.class}##{__method__}") | |
end | |
private | |
def create_csv | |
CSV.open(file_path, 'w', options) do |csv| | |
items.each do |item| | |
csv.puts row(item) | |
end | |
end | |
end | |
def row(_item) | |
raise(NotImplementedError, "You must implement #{self.class}##{__method__}") | |
end | |
def file_path | |
File.expand_path("#{directory}/#{file_name}", Rails.root) | |
end | |
end |
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
class ExampleCsvCreater < CSVCreator | |
directory 'books/csv' | |
file_name 'books.csv' | |
items Book.stock # as ActiveRecord::Relation | |
options { headers: ['title', 'author', 'asin'], row_sep: ',' } | |
def do | |
Logger.info 'start' | |
create_csv | |
end | |
private | |
def row(book) | |
[book.title, book.author, asin(book.asin)] | |
end | |
def asin(asin) | |
'none' if asin.nil? | |
asin | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment