3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rubyでオープンクラスに警告を出す

Posted at

ピピー!✋👮 こちらオープンクラス警察です。

open_class_alarm.rb
module OpenClassAlarm
  @status = :disable
  @modules = ObjectSpace.each_object(Module).to_a

  def self.enable
    @status = :enable

    if block_given?
      yield
      disable
    end
  end

  def self.disable
    @status = :disable
  end

  TracePoint.trace(:class) do |tp|
    if @modules.include?(tp.self)
      if @status == :enable && tp.self.instance_of?(Class)
        warn "#{tp.path}:#{tp.lineno} found open class `#{tp.self}'"
      end
    else
      @modules << tp.self
    end
  end
end

OpenClassAlarm.enable

class String
end

出力

open_class_alarm.rb:31 found open class `String'

検知する範囲をブロックで囲むことも出来ます。

OpenClassAlarm.enable do
  class String
  end
end

class Hash
end

出力

open_class_alarm.rb:30 found open class `String'

https://github.com/jeremyevans/ruby-refrigerator を見て

:thought_balloon: 「TracePointを使って似たようなことが出来そうだな」

と思い作ってみました。

ついでにgemも作りました。

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?