Created
November 6, 2024 12:02
-
-
Save Hasstrup/27d6cd04e0d6ce297f3e6c6fe97f2600 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
# PdfMailer is responsible for sending emails that contain PDF attachments. | |
# It formats the email using the user's details and attaches the generated PDF. | |
class PdfMailer < ApplicationMailer | |
# Sends an email with the generated PDF attachment. | |
# | |
# @param input [Hash] A hash containing input data including: | |
# - :user [User] The user receiving the email. | |
# - :template [Templates::Template] The template associated with the PDF. | |
# - :tmpfile [Tempfile] The temporary file containing the generated PDF. | |
# | |
# @return [Mail::Message] The mail object. | |
def pdf_generated(input) | |
after_inserting_attachments(input) do | |
@user = input[:user] | |
mail(**mailer_params_from_input(input)) | |
end | |
end | |
private | |
# Prepares the parameters for the mailer from the input hash. | |
# | |
# @param input [Hash] The input data for generating the email. | |
# | |
# @return [Hash] A hash containing the parameters for the mailer. | |
def mailer_params_from_input(input) | |
{ | |
to: input[:user].email, | |
from: "#{input[:user].first_name} <#{default_email_sender}>", | |
template_path: 'pdf_mailer', | |
template_name: 'basic_example', | |
formats: [:html], | |
subject: "#{input[:user].first_name}'s Invoice - #{formatted_todays_date}" | |
} | |
end | |
# Inserts the PDF attachment into the email. | |
# | |
# @param input [Hash] The input data containing the PDF details. | |
# | |
# @yield [void] Yields control to the block after attachments are inserted. | |
def after_inserting_attachments(input) | |
attachments[input[:template].reference_file_name] = File.read(input[:tmpfile].path) | |
yield | |
end | |
# Formats today's date into a string. | |
# | |
# @return [String] The formatted date string. | |
def formatted_todays_date | |
Date.today.strftime('%a, %b %e, %Y') | |
end | |
# Retrieves the default email sender address from the environment variable. | |
# | |
# @return [String] The default email sender address. | |
def default_email_sender | |
@default_email_sender ||= ENV["EMAIL_SENDER"] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment