gpt4 book ai didi

ruby-on-rails - Rails 3.1 SASS Assets 助手不包括 RAILS_RELATIVE_URL_ROOT/relative_url_root

转载 作者:行者123 更新时间:2023-12-02 00:30:06 25 4
gpt4 key购买 nike

我一直致力于从 2.3.11 升级到 Rails 3.1。需要清除的主要障碍之一是向 Assets 管道的转换。在这个过程中,我决定将我的 css 转换为 sass (scss)。在 rails 3.1 中,所有通过管道交付的 Assets 都会收到附加到生产文件名的哈希值。因此,我的 css 中引用的所有图像现在都需要使用 sass 中的 image-path 或 image-url 助手。问题是,即使我在我的 environment.rb 文件中设置了我的 ENV['RAILS_RELATIVE_URL_ROOT'],sass Assets 助手也无法包含 relative_url_root。

为了清楚起见,为了在 rails 3.1 中添加 relative_url_root,我在我的 environment.rb 文件中添加了以下行:

ENV['RAILS_RELATIVE_URL_ROOT'] = '/foo'

并将以下行添加到我的虚拟主机:

RailsBaseURI /foo

此策略似乎适用于所有链接等。只是 sass 中的 Assets 助手似乎无法正常工作。任何想法将不胜感激。

最佳答案

经过一番挖掘,我发现了问题所在。问题出在 Rails 中,特别是 Sprockets::Helpers::RailsHelper::AssetPaths#compute_public_path。 Sprockets::Helpers::RailsHelper::AssetPaths 继承自 ActionView::AssetPaths 并重写了一些方法。当通过 Sass::Rails::Resolver#public_path 方法调用 compute_public_path 是 sass-rails 时,rails sprocket 助手会接手解析 Assets 的任务。 Sprockets::Helpers::RailsHelper::AssetPaths#compute_public_path 遵从 super,即 ActionView::AssetPaths#compute_public_path。在这个方法中有一个条件是 has_request?在 rewrite_relative_url_root 上如下所示:

def compute_public_path(source, dir, ext = nil, include_host = true, protocol = nil)
...
source = rewrite_relative_url_root(source, relative_url_root) if has_request?
...
end

def relative_url_root
config = controller.config if controller.respond_to?(:config)
config ||= config.action_controller if config.action_controller.present?
config ||= config
config.relative_url_root
end

如果您查看 rewrite_relative_url_root 的内部结构,它依赖于存在的请求以及从 Controller 变量派生它的能力,以便解析相对 url 根。问题在于,当 sprockets 为 sass 解析这些 Assets 时,它没有 Controller 存在,因此没有请求。

上面的解决方案对我来说在开发模式下不起作用。这是我目前使用的解决方案:

module Sass
module Rails
module Helpers
protected
def public_path(asset, kind)
resolver = options[:custom][:resolver]
asset_paths = resolver.context.asset_paths
path = resolver.public_path(asset, kind.pluralize)
if !asset_paths.send(:has_request?) && ENV['RAILS_RELATIVE_URL_ROOT']
path = ENV['RAILS_RELATIVE_URL_ROOT'] + path
end
path
end
end
end
end

关于ruby-on-rails - Rails 3.1 SASS Assets 助手不包括 RAILS_RELATIVE_URL_ROOT/relative_url_root,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7363733/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com