Ruby 方法的条件参数

Ruby Conditional argument to method

我有一些 'generic' 方法可以根据 css 选择器提取数据,这些选择器在许多网站中通常都是相同的。但是,我有另一种方法接受给定网站的 css 选择器作为参数。

如果未传递 title_selector 参数,我需要调用 get_title 方法。我该怎么做?

接受 css 个选择器作为参数的抓取

  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 为假(无),它将调用 get_title

:title => page.css(title_selector || get_title(doc)).text,

不过,我不确定在这种情况下 doc 实际上应该是什么。

编辑

根据您在下方的评论,我认为您可以重构 get_title 来处理所有逻辑。允许 get_title 使用可选的 title_selector 参数并将此行添加到方法的顶部:

return doc.css(title_selector).text if title_selector

那么,我原来的那一行就变成了:

:title => get_title(page, title_selector)