Skip to content

Instantly share code, notes, and snippets.

@NARKOZ
Created July 12, 2019 05:27
Show Gist options
  • Save NARKOZ/e7daf5f34d236f58e0237be7b1de85b6 to your computer and use it in GitHub Desktop.
Save NARKOZ/e7daf5f34d236f58e0237be7b1de85b6 to your computer and use it in GitHub Desktop.
Задание по рефакторингу

Задание по рефакторингу

Инструкции

Для выполнения задания требуется:

  • Отрефакторить данный пример в тот вид, который считаешь приемлимым
  • Добавить описание:
    • того, что изменилось и почему
    • с какими проблемами столкнулся в процессе
    • любые идеи и мысли, чтобы еще сделал при наличии дополнительного времени, и т.д.

История

Нам захотелось попробовать возможность отправки различных промо сообщений новым пользователям. Поэтому, мы разработали функционал, который позволяет администраторам:

  • Создавать и отправлять промо сообщения пользователям, которые опубликовали свое первое объявление в указанный промежуток времени.
  • Скачать CSV файл со списком получателей.

Для упрощения модели и контроллеры находятся в одном файле (example.rb), что должно дать общее представление для выполнения задания.

# Модели
class PromoMessage < ActiveRecord::Base
end
class User < ActiveRecord::Base
has_many :ads
scope :recent, -> { order("created_at DESC") }
end
class Ad < ActiveRecord::Base
end
# Контроллеры
class PromoMessagesController < ApplicationController
attr_reader :provider
def new
@message = PromoMessage.new
if params[:date_from].present? && params[:date_to].present?
get_users
end
end
def create
@message = PromoMessage.new(promo_message_params)
users = get_users
recipients = []
users.each do |user|
recipients << user.phone
end
if @message.save && send_message(recipients)
redirect_to promo_messages_path, notice: "Messages Sent Successfully!"
end
end
def download_csv
users = get_users
send_data to_csv(users), filename: "promotion-users-#{Time.zone.today}.csv"
end
private
def to_csv(data)
attributes = %w(id phone name)
CSV.generate(headers: true) do |csv|
csv << attributes
data.each do |user|
csv << attributes.map { |attr| user.send(attr) }
end
end
end
def send_message(recipients)
recipients.each do |r|
PromoMessagesSendJob.perform_later(r)
end
end
def get_users
@users = User.recent.joins(:ads).group("ads.user_id").where("`published_ads_count` = 1").
where("published_at Between ? AND ?", Date.parse(params[:date_from]), Date.parse(params[:date_to])).page(params[:page])
end
def promo_message_params
params.permit(:body, :date_from, :date_to)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment