lib/book.rb
# Gets genres, images and dates.
Gets genres, images and dates.
Gets genres images and dates .
def fetch_data
    url = "https://www.goodreads.com/book/show/#{id}?format=xml&key=AtaRYksgV1LDWkg2dTOg"
    uri = URI.parse url
    document = Nokogiri::XML(uri.read.split("\n").map {|l| l.strip }.join '')
    self.genres = document.xpath("//shelf/@name").map {|g| g.value }.delete_if {|g| /read|fav|kindle|book-club|club|series|school/.match g }.uniq.map do |g|
      Genre.where(name: g).first_or_create
    end
    self.image_url = document.at_xpath("//image_url").text
    begin
      year = document.at_xpath("//book/publication_year").text.to_i
      day = document.at_xpath("//book/publication_day").text.to_i
      month = document.at_xpath("//book/publication_month").text.to_i
      if year > 1000
        day = [day, 1].max
        month = [month, 1].max
        self.pub_date = Date.new(year,month,day)
      else
        self.pub_date = nil
      end
    rescue
      puts "#{year}-#{month}-#{day} is not a valid pub date."
      self.pub_date = nil
    end
  end
def fetch_data url = "https://www.goodreads.com/book/show/#{id}?format=xml&key=AtaRYksgV1LDWkg2dTOg" uri = URI . parse url document = Nokogiri :: XML ( uri . read . split ( "\n" ) . map { | l | l . strip } . join '' ) self . genres = document . xpath ( "//shelf/@name" ) . map { | g | g . value } . delete_if { | g | / read|fav|kindle|book-club|club|series|school / . match g } . uniq . map do | g | Genre . where ( name : g ) . first_or_create end self . image_url = document . at_xpath ( "//image_url" ) . text begin year = document . at_xpath ( "//book/publication_year" ) . text . to_i day = document . at_xpath ( "//book/publication_day" ) . text . to_i month = document . at_xpath ( "//book/publication_month" ) . text . to_i if year > 1000 day = [ day , 1 ] . max month = [ month , 1 ] . max self . pub_date = Date . new ( year , month , day ) else self . pub_date = nil end rescue puts "#{year}-#{month}-#{day} is not a valid pub date." self . pub_date = nil end end
Gets genres, images and dates.
Gets genres images and dates .
# Example: https://www.goodreads.com/book/show/50?format=xml&key=AtaRYksgV1LDWkg2dTOg # TODO(icco): Support a wider variety of granularity (for instance if the # pub date is just a year.