Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails 3 : "superclass mismatch for class ..."

Platform: Mac OSX 10.6

In my terminal, i start the Ruby console with "rails c"

While following the Ruby on Rails 3 tutorial to build a class:

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

i get the error message:

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>'

The tutorial shows that it has no problem and i know the code is fine; I've searched other related questions, but they all involved migrating from Ruby 2 to 3 or erb vs eruby.

like image 494
Matthew Avatar asked Apr 01 '11 10:04

Matthew


3 Answers

You already have a Word class defined elsewhere. I tried within a Rails 3 app but was not able to replicate.

If you have not created a second Word class yourself, it is likely one of your Gems or plugins already defines it.

like image 152
Douglas F Shearer Avatar answered Nov 13 '22 22:11

Douglas F Shearer


This can also happen as such:

# /models/document/geocoder.rb
class Document
  module Geocoder
  end
end

# /models/document.rb
require 'document/geocoder'

class Document < ActiveRecord::Base
  include Geocoder
end

The require loads Document (which has a superclass of Object) before Document < ActiveRecord::Base (which has a different superclass).

I should note that in a Rails environment the require is not usually needed since it has auto class loading.

like image 21
Kris Avatar answered Nov 13 '22 21:11

Kris


I had the problem with a Rails 4 application. I used concerns under the user namespace.

class User
  module SomeConcern
  end
end

In development everything worked fine but in production (I guess because of preload_app true) I got the mismatch error. The fix was pretty simple. I just added an initializer:

require "user"

Cheers!

like image 22
2called-chaos Avatar answered Nov 13 '22 20:11

2called-chaos