Joh*_*ghn 6 ruby versioning idioms
我有一系列Ruby对象,它们为底层XML建模(比如OXM).不幸的是,XML正在被更改,相应的版本正在受到冲击.我需要更新我的Ruby对象才能处理这两个版本.在我的方法中,我想要比大量的if/else子句更清洁,因为这可能会再次发生.是否有一种惯用的Ruby方法来处理这个问题?我正在考虑使用基类作为各种"版本化"类的代理,即
class XMLModel
class V1
# V1 specific implementation
end
class V2;
# V2 specific implementation
end
def initialize
# create a new V? and set up delegation to that specific version of the object
end
def from_xml(xml_string)
# use the XML string to determine correct version and return a
# specific version of the object
end
end
Run Code Online (Sandbox Code Playgroud)
上述方法的优点是每个版本在代码中都是不同的,并允许我添加/删除版本,只需很少的向后兼容性测试.糟糕的是,我可能最终会遇到很多代码重复.此外,在这种情况下,XMLModel.new返回一个new XMLModel,而XMLModel.from_xmlfactory方法返回一个new XMLModel::V1.
想法?
为什么不构建继承自 XMLModel 的子类,那么类之间的决定仅在代码中的某一点进行。
class XMLModel_V1 < XMLModel
def from_xml(xml_string)
# do V1 specific things
end
end
class XMLModel_V2 < XMLModel
def from_xml(xml_string)
# do V2 specific things
end
end
# Sample code wich shows the usage of the classes
if(V1Needed)
m = XMLModel_V1
else
m = XMLModel_V2
end
Run Code Online (Sandbox Code Playgroud)