docbrown/app/services/exporter/service.rb
rhymes 915e2d77b6 Export articles/posts (#576)
* Add EditorConfig file for all editors

* Add article export service

* Add setting to request an export of all articles

* On the outside they are called posts

* Add articles exported email to mailer and service

* Refactor to one public method and test flags

* Trigger the export if it was requested and send the email

* Recreated migration file with generic export fields

* Rename fields and switch to a whitelist

* Refactor ArticleExportService into a more generic structure

* Rename articles_exported_email to export_email

* Fix notify mailer spec

* Rename Exporter::Exporter to Exporter::Service

* Remove commented out line

* Removed body_html, coordinates and updated_at from export

* Invert DJ config

* Update spec
2018-11-21 11:13:36 -05:00

64 lines
1.3 KiB
Ruby

require "zip"
module Exporter
class Service
attr_reader :user
EXPORTERS = [
Articles,
].freeze
def initialize(user)
@user = user
end
def export(send_email: false, config: {})
exports = {}
# export content with filenames
EXPORTERS.each do |exporter|
files = exporter.new(user).export(config.fetch(exporter.name.to_sym, {}))
files.each do |name, content|
exports[name] = content
end
end
zipped_exports = zip_exports(exports)
send_exports_by_email(zipped_exports) if send_email
update_user_export_fields
zipped_exports.rewind
zipped_exports
end
private
def zip_exports(exports)
buffer = StringIO.new
Zip::OutputStream.write_buffer(buffer) do |stream|
exports.each do |name, content|
stream.put_next_entry(
name,
nil, # comment
nil, # extra
Zip::Entry::DEFLATED,
Zlib::BEST_COMPRESSION,
)
stream.write content
end
end
buffer
end
def send_exports_by_email(zipped_exports)
zipped_exports.rewind
NotifyMailer.export_email(user, zipped_exports.read).deliver
end
def update_user_export_fields
user.update!(export_requested: false, exported_at: Time.current)
end
end
end