samedi 28 août 2021

Refactor Rails controller

I am trying to achieve this feature:

Sent texts out to new authors.

It enables admin users to

  1. when authors published their first article in a specified timeframe, Compose and send out emails to authors

  2. Download a CSV file with a list of recipients.

I want to refactor the controller code in efficient way

 Models
class Email < ActiveRecord::Base
end

class User < ActiveRecord::Base
  has_many :articles
  scope :recent, -> { order("created_at DESC") }
end

class Article < ActiveRecord::Base
end




# Controller
class EmailsController < ApplicationController
  attr_accessor :email

  def new
    @email = Email.new
    if params[:date_from].present? && params[:date_to].present?
      fetch_users
    end
  end

  def create
    @email = Email.new(email_params)

    users = fetch_users
    recipients = []
    users.each do |user|
      recipients << user.email
    end

    if @email.save && send_mail_to_user(recipients)
      redirect_to emails_path, notice: "Emails Sent Successfully!"
    end
  end

  def download_csv
    users = fetch_users
    send_data to_csv(users), filename: "users-article-#{Time.zone.today}.csv"
  end

  private

    def to_csv(data)
      inputs = %w{id email name}
      CSV.generate(headers: true) do |csv|
        csv << attributes
        data.each do |user|
          csv << inputs.map { |attr| user.send(attr) }
        end
      end
    end

    def send_mail_to_user(users)
      users.each do |r|
        UserMailer.bulk_email(r).deliver_later
      end
    end

    def fetch_users
      @users = User.recent.joins(:articles).group("articles.user_id").where("`published_article_count` = 1").
        where("published_at Between ? AND ?", Date.parse(params[:date_from]), Date.parse(params[:date_to])).page(params[:page])
    end

    def email_params
      params.permit(:body, :date_from, :date_to)
    end
end

Aucun commentaire:

Enregistrer un commentaire