Sha256: 429b520baddb28440b2c8a7a49afcdacf9770f9d8b3276431be6cadf26104040

Contents?: true

Size: 1.7 KB

Versions: 11

Compression:

Stored size: 1.7 KB

Contents

module SimpleNotifications
  class Delivery < ActiveRecord::Base
    self.table_name = 'deliveries'

    # Class Attribute Accessors
    cattr_accessor :after_delivered, :after_read

    # Associations
    belongs_to :simple_notification,
               class_name: 'SimpleNotifications::Record',
               inverse_of: :deliveries
    belongs_to :receiver, polymorphic: true

    # Callbacks
    before_update :before_read, if: proc {!!SimpleNotifications::Base.options[:before_read] && changes['is_read'] == [false, true]}
    before_update :before_delivered, if: proc {!!SimpleNotifications::Base.options[:before_delivered] && changes['is_delivered'] == [false, true]}
    after_update_commit :after_read, if: proc {!!SimpleNotifications::Base.options[:after_read] && previous_changes['is_read'] == [false, true]}
    after_update_commit :after_delivered, if: proc {!!SimpleNotifications::Base.options[:after_delivered] && previous_changes['is_delivered'] == [false, true]}

    # Scopes
    scope :read, -> {where(is_read: true)}
    scope :unread, -> {where.not(is_read: true)}

    def entity
      simple_notification.entity
    end

    private

    %w(read delivered).each do |update_type|
      define_method("before_#{update_type}") do
        call_method(SimpleNotifications::Base.options["before_#{update_type}".to_sym])
      end

      define_method("after_#{update_type}") do
        call_method(SimpleNotifications::Base.options["after_#{update_type}".to_sym])
      end
    end

    def call_method(_method)
      if _method.class == Symbol
        entity.method(_method).call if entity.class.instance_methods(false).include?(_method)
      elsif _method.class == Proc
        _method.call
      end
    end
  end
end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
simple_notifications-1.2.5 lib/simple_notifications/app/models/delivery.rb
simple_notifications-1.2.4 lib/simple_notifications/app/models/delivery.rb
simple_notifications-1.2.3 lib/simple_notifications/app/models/delivery.rb
simple_notifications-1.2.2 lib/simple_notifications/app/models/delivery.rb
simple_notifications-1.2.1 lib/simple_notifications/app/models/delivery.rb
simple_notifications-1.1.9 lib/simple_notifications/app/models/delivery.rb
simple_notifications-1.1.8 lib/simple_notifications/app/models/delivery.rb
simple_notifications-1.1.7 lib/simple_notifications/app/models/delivery.rb
simple_notifications-1.1.6 lib/simple_notifications/app/models/delivery.rb
simple_notifications-1.1.5 lib/simple_notifications/app/models/delivery.rb
simple_notifications-1.1.4 lib/simple_notifications/app/models/delivery.rb