有没有办法redefine/disableself.new?
Is there a way to redefine/disable self.new?
我正在尝试找到一种安全释放 class 获取的资源的方法。我尝试使用 finalize
,但它不可靠。有时我会在 GC 有机会释放资源之前关闭我的程序。
所以我决定在这样的块中使用 class 实例:
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
创建一个实例,我必须明确地 destroy
。我尝试编写自己的 new
,但它似乎在默认情况下只是超载了 new
。
有没有办法redefine\disablenew
?
即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
我正在尝试找到一种安全释放 class 获取的资源的方法。我尝试使用 finalize
,但它不可靠。有时我会在 GC 有机会释放资源之前关闭我的程序。
所以我决定在这样的块中使用 class 实例:
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
创建一个实例,我必须明确地 destroy
。我尝试编写自己的 new
,但它似乎在默认情况下只是超载了 new
。
有没有办法redefine\disablenew
?
即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