Sha256: c7c1251e0a1ff4d66e6af0f30afd3aa315dd84970ef5c63116250548b4f842f0

Contents?: true

Size: 1.33 KB

Versions: 4

Compression:

Stored size: 1.33 KB

Contents

require 'enumerize'

class JeraPush::Device < ActiveRecord::Base
  extend Enumerize

  DEFAULT_TOPIC = 'general'

  self.table_name = "jera_push_devices"

  has_many :messages, through: :message_devices, table_name: "jera_push_messages"
  has_many :message_devices, table_name: "jera_push_message_devices"
  belongs_to :resource, class_name: JeraPush.resource_name

  validates :token, :platform, presence: true
  validates :token, uniqueness: { scope: :platform }

  after_create :register_to_current_topic
  before_destroy :unregister_from_current_topic

  enumerize :platform, in: [:android, :ios, :chrome], predicate: true

  scope :ios,  -> { where(platform: :ios) }
  scope :android, -> { where(platform: :android) }
  scope :chrome, -> { where(platform: :chrome) }

  def send_message(message)
    JeraPush::Message.send_to self, content: message
  end

  def subscribe(topic)
    client = JeraPush::Firebase::Client.instance
    client.add_device_to_topic(topic: topic, device: self)
  end

  def unsubscribe(topic)
    client = JeraPush::Firebase::Client.instance
    client.remove_device_from_topic(topic: topic, devices: [self])
  end

  private

    def register_to_current_topic
      subscribe(JeraPush.send("topic_#{self.platform}"))
    end

    def unregister_from_current_topic
      unsubscribe(JeraPush.send("topic_#{self.platform}"))
    end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
jera_push-1.0.3 lib/jera_push/models/device.rb
jera_push-1.0.2 lib/jera_push/models/device.rb
jera_push-1.0.1.1 lib/jera_push/models/device.rb
jera_push-1.0.1 lib/jera_push/models/device.rb