rails g model EmailLog user:belongs_to type:string
module Notifications module Notification class Base attr_reader :user def initialize(user) @user = user end def perform? false end def send! NotificationMailer.send(notification_type, user).deliver create_log! end private def notification_params { user_id: user.id, type: notification_type } end def notification_type self.class.name.demodulize.underscore end def create_log! EmailLog.create!(notification_params) end end end end
module Notifications module Notification class FiveDaysAfterRegistration < Base def perform? user.created_at.to_date == 5.days.ago.to_date && EmailLog.where(log_params).blank? end end end end
module Notifications class Worker EMAIL_TYPES = %w( five_days_after_registration ) attr_reader :user def initialize(user) @user = user end def go! EMAIL_TYPES.each do |notification_type| notification_class = "notifications/notification/#{notification_type}".classify.constantize notification = notification_class.new(user) if notification.perform? notification.send! puts "Notification «#{notification_type}» was sent to #{user.email}" break end end end end end
Notifications::Worker.new(user).go!
namespace :notifications do desc 'Lets send emails' task send: :environment do User.where(receive_email_notifications: true).each do |user| Notifications::Worker.new(user).go! end end end
every :day, at: '10:00am' do rake 'notifications:send', output: 'log/notifications.log' end
Source: https://habr.com/ru/post/251973/
All Articles