Skip to content
Permalink
Browse files

Imported seed data for book covers and average ratings

  • Loading branch information...
mattboldt committed Feb 9, 2019
1 parent 5ae44f8 commit 21ae42a6d5415810d7463cc59ad15d18ca2901d9
Showing with 33 additions and 1 deletion.
  1. +2 −0 app/graphql/types/book_type.rb
  2. +6 −0 db/migrate/20190209184628_add_fields_to_books.rb
  3. +3 −1 db/schema.rb
  4. +22 −0 lib/tasks/book_data.rake
@@ -1,5 +1,7 @@
module Types
class BookType < Types::BaseObject
field :title, String, null: false
field :cover_url, String, null: true
field :average_rating, Integer, null: true
end
end
@@ -0,0 +1,6 @@
class AddFieldsToBooks < ActiveRecord::Migration[5.2]
def change
add_column :books, :cover_url, :string
add_column :books, :average_rating, :integer
end
end
@@ -10,13 +10,15 @@
#
# It's strongly recommended that you check this file into your version control system.

ActiveRecord::Schema.define(version: 2018_12_27_042909) do
ActiveRecord::Schema.define(version: 2019_02_09_184628) do

create_table "books", force: :cascade do |t|
t.integer "user_id"
t.string "title"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "cover_url"
t.integer "average_rating"
t.index ["user_id"], name: "index_books_on_user_id"
end

@@ -0,0 +1,22 @@
require 'open-uri'

namespace :book_data do

task import: :environment do
Book.all.each do |book|
url = "https://openlibrary.org/search.json?title=#{book.title}"
response = JSON.parse(open(url).read)
doc = response['docs'].find { |d| d['cover_i'].present? }

img_url = if doc
"http://covers.openlibrary.org/b/ID/#{doc['cover_i']}-L.jpg"
else
'http://covers.openlibrary.org/b/ID/8346276-L.jpg'
end

random_rating = (1..5).to_a.sample
book.update(cover_url: img_url, average_rating: random_rating)
end
end

end

0 comments on commit 21ae42a

Please sign in to comment.
You can’t perform that action at this time.