Sha256: dfa810c8e7a056cb724d3e97bdaafccf090f57600af2068bae5a3fe11cbcb123

Contents?: true

Size: 1.16 KB

Versions: 1

Compression:

Stored size: 1.16 KB

Contents

module Observed
  module ObserverHelpers
    module Timer

      require 'timeout'

      def time(options={}, &block)
        timeout_in_seconds = options[:timeout_in_seconds] ||
            fail("The key `:timeout_in_seconds` must be exist in the options: #{options}")

        begin
          before = system.now
          r = Timeout::timeout(timeout_in_seconds) do
            { status: :success, result: block.call }
          end
          after = system.now
          elapsed_time = after - before
          r[:elapsed_time] = elapsed_time
          r
        rescue Timeout::Error => e1
          { status: :error, error: {message: "#{e2.message}\n#{e2.backtrace}"}, timed_out: true }
        rescue => e2
          { status: :error, error: {message: "#{e2.message}\n#{e2.backtrace}"} }
        end
      end

      def time_and_report(options={}, &block)
        tag = options[:tag] || (self.respond_to?(:tag) && self.tag) || fail("The key `:tag` must be exist in the options: #{options}")
        format = options[:format] || ->(r){ r }
        result = time(options, &block)

        system.report("#{tag}.#{result[:status]}", format.call(result))
      end

    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
observed-0.1.1 lib/observed/observer_helpers/timer.rb