Skip to content

Instantly share code, notes, and snippets.

@ccyrille
Last active February 6, 2020 09:17
Show Gist options
  • Select an option

  • Save ccyrille/9539ba0bc9b5f553c8dd15082bb21a69 to your computer and use it in GitHub Desktop.

Select an option

Save ccyrille/9539ba0bc9b5f553c8dd15082bb21a69 to your computer and use it in GitHub Desktop.
# Module used to build a service.
#
# Example usage :
# ```
# class SayHello
# include Service
# attr_accessor :name
#
# def call
# puts "Hello #{name} !"
# end
# end
#
# SayHello.call(name: "toto")
# ```
#
module Service
extend ActiveSupport::Concern
included do
# Proxy to #call instance method
def self.call(*args)
new(*args).call
end
# Service initializer
def initialize(args={})
unless args.is_a?(Hash)
raise ArgumentError, "provided 'args' should be a hash."
end
args.each { |k,v| send("#{k.to_s}=", v) }
end
# Wait for a collection to be commited
# before executing the given block.
# Requires ActiveRecord::InstanceCallbacks
def after_commit_all(collection)
committed = Set.new
lock = Mutex.new
collection.each do |item|
item.after_commit do
lock.synchronize do
committed.add(item)
yield if committed.size >= collection.size
end
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment