Skip to content

Instantly share code, notes, and snippets.

@supremebeing7
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save supremebeing7/0081ca880c0843a77b7e to your computer and use it in GitHub Desktop.
Save supremebeing7/0081ca880c0843a77b7e to your computer and use it in GitHub Desktop.
Refactored mailer methods
# This is an exercise in refactoring. The attempt is to make the code more DRY (Don't Repeat Yourself) while
# maintaining or increasing readability. While it's certainly more DRY, readability seems to have suffered.
# Therefore, this may be a case where less DRY code is ultimately better for the project and future devs.
def report_email(user, report, template_name)
@user = user
@report = report
mail(to: @user.email,
from: "\"Company Reports\" reports@example.com",
subject: "#{template_name.chomp('_email').humanize} for #{@user.account.name}",
template_name: template_name)
end
def rating_email(user, rating, template_name)
@user = user
@rating = rating
mail(to: @user.email,
from: "\"Company Alerts\" alerts@example.com",
subject: "#{template_name.chomp('_email').humanize} for #{@user.account.name}",
template_name: template_name)
end
# REFACTORED TO ONE METHOD:
def report_or_alert_email(user, object, template_name)
@user = user
@object = object
# Ensure the instance vars in the mailer templates are changed accordingly
@template_name = template_name
mail(to: @user.email,
from: sent_from,
subject: email_subject,
template_name: template_name)
end
private
def sent_from
"\"Company #{class_name.capitalize.pluralize}\" #{class_name.downcase.pluralize}@example.com"
# => example: "Company Reports" reports@company.com
end
def class_name
@object.class.to_s
end
def email_subject
"#{@template_name.chomp('_email').humanize} for #{@user.account.name}"
# => example: "Week Report for Cooper Account"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment