Resources 有没有办法重新定义/禁用self.new?
我试图找出一种安全释放类获取的资源的方法。我试过使用Resources 有没有办法重新定义/禁用self.new?,resources,instance,crystal-lang,Resources,Instance,Crystal Lang,我试图找出一种安全释放类获取的资源的方法。我试过使用finalize,但不可靠。有时我在GC有机会释放资源之前就关闭了我的程序 所以我决定在块中使用类实例,如下所示: class Foo def destroy # free resources #... end #... def self.create(*args) instance = self.new(*args) begin yield instance
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
这很好,但我仍然可以使用new
创建一个实例,我必须显式地销毁它。我试着写我自己的new
,但它似乎只是默认情况下过载了new
是否有一种方法可以重新定义\禁用新建
?即初始化
方法,该方法应设置为私有
:
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
这不是ruby
,我不能将.new
设为私有。我猜默认情况下它是超负荷的。new
@Anon抱歉。我以为我是在[Ruby]标签上过滤的。我已经删除了这些评论。@WPeN2Ic850EU请将其作为完整答案写在下面