Permalink
Browse files

modified send_notifications_for_cert routine to decrease db load

Rather than making a query for each device, we can get all unsent
notifications for a given app with one SQL query.

The change also required a slight update of the app_spec.
  • Loading branch information...
1 parent 5327611 commit e6e9b8da64bcbba9062901a18cbbb24ff35677b0 @andreasmueller committed Jan 27, 2011
Showing with 11 additions and 16 deletions.
  1. +8 −9 lib/apn_on_rails/app/models/apn/app.rb
  2. +3 −7 spec/apn_on_rails/app/models/apn/app_spec.rb
@@ -40,18 +40,17 @@ def self.send_notifications
def self.send_notifications_for_cert(the_cert, app_id)
# unless self.unsent_notifications.nil? || self.unsent_notifications.empty?
if (app_id == nil)
- conditions = "app_id is null"
+ conditions = "app_id is null and sent_at is null"
else
- conditions = ["app_id = ?", app_id]
+ conditions = ["app_id = ? and sent_at is null", app_id]
end
begin
APN::Connection.open_for_delivery({:cert => the_cert}) do |conn, sock|
- APN::Device.find_each(:conditions => conditions) do |dev|
- dev.unsent_notifications.each do |noty|
- conn.write(noty.message_for_sending)
- noty.sent_at = Time.now
- noty.save
- end
+ notifications = APN::Notification.find(:all, :conditions => conditions, :joins => " INNER JOIN apn_devices ON apn_devices.id = apn_notifications.device_id")
+ notifications.each do |noty|
+ conn.write(noty.message_for_sending)
+ noty.sent_at = Time.now
+ noty.save
end
end
rescue Exception => e
@@ -148,4 +147,4 @@ def log_connection_exception(ex)
puts ex.message
end
-end
+end
@@ -20,10 +20,7 @@
APN::App.should_receive(:all).once.and_return([app])
app.should_receive(:cert).twice.and_return(app.apn_dev_cert)
- APN::Device.should_receive(:find_each).twice.and_yield(device)
-
- device.should_receive(:unsent_notifications).and_return(notifications,[])
-
+ APN::Notification.should_receive(:find).and_return(notifications, [])
ssl_mock = mock('ssl_mock')
ssl_mock.should_receive(:write).with('message-0')
@@ -52,8 +49,7 @@
notify.should_receive(:save)
end
- APN::Device.should_receive(:find_each).and_yield(device)
- device.should_receive(:unsent_notifications).and_return(notifications)
+ APN::Notification.should_receive(:find).and_return(notifications)
ssl_mock = mock('ssl_mock')
ssl_mock.should_receive(:write).with('message-0')
@@ -227,4 +223,4 @@
end
end
-end
+end

0 comments on commit e6e9b8d

Please sign in to comment.