Ruby-on-Rails 中的模型继承、工厂模式和自解析
我正在与一个网站合作,该网站将从许多不同的来源提取提要,然后将这些流保存到一个通用模型中,在本例中是一个特征。 FeedEntry 类中的代码示例可能是:
feed = Feedzirra::Feed.fetch_and_parse(feed_url)
add_entries(feed.entries)
...
def self.add_entries(entries)
entries.each do |entry|
# Should know how to parse itself into a trait
@trait = parse(entry)
if @trait.save
...
end
end
不可否认,我来自 java 背景,在 java 中,我将设置一个继承层次结构,然后在 FeedEntry 的每个子类上扩展 parse 方法,以便每个 FeedEntry 都知道如何解析自身。所以我的问题是:
1)这在rails中是一个可行的计划吗?
2) 如果是这样,是否只包含一列基本上是“类型”的列,表示 FeedEntry 是什么子类?
3)如果没有,有什么关于最干燥的方法的建议吗?
谢谢!
I am working with a site that will be pulling down feeds from a lot of different sources, and then saving those streams into a common model, in this case a trait. An example of the code from within the FeedEntry class might be:
feed = Feedzirra::Feed.fetch_and_parse(feed_url)
add_entries(feed.entries)
...
def self.add_entries(entries)
entries.each do |entry|
# Should know how to parse itself into a trait
@trait = parse(entry)
if @trait.save
...
end
end
Admittedly I come from a java background, and in java here, I would set up an inheritance heirarchy, and then on each subclass of FeedEntry extend the parse method so that each FeedEntry knew how to parse itself. So my questions:
1) Is this a feasible plan in rails?
2) If so, would one just include a column that was basically "type" that said what subclass the FeedEntry was?
3) If not, any suggestions on the DRYest way to do this?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为你可以使用rails提供的单表继承。参考 :
http://juixe.com/techknow /index.php/2006/06/03/rails-single-table-inheritance/ 和 http://api.rubyonrails.org/classes/ActiveRecord/Base.html 。
之后,您可以在每个“继承”类中添加解析方法。您可能想要添加 before_save 回调并调用 self.parse 。我不确定这是否是最干燥的方法..看看其他人怎么说会很有趣。
I think you can use Single table inheritance that rails provide . Refer :
http://juixe.com/techknow/index.php/2006/06/03/rails-single-table-inheritance/ and http://api.rubyonrails.org/classes/ActiveRecord/Base.html .
After that you could add the parse method in each one of your "inherited" classes . You might want to add a before_save callback and call self.parse . I am not sure if this is the DRYest way to do this .. would be interesting to see what others say .