我需要阅读我被告知的更多 Ruby 理论,这很好,但是我阅读的大多数文献都是在非常高的水平上解释的,我不明白。所以这让我想到了这个问题和我的代码
我有一个处理我的 api 调用的模块
module Book::BookFinder
BOOK_URL = 'https://itunes.apple.com/lookup?isbn='
def book_search(search)
response = HTTParty.get(BOOK_URL + "#{search}", :headers => { 'Content-Type' => 'application/json', 'Accept' => 'application/json' })
results = JSON.parse(response.body)["results"]
end
end
然后是我的控制器
class BookController < ApplicationController
before_filter :authenticate_admin_user!
include Book::BookFinder
def results
results = book_search(params[:search])
@results = results
@book = Book.new
@book.author = results[0]["artistName"]
end
def create
@book = Book.new(params[:book])
if @book.save
redirect_to @book, notice: 'Book was successfully saved'
else
render action:new
end
end
end
我想要做的是将作者值保存到我的 Book 模型中。我收到错误消息
undefined method `new' for Book:Module
在进行之前的帖子中已向我解释过的搜索时。无法实例化模块。解决方案是上课?但也许我没有正确理解,因为我不知道该把这门课放在哪里。给我的解决方案是
class Book
def initialize
# put constructor logic here
end
def some_method
# methods that can be called on the instance
# eg:
# @book = Book.new
# @book.some_method
end
# defines a get/set property
attr_accessor :author
# allows assignment of the author property
end
现在我确信这是一个有效的答案,但谁能解释发生了什么?看到一个有解释的例子对我来说比阅读书中的一行又一行的文字更有益。