Rails:从控制器中的 lib 文件夹加载自定义类 [英] Rails: Loading custom class from lib folder in controller

查看:49
本文介绍了Rails:从控制器中的 lib 文件夹加载自定义类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个文件 lib/services/my_service.rb.

I've created a file as lib/services/my_service.rb.

# /lib/services/my_service.rb
class MyService
...
end

我想在 app/controllers/my_controller 中使用它

I want to use it in app/controllers/my_controller

class MyController < ApplicationController
     def method
          service = MyService.new()
     end

我收到一个错误,指出 MyService 是一个未初始化的常量.我试过用

I'm getting an error that MyService is an uninitialized constant. I've tried to import it with

require '/lib/services/my_service.rb'

但是我得到了

cannot load such file -- /lib/services/my_service.rb

我尝试使用

config.autoload_paths << Rails.root.join('lib')

但没有骰子.仍然得到未初始化的常量 MyController::MyService

But no dice. Still getting uninitialized constant MyController::MyService

推荐答案

Ruby on Rails 期望某些命名约定支持自动加载.

Ruby on Rails expects certain naming conventions to support autoloading.

如果模型/类结构是 Services::MyService,Rails 可以自动加载位于 lib/services/my_service.rb 的文件.

Rails can autoload a file located at lib/services/my_service.rb if the model/class structure was Services::MyService.

将您的 lib/services/my_service.rb 更改为:

module Services
  class MyService
    # ...
  end
end

并在您的控制器中像这样使用该类:

And use that class like this in your controller:

service = Services::MyService.new

请注意,根据您的 Ruby on Rails 版本,您可能需要将 lib 文件夹添加到查找要自动加载的文件时查询的文件夹列表中:

Please note that depending on your Ruby on Rails version you might need to add the lib folder to the list of folders which are queried when looking for a file to autoload:

# add this line to your config/application.rb:
config.autoload_paths << "#{Rails.root}/lib"

在 Rails 指南中详细了解自动加载.

Read more about autoloading in the Rails Guides.

这篇关于Rails:从控制器中的 lib 文件夹加载自定义类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆