簡體   English   中英

使用克隆方法使用超級類而非寶石來制作紅寶石對象的深層副本

[英]Making deep copy's of ruby objects using clone method using super class not a gem

我有紅寶石類,我正在嘗試實現克隆方法。 我希望能夠使用所有類都可以繼承的通用克隆方法。 類的屬性可以是數組類型,哈希或其他一些對象。

我可以使它更通用,以便深度克隆嗎? 可能在超類QueryModel中定義一個克隆方法? 那將如何工作?

class Bool < QueryModel

  attr_accessor :name, :should, :must, :must_not

  def clone
    Bool.new(self.name, self.should.clone, self.must.clone, self.must_not.clone) 
  end


  def serialize
      result_hash = {}
      query_hash = {}

      if( instance_variable_defined?(:@should) )
      query_hash[:should] = @should.serialize
      end

      if( instance_variable_defined?(:@must) )
        query_hash[:must] = @must.serialize
      end

      if( instance_variable_defined?(:@must_not) )
        query_hash[:must_not] = @must_not.serialize
      end

      if( instance_variable_defined?(:@should) || instance_variable_defined?(:@must) || instance_variable_defined?(:@must_not) )
        return result_hash = query_hash
    end
  end
end

這是可能使用克隆的地方:

class Query < QueryModel

  attr_accessor :query_string, :query, :bool

  def serialize 
    result_hash = {}
    query_hash = {}

    if( instance_variable_defined?(:@query_string) )
      query_hash[:query_string] = @query_string.serialize
      #result_hash[:query] = query_hash
    end

    if( instance_variable_defined?(:@query) )
      query_hash[:query] = @query
    end

    if( !instance_variable_defined?(@bool) )
      if( instance_variable_defined?(:@query) || instance_variable_defined?(:@query_string) )
        result_hash[:query] = query_hash
        return result_hash
      end
    else
      bool =  @bool.clone
      result_hash[:query] = bool
    end

  end

end

如果您不害怕新的寶石,那么變形蟲寶石擁有克隆AR對象所需的一切。 如果您真的只想復制對象屬性而不是關系,那么dup方法就是您想要的。

更新:對不起,昨天很晚,我以為您以某種方式使用了ActiveRecord。 對於純紅寶石解決方案,只需使用不帶覆蓋的Object#clone方法,並指定指定Object#clone的行為,如下所示:

class Bool
  def initialize_copy(original)
    super # this already clones instance vars that are not objects

    # your custom strategy for 
    # referenced objects can be here

  end
end

這是文檔對此的評價。

如果您使用創新/原型設計模式解決問題,則可以像下面的示例一樣進行操作-

class ConcretePrototype
  def copy
  prototype = clone

    instance_variables.each do |ivar_name|
      prototype.instance_variable_set( ivar_name,
      instance_variable_get(ivar_name).clone)
    end

    prototype
  end
end

class Application
  def run
    concreate_prototype = ConcretePrototype.new
    concreate_prototype_2 = concreate_prototype.copy
    puts concreate_prototype.inspect
    puts concreate_prototype_2.inspect
  end
end

這樣,您可以在沒有任何寶石的情況下深克隆對象。 參考-https://github.com/vatrai/design_patterns/blob/master/creational/prototype.rb

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM