Ruby on rails - 模块不允许创建类的实例



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

现在我确信这是一个有效的答案,但有人能解释一下发生了什么吗?看到一个有解释的例子对我来说比阅读一本书中的一行行更有好处。

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

在您的代码中,您正在创建一个具有相同名称的模块和一个类——这是不允许的。模块重写类,因为它是第二次加载的。

相关内容

  • 没有找到相关文章

最新更新