Expected to define. When calling class inside a module

后端 未结 6 1859
星月不相逢
星月不相逢 2020-12-15 05:12

I new to rails. I have a setup in the lib directory like so:

lib/
   blog/
     core/
        search/
            base.rb

The base.rb defin

相关标签:
6条回答
  • 2020-12-15 05:22

    I had the same problem. It comes from the fact that you try to load /lib/blog/core/search/base.rb directly in application.rb with /lib/**/

    Error I had:

    Expected /[...]/myapp/lib/durative/base.rb to define Base (LoadError)
    

    Directory structure:

    lib/
     --durative/
       --base.rb
    

    base.rb:

    module Durative
      class Base
        def initialize(config)
           @config = {}
        end
        #...
      end
    end
    

    application.rb:

    config.autoload_paths += Dir["#{config.root}/lib/**/"]
    

    Here are the changes I made to make it work

    Directory structure:

    lib/
     --durative.rb **(added)**
     --durative/
       --base.rb
    

    durative.rb:

    require 'durative/base'
    

    base.rb (no change)

    application.rb (changed):

    config.autoload_paths += Dir["#{config.root}/lib/"]
    

    Tell us if it worked for you too.

    0 讨论(0)
  • 2020-12-15 05:23

    I had the same issue. The problem was because I was including subdirs without including their parent lib dir:

    # did not work
    config.autoload_paths += %W(#{config.root}/lib/foo)
    

    and

    # in lib/foo/my_class.rb
    module Foo
      class MyClass
      end
    end
    

    Foo::MyClass would return Expected to define MyClass

    adding the lib dir to config.autoload_paths fixes the problem

    # worked
    config.autoload_paths += %W(#{config.root}/lib #{config.root}/lib/foo)
    
    0 讨论(0)
  • 2020-12-15 05:27

    If you have that deeply hidden class then access it this way:

    Blog::Core::Search::Base.new 'foo'
    
    0 讨论(0)
  • 2020-12-15 05:36

    Also, one thing to check is that your controller is named appropriately.

    For instance, make sure that your posts_controller.rb looks like this on the first line

    class PostsController < ApplicationController
    

    I have made mistakes where I copied a controller and tracked it down to not changing the controller classes name

    0 讨论(0)
  • 2020-12-15 05:47

    My error with this was that I had

    app/
      controllers/
          projects/
              some_controller.rb
          projects_controller.rb
    

    I was trying to keep my app organized and, when having a namespace - was splitting up the controller. Unfortunately it looks like Rails would randomly jump between the two and there would be conflicts causing the error in OP.

    Solution: Rename your sub-directory and adjust any routes.

    0 讨论(0)
  • 2020-12-15 05:49

    Just add: require base.rb in your environment.rb file.

    source: http://icebergist.com/posts/expected-xrb-to-define-x-loaderror

    0 讨论(0)
提交回复
热议问题