Skip to content

Instantly share code, notes, and snippets.

@RichardJordan
Created February 15, 2019 02:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RichardJordan/48546c318b62e13cbe6c85cdf76c26f3 to your computer and use it in GitHub Desktop.
Save RichardJordan/48546c318b62e13cbe6c85cdf76c26f3 to your computer and use it in GitHub Desktop.
Command Pattern - notifications and observers
module RJ
module Utils
module Commands
module Notifications
extend ActiveSupport::Concern
module ClassMethods
def observer(*observer_methods, of_event: :success)
observer_methods.each do |observer|
observers[of_event] ||= Set.new
observers[of_event] << observer
end
end
def observers
@observers ||= {}
end
end
def notify_observers(of_event: :success)
observers_array.each { |observer| safe_call observer }
rescue StandardError => e
Rails.logger.warn "#{self.class} observers failed with #{e.message}"
Rails.logger.debug e.backtrace.join("\n")
end
def observers
@observers ||=
self.class.observers.each_with_object({}) do |(event, observer_methods), observers|
observer_methods.each do |meth|
observers[event] ||= Set.new
observers[event] << send(meth)
end
end
end
private
def observers_array(of_event: :success)
Array(observers[of_event]).compact
end
def safe_call(observer)
if observer.respond_to?(:call)
observer.call
else
send observer
end
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment