Search code examples
rubymethodsweb-scrapingopen-uri

Using variable declared in one method to open webpage in another method


I am working on a CLI Project and trying to open up a web page by using url variable declared in another method.

def self.open_deal_page(input)
  index = input.to_i - 1
  @deals = PopularDeals::NewDeals.new_deals
  @deals.each do |info|
  d = info[index]
  @product_url = "#{d.url}"
  end
  @product_url.to_s
  puts "They got me!"
end

def self.deal_page(product_url)
  #self.open_deal_page(input)
  deal = {}
  html = Nokogiri::HTML(open(@product_url))
  doc = Nokogiri::HTML(html)
  deal[:name] = doc.css(".dealTitle h1").text.strip
  deal[:discription] = doc.css(".textDescription").text.strip
  deal[:purchase] = doc.css("div a.button").attribute("href")
  deal
  #binding.pry
end

but I am receiving this error.

  `open': no implicit conversion of nil into String (TypeError)

any possible solution? Thank you so much in advance.


Solution

  • Try returning your @product_url within your open_deal_page method, because now you're returning puts "They got me!", and also note that your product_url is being created inside your each block, so, it won't be accessible then, try creating it before as an empty string and then you can return it.

    def open_deal_page(input)
      ...
      # Create the variable
      product_url = ''
      # Assign it the value
      deals.each do |info|
        product_url = "#{info[index].url}"
      end
      # And return it
      product_url
    end
    

    In your deal_page method tell to Nokogiri to open the product_url that you're passing as argument.

    def deal_page(product_url)
      ...
      html = Nokogiri::HTML(open(product_url))
      ...
    end