2011-07-27 5 views
1

私はペーパークリップオブジェクトのasset_hostで絶対URLを取得するためのソリューションを探しています。 urlメソッドは相対URLのみを返します。だから私はこれを試しました:paperclip url to return 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

それは多少複雑なソリューションですが、あなたは最初に、このようにそれを行うリクエストがSSLであるかどうかを保持する変数を設定するためにbefore_filterを使用することができます、あなた」が定義されてこれにより

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ストレージがどのように魔法をするのかということです)。

+0

素晴らしいです!ありがとうございました! – Oliver

+0

素晴らしい!私はコントローラーの中と外にブロックする必要はないと思う。代わりに私は '#{request.protocol}#{request.host_with_port}' – brutuscat

+0

を使ってビューヘルパーをやっていましたが、遅れたメールやバックグラウンドジョブのような非要求環境下で動作させるための回避策が必要です。 – lidaobing