ruby-on-rails 在Rails 7.1中调用服务类方法时出错

nuypyhwy  于 2023-11-20  发布在  Ruby
关注(0)|答案(1)|浏览(203)

Rails 7.1
在我的app/services/tools中,我有一个文件:services_tools.rb
在services_tools.rb中,我有:

  1. module ServicesTools
  2. class ErbToSlim
  3. def convert_erb_to_slim(erb_file)
  4. ...........
  5. end
  6. end
  7. class NestedMigrationCreator
  8. def generate_nested_migration(migration_namespace:, migration_name:, migration_code: nil)
  9. ..........
  10. end
  11. end
  12. end

字符串
我转到命令行,并执行:

  1. rails c


然后我做了:

  1. creator = ServicesTools::NestedMigrationCreator.new


我收到以下信息:

  1. (irb):1:in `<main>': uninitialized constant ServicesTools (NameError)


在控制台中,当我这样做时:

  1. ActiveSupport::Dependencies.autoload_paths


我明白了:

  1. "/lib",
  2. "/test/mailers/previews",
  3. "/app/channels",
  4. "/app/controllers",
  5. "/app/controllers/concerns",
  6. "/app/helpers",
  7. "/app/jobs",
  8. "/app/mailers",
  9. "/app/models",
  10. "/app/models/concerns",
  11. "/app/services",
  12. ...


有什么想法吗?

yb3bgrhw

yb3bgrhw1#

您的app/services是根目录,这意味着相对于该目录的文件必须对应于模块/类名才能自动加载:

  1. # app/services/tools/services_tools.rb
  2. # '^^^' '^^^^^^^^^^^^'
  3. # | |
  4. module Tools # --' |
  5. module ServicesTools # --'
  6. end
  7. end

字符串
听起来有点尴尬。这样更好:

  1. # app/services/tools/erb_to_slim.rb
  2. module Tools
  3. class ErbToSlim
  4. end
  5. end
  6. # app/services/tools/nested_migration_creator.rb
  7. module Tools
  8. class NestedMigrationCreator
  9. end
  10. end


一般来说,最好每个文件定义一个常量。然而,这也是可行的,只要文件名对应于类/模块名,你就可以在里面做任何事情:

  1. # app/services/tools.rb
  2. module Tools
  3. class ErbToSlim
  4. end
  5. class NestedMigrationCreator
  6. end
  7. end

  • https:github.com/fxn/zeitwerk#file-structure*
展开查看全部

相关问题