代码之家  ›  专栏  ›  技术社区  ›  Marcos Placona

快速帮助重构Ruby类

  •  4
  • Marcos Placona  · 技术社区  · 16 年前

    class FeedManager
      attr_accessor :feed_object, :update, :new_entries
    
      require 'feedtosis'
    
      def initialize(feed_url)
        @feed_object = Feedtosis::Client.new(feed_url)
        fetch
      end
    
      def fetch
        @feed_object.fetch
      end
    
      def update
        @updates = fetch
      end
    
      def updated?
        @updates.new_entries.count > 0 ? true : false
      end
    
      def new_entries
        @updates.new_entries
      end
    end
    

    正如你所见,这很简单,但我看到的不太正确的地方是:

    1. 每当我通过终端调用fetch时,它就会打印一个包含更新的列表,而实际上它应该返回一个对象。

    举个例子,在终端中,如果我做了如下操作:

    client = Feedtosis::Client.new('http://stackoverflow.com/feeds')
    result = client.fetch
    

    <Curl::Easy http://stackoverflow.com/feeds>
    

    这正是我所期望的。但是,在“投球”课上做同样的事情时:

    FeedManager.new("http://stackoverflow.com/feeds")
    

    我让对象以数组的形式返回,其中包含提要上的所有项。

    当然,我做错了什么,所以任何重构这个类的帮助他都会非常感激。

    另外,我希望看到关于我的实现的评论,以及任何使它更好的评论都是受欢迎的。

    提前谢谢

    3 回复  |  直到 16 年前
        1
  •  1
  •   Harish Shetty    16 年前

    试试这个:

    class FeedManager
    
      require 'feedtosis'
    
      attr_accessor :feed_object    
    
      def initialize(feed_url)
        self.feed_object = Feedtosis::Client.new(feed_url)
      end    
      def fetch
        feed_object.fetch
      end    
      def updates (reload = true)
        @updates = reload ? fetch : @updates
      end    
      def updated?
        updates(false).new_entries.count > 0
      end    
      def new_entries
        updates(false).new_entries
      end
    end
    

    result = FeedManager.new("http://stackoverflow.com/feeds").updates
    

    PS:我已经删除了:update和:new\u条目的attr\u访问器。

    编辑

    feed = FeedManager.new("http://stackoverflow.com/feeds")
    updates = feed.updates # reloads the updates
    # do something
    
    updates = feed.updates(false) # get the updates from cache.
    
        2
  •  0
  •   wilhelmtell    16 年前
    1. :update @updates

    2. count > 0 ? true : false 可能只是 count > 0

        3
  •  0
  •   Mike Cargal    16 年前

    您似乎希望initialize方法返回调用update的结果。Initialize在Ruby中基本上是一个构造函数,因此它将返回新的FeedManager对象。

    在一个类定义的中间放置一个要求语句也是非常“不寻常”的。

    推荐文章