Экспортируйте файл xlsx в виде ссылки в письме, используя axlsx-rails - PullRequest
0 голосов
/ 06 мая 2019

Я использую Rails 4.2, sidekiq, rubyzip, axlsx и axlsx-rails

Что мне нужно сделать: Мне нужно экспортировать файл по почте, но как ссылку, а не как вложение. Я хочу отправить письмо с URL-адресом для загрузки

Проблема: Я не знаю, как это сделать с этим гемом, в документации по git ничего нет, и каждый URL, который я использую, не работает. Мне нужно знать, как создать для него ссылку для скачивания, а не как вложение в почту

Код:

Контроллер:

def export
      export_args = {account_id: current_account.id}
      ExportReportJob.perform_later(export_args)
      redirect_to action: :index
end

работа:

def perform(export_args)
      begin
        export_failed = false
        account = Admin::Account.find_by(id: export_args[:account_id])
        account.connect_to_target_db
        @accounts = Admin::Account.active_accounts
        file_name = "#{Time.now.strftime("%d_%m_%Y_at_%I_%M%p")}_export.xlsx"
        dir_path = "#{Rails.root}/public/exports"
        FileUtils.mkdir_p(dir_path) unless File.directory?(dir_path)
        file_location = "#{absolute_path}/#{file_name}"
        Admin::Mailer.export(account.pi, @accounts, file_location).deliver
        rescue => e
          export_failed = true
          Airbrake.notify(e, environment_name: Rails.env, error_message: "export account failed #{e.message}")
        ensure
          ActiveRecord::Base.clear_active_connections!
        end
      end

шаблон:

wb = xlsx_package.workbook

wb.add_worksheet(name: "Accounts") do |sheet|
  sheet.add_row ["Account id", "Account name", "Organization"]

   accounts.each do |account|
    sheet.add_row [account.id, accoount.name, account.organization_id]
   end
end

xlsx_package.to_stream.read 

почтовая программа:

def export(member, accounts, file_location)
    @member = member
    @title = "Export"
    @header = subject = "Your Export is Ready"
    @link = file_location
    xlsx = render_to_string(layout: false, handlers: [:xlsx], template: "export.xlsx.axlsx", locals: {accounts: accounts})
    # attachment = Base64.encode64(xlsx)
    # attachments["export_#{DateTime.now.strftime("%d_%m_%Y_%HH%MM")}.xlsx"] = {mime_type: Mime::XLSX, content: attachment, encoding: 'base64'}
    # ^ this is not what I want, I want to get the url for it and insert to @link
    mail(:to => member.email, :subject => subject) do |format|
      format.html
    end
  end

почтовый шаблон:

= render partial: 'header'
= h_tag 'The export you requested has been completed'
= button 'Download the file', @link, { download: true }
= p_tag '(the file download will expire after <b>2</b> days)'
= render partial: 'footer'
...