指定“app”路径的正确方法是什么?在 Rails 插件中?

发布于 2024-08-25 16:43:19 字数 412 浏览 3 评论 0原文

出现这个问题是因为 cells gem 使用 File.join('app','cells') 指定模板目录。除非您将 Rails 作为守护进程运行(scripts/server -d),否则效果很好。守护进程将目录切换到 / ,这使得单元模板路径指向错误的绝对路径。

我的解决方案是将默认路径设置为 File.join(RAILS_ROOT, 'app', 'cells')。这在 Rails 中有效,但插件的单元测试失败,因为未定义 RAILS_ROOT。使用 File.join(File.dirname(__FILE__),'..' ... 也可以,但需要大约 6 个级别的 '..' 这似乎是错误的。

所以我的问题是什么是正确的在 Rails 插件中指定“app”下目录的路径的方法?还是有其他错误导致守护进程 Rails 无法找到相对路径?

This question came about because the cells gem specifies template directories using File.join('app','cells'). That works fine until you run Rails as a daemon (scripts/server -d). The daemon switches directories to / which leaves the cells template paths pointing to the wrong absolute path.

My solution was to set the default paths to File.join(RAILS_ROOT, 'app', 'cells'). This works in Rails, but the unit tests for the plugin fail because RAILS_ROOT isn't defined. Using File.join(File.dirname(__FILE__),'..' ... also works but requires about 6 levels of '..' which seems wrong.

So my question is what is the proper way to specify the path to a directory under 'app' in a Rails plugin? Or is there something else wrong that would cause daemonizing Rails to fail to find the relative paths?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

人│生佛魔见 2024-09-01 16:43:19

我建议将您的更改从插件中移出并放入初始值设定项中。在初始化程序中重写使用 File.join('app','cells') 的方法。这有几个好处。

  1. 您不会直接修改第三方代码,因此您更有可能不必担心在升级时重新应用更改。
  2. 通过不修改插件本身,插件单元测试仍然会通过。
  3. 您可以使用 RAILS_ROOT 我认为这是正确的解决方案。

I suggest moving your changes out of the plugin and into an initializer. In the initializer override the method that uses File.join('app','cells'). This has several benefits.

  1. You are not modifying third-party code directly so you are more likely not to have to worry about re-applying changes on an upgrade.
  2. By not modifying the plugin itself the plugin unit tests will still pass.
  3. You are able to use RAILS_ROOT which I think is the right solution.
青衫负雪 2024-09-01 16:43:19

对于那些难以破译这个答案的人,这对我有用:

创建一个文件 config/initializers/cells.rb

在其中

Cell::Base.view_paths=[
  File.join(RAILS_ROOT, 'app', 'cells'),
  File.join(RAILS_ROOT, 'app', 'cells', 'layouts')
]

:希望这会有所帮助

For those who had trouble deciphering this answer, here is what worked for me:

Create a file config/initializers/cells.rb

in it put:

Cell::Base.view_paths=[
  File.join(RAILS_ROOT, 'app', 'cells'),
  File.join(RAILS_ROOT, 'app', 'cells', 'layouts')
]

Hope this helps

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文