Sha256: 552931d98580999697ceeef3ebc66de46e279b94b351c949c2f0c1ab0d32e97b

Contents?: true

Size: 1.55 KB

Versions: 10

Compression:

Stored size: 1.55 KB

Contents

require 'enumerize'

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

  DEFAULT_TOPIC = 'general'

  self.table_name = "jera_push_devices"

  has_many :message_devices, table_name: "jera_push_message_devices"
  has_many :messages, through: :message_devices, table_name: "jera_push_messages"

  belongs_to :pushable, polymorphic: true

  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) }
  scope :with_joins, -> (resource_type) { joins("INNER JOIN #{resource_type.downcase.pluralize} ON  jera_push_devices.pushable_id = #{resource_type.downcase.pluralize}.id AND jera_push_devices.pushable_type  = '#{resource_type}'") }

  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

10 entries across 10 versions & 1 rubygems

Version Path
jera_push-1.2.4 lib/jera_push/models/device.rb
jera_push-1.2.3 lib/jera_push/models/device.rb
jera_push-1.2.1 lib/jera_push/models/device.rb
jera_push-1.1.7 lib/jera_push/models/device.rb
jera_push-1.1.6 lib/jera_push/models/device.rb
jera_push-1.1.5 lib/jera_push/models/device.rb
jera_push-1.1.4 lib/jera_push/models/device.rb
jera_push-1.1.3 lib/jera_push/models/device.rb
jera_push-1.1.2 lib/jera_push/models/device.rb
jera_push-1.1.1 lib/jera_push/models/device.rb