module PoBox module Emailable extend ActiveSupport::Concern included do has_many :inboxes, as: :emailable, class_name: "PoBox::Inbox", dependent: :destroy after_create_commit :generate_inbox accepts_nested_attributes_for :inboxes, allow_destroy: true private def generate_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::Inbox.find_by(address: inbox.address).present? end save end end end end