我正在寻找一种解决方案,以使用回形针对象的 asset_host 获取绝对 URL。 url 方法只返回相对 url。所以我尝试了这个:
Paperclip::Attachment.default_options.update({
:url => "#{ActionController::Base.asset_host.call(nil, request)}/system/:attachment/:id/:style/:filename",
:path => ":rails_root/public/system/:attachment/:id/:style/:filename"
})
但初始化程序中缺少请求。或者我如何获得它?
我的 asset_host 配置如下所示:
ActionController::Base.asset_host = Proc.new do |source, request|
if request.ssl?
"#{request.protocol}#{request.host_with_port}"
else
"http://cdn.somehost.com"
end
end
我被这个困住了!
感谢您的宝贵时间!
最佳答案
这是一个有点复杂的解决方案,但您可以这样做,首先使用 before_filter 设置一个变量,如果请求是 SSL 或不是 SSL,该变量将保持不变:
class ApplicationController < ActionController::Base
before_filter :set_current_request
after_filter :unset_current_request
protected
def set_current_request
Thread.current[:current_request] = request
end
def unset_current_request
Thread.current[:current_request] = nil
end
end
有了这个定义,你就必须定义一个回形针插值:
Paperclip.interpolates :assets_host do |attachment, style|
request = Thread.current[:current_request]
if request.ssl?
"#{request.protocol}#{request.host_with_port}"
else
"http://cdn.somehost.com"
end
end
然后你可以在你的配置中包含这个插值:
Paperclip::Attachment.default_options.update({
:url => ":assets_host/system/:attachment/:id/:style/:filename",
:path => ":rails_root/public/system/:attachment/:id/:style/:filename"
})
我没有像这样完全这样做,但我已经多次使用插值(这也是 S3 存储的神奇之处),所以它应该可以工作。
关于ruby-on-rails - 返回 asset_host 的回形针 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6846713/