1class Apn
 2
 3  @@config ||= YAML.load_file('config/apn.yml')[Rails.env]
 4
 5  def initialize user_id
 6    @user_id = user_id
 7    @tokens = Client.where(user_id: user_id).pluck(:device_token).compact
 8  end
 9
10  def send_reminder!
11    @tokens.each do |token|
12      Reminder.create user_id: @user_id, device_token: token
13      notify device: token, alert: 'How are you doing?', custom_data: { notification_type: 'capture' }
14    end
15  end
16
17  def notify_with attrs
18    @tokens.each do |token|
19      notify attrs.merge(device: token)
20    end
21  end
22
23  def notify attrs
24    raise ArgumentError unless attrs[:device]
25
26    Rails.logger.info "sending #{attrs[:alert]} to #{attrs[:device][0..4]}..."
27
28    reminder = Houston::Notification.new attrs
29    push reminder
30  end
31
32  def push reminder
33    connection.open
34    connection.write reminder.message
35    connection.close
36  end
37
38  def certificate; File.read @@config['certificate']; end
39  def passphrase;  @@config['passphrase']; end
40  def gateway;     @@config['gateway']; end
41  def port;        @@config['port']; end
42
43  def connection
44    @connection ||= Houston::Connection.new("#{gateway}:#{port}", certificate, passphrase)
45  end
46end
47
posted Dec 9 '14 at 22:55

0 Refactors