Guest User

Untitled

a guest
Apr 24th, 2018
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. # Controller for an admin screen
  2. # Admin wants to rapidly prototype different texts/wordings sent out to new authors
  3. # Used to compose and send out retention emails to authors who published their first recipe within a specified timeframe
  4. # Admin can download CSV of recipients for each email
  5.  
  6. # Model
  7. class RetentionEmail < ActiveRecord::Base
  8. end
  9.  
  10. class User < ActiveRecord::Base
  11. has_many :recipes
  12. scope :recent, -> { order("created_at DESC") }
  13. scope :first_publication_in, (from, to)-> {
  14. joins(:recipes).group("recipes.user_id").where(published_recipes_count: 1).
  15. where(published_at: from..to)
  16. }
  17. end
  18.  
  19. class Recipe < ActiveRecord::Base
  20. end
  21.  
  22. class CsvBuilder
  23. def initialize(attributes, data)
  24. @data = data
  25. @attributes = attributes
  26. end
  27.  
  28. def generate
  29. CSV.generate(headers: true) do |csv|
  30. csv << @attributes
  31. @data.each do |line|
  32. csv << @attributes.map { |attr| line.send(attr) }
  33. end
  34. end
  35. end
  36. end
  37.  
  38. class BulkEmailWorker
  39. def perform(recipients)
  40. recipients.find_each do |r|
  41. UserMailer.bulk_email(r).deliver_later
  42. end
  43. end
  44. end
  45.  
  46. # Controller
  47. class RetentionEmailsController < ApplicationController
  48. attr_reader :provider
  49.  
  50. def new
  51. @email = RetentionEmail.new
  52. if params[:date_from].present? && params[:date_to].present?
  53. users
  54. end
  55. end
  56.  
  57. def create
  58. @email = RetentionEmail.new(retention_email_params)
  59.  
  60. recipients = []
  61. users.each do |user|
  62. recipients << user.email
  63. end
  64.  
  65. if @email.save && send_mail(recipients)
  66. redirect_to retention_emails_path, notice: "Emails Sent Successfully!"
  67. end
  68. end
  69.  
  70. def download_csv
  71. csv = CsvBuilder.new(%w{id email name}, users).generate
  72. send_data csv, filename: "author-retention-users-#{Time.zone.today}.csv"
  73. end
  74.  
  75. private
  76.  
  77. def send_mail(recipients)
  78. BulkEmailWorker.new.perform recipients
  79. end
  80.  
  81. def users
  82. @users ||= User.recent
  83. .first_publication_in(Date.parse(params[:date_from], Date.parse(params[:date_to]))
  84. .page(params[:page])
  85. end
  86.  
  87. def retention_email_params
  88. params.permit(:body, :date_from, :date_to)
  89. end
  90. end
Add Comment
Please, Sign In to add comment