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.

Answers


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
    

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

Need Your Help

Convert a QString for using in SQL queries

sql qt

I want to generate SQL queries from user input for inserting some data into a database.

Use TreeView to display hierarchical structure with context-sensitive contexts in XAML

c# wpf xaml mvvm treeview

I'd like to "translate" my earlier Forms-Application into an WPF Solution trying to follow the MVVM-Pattern.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.