Skip to content
serepo edited this page Sep 6, 2014 · 1 revision

This shows an example of how you can move success/failure responses (e.g. sending email) out of a command in to a separate object (the subscriber). This allows testing of the command without having to mock/stub the sending of email.

class CreateFolders
  include Wisper::Publisher
  attr_reader :entry

  def initialize(entry)
    @entry = entry
  end

  def execute
    # ...
    broadcast(:successful, entry)
  end
end
class AfterCreateFolder
  def successful(entry)
    # ...
  end 
end
command = CreateFolder.new(entry)
command.subscribe(AfterCreateFolder.new)
command.execute

broadcast conditional

Here are some other patterns for the conditionally broadcasting you might want to consider:

broadcast based on exceptions

def execute
  # ...
rescue exception
  broadcast(:failed, exception)
else
  broadcast(:successful)
end

broadcast based on validity

def execute(form)
  if form.valid?
    new_order = Order.create(form.attributes)
    broadcast(:successful, new_order)
  else
    broadcast(:failed, form)
  end
end

form would be something like:

class OrderForm
  include ActiveModel
  include Virtus

  attribute :customer
  attribute :quantity
  attribute :deliver_at

  validates :customer, :presence => true, :strict => true
  validates :quantity, :deliver_at, :presence => true
end