开发者

paperclip url to return asset_host

开发者_运维技巧i'm searching for a solution to get the absolute url with asset_host of a paperclip object. the url method only returns the relative url. so i tried this:

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"
})

but the request is missing in the initializer. or how do i get it?

my asset_host config looks like this:

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

i'm stuck with this!

thanks for your time!


It's a somewhat complicated solution, but you could do it like this, first use a before_filter to set a variable that will hold if a request is SSL or not:

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

With this defined, you'll have to define a Paperclip interpolation:

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

Then you can include this interpolation at your config:

Paperclip::Attachment.default_options.update({
  :url => ":assets_host/system/:attachment/:id/:style/:filename",
  :path => ":rails_root/public/system/:attachment/:id/:style/:filename"
})

I haven't done this exactly like this, but I have used interpolations many times (and that's also how the S3 storage does it's magic), so it should work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜