lib/and-son/call_runner.rb in and-son-0.7.0 vs lib/and-son/call_runner.rb in and-son-0.8.0

- old
+ new

@@ -9,32 +9,39 @@ class CallRunner DEFAULT_TIMEOUT = 60 # seconds attr_reader :host, :port + attr_reader :before_call_procs, :after_call_procs attr_accessor :timeout_value, :params_value, :logger_value def initialize(host, port) @host = host @port = port - @params_value = {} + @params_value = {} @timeout_value = (ENV['ANDSON_TIMEOUT'] || DEFAULT_TIMEOUT).to_f - @logger_value = NullLogger.new + @logger_value = NullLogger.new + @before_call_procs = [] + @after_call_procs = [] end # chain runner methods by returning itself def call_runner; self; end def call(name, params = nil) params ||= {} if !params.kind_of?(Hash) raise ArgumentError, "expected params to be a Hash instead of a #{params.class}" end + call_params = self.params_value.merge(params) + + self.before_call_procs.each{ |p| p.call(name, call_params, self) } client_response = nil benchmark = Benchmark.measure do - client_response = self.call!(name, params) + client_response = call!(name, call_params) end + self.after_call_procs.each{ |p| p.call(name, call_params, self) } summary_line = SummaryLine.new({ 'time' => RoundedTime.new(benchmark.real), 'status' => client_response.protocol_response.code, 'host' => "#{self.host}:#{self.port}", @@ -48,23 +55,10 @@ else client_response.data end end - def call!(name, params) - call_params = self.params_value.merge(params) - AndSon::Connection.new(host, port).open do |connection| - connection.write(Sanford::Protocol::Request.new(name, call_params).to_hash) - connection.close_write - if !connection.peek(timeout_value).empty? - AndSon::Response.parse(connection.read(timeout_value)) - else - raise AndSon::ConnectionClosedError.new - end - end - end - def hash [ self.host, self.port, self.timeout_value, self.params_value, @@ -75,10 +69,24 @@ def ==(other) other.kind_of?(self.class) ? self.hash == other.hash : super end alias :eql? :== + private + + def call!(name, params) + AndSon::Connection.new(host, port).open do |connection| + connection.write(Sanford::Protocol::Request.new(name, params).to_hash) + connection.close_write + if !connection.peek(timeout_value).empty? + AndSon::Response.parse(connection.read(timeout_value)) + else + raise AndSon::ConnectionClosedError.new + end + end + end + module InstanceMethods # define methods here to allow configuring call runner params. be sure to # use `tap` to return whatever instance `self.call_runner` returns so you # can method-chain. `self.call_runner` returns a new runner instance if @@ -95,9 +103,17 @@ self.call_runner.tap{ |r| r.params_value.merge!(stringify_keys(hash)) } end def logger(passed_logger) self.call_runner.tap{ |r| r.logger_value = passed_logger } + end + + def before_call(&block) + self.call_runner.tap{ |r| r.before_call_procs << block } + end + + def after_call(&block) + self.call_runner.tap{ |r| r.after_call_procs << block } end private def stringify_keys(hash)