有没有办法重新定义/禁用 self.new?

Ano*_*non 2 resources instance crystal-lang

我试图找出一种方法来安全地释放类获得的资源。我尝试使用finalize,但它不可靠。有时我在 GC 有机会释放资源之前关闭我的程序。

所以我决定在这样的块中使用类实例:

class Foo

  def destroy # free resources
      #...
  end

  #...

  def self.create(*args)
      instance = self.new(*args)
      begin
        yield instance
      ensure
        instance.destroy
      end
end

Foo.create do |foo|
  # use foo
end
Run Code Online (Sandbox Code Playgroud)

这工作正常,但我仍然可以使用new我必须destroy明确创建的实例。我试图自己写,new但似乎默认情况下它只是超载了new

有没有办法重新定义\禁用new

WPe*_*0EU 5

那就是initialize方法,应该这样做private

class Foo
  @foo : String

  private def initialize(@foo)
  end

  def destroy
    puts "Destroying #{self}"
  end

  def self.create(arg)
    instance = new(arg)
    yield instance
  ensure
    instance.destroy if instance
  end
end

Foo.create("bar") do |foo| # will work
  p foo
end

Foo.new("bar")             # will raise
Run Code Online (Sandbox Code Playgroud)

操场