I have ruby classes in which I'm trying to implement clone method. I want to be able to use a generalized clone method that all the classes can inherit from. The attributes of a class could be an array type, a hash or some other object.
can I make this more generic so that it deep clones? Possibly define a clone method in the superclass QueryModel? how would that work?
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
Here is where clone could possibly be used:
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