Issue #13838 has been updated by mame (Yusuke Endoh).

Status changed from Open to Closed

I think this is a duplicate of #13667.  Let us discuss this issue in that ticket.  Thank you!

----------------------------------------
Feature #13838: Add the ability to detect Coverage status
https://bugs.ruby-lang.org/issues/13838#change-66273

* Author: yui-knk (Kaneko Yuichiro)
* Status: Closed
* Priority: Normal
* Assignee: 
* Target version: 
----------------------------------------
## Description

I want to detect current status of Coverage, which is enabled or not.
Now we can detect status only trying `Coverage.peek_result` or `Coverage.result` and catch RuntimeError.
Attached patch enable us to detect status without any exceptions.

## Why

My daily work is developing a web application with Ruby.

I am using `Coverage.peek_result` to record coverage information on a per-request basis.

When recording coverage information, I want to start Coverage on a part of production servers,
because Coverage tool may have some overhead.

In this case, the code of my program looks like

```ruby
# Implement as Rack middleware
class CoverageMiddleware
  def initialize(app)
    @app = app
  end 

  def call(env)
    # To ensure return response, rescue exceptions
    before = Coverage.peek_result rescue nil
    res = @app.call(env)
    after = Coverage.peek_result rescue nil

    if (before && after)
      write_file(diff(before, after))
    end

    return res
  end
end
```

## Example

By using `Coverage.enabled?, I can

```ruby
class CoverageMiddleware
  def initialize(app)
    @app = app
  end 

  def call(env)
    if Coverage.enabled?
      before = Coverage.peek_result
      res = @app.call(env)
      after = Coverage.peek_result

      write_file(diff(before, after))
    else
      res = @app.call(env)
    end

    return res
  end
end
```



---Files--------------------------------
Coverage.patch (1.47 KB)


-- 
https://bugs.ruby-lang.org/

Unsubscribe: <mailto:ruby-core-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>