Ruby on Rails 3 : “superclass mismatch for class …”

后端 未结 5 1032
长发绾君心
长发绾君心 2020-12-02 16:43

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:



        
5条回答
  •  [愿得一人]
    2020-12-02 17:08

    Sometimes we 'open class' without us knowing. For example with some deep module nesting:

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

    When we define trigger, we open the existing SpaceGun class. This works. However if we load the two file in the reverse order, the error would be raised, because we would define a SpaceGun class first, but is not a Weapon.

    Sometimes we make this mistake because we explicitly require sub module (e.g. trigger) from the parent class. Which means the class definition will be done the reverse order, causing this issue.

    # 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
    

    Either

    1. rely on auto loading
    2. always put inheritance to every open class occurrence.

提交回复
热议问题