992f15066b
ZipKit can read and write files directly from S3 which makes both imports and exports way more efficient in terms of disk usage.
54 lines
1.1 KiB
Ruby
54 lines
1.1 KiB
Ruby
class Export < ApplicationRecord
|
|
belongs_to :account
|
|
belongs_to :user
|
|
|
|
has_one_attached :file
|
|
|
|
enum :status, %w[ pending processing completed failed ].index_by(&:itself), default: :pending
|
|
|
|
scope :current, -> { where(created_at: 24.hours.ago..) }
|
|
scope :expired, -> { where(completed_at: ...24.hours.ago) }
|
|
|
|
def self.cleanup
|
|
expired.destroy_all
|
|
end
|
|
|
|
def build_later
|
|
ExportDataJob.perform_later(self)
|
|
end
|
|
|
|
def build
|
|
processing!
|
|
|
|
with_account_context do
|
|
ZipFile.create_for(file, filename: "fizzy-export-#{id}.zip") do |zip|
|
|
populate_zip(zip)
|
|
end
|
|
mark_completed
|
|
ExportMailer.completed(self).deliver_later
|
|
end
|
|
rescue => e
|
|
update!(status: :failed)
|
|
raise e
|
|
end
|
|
|
|
def mark_completed
|
|
update!(status: :completed, completed_at: Time.current)
|
|
end
|
|
|
|
def accessible_to?(accessor)
|
|
accessor == user
|
|
end
|
|
|
|
private
|
|
def with_account_context
|
|
Current.set(account: account) do
|
|
yield
|
|
end
|
|
end
|
|
|
|
def populate_zip(zip)
|
|
raise NotImplementedError, "Subclasses must implement populate_zip"
|
|
end
|
|
end
|