css - undefined method `attr' for nil:NilClass (NoMethodError) -
i have method in cli app giving me error.
the method is:
def self.deal_page(input, product_url) self.open_deal_page(input) deal = {} html = open(@product_url) doc = nokogiri::html(html) data = doc.text.strip deal[:name] = doc.css("h1").text.strip deal[:discription] = doc.css(".textdescription").text.strip @purchase_link = nil @purchase_link= doc.at_css("div.detailleftcolumn a.success").attr("href") if @purchase_link.nil? deal[:purchase] = @product_url else deal[:purchase] = @purchase_link end deal end and error is:
/home/himachhag-45739/code/popular-deals-from-slickdeals.net-cli/lib/popular_deals/newdeals.rb:54:in `deal_page': undefined method `attr' nil:nilclass (nomethoderror) /home/himachhag-45739/code/popular-deals-from-slickdeals.net-cli/lib/popular_deals/cli.rb:70:in `disply_deal' /home/himachhag-45739/code/popular-deals-from-slickdeals.net-cli/lib/popular_deals/cli.rb:49:in `menu' /home/himachhag-45739/code/popular-deals-from-slickdeals.net-cli/lib/popular_deals/cli.rb:9:in `call' /home/himachhag-45739/code/popular-deals-from-slickdeals.net-cli/bin/popular-deals:10:in `<top (required)>' /usr/local/rvm/gems/ruby-2.3.1/bin/popular-deals:22:in `load' /usr/local/rvm/gems/ruby-2.3.1/bin/popular-deals:22:in `<main>' /usr/local/rvm/gems/ruby-2.3.1/bin/ruby_executable_hooks:15:in `eval' /usr/local/rvm/gems/ruby-2.3.1/bin/ruby_executable_hooks:15:in `<main>' i tried xpath, at_css, unless, if..else, doesn't help. also, don't error everytime, rid of it.
one way address problem bit paranoid:
@purchase_link = doc.at_css("div.detailleftcolumn a.success").try(:attr, "href") deal[:purchase] = @purchase_link || @product_url a couple of things keep in mind here. in ruby only nil , false logically false, it's rare need test nil? on things. case that's necessary when want distinguish between nil , false, can imagine not often.
so in case either hit at_css or didn't, in case try call doesn't anything. if finds try call carries on 1 more call. can assignment simple || (or) operator pick them in priority.
another thing since code inside class method, casually using instance variables can trouble. if things purchase_link used within method, remove @ makes them persistent.
another thing careful how method defined as:
def self.deal_page(input, product_url) that declares argument product_url, inside:
html = open(@product_url) this references class instance variable @product_url not same. may calling open wrong variable here.
Comments
Post a Comment