2011-04-06 164 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