我从新闻API中获取rss数据。但是,有时条目会包含某些字段,例如summary
或url = "http://rss.cnn.com/rss/cnn_topstories.rss"
feed = Feedjira::Feed.fetch_and_parse url
api_json = JSON.parse(feed.to_json)
data_array = []
feed.entries.each_with_index do |entry,index|
data_array << { title: entry.title, link: entry.url, image_url: entry.image, summary: entry.summary }.as_json
end
,有时则不会。在调用之前如何检查对象是否为空?
entry.image
在上面的代码中,有时entry.summary
和undefined method `image' for #<Feedjira::Parser::ITunesRSSItem:0x007fb25c452688>
为空,并返回错误,例如:
if entry.image.exists?
image = entry.image
else
image = ""
end
if entry.summary.exists?
summary = entry.summary
else
summary = ""
end
一种显而易见的方法是在将每个对象保存为变量之前检查它们。但这是最好的方法吗?
select * from forms order by column
答案 0 :(得分:0)
使用try()
,如果相关属性缺失,它将返回nil
entry.try(:image)
在您的代码中,您可以这样做
data_array << { title: entry.try(:title), link: entry.try(:url), image_url: entry.try(:image), summary: entry.try(:summary) }.as_json
希望这有帮助!
答案 1 :(得分:0)
如果您使用的是Ruby 2.3.0或更高版本,则可以使用全新的Safe Navigation Operator
:
entry&.image # same thing as entry.try(:image) but shorter
您甚至可以根据需要进行导航,例如:
entry&.image&.urls&.small # Works as a charm even if "urls" is not present