lundi 6 janvier 2020

Preciso criar uma exceção caso o relatório venha em branco ou com dados zerados [closed]

Tentei criar um raise mas como sou novato em ruby on rails to perdido sobre o que fazer uma exceção caso o relatório venha vazio. Segue abaixo o código do service:

class ReportService def self.generate_report(params, type, data_type = 'data') "#{type}Report".constantize.send("report_#{data_type}", params) end

def Not_Blank raise Exception.new('Deu ruim!') unless @data_type.blank? end end

O controller ficou assim:

class Backend::ReportUsersController < Backend::Controller respond_to :html, :xlsx, :pdf load_and_authorize_resource :user, :parent => false before_action :check_permissions

def report if params[:user_report][:institutes].reject!(&:blank?).blank? return redirect_to( report_users_path, alert: I18n.t('report.user.error.institute_required') ) end

if params[:user_report][:start_at].blank?
  params[:user_report][:start_at] = I18n.l(User.first.created_at.to_date, format: :default)
end

if params[:user_report][:end_at].blank?
  params[:user_report][:end_at] = I18n.l(Date.current, format: :default)
end

params[:user_report][:current_user] = current_user.name
if params [:user_report][:total_participants].blank?
  return redirect_to(
    report_users_path,
    alert: I18n.t('report.user.error.cannot_generate_blank_or_empty_report')
  )
end
@report = ReportService.generate_report(params[:user_report], 'User')
@pagy, @report_data = pagy_array(JSON[@report[:data]], size: [2,2,2,2])

end

def generate_file if params[:format] == 'pdf' institutes = Institute.where(id: params[:report][:institute_ids])

  if institutes.size == 1
    @logo = institutes[0].logo
  end

  respond_to do |format|
    format.pdf do
      render pdf: I18n.t('activerecord.models.user.other'),
      margin: { top: 30 },
      footer: {
        font_size: 10,
        left: "#{I18n.t('report.research.general_labels.generated_at')}: " +
          "#{I18n.l(DateTime.current, format: :default_without_seconds)} | " +
          "#{I18n.t('report.research.general_labels.by')}: " +
          "#{@current_user.name}",
        right: "[page] #{I18n.t('report.research.general_labels.of')} [topage]"
      },
      orientation: 'Landscape',
      template: "backend/report_users/layout_pdf.html.erb"
    end
  end
elsif params[:format] == 'xlsx'
  report = ReportService.generate_report(params, 'User', 'excel')

  respond_to do |format|
    format.xlsx { render xlsx: report[:file], filename: I18n.t('report.user.file_name.report_users') }
  end
end

end

private

def check_permissions raise CanCan::AccessDenied unless @current_user.full_manager? end end

Aucun commentaire:

Enregistrer un commentaire