开发者

Check if source exists

I'm writing a website in Rails and I need to reed a RSS feed. The script works as intended, but I just got an error indicating that the source could not be read.

This is the script:

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

My concern is that the site will produce an error or just "crash" if the source isn't available for whatever reasons. How can I protect myself against this?

This is the exact error:

Errno::EN开发者_如何转开发OENT in WelcomeController#index

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


EDIT Found a more recent link: http://binarysoul.com/blog/rails-3-url-validation by Eric Himmelreich

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


Generally, you'll want to handle external requests like this in the background.

It's a bit too involved to provide a simple example here, but the main steps are:

  1. Create a model to store the data from your feed
  2. Write a rake task to perform the request, and save the result into your model
  3. Setup a cron job to run the rake task periodically
  4. Display the contents of your model on the page

This way, page loads are dependent only on your own database, not on any external resources that you may not control.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜