具有与顶层 class 同名的模块 class:'expected module_classe_file to define top_level class'
Having a module class with the same name as a top level class: 'expected module_classe_file to define top_level class'
我的 apps/model 文件夹如下所示:
models/
module/
category.rb
category.rb
但我似乎找不到正确自动加载的方法module/category:我总是遇到错误Expected /app/models/module/category.rb to define Category
。
目前我只看到两个选项:不将其添加到自动加载,或将 module/category.rb
重命名为 module/module_category.rb
,这似乎都不是一个好主意
我认为在你的情况下最好的办法是将 module/category.rb
添加到 lib
目录中。
从 category.rb
中获取代码并创建一个 lib/category.rb
文件。
然后将您的模块代码包含到您的 app/models/category.rb
在application.rb
一定要加载lib
目录config.autoload_paths << "#{Rails.root}/lib
.
class Category < ActiveRecord::Base
include Category
不过我个人不会这样做。命名变得令人困惑。您是否尝试过为您的代码命名空间?
例如,您也可以试试这个:
models/
category/
category_something.rb #change the name of the file to something else
category.rb
然后在你的 category_something.rb
class Category::CategorySomething
#code code code
end
这样您就可以像使用模块一样使用代码。
我的 apps/model 文件夹如下所示:
models/
module/
category.rb
category.rb
但我似乎找不到正确自动加载的方法module/category:我总是遇到错误Expected /app/models/module/category.rb to define Category
。
目前我只看到两个选项:不将其添加到自动加载,或将 module/category.rb
重命名为 module/module_category.rb
,这似乎都不是一个好主意
我认为在你的情况下最好的办法是将 module/category.rb
添加到 lib
目录中。
从
category.rb
中获取代码并创建一个lib/category.rb
文件。然后将您的模块代码包含到您的
app/models/category.rb
在
application.rb
一定要加载lib
目录config.autoload_paths << "#{Rails.root}/lib
.class Category < ActiveRecord::Base include Category
不过我个人不会这样做。命名变得令人困惑。您是否尝试过为您的代码命名空间?
例如,您也可以试试这个:
models/
category/
category_something.rb #change the name of the file to something else
category.rb
然后在你的 category_something.rb
class Category::CategorySomething
#code code code
end
这样您就可以像使用模块一样使用代码。