模块不允许创建类的实例

时间:2013-01-04 14:33:07

标签: ruby-on-rails ruby-on-rails-3 class module

我需要阅读更多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

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

1 个答案:

答案 0 :(得分: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

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