Rails GoogleBookから取得したオブジェクトをrubyの型へ変換

map関数で変換

  • 取得した値を、プロパティに詰め込む。
  • jsonのパース用ライブラリも読み込む
 require "net/http"
  require "open-uri"
  require 'uri'
  require 'json'

class BooksController < ApplicationController
 

  
  before_action :set_book, only: [:show, :edit, :update, :destroy]

  # GET /books
  # GET /books.json
  def index
//ここがポイント
    @books = GoogleBooks.search(params[:search],{:count => 20}).map{|googlebook| book = Book.new
      book.title = googlebook.title
      book.author = googlebook.authors
      book.publish = googlebook.publisher
      book.published = googlebook.published_date
      book.image_link = googlebook.image_link
      book
    }
  end


  private
    # Use callbacks to share common setup or constraints between actions.
    def set_book
      @book = Book.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def book_params
      params.require(:book).permit(:title, :author, :published, :image_link)
    end
    
  end