Skip to content

Instantly share code, notes, and snippets.

@patrick99e99
Created May 14, 2010 01:16
Show Gist options
  • Save patrick99e99/400684 to your computer and use it in GitHub Desktop.
Save patrick99e99/400684 to your computer and use it in GitHub Desktop.
class PdfFile < ActiveRecord::Base
belongs_to :result_list
has_attached_file :attachment, :path => "pdf/:id/:basename.:extension"
before_post_process :set_file_name
def generate_labels(params)
unless job_finish.nil?
# mailing_list is whether to filter only mailing list contacts or not
mailing_list = params[:mailing_list]
setting_id = params[:from_shipping_address_id]
self.attachment.destroy
update_attributes(:job_start => Time.now,
:job_finish => nil,
:job_error => nil,
:label_count => 0)
background_process(mailing_list, setting_id)
end
end
def set_to_and_from_addresses(mailing_list, setting_id)
@from_address = Setting.find(setting_id).value
# get addresses that have a region and country
@addresses = result_list.contacts.map(&:addresses).flatten.compact.select{|a| a.region && a.country}
@addresses = @addresses.select{|a| a.mailing_list} if mailing_list
end
def background_process(mailing_list, setting_id)
begin
set_to_and_from_addresses(mailing_list, setting_id)
unless @addresses.length.zero?
shipping_label_renderer = ShippingLabelRenderer.new
@addresses.each do |to_address|
shipping_label_renderer.create_label(@from_address, to_address)
self.increment!(:label_count, 1)
end
pdf_file = Tempfile.new("shipping_labels.pdf")
pdf_file.write(shipping_label_renderer.output_prawn_object.render)
self.attachment = pdf_file
self.save
end
rescue => e
update_attribute(:job_error, e)
ensure
update_attribute(:job_finish, Time.now)
end
end
handle_asynchronously :background_process
private
def set_file_name
# when using Tempfile, filename becomes "shipping_labels,12928,0.pdf" which becomes "shiping_labels_12928_0.pdf"
formatted_date = self.updated_at.strftime('%m-%d-%Y')
self.attachment.instance_write(:file_name, "shipping_labels_#{formatted_date}.pdf")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment