Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Controller for an admin screen
- # Admin wants to rapidly prototype different texts/wordings sent out to new authors
- # Used to compose and send out retention emails to authors who published their first recipe within a specified timeframe
- # Admin can download CSV of recipients for each email
- # Model
- class RetentionEmail < ActiveRecord::Base
- end
- class User < ActiveRecord::Base
- has_many :recipes
- scope :recent, -> { order("created_at DESC") }
- scope :first_publication_in, (from, to)-> {
- joins(:recipes).group("recipes.user_id").where(published_recipes_count: 1).
- where(published_at: from..to)
- }
- end
- class Recipe < ActiveRecord::Base
- end
- class CsvBuilder
- def initialize(attributes, data)
- @data = data
- @attributes = attributes
- end
- def generate
- CSV.generate(headers: true) do |csv|
- csv << @attributes
- @data.each do |line|
- csv << @attributes.map { |attr| line.send(attr) }
- end
- end
- end
- end
- class BulkEmailWorker
- def perform(recipients)
- recipients.find_each do |r|
- UserMailer.bulk_email(r).deliver_later
- end
- end
- end
- # Controller
- class RetentionEmailsController < ApplicationController
- attr_reader :provider
- def new
- @email = RetentionEmail.new
- if params[:date_from].present? && params[:date_to].present?
- users
- end
- end
- def create
- @email = RetentionEmail.new(retention_email_params)
- recipients = []
- users.each do |user|
- recipients << user.email
- end
- if @email.save && send_mail(recipients)
- redirect_to retention_emails_path, notice: "Emails Sent Successfully!"
- end
- end
- def download_csv
- csv = CsvBuilder.new(%w{id email name}, users).generate
- send_data csv, filename: "author-retention-users-#{Time.zone.today}.csv"
- end
- private
- def send_mail(recipients)
- BulkEmailWorker.new.perform recipients
- end
- def users
- @users ||= User.recent
- .first_publication_in(Date.parse(params[:date_from], Date.parse(params[:date_to]))
- .page(params[:page])
- end
- def retention_email_params
- params.permit(:body, :date_from, :date_to)
- end
- end
Add Comment
Please, Sign In to add comment