方法的 Ruby 条件参数 [英] Ruby Conditional argument to method
问题描述
我有一些基于 css 选择器提取数据的通用"方法,这些选择器在许多网站中通常是相同的.但是,我有另一种方法可以接受给定网站的 css 选择器作为参数.
I have some 'generic' methods that extract data based on css selectors that usually are the same in many websites. However I have another method that accept as argument the css selector for a given website.
如果没有传递 title_selector 参数,我需要调用 get_title 方法.我该怎么做?
I need to call the get_title method if title_selector argument is nos passed. How can I do that?
def scrape(urls, item_selector, title_selector, price_selector, image_selector)
collection = []
urls.each do |url|
doc = Nokogiri::HTML(open(url).read) # Opens URL
@items = doc.css(item_selector)[0..1].map {|item| item['href']} # Sets items
@items.each do |item| # Donwload each link and parse
page = Nokogiri::HTML(open(item).read)
collection << {
:title => page.css(title_selector).text, # I guess I need conditional here
:price => page.css(price_selector).text
}
end
@collection = collection
end
end
通用标题提取器
def get_title(doc)
if doc.at_css("meta[property='og:title']")
title = doc.css("meta[property='og:title']")
else doc.css('title')
title = doc.at_css('title').text
end
end
推荐答案
在 page.css
调用中使用 or
运算符.如果 title_selector
为 false (nil),它将调用 get_title
.
Use an or
operator inside your page.css
call. It will call get_title
if title_selector
is falsey (nil).
:title => page.css(title_selector || get_title(doc)).text,
不过,我不确定 doc
在这种情况下实际上应该是什么.
I'm not sure what doc
should actually be in this context, though.
编辑
鉴于您在下面的评论,我认为您可以重构 get_title
来处理所有逻辑.允许 get_title
采用可选的 title_selector
参数并将此行添加到您的方法的顶部:
Given your comment below, I think you can just refactor get_title
to handle all of the logic. Allow get_title
to take an optional title_selector
parameter and add this line to the top of your method:
return doc.css(title_selector).text if title_selector
然后,我原来的行变成:
Then, my original line becomes:
:title => get_title(page, title_selector)
这篇关于方法的 Ruby 条件参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!