Reputation: 1948
I am working on a mailer for a job board which entails sending an email notification to subscribers based on jobs posted within every 12 hours.
send_post_email.html.erb(Mailer Template)
<!DOCTYPE html>
<html>
<head>
<meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
</head>
<body>
<div>
<h3> Hi, new job just posted on FarFlungJobs.com! </h3>
</div>
<section>
<p>Fresh Job</p>
<hr>
<p>
<%= Job.select do |job| %>
<section class="container">
<div class="row jobs">
<div class="col-md-4" style="font-size: 20px;"><strong><%= job.company_name %></strong></div>
<div class="col-md-4" style="font-size: 20px;"><%= link_to(job.title, job) %></div>
<div class="col-md-4 text-right" style="font-size: 20px; float: left;"><%= job.created_at.strftime('%d %B %y') %></div>
</div>
<%= render 'shared/two_breaks'%>
</section>
<% end %>
</p>
<p>Thanks for subscribing to FarFlungJobs once again. <%= jobs_url %> </p>
</section>
</body>
</html>
job_notifier.rb
class JobNotifier < ApplicationMailer
def send_post_email(job)
@user = User.where(:email => true).all
emails = @user.collect(&:email).join("#{','}")
@jobs = job
@job = job
mail(:to => emails, :bcc => User.pluck(:email).uniq, :subject => 'New job posted on FarFlungJobs')
end
end
jobs_controller.rb
class JobsController < ApplicationController
def update
@job = Job.find(params[:id])
if !(@job.paid?)
@job.update_attributes(stripeEmail: params[:stripeEmail], payola_sale_guid: params[:payola_sale_guid])
if @job.paid?
JobNotifier.send_post_email(@job).deliver_now
end
@job.update(job_params) if params.has_key?(:job)
redirect_to preview_job_path(@job) #show_job_path
else
render :edit
end
end
end
job.rb(model)
class Job < ActiveRecord::Base
def self.jobs_posted_12hrs_ago
where.not('stripeEmail' => nil).where.not('payola_sale_guid' => nil).where('created_at > ?', 18.hours.ago)
end
end
Note: This sends emails, but it sends all the posted jobs in the database, which I dont want.
What I like to do is send just the newly posted jobs within the last 12 hours to emails subscribers.
Upvotes: 1
Views: 46
Reputation: 105
As I see it, you should have a job (ActiveJob) that uses the scope you defined in the "Job" model, and set it to repeat daily, you have to use a job server like sidekiq or any other, info here.
The job should look something like this.
class NewJobsMailer < ApplicationJob
queue_as :default
def perform(*guests)
jobs = Job.jobs_posted_12hrs_ago
jobs.each do
JobNotifier.send_post_email(@job).deliver_now
end
end
end
Its not perfect, but i hope you can use it as guidelines.
Upvotes: 2