0

I'm new in rails task and I want to execute and pass parameter in a task then in a loop to say if yes or no execute other task (not depending on the ENV but on my 'on moment' needs). Here is the code :

My task :

namespace :invoices do
  desc "CREATE PDF AND SEND MAIL TASK"
  task create_and_send_pdf: :environment do
    Invoice.all.each do |invoice|
        invoice.create_and_send_pdf({send_invoice: true})
    end
  end
end

My other function to call :

def create_and_send_pdf(options = {})
    begin
        to_print = self
        ...
        if options[:send_invoice].blank? || options[:send_invoice]
            send_to_customer(to_print) 
        end
        ...

    end

    return true
end


private

    # Call mailer and send mail to customer
    def send_to_customer(invoice)
        unless invoice.send_at
            key = SecureRandom.hex(10)
            # Update invoice attibutes
            invoice.update_attributes({track_number: key, send_at: DateTime.now})
            InvoiceMailer.sample_email(invoice, key).deliver!
        end
    end

And my rake task :

rake invoices:create_and_send_pdf

So here is the deal, I don't want to call send_to_customer function if I execure my task with a send_invoice: false parameter

Thanks

ansmonjol
  • 83
  • 1
  • 8
  • You can check this http://stackoverflow.com/questions/1357639/rails-rake-how-to-pass-in-arguments-to-a-task-with-environment – Prosenjit Saha Jul 22 '15 at 10:09
  • possible duplicate of [How to invoke rake with non-rake parameters](http://stackoverflow.com/questions/24491583/how-to-invoke-rake-with-non-rake-parameters) – Kirill Fedyanin Jul 22 '15 at 10:28

1 Answers1

0
task :create_and_send_pdf, [:send_invoice] => :environment do |task, args|
  Invoice.all.each do |invoice|
    invoice.create_and_send_pdf({send_invoice: args.send_invoice})
  end
end

rake invoices:create_and_send_pdf[true]
rake invoices:create_and_send_pdf[false]
  • Thanks for reply but it still doesn't work, I try to set args next to invoice in the each loop then remove send_invoice of args.send_invoice to get only the passed value but the code still execute the other function. Is it a problem with my if condition ? ` if options[:send_invoice].blank? || options[:send_invoice] ` – ansmonjol Jul 22 '15 at 11:47
  • Ok it was my condition, I juste add a == true for || options[:send_invoice], Thank you ! – ansmonjol Jul 22 '15 at 12:12