jeudi 8 octobre 2015

Sinatra web request logging LocalJumpError

I create some code in Ruby to log the sinatra web requests. I implemented a module

module RequestLogger

  def enhance_with_logging(requested_path, requested_method, &original_block)
    return lambda do
      start_time = Time.now
      begin
        return_exp = self.instance_eval &original_block
      rescue
        raise
      ensure
        finish_time = Time.now
        diff = finish_time-start_time
        log_debug("#{requested_method}->#{requested_path}"\
                  " - #{request.ip} - session_id:#{session.id} - #{diff}")
        return_exp
      end
    end
  end

  def getl(path, ops = {}, &block)
    log_debug("Included logged route GET: #{path}")
    new_block = enhance_with_logging(path, 'GET', &block)
    get(path, ops, &new_block)
  end

  def postl(path, ops = {}, &block)
    log_debug("Included logged route POST: #{path}")
    new_block = enhance_with_logging(path, 'POST', &block)
    post(path, ops, &new_block)
  end
end

In the application routes that I want to log, I just need to change get() and put instead getl().

And it works fine unless the original route use a return. In those cases I get a LocalJumpError. I know is because a block is not supposed to have a return.

Any idea of how to make my code work?




Aucun commentaire:

Enregistrer un commentaire