user2291579
user2291579

Reputation: 3

Automatically generating PDF's in ruby on rails

I'm currently working on a ruby on rails project. I need the system to automatically generate a PDF every 12 hours based off information from a data base.

Currently I'm looking at the prawn gem to generate the PDF's but I was wondering if there was a way to make this gem (or any other) produce the PDF every so many hours.

Upvotes: 0

Views: 574

Answers (2)

oldhomemovie
oldhomemovie

Reputation: 15129

If you know how to generate PDFs via Ruby (using prawn or wicked_pdf), there are only 2 steps left to take:

  1. Create a rake task, call it, like this:

    # lib/tasks/my_pdf_task.rake
    
    desc "Generate pdf"
    task :generate_pdf => :environment do
      MyPdfGenerator.new.generate
    end
    
  2. Run it via cron, using whenever gem. After installing & initializing the gem, edit the config/schedule.rb:

    # config/schedule.rb
    
    every 3.hours do
      rake "generate_pdf"
    end
    

Upvotes: 1

Deej
Deej

Reputation: 5352

Something like this can be achieved by using Wicked PDF. From my past understanding and your question it seems that you want to generate some sort of email that contains the attachment pdf. If I stand correctly you would have something like this in your mailer.

 def overtime_pdf(user, booking)
    @bookings = booking
    @user = user
    mail(:subject => 'Overtime', :to => user.email) do |format|
      format.text # renders overtime_pdf.text.erb for body of email
      format.pdf do
        attachments['bookings.pdf'] = WickedPdf.new.pdf_from_string(
            render_to_string(:pdf => 'overtime', :template =>
                'bookings/index.pdf.erb', :layouts => 'pdf.html')
        )
      end
    end
  end

Upon doing this if you are using heroku you can use heroku-scheduler. What you want to do is create a class method that take a user argument, then you can pass the user in the controller action and use this in the rake task. So you could have something like this.

Class

 def self.send_overtime_mail(user, bookings)
    BookingMailer.booking_pdf(user, bookings).deliver
  end

Rake task

task :overtime_report => :environment do
  every 3.hours do
    user = User.where(:role => :administrator).first
    bookings = Bookings.where(:day => Date.today.beginning_of_month..Date.today.end_of_month)
    Booking.send_overtime_mail(user, bookings)
  end
end

Upvotes: 0

Related Questions