简体   繁体   English

Ruby条件方法的参数

[英]Ruby Conditional argument to method

I have some 'generic' methods that extract data based on css selectors that usually are the same in many websites. 我有一些基于CSS选择器的数据提取方法,这些方法通常在许多网站中都是相同的。 However I have another method that accept as argument the css selector for a given website. 但是,我有另一种方法可以接受给定网站的CSS选择器作为参数。

I need to call the get_title method if title_selector argument is nos passed. 如果未传递title_selector参数,则需要调用get_title方法。 How can I do that? 我怎样才能做到这一点?

Scrape that accept css selectors as arguments 刮擦接受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

Generic title extractor 通用标题提取器

  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

Use an or operator inside your page.css call. page.css调用中使用or运算符。 It will call get_title if title_selector is falsey (nil). 如果title_selector为false(nil),它将调用get_title

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

I'm not sure what doc should actually be in this context, though. 不过,我不确定在这种情况下实际应该使用什么doc

EDIT 编辑

Given your comment below, I think you can just refactor get_title to handle all of the logic. 鉴于您在下面的评论,我认为您只需重构get_title即可处理所有逻辑。 Allow get_title to take an optional title_selector parameter and add this line to the top of your method: 允许get_title使用可选的title_selector参数,并将此行添加到方法的顶部:

return doc.css(title_selector).text if title_selector

Then, my original line becomes: 然后,我的原始行变为:

:title => get_title(page, title_selector)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM