Last active
June 24, 2016 10:06
AmazonSnsInfo Model Setup
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# In db/migrate/XXXXXXX_create_amazon_sns_infos.rb | |
class CreateAmazonSnsInfos < ActiveRecord::Migration | |
def change | |
create_table :amazon_sns_infos do |t| | |
t.references :user, :foreign_key => true, :index => true, :null => false | |
t.string :platform | |
t.string :device_token | |
t.string :endpoint_arn | |
t.string :platform_application_arn | |
t.string :env | |
t.timestamps null: false | |
end | |
end | |
end | |
###################################################### | |
# In app/models/user.rb | |
class User < ActiveRecord::Base | |
... | |
has_many :amazon_sns_infos | |
... | |
end | |
###################################################### | |
# In app/models/amazon_sns_info.rb | |
class AmazonSnsInfo < ActiveRecord::Base | |
belongs_to :user | |
store :subscribed_topics, :accessors => [:subscription_arns], :coder => JSON | |
validates_presence_of :user | |
before_destroy :delete_amazon_sns_platform_endpoint | |
def update_topic_subscription | |
if self.endpoint_arn.present? | |
subscription_arns = AmazonSnsWrapper.subscribe_amazon_sns_topic(self) | |
if subscription_arns.present? | |
self.subscribed_topics[:subscription_arns] = subscription_arns | |
else | |
# device need to confirm the subscription with callback token | |
# currently amazon return the `subscription_arn` then no need to confirm the subscription | |
self.subscribed_topics = nil | |
end | |
else | |
update_endpoint_registration | |
end | |
self.save! | |
end | |
def unsubscribe_topic_subscriptions | |
unsubscribed_topic_arns = AmazonSnsWrapper.unsubscribe_amazon_sns_topic(self) | |
self.subscribed_topics[:subscription_arns] -= unsubscribed_topic_arns if self.subscribed_topics[:subscription_arns].present? | |
self.save! | |
end | |
private | |
def delete_amazon_sns_platform_endpoint | |
if AmazonSnsWrapper.check_amazon_sns_platform_endpoint(self) | |
AmazonSnsWrapper.unsubscribe_amazon_sns_topic(self) | |
AmazonSnsWrapper.delete_amazon_sns_platform_endpoint(self) | |
end | |
end | |
def update_endpoint_registration | |
unless AmazonSnsWrapper.check_amazon_sns_platform_endpoint(self) | |
endpoint_arn = AmazonSnsWrapper.create_amazon_sns_platform_endpoint(self) | |
self.endpoint_arn = endpoint_arn | |
self.platform_application_arn = AmazonSnsWrapper::AWS_SNS_CONFIG[self.platform.to_sym] | |
self.env = Rails.env | |
self.save | |
end | |
self.update_topic_subscription | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment