Ruby on Rails 3:“类的超类不匹配”

平台:Mac OSX 10.6

在我的terminal中,我用“rails c”启动了Ruby控制台

遵循Ruby on Rails 3教程构build一个类:

class Word < String def palindrome? #check if a string is a palindrome self == self.reverse end end 

我收到错误消息:

 TypeError: superclass mismatch for class Word from (irb):33 from /Users/matthew/.rvm/gems/ruby-1.9.2-p180@rails3tutorial/gems/railties-3.0.5/lib/rails/commands/console.rb:44:in `start' from /Users/matthew/.rvm/gems/ruby-1.9.2-p180@rails3tutorial/gems/railties-3.0.5/lib/rails/commands/console.rb:8:in `start' from /Users/matthew/.rvm/gems/ruby-1.9.2-p180@rails3tutorial/gems/railties-3.0.5/lib/rails/commands.rb:23:in `<top (required)>' from script/rails:6:in `require' from script/rails:6:in `<main>' 

教程显示它没有问题,我知道代码是好的; 我search了其他相关的问题,但都涉及从Ruby 2迁移到3或者erb vs eruby。

您已经有一个在其他地方定义的Word类。 我尝试了一个Rails 3应用程序,但无法复制。

如果您还没有自己创build第二个Word类,那么很可能您的Gem或插件已经定义了它。

这也可以这样发生:

 # /models/document/geocoder.rb class Document module Geocoder end end # /models/document.rb require 'document/geocoder' class Document < ActiveRecord::Base include Geocoder end 

Document < ActiveRecord::Base (它具有不同的超类)之前,require需要加载Document (它具有Object的一个超类)。

我应该注意到,在Rails环境中,通常不需要require,因为它具有自动类加载。

我有一个Rails 4应用程序的问题。 我在用户名空间下使用了关注点。

 class User module SomeConcern end end 

在开发中一切正常,但在生产(我猜是因为preload_app真)我得到了不匹配的错误。 修复非常简单。 我刚刚添加了一个初始化程序:

 require "user" 

干杯!

我现在有同样的问题。 基本上这意味着Word被定义为其他地方的一个类,我的猜测是它在轨道上的gem。 只要将Word更改为Word2,它应该在教程中正常工作。

有时我们不知道我们是“开放课堂”。 例如一些深层模块嵌套:

 # space_gun.rb class SpaceGun << Weapon def fire Trigger.fire end end # space_gun/trigger.rb class SpaceGun class Trigger end end 

当我们定义触发器时,我们打开现有的SpaceGun类。 这工作。 但是,如果我们以相反的顺序加载这两个文件,则会引发错误,因为我们会先定义一个SpaceGun类,但不是一个武器。

有时我们会犯这个错误,因为我们明确地要求父类的子模块(例如触发器)。 这意味着类定义将以相反的顺序完成,导致这个问题。

 # surely nothing can go wrong if we require what we need first right? require 'space_gun/trigger' class SpaceGun << Weapon def fire Trigger.fire end end # BOOM 

  1. 依靠自动加载
  2. 总是把inheritance放在每一个公开课上。