简体   繁体   中英

How to get path to S3 assets from Rails controller

My setup

I'm using Rails 3, asset_sync and paperclip.

  • When I'm developing on my local machine, I want assets to be served through asset pipeline .
  • In production, I want assets to be served from S3 .

My question

How can I access to the asset path from Controller/Model/whatever? (The same URL that I get if I use image_path("favicon.ico") in views)

I have seen countless of SO questions, where the accepted answer suggest use of ActionController::Base.helpers.asset_path("favicon.ico") . That's fine, BUT, when I try it in production, I get an URL pointing to my production server, NOT to S3.

I added a piece of test code to my production HAML to demonstrate the issue:

%link{:rel => "image_src", :href => image_path("test.png")} %link{:rel => "image_src", :href => ActionController::Base.helpers.image_path("test.png")}

...which generates HTML:

<link href='http://mybucket.s3.amazonaws.com/assets/test-2cfd63058597b0c73221f3c1988c121e.png' rel='image_src'> <link href='/assets/test-2cfd63058597b0c73221f3c1988c121e.png' rel='image_src'>

So, I think ActionController::Base.helpers.image_path is not the right way to solve the issue.

I've also seen many answers saying that view_context should be used. However, I do not have instance of a controller at the time when I need the URL, so also this approach does not work for me.

More background (in case you're interested)

What I'm trying to achieve is to serve Paperclip default image from S3.

has_attached_file :logo, :styles => { ... }, :default_url => # Here, I need the URL that points to S3, if this is run in production.

I don't want to hard-code the URL to point to my S3 bucket, since I'd like to serve the file from local machine when I'm developing (as suggested here: https://github.com/thoughtbot/paperclip/issues/1092 )

Seems like the issue described here: https://github.com/rails/rails/issues/10051 and which seems to be fixed in Rails 4 with https://github.com/rails/rails/pull/12622 .

The first discussion describes a possible workaround with an initializer for Rails 3:

class ActionController::Base
  def self.helpers
    @helper_proxy ||= begin
      proxy = ActionView::Base.new
      proxy.config = config.inheritable_copy
      proxy.extend(_helpers)
    end
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM