Skip to content

Instantly share code, notes, and snippets.

@timbaas
Created September 3, 2015 09:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timbaas/1b2b3077bf5cd76a6823 to your computer and use it in GitHub Desktop.
Save timbaas/1b2b3077bf5cd76a6823 to your computer and use it in GitHub Desktop.
class Notification < ActiveRecord::Base
belongs_to :user
scope :nostatus, ->{ where( status: nil ) }
scope :queued, ->{ where( status: 'queued' ) }
scope :pushed, ->{ where( status: 'pushed' ) }
scope :seen, ->{ where( status: 'seen' ) }
scope :unseen, ->{ where( "`notifications`.`status` != ?", "seen" ) }
before_save :queue_push_notification
def queue_push_notification
if user_can_receive_push_notification
self.status = 'queued'
end
end
def push_notification
apn_opts = { alert: notification_content, badge: badge_count, sound: 'true', id: id }
apn = RubyPushNotifications::APNS::APNSNotification.new( [user.device_token], { aps: apn_opts } )
apn
end
def badge_count
user.notifications.unseen.count + user.received_messages.unread.count
end
# iOS Push Notification Service
def self.push_new_notifications
push Notification.queued.all.collect { |n| n.push_notification }
end
def self.push notifications
pusher.push notifications
notifications.each do |notification|
puts "Results for notification #{notification}"
puts notification.results.success
puts notification.results.failed
puts notification.inspect
puts notification.individual_results
end
end
def self.pusher
RubyPushNotifications::APNS::APNSPusher.new File.read(certificate), Rails.env.development?
end
def self.certificate
if Rails.env.development?
"/xxx/apns-pro.pem"
else
"/xxx/apn_production.pem"
end
end
private
def user_can_receive_push_notification
user.device_token.present?
end
def notification_content
return "Notification Content"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment