Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 为类初始化以避免处理已知信息的备选方案_Ruby_Architecture_Initialization_Inheritance - Fatal编程技术网

Ruby 为类初始化以避免处理已知信息的备选方案

Ruby 为类初始化以避免处理已知信息的备选方案,ruby,architecture,initialization,inheritance,Ruby,Architecture,Initialization,Inheritance,我有一个类Autodrop,它包含几个方法,即调用外部API(dropbox)的“元数据”。他们很慢。 但是,在初始化AutodropImage时,我已经经常使用这些元数据,因此我应该使这些方法更智能 我的想法是: class Autodrop include Dropbox attr_reader :path def initialize(path) @path = path end def self.from_entry(drop_entry) @dr

我有一个类Autodrop,它包含几个方法,即调用外部API(dropbox)的“元数据”。他们很慢。 但是,在初始化AutodropImage时,我已经经常使用这些元数据,因此我应该使这些方法更智能

我的想法是:

class Autodrop
  include Dropbox
  attr_reader :path

  def initialize(path)
    @path = path
  end

  def self.from_entry(drop_entry)
    @drop_entry = drop_entry
    self.initialize(@drop_entry.path)
  end

  def metadata
    if @drop_entry = nil
      return heavy_lifting_and_network_traffic
    else
      return @drop_entry.metadata
    end
  end
  #...
end
现在,我想打电话给你

entry = BarEntry.new()
foo = Autodrop.from_entry(entry)
foo.metadata
为了避免繁重的工作和网络流量呼叫

但这是行不通的。不知何故,在我所有的新手中,我确信我在这件事上完全错了。 有没有一个术语我应该先去寻找和阅读?你会怎么做


请注意,示例已简化:例如,在我的代码中,我继承了AutodropImage您需要将元数据缓存在类变量中

编辑:或在类级实例变量中。
也许这一阅读会有所帮助:

您需要将元数据缓存在类变量中

编辑:或在类级实例变量中。
也许这篇文章会有所帮助:

您正在类方法
中创建一个实例变量
@drop\u entry
,该变量来自\u entry
,显然您在该方法中创建的对象将不可用。一种解决方法是在初始化类时将其作为参数传递。如果您进行以下修改,它应该可以工作:

  • 在您的
    from\u条目中
    类方法更改

    self.initialize(@drop_entry) 
    

  • 初始化
    方法修改为:

    def initialize(drop_entry)
      @drop_entry = drop_entry
      @path = @drop_entry.path
    end
    
  • 或者,如果您的类被绑定为只传递
    路径
    参数,即您不想更改其他现有代码,那么您可以使用如下可选的参数删除条目

        def initialize(path, drop_entry=nil)
    

    您正在从\u entry
    在类方法
    中创建一个实例变量
    @drop\u entry
    ,显然,您在此方法中创建的对象将无法使用该实例变量。一种解决方法是在初始化类时将其作为参数传递。如果您进行以下修改,它应该可以工作:

  • 在您的
    from\u条目中
    类方法更改

    self.initialize(@drop_entry) 
    

  • 初始化
    方法修改为:

    def initialize(drop_entry)
      @drop_entry = drop_entry
      @path = @drop_entry.path
    end
    
  • 或者,如果您的类被绑定为只传递
    路径
    参数,即您不想更改其他现有代码,那么您可以使用如下可选的参数删除条目

        def initialize(path, drop_entry=nil)
    

    我就是这么想的。然而,我没有提到这是在西纳特拉使用。我被告知class@@变量在所有用户/线程之间共享。但是我可能在那里得到了错误的信息。但是你没有使用类变量,你使用的是实例变量,这就是我所想的。然而,我没有提到这是在西纳特拉使用。我被告知class@@变量在所有用户/线程之间共享。但是我可能在那里被误导了。但是你没有使用类变量,你使用的是实例变量