Skip to content

Instantly share code, notes, and snippets.

@alexshapalov
Last active October 13, 2020 15:15
Show Gist options
  • Save alexshapalov/1184f0b71abf51af47ff2a513eeddb87 to your computer and use it in GitHub Desktop.
Save alexshapalov/1184f0b71abf51af47ff2a513eeddb87 to your computer and use it in GitHub Desktop.
# This is a Service Object for generating special PDF with a list of countries.
# country_pdf_list.rb
# I prefer to use Sendi Matz rule
# Classes can be no longer than one hundred lines of code.
# Methods can be no longer than five lines of code.
# Pass no more than four parameters into a method. Hash options are parameters.
# Controllers can instantiate only one object
require "wicked_pdf"
class CountryPdfList
def call
save_data_to_pdf(pdf_infection_country_render)
end
def file_path
Rails.root.join('tmp', 'pdfs', "pdf_infection_country_list_#{time_now}.pdf")
end
private
def pdf_infection_country_render
ac = ActionController::Base.new.render_to_string(pdf_params)
WickedPdf.new.pdf_from_string(ac)
end
def pdf_params
{
template: "admin/travel_check/countries/generate_list_of_country_pdf.html.erb",
title: "Countries Infection List, #{time_now}",
encoding: 'utf-8'
}
end
def save_data_to_pdf(pdf_file)
File.open(file_path, 'wb') do |file|
file << pdf_file
end
end
def time_now
Time.now.strftime("%Y-%m-%d")
end
end
# method from controller.rb
def generate_list_of_country_pdf
create_pdf_list = CountryPdfList.new
create_pdf_list.call
send_file create_pdf_list.file_path, :disposition => 'attachment'
end
# Also it eaysy to test
require 'rails_helper'
RSpec.describe CountryPdfList, type: :service do
before(:each) do
@pdf_country_list = CountryPdfList.new.create_country_pdf
end
context "create a pdf with countrry list" do
it { @pdf_country_list.create_country_pdf be_kind_of(File) }
it "create_country_pdf " do
expect(@pdf_country_list).with("pdf_infection_country_list_2020-02-07.pdf", "w")
@pdf_country_list.should be_true
File.should_receive(:open).with("filename", "w").and_yield(file)
end
it 'generated PDF file' do
filename = "pdf_infection_country_list_2020-02-07.pdf"
allow(File).to receive(:open).with(filename,'w')
# call the function that writes to the file
File.open(@filename, 'w') {|f| f.write(@content)}
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment