【问题标题】:returning objects in ruby在红宝石中返回对象
【发布时间】:2009-02-02 14:39:04
【问题描述】:

在这里,我开始使用 ruby​​ 开发一个新闻发布应用程序。创建一篇文章效果很好,但我不知道如何检索一篇文章。我希望我的 Article.get 方法返回一个 article 对象,.. 但似乎唯一的方法是让所有 Article 属性都可写,我真的不想这样做。有没有更好的方法来做到这一点?

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

【问题讨论】:

  • 请注意,出现在 attr_reader 和 attr_writer 中的项目可以组合在 attr_accessor 子句中。

标签: ruby oop


【解决方案1】:

我认为这里的问题是您使用初始化方法将记录保存到文件系统,当您想实例化一个文章对象以返回时

Article.new

那也将调用初始化方法;这可能就是它令人困惑的原因;您似乎将两件事合二为一。

所以为了简化它,我将有一个单独的 persist(保存)方法,与您的 initialize 方法不同。

我相信您有充分的理由在文件系统而不是数据库上执行此操作,但我不禁觉得阅读有关活动记录模式的信息会很有启发性,无论是 Ruby implementation 的它(如果您决定使用数据库)或只是the pattern

【讨论】:

    【解决方案2】:

    我可能会创建两个类,一个负责将文章读写到磁盘(或数据库或其他任何地方),另一个负责文章。然后,存储类(例如 ArticleStorage)就可以轻松地从磁盘读取并创建一个 Article-instance,然后可以将其返回。

    类似

    
    class ArticleStorage
      def self.save(article)
        # Make sure the folder is available, and the file is writable
        file.puts(article.to_s)
      end
    
      def self.load(title)
        # Open the file named title in the right directory
        # Read the file into a hash for example
        return Article.new(file[:author], file[:topic], file[:body], file[:created])
      end
    end
    
    class Article
      def initialize(author, topic, body, created)
        # save variables
      end
    
      def to_s
        # Format and prepare the article for saving
      end
    end
    

    然后您可以执行a = Article.new("author", "my topic", "long text", Time.now) 之类的操作并使用ArticleStorage.save(a) 保存并使用a = ArticleStorage.load("my topic") 加载

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-06
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 2015-08-03
      • 1970-01-01
      • 2014-05-27
      • 2019-03-18
      相关资源
      最近更新 更多