Mailboxer Gem--Restrict messaging

2019-08-23 22:35发布

问题:

Mailboxer allows you to connect multiple models as in the example from the gem page. Mailboxer Github page

You can use Mailboxer in any other model and use it in several different models. If you have ducks and cylons in your application and you want to exchange messages as if they were the same, just add acts_as_messageable to each one and you will be able to send duck-duck, duck-cylon, cylon-duck and cylon-cylon messages.

How can we restrict messaging to only between duck-cylon and vice versa? So, only a duck can initiate a conversation and a cylon can reply? And, no duck-duck and cylon-cylon conversations are possible?

回答1:

You could add a module to the models

class Duck < ActiveRecord::Base
  acts_as_messageable
  include mailboxer_filter
end

and

class Cylon < ActiveRecord::Base
  acts_as_messageable
  include mailboxer_filter
end

your module...

module MalboxerFilter
  def initiator?
    self.class == Duck
  end
  def replyer?
    self.class == Cylon
  end

  def send_message_filtered(beta, body, subject)
    self.send_message(beta, body, subject) if initiator? && beta.replyer?
  end

  def reply_to_sender_filtered(*args)
    self.reply_to_sender(*args) if replyer?
  end
end

Then use send_message_filtered and reply_to_sender_filtered in your app. This can be more sophisticated if you need it... perhaps raise an exception if a Cylon attempts to initiate a message or a Duck attempts to reply.