【Rails】楽天BooksAPIで新刊を抽出する

残念なことに楽天APIでは入力パラメーターに発売日を指定して検索をかけることはできないみたいなので、無理やり新刊を検索するコードを書きました。

入力可能なパラメーターはいくつかありますが、その中でも出版社毎に新刊を抽出します。

  def download
    @page = '1'
    @month = params[:month]
    if @month == '01'
      @month = '13'
    end
    @pre_month = @month.to_i - 1
    @check_page = 0
    @publisherName = params[:publisher_select]
    @books = []

    if @publisherName.present?
      books_search
      while @check_page == 0
        @page = @page.to_i + 1
        @page.to_s
        books_search
      end
    end
    
  end

private

  def books_search
    results = RakutenWebService::Books::Book.search({
      publisherName: @publisherName,
      booksGenreId: '001001',
      outOfStockFlag: '1',
      sort: '-releaseDate',
      page: @page
    })
    results.each do |result|
      book = Book.new(read(result))
      if book.salesDate =~ /#{@pre_month.to_s}/
        @check_page = 1
      end
      unless book.title =~ /コミックカレンダー|(||BOX)セット/
        if book.salesDate =~ /#{@month}/
          comic = Book.find_or_initialize_by(isbn: book.isbn)
          unless comic.persisted?
            book.save
          end
        end
      end
    end
  end

  def read(result)
    title = result['title']
    author = result['author']
    publisherName = result['publisherName']
    url = result['itemUrl']
    salesDate = result['salesDate']
    isbn = result['isbn']
    image_url = result['mediumImageUrl'].gsub('?_ex=120x120', '?_ex=350x350')
    series = result['title'].sub(/\(.*|\(.*|\s.*|公式ファンブック.*/,"")
    salesint = result['salesDate'].gsub(/||/,"").to_i
    {
      title: title,
      author: author,
      publisherName: publisherName,
      url: url,
      salesDate: salesDate,
      isbn: isbn,
      image_url: image_url,
      series: series,
      salesint: salesint,
    }
  end

新刊を取得するコントローラーです。

(新刊というのは指定した月に出版されるものとする)

楽天APIでは1ページ毎に取得できる本の数は30冊まで。

それ以上取得するにはpageを指定してあげる必要がありますので、while文を利用し繰り返す毎に@pageに1を足しています。

APIで指定するときpageは文字列なので、一旦数値化し(.to_i)そこから文字列化に(.to_s)戻しています。

問題なのはこの繰り返しをいつ止めるか。

出版社を指定し、そこから新しい順でひたすら取得しているので、どこかのタイミングで前の月に出版された本が混ざってきます。

それを検知させるのがbooks_searchの11行目付近。

前の月の文字列がbookに含まれていたとき、@check_page に1を代入しています。

while文の条件は@check_page == 0となっているので、この段階で繰り返しは止まるということです。

これで、指定した月、指定した出版社の本のデータを抽出し、DBに保存できるのであとは検索フォームを作りそこに表示するだけで、新刊ページ的なものを作ることができました。