Ruby on rails 制作深度拷贝';使用克隆方法的ruby对象,使用超类而不是gem
我有一些ruby类,我试图在其中实现clone方法。我希望能够使用所有类都可以继承的通用克隆方法。类的属性可以是数组类型、哈希或其他对象 我能把它做得更通用一些吗?是否可能在超类QueryModel中定义克隆方法?那怎么办Ruby on rails 制作深度拷贝';使用克隆方法的ruby对象,使用超类而不是gem,ruby-on-rails,ruby,ruby-on-rails-4,ruby-on-rails-3.2,Ruby On Rails,Ruby,Ruby On Rails 4,Ruby On Rails 3.2,我有一些ruby类,我试图在其中实现clone方法。我希望能够使用所有类都可以继承的通用克隆方法。类的属性可以是数组类型、哈希或其他对象 我能把它做得更通用一些吗?是否可能在超类QueryModel中定义克隆方法?那怎么办 class Bool < QueryModel attr_accessor :name, :should, :must, :must_not def clone Bool.new(self.name, self.should.clone, self.
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 Bool
以下是可能使用克隆的地方:
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
类查询
如果你不怕新的gem,那么gem拥有克隆AR对象所需的一切。如果您真的只想复制对象属性而不想复制关系,那么该方法就是您要寻找的
更新:很抱歉昨天晚了,我还以为你在用ActiveRecord呢。对于纯ruby解决方案,只需使用不带覆盖的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
通过这种方式,您可以在没有任何宝石的情况下深度克隆对象。
参考-对象#dup如何?可能的重复如何是重复的?你能解释一下如何使用一个超级类来做这件事吗?我不想使用其他gem来做这件事。需要学习如何在纯ruby中以正确的方式实现这一点。dup会有什么帮助?你能举个例子吗?非常感谢。