在这里,我开始使用 ruby 开发新闻发布应用程序。创建一篇文章效果很好,但我不知道如何检索一篇文章。我希望我的 Article.get 方法返回一个文章对象,..但似乎唯一的方法是使所有文章属性都可写,我真的不想这样做。有没有更好的方法来做到这一点?
require 'date'
require 'ftools'
require 'find'
module News
class Article
attr_reader :topic, :body, :created, :directory, :file_name, :file, :author
attr_writer :topic, :body, :created, :directory, :file_name, :file, :author
def initialize(author, topic, body)
@topic = topic
@body = body
@author = author
@created = DateTime.now()
@directory = 'archive/' + @created.strftime('%Y/%m') + '/'
@file_name = @created.strftime('%H-%M-%S')
@file = @directory + @file_name
File.makedirs(@directory) unless File.directory?(@directory)
if !File.file?(@file)
@article = File.new(@file, 'w', 0777)
@article.print "#{@topic}\n#{@author}\n#{@body}"
@article.close()
end
end
def Article.get(path)
#???
end
end
最佳答案
我认为这里的问题是你正在使用初始化方法将记录保存到文件系统,如果你想实例化一个文章对象以返回
Article.new
然后那也将调用初始化方法;这可能就是它令人困惑的原因;您似乎将两件事混为一谈。
因此,为了简化它,我将有一个单独的 persist
(保存)方法,与您的 initialize
方法不同。
我确定您有充分的理由在文件系统而不是数据库上执行此操作,但我不禁觉得阅读有关事件记录模式的信息会很有启发性,无论它是 Ruby implementation它的(如果你决定使用数据库)或只是the pattern .
关于ruby - 返回 ruby 中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/503404/