0

我需要阅读我被告知的更多 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

现在我确信这是一个有效的答案,但谁能解释发生了什么?看到一个有解释的例子对我来说比阅读书中的一行又一行的文字更有益。

4

1 回答 1

1
module Finders

  ## Wrap BookFinder inside another module, Finders, to better organise related
  ## code and to help avoid name collisions
  ## lib/finders/book_finder.rb
  module BookFinder
    def bar
      puts "foo"
    end
  end  
end


## Another BookFinder module, but this one is not wrapped.
## lib/book_finder.rb
module BookFinder
  def foo
    puts 'bar'
  end
end


## Book is a standard Rails model inheriting from ActiveRecord
## app/models/book.rb
class Book < ActiveRecord::Base
  ## Mixin methods from both modules
  include BookFinder
  include HelperLibs::BookFinder
end

## app/controllers/books_controller.rb
class BookController
  def create
    book = Book.new
    book.foo
    book.bar

  end
end


BookController.new.create
 - bar
 - foo

在您的代码中,您正在创建一个具有相同名称的模块和一个类 - 这是不允许的。该模块将覆盖该类,因为它是第二个加载的。

于 2013-01-04T14:50:36.930 回答