I need to read more Ruby theory I have been told, which is fine but most literature I read is explained at a very high level and I don’t understand it. So this leads me to the question and my code
I have a module that deals with my api call
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
and then my controller
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
What I want to do is save the author value to my Book model. I get the error message
undefined method `new' for Book:Module
when conducting a search which in a previous post has been explained to me. A module cannot be instanced. The solution was to make a class? but maybe I am not understanding correctly as I am not sure where to put this class. The solution given to me was
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
Now I am sure that this is a valid answer, but could anyone explain what is going on? Seeing an example with an explanation is more beneficial to me than reading lines and lines of text in a book.
In your code you are creating a module and a class with the same name – this is not allowed. The module overrides the class since it is loaded second.