【问题标题】:New instances from instance methods when Class.new is private当 Class.new 为私有时,来自实例方法的新实例
【发布时间】:2012-02-15 06:17:24
【问题描述】:

我有一个类,其new 方法已设为私有,因为我只希望我的类方法“构造函数”创建新实例。但是,我现在还需要一些实例方法来创建新实例。

例如看下面的sn-p。我在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 有人知道这里发生了什么吗?

【问题讨论】:

    标签: ruby


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2012-12-17
      • 1970-01-01
      • 2017-06-11
      • 1970-01-01
      • 2011-01-28
      • 1970-01-01
      • 2015-04-25
      • 1970-01-01
      • 2010-09-30
      相关资源
      最近更新 更多