I have in challenge_reminder.rake
task challenge_reminder: :environment do
Challenge.unaccomplished.all.each do |challenge|
if challenge.remind.include? Date::ABBR_DAYNAMES[Date.current.wday].downcase
if challenge.mail == true # This Works
UserMailer.challenge_reminder(challenge).deliver_now
end
if challenge.push == true
# How to send webpush notification for challenge
end
end
end
end
The user can receive a push notification if he manually clicks the button...
<%= content_tag(:button, "Foo", class: "webpush-button") %>
<script>
$('.webpush-button').on('click', (e) => {
navigator.serviceWorker.ready
.then((serviceWorkerRegistration) => {
serviceWorkerRegistration.pushManager.getSubscription()
.then((subscription) => {
console.log('Almost there, Daddy!');
$.post('/push', {
subscription: subscription.toJSON(),
message: 'You clicked a button!'
});
});
});
});
</script>
leading to...
class PushNotificationsController < ApplicationController
def push
Webpush.payload_send(
message: params[:message],
endpoint: params[:subscription][:endpoint],
p256dh: params[:subscription][:keys][:p256dh],
auth: params[:subscription][:keys][:auth],
vapid: {
subject: "mailto:sender@example.com",
public_key: ENV['VAPID_PUBLIC_KEY'],
private_key: ENV['VAPID_PRIVATE_KEY']
}
)
end
end
How can I adjust the script code for the rake task?
I implemented push via serviceworker gem , webpush gem , and VAPID credentials.
You should move whole logic from PushNotificationsController#push to some domain logic or maybe service - PushNotificationsService
which could be used from diff places:
class PushNotificationsService
def self.call(params)
Webpush.payload_send(
message: params[:message],
endpoint: params[:subscription][:endpoint],
p256dh: params[:subscription][:keys][:p256dh],
auth: params[:subscription][:keys][:auth],
vapid: {
subject: "mailto:sender@example.com",
public_key: ENV['VAPID_PUBLIC_KEY'],
private_key: ENV['VAPID_PRIVATE_KEY']
}
)
end
end
Then you can call this service from diff places in your app, ie. PushNotificationsService.call(params)
Hope this helps !
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.