【问题标题】:How to fetch assets inside vendor subfolders in Rails?如何在 Rails 的供应商子文件夹中获取资产?
【发布时间】:2018-11-14 07:50:27
【问题描述】:

我需要在我的应用程序中安装一系列库,将它们保存在 /vendor/plugins/ 内的各自文件夹中

例如,ckeditor 库:

  • /vendor/plugins/ckeditor/ 中的主文件夹
  • /vendor/plugins/ckeditor/js/Chart.js中的js文件
  • /vendor/plugins/ckeditor/css/chart.min.css 中的 css 文件

这样我就可以像这样导入到我的 application.scss 中:

*= require chart.min

在我的 application.js 中是这样的:

//= require Chart.js

当我尝试这样做时,rails 仅访问文件夹 /vendor/assets/plugins/ plugins,生成错误:

could not find file 'chart.min' with type 'text/css'

如何让项目扫描所有供应商的子文件夹,直到找到我正在导入的文件?

【问题讨论】:

  • 我将它添加到我的初始化程序/assets.rb 中但没有成功:Rails.application.config.assets.paths += Dir["#{Rails.root}/vendor/plugins/*"]。排序依据 { |目录| -dir.size }

标签: ruby-on-rails ruby asset-pipeline vendor


【解决方案1】:

首先将/vendor/plugins目录添加到资产加载路径:

module MyApp
  class Application < Rails::Application
    config.assets.paths << Rails.root.join("vendor", "plugins")
    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration should go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded.
  end
end

但是,将目录添加到资产加载路径并不意味着 Sprockets 会递归搜索所有子目录。将其配置为这样做也不是一个好主意。

您仍然需要提供从/vendor/plugins 开始的完整路径。

app/assets/javascripts/application.js:

//= require ckeditor/js/Chart

app/assets/stylesheets/application.css:

*= require ckeditor/css/chart.min

或者您可以直接使用Rails integration gem 并跳过所有麻烦。

【讨论】:

  • 恕我直言,我会摆脱 plugins 目录。较少的配置通常是一件好事。
  • 我将插件文件夹放在 vendor/assets/ 中,然后我可以跳过“config.assets.paths”代码。我一直在为文件路径而苦苦挣扎,这是您根据要求确定的。谢谢!
  • 使用 ckeditor 的 gem 会更容易,问题是我需要安装 15 个特定版本的库来集成 html 管理仪表板,所以如果我使用附带的文件会更容易包裹。这就是我需要插件文件夹的原因。
猜你喜欢
  • 2014-11-16
  • 2012-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-17
  • 2014-07-01
  • 2013-12-09
相关资源
最近更新 更多