2011-07-27 61 views
1

我正在尋找一個解決方案來獲取回形針對象的asset_host的絕對url。 url方法只返回相對url。所以我試過這個:回形針URL返回asset_host

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 

我很堅持這一!

感謝您的時間!

回答

4

這是一個比較複雜的解決方案,但你可以做到這樣的,首先使用的before_filter設置一個變量如果請求是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::Attachment.default_options.update({ 
    :url => ":assets_host/system/:attachment/:id/:style/:filename", 
    :path => ":rails_root/public/system/:attachment/:id/:style/:filename" 
}) 

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 

然後你就可以在你的配置包括該插值

我還沒有完全做到這一點,但我多次使用插值(這也是S3存儲是如何變魔術的),所以它應該可以工作。

+0

真棒這個作品!謝謝! – Oliver

+0

太棒了!我認爲在進出控制器時不需要阻塞。相反,我使用'#{request.protocol}#{request.host_with_port}' – brutuscat

+0

做了一個View Helper,你需要一個解決方法來使它在非請求環境下工作,比如延遲的電子郵件,後臺作業...... – lidaobing