diff --git a/README.md b/README.md index 55f572f..dd8b032 100644 --- a/README.md +++ b/README.md @@ -103,29 +103,26 @@ class AuthenticationHook # Registers the hook at a namespace with a key register_hook :some_namespace, :authentication - # Service is passed to an attach method - def self.attach(service) - # Typical Twirp service hooks - svc.before do |rack_env, env| - env[:user_id] = authenticate(rack_env) - env[:enviornment] = (ENV['ENVIRONMENT'] || :local).to_sym - end + # Typical Twirp service hook methods + def before(rack_env, env) + env[:user_id] = authenticate(rack_env) + env[:enviornment] = (ENV['ENVIRONMENT'] || :local).to_sym + end - svc.on_success do |env| - Stats.inc("requests.success") - end + def on_success(env) + Stats.inc("requests.success") + end - svc.on_error do |twerr, env| - Stats.inc("requests.error.#{twerr.code}") - end + def on_error(twerr, env) + Stats.inc("requests.error.#{twerr.code}") + end - svc.exception_raised do |e, env| - if env[:environment] == :local - puts "[Exception] #{e}" - puts e.backtrace.join("\n") - else - ExceptionTracker.send(e) - end + def exception_raised(e, env) + if env[:environment] == :local + puts "[Exception] #{e}" + puts e.backtrace.join("\n") + else + ExceptionTracker.send(e) end end end diff --git a/lib/twirp/rails/helpers/hooks.rb b/lib/twirp/rails/helpers/hooks.rb index 19757c7..05ac378 100644 --- a/lib/twirp/rails/helpers/hooks.rb +++ b/lib/twirp/rails/helpers/hooks.rb @@ -4,6 +4,8 @@ module Twirp module Rails module Helpers module Hooks + HOOK_METHODS = [:before, :on_success, :on_error, :exception_raised] + def self.included(klass) klass.extend ClassMethods end @@ -26,6 +28,40 @@ def register_hook(namespace, key) Twirp::Rails.hooks[namespace][key] = self end + + def attach(service) + hook_instance = self.new + + unless HOOK_METHODS.any? {|method| hook_instance.respond_to?(method)} + raise NotImplementedError.new( + "#{self.name} must implement one of the following methods: #{HOOK_METHODS.join(", ")}" + ) + end + + if hook_instance.respond_to?(:before) + service.before do |rack_env, env| + hook_instance.before(rack_env, env) + end + end + + if hook_instance.respond_to?(:on_success) + service.on_success do |env| + hook_instance.on_success(env) + end + end + + if hook_instance.respond_to?(:on_error) + service.on_error do |twerr, env| + hook_instance.on_error(twerr, env) + end + end + + if hook_instance.respond_to?(:exception_raised) + service.exception_raised do |e, env| + hook_instance.exception_raised(e, env) + end + end + end end end end diff --git a/lib/twirp/rails/version.rb b/lib/twirp/rails/version.rb index 0d6fad5..6e6cb57 100644 --- a/lib/twirp/rails/version.rb +++ b/lib/twirp/rails/version.rb @@ -1,5 +1,5 @@ module Twirp module Rails - VERSION = "0.2.0" + VERSION = "0.3.0" end end