module PoBox module Emailable extend ActiveSupport::Concern included do has_many :inboxes, as: :emailable, class_name: "PoBox::Inbox", dependent: :destroy after_create_commit :set_inbox accepts_nested_attributes_for :inboxes, allow_destroy: true private def set_inbox return if inboxes.any? inbox_address = if email.present? "#{email.split("@").first}##{SecureRandom.hex(2)}" else SecureRandom.hex(8) end inbox = inboxes.new loop do inbox.address = inbox_address break unless PoBox.emailable_class.joins(:inboxes).where(po_box_inboxes: {address: inbox.address}).exists? end save end end end end