Skip to content

Wisper with Rails Engines

Kyle Decot edited this page Apr 16, 2017 · 2 revisions

It's convenient to use Global Listeners like described in the README. Just define them in some initializer e.g. engine_name/config/initializers/wisper.rb. Inside this file you can subscribe all required observers e.g.

# add observers
Wisper.subscribe(SomeNamespace::OrderHistoryObserver.new)
# and more

Observers may be placed anywhere but i choose observers/ directory in order to keep models/ as clean as possible. Observer doesn't have to be ActiveRecord subclass e.g. core/app/observers/somenamespace/order_history_observer.rb

class SomeNamespace::OrderHistoryObserver
  # subscribe to order after_save notification
  def order_after_save order
    # EXAMPLE content
    add_history(order)
  end

  def add_history order
    # EXAMPLE content
    # skip if status doesn't change but history is present
    return if order.order_history.present? && order.order_history.last.status == order.status

    order.order_history << SomeNamespace::OrderHistory.new(status: order.status, order: order, name: order.status.name)
  end

end

Publisher class may look like this (in my case it is file core/app/models/somenamespace/order.rb):

class SomeNamespace::Order < ActiveRecord::Base
  include Wisper::Publisher

  after_save :after_save

  def after_save
    publish(:order_after_save, self)
  end

My (example) file structure:

  • engine_name/config/initializers/wisper.rb
  • core/app/observers/somenamespace/order_history_observer.rb
  • core/app/models/somenamespace/order.rb