2011-04-06 167 views
2

我正在Rails上编写一个网站,我需要芦苇RSS饲料。该脚本按预期工作,但我收到一个错误,指示无法读取源文件。检查源是否存在

这是脚本:

def setup_feed 
    source = "http://path_to_feed/" 
    content = "" # raw content of rss feed will be loaded here 

    open(source) do |s| 
    content = s.read 
    end 
    @rss = RSS::Parser.parse(content, false) 
end 

我担心的是,该网站将产生错误或只是“死机”如果源不提供任何理由。我该如何保护自己免受这种伤害呢?

这是确切的错误:

Errno::ENOENT in WelcomeController#index 

No such file or directory - http://path_to_feed/ 

回答

1

编辑 找到一个更近的链接:由Eric Himmelreich http://binarysoul.com/blog/rails-3-url-validation

class Example 
    include ActiveModel::Validations 

    ## 
    # Validates a URL 
    # 
    # If the URI library can parse the value, and the scheme is valid 
    # then we assume the url is valid 
    # 
    class UrlValidator < ActiveModel::EachValidator 
    def validate_each(record, attribute, value) 
     begin 
     uri = Addressable::URI.parse(value) 

     if !["http","https","ftp"].include?(uri.scheme) 
      raise Addressable::URI::InvalidURIError 
     end 
     rescue Addressable::URI::InvalidURIError 
     record.errors[attribute] << "Invalid URL" 
     end 
    end 
    end 

    validates :field, :url => true 
end 
+0

我不能让URI解析器工作,但我添加了救援位,它似乎照顾了错误。谢谢 – Frank 2011-04-06 11:01:06

0

一般情况下,你要处理这样的外部请求在背景中。

这有点太涉及到在这里提供一个简单的例子,但主要步骤是:

  1. 创建一个模型从您的饲料存储数据
  2. 写rake任务来执行请求,并将结果保存到模型
  3. 设置一个cron作业运行rake任务周期性
  4. 显示模型的页面
上的内容

这样,页面加载仅取决于您自己的数据库,而不取决于您可能无法控制的任何外部资源。

+0

感谢Tobias,理想的情况是我会这样做,我可能会在稍后做,但这是一项紧迫的任务,所以我不得不为此做一个快速解决。我谨记你的建议,以便以后可以实施。 – Frank 2011-04-06 11:00:21