Rails 2 and RSS parsing gives weird errors

Finally! After many weeks I managed to track down a very strange bug. When parsing RSS feeds using Ruby’s built-in RSS::Parser, sometimes I would get bombs in Rails when trying to insert item.pubDate into the database.

Have you seen this one?

open location do |http|
  result = RSS::Parser.parse(http.read, false)
  result.items.each do |item|
    feed_items.create(
      :title => item.title,
      :link => item.link,
      :description => item.description,
      :published_at => item.pubDate
    )
  end
end

and then this error: ArgumentError in ‘Feed when fetching a feed should be valid’ wrong number of arguments (1 for 0)? I have and it has been driving me bonkers!

Turns out there is some nastiness in the item.pubDate and Rails’ built in methods to save time fields to a datetime column. The fix is easy, just tack a .to_s after:

open location do |http|
  result = RSS::Parser.parse(http.read, false)
  result.items.each do |item|
    feed_items.create(
      :title => item.title,
      :link => item.link,
      :description => item.description,
      :published_at => item.pubDate.to_s
    )
  end
end
  1. Hmmm… that error message looks like it’s because of an invalid feed, not because of Rails’ datetime column handling.

    Rails allows you to assign either a String or a Time to datetime column, so you shouldn’t have to coerce via #to_s first.

  2. I checked the class of the pubDate and it was a Time, so something is afoul; either in Rails or RSS::Parser. And since this is happening since Rails 2.x I think the former (I have not changed Ruby). Coercing to string does fix the issue though.

  1. No trackbacks yet.