Sha256: 16c347ff31b2fdc4c560814dacd77b9afd49c3c009b9bae6a5a9c5e59440460a

Contents?: true

Size: 1.64 KB

Versions: 15

Compression:

Stored size: 1.64 KB

Contents

# frozen_string_literal: true

module Decidim
  module Messaging
    #
    # Holds a single message in a conversation. A message has a body, and sender
    # and a set of receipts, which correspond to each user that will receive the
    # message, namely, the interlocutors of the sender in the conversation.
    #
    class Message < ApplicationRecord
      include Decidim::FriendlyDates

      belongs_to :sender,
                 foreign_key: :decidim_sender_id,
                 class_name: "Decidim::User"

      belongs_to :conversation,
                 foreign_key: :decidim_conversation_id,
                 touch: true,
                 class_name: "Decidim::Messaging::Conversation"

      has_many :receipts,
               dependent: :destroy,
               foreign_key: :decidim_message_id,
               inverse_of: :message

      validates :sender, :body, presence: true
      validates :body, length: { maximum: 1_000 }

      default_scope { order(created_at: :asc) }

      validate :sender_is_participant

      #
      # Associates receipts for this message for each of the given users,
      # including also a receipt for the remitent (sender) of the message.
      # Receipts are unread by default, except for the sender's receipt.
      #
      # @param recipients [Array<Decidim::User>]
      #
      def envelope_for(recipients)
        receipts.build(recipient: sender, read_at: Time.current)

        recipients.each { |recipient| receipts.build(recipient: recipient) }
      end

      private

      def sender_is_participant
        errors.add(:sender, :invalid) unless conversation.participants.include?(sender)
      end
    end
  end
end

Version data entries

15 entries across 15 versions & 1 rubygems

Version Path
decidim-core-0.21.0 app/models/decidim/messaging/message.rb
decidim-core-0.20.1 app/models/decidim/messaging/message.rb
decidim-core-0.20.0 app/models/decidim/messaging/message.rb
decidim-core-0.19.1 app/models/decidim/messaging/message.rb
decidim-core-0.18.1 app/models/decidim/messaging/message.rb
decidim-core-0.19.0 app/models/decidim/messaging/message.rb
decidim-core-0.17.2 app/models/decidim/messaging/message.rb
decidim-core-0.18.0 app/models/decidim/messaging/message.rb
decidim-core-0.17.1 app/models/decidim/messaging/message.rb
decidim-core-0.16.1 app/models/decidim/messaging/message.rb
decidim-core-0.17.0 app/models/decidim/messaging/message.rb
decidim-core-0.16.0 app/models/decidim/messaging/message.rb
decidim-core-0.15.2 app/models/decidim/messaging/message.rb
decidim-core-0.15.1 app/models/decidim/messaging/message.rb
decidim-core-0.15.0 app/models/decidim/messaging/message.rb