Skip to content

Instantly share code, notes, and snippets.

@TrumpClone
Created December 26, 2017 12:19
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 TrumpClone/ab59f9232fb3d7defd50edf07d4a650d to your computer and use it in GitHub Desktop.
Save TrumpClone/ab59f9232fb3d7defd50edf07d4a650d to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
module Distribution::Transmission::Hooks::Hookable
HookError = Class.new(StandardError)
UnexistentHookError = Class.new(HookError)
class << self
def included(base_class)
base_class.extend ClassMethods
end
end
def call_abort_hooks!(source, **params)
results = self.class.send(:abort_hooks).map { |hook| hook.call(source, params) }
results.any? { |result| result == true }
end
def call_before_hooks!(source, **params)
self.class.send(:before_hooks).each { |hook| hook.call(source, params) }
end
def call_after_hooks!(source, result, **params)
self.class.send(:after_hooks).each { |hook| hook.call(source, result, params) }
end
module ClassMethods
def before_hook(hook_name, **options)
hook_instance = create_hook(hook_name, **options)
add_before_hook(hook_instance)
end
def after_hook(hook_name, **options)
hook_instance = create_hook(hook_name, **options)
add_after_hook(hook_instance)
end
def abort_hook(hook_name, **options)
hook_instance = create_hook(hook_name, **options)
add_abort_hook(hook_instance)
end
private
def create_hook(hook_name, **options)
hook_class = resolve_hook_class(hook_name)
hook_class.new(**options)
end
def resolve_hook_class(hook_name)
"Distribution::Transmission::Hooks::#{hook_name.to_s.camelize}".constantize
rescue NameError
raise UnexistentHookError
end
def after_hooks
@after_hooks ||= []
end
def before_hooks
@before_hooks ||= []
end
def abort_hooks
@abort_hooks ||= []
end
def add_after_hook(hook_instance)
after_hooks << hook_instance
end
def add_before_hook(hook_instance)
before_hooks << hook_instance
end
def add_abort_hook(hook_instance)
abort_hooks << hook_instance
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment