2012-02-15 76 views
1

我有一个类,它的new方法已经被私有化了,因为我只希望我的类方法“constructors”创建新的实例。不过,我现在也需要让一些实例方法也创建新的实例。当Class.new是私有的时候实例方法的新实例

例如,请看下面的代码片段。这是method_a在那里我遇到了问题:

Class Foo 

    class << self 

    #a "constructor" method 
    def from_x arg 
     stuff_from_arg = arg.something #something meaningful from arg 
     new(stuff_from_arg) 
    end 
    end 

    def initialize stuff 
    @stuff = stuff 
    end 

    private_class_method :new #forces use of Foo.from_x 

    def method_a 
    other_stuff = "blah" 
    #These do not work 
    return new(blah) #nope, instance cannot see class method 
    return self.class.new(blah) #nope, new is private_class_method 
    return Foo.new(blah) #same as previous line 
    return initialize(blah) #See *, but still doesn't work as expected 
    end 
end 

我刚开始想的是,我可以以这样的方式,我需要再拍类的构造方法创建一个新的设计了这个类Foo,像这样:

#in addition to previous code 
Class Foo 
    class << self 
    def just_like_new stuff 
     new(stuff) 
    end 
    end 
end 

这并不感到很正确的或非常干燥,但也许这是我为自己铺床。有什么我可以做的吗?

*此行有点令人惊讶。它返回blah。在类定义之外,还有一个initialize,它需要0个参数并返回nil有人知道这里发生了什么吗?

回答

1

您可以随时使用send绕过访问控制:

def from_x arg 
    stuff_from_arg = arg.something #something meaningful from arg 
    self.class.send(:new, stuff_from_arg) 
end