1

我的设置

我正在使用 Rails 3、asset_sync 和回形针。

  • 当我在本地机器上开发时,我希望通过资产管道提供资产。
  • 在生产中,我希望从S3提供资产。

我的问题

如何从 Controller/Model/whatever 访问资产路径?(如果我image_path("favicon.ico")在视图中使用相同的 URL)

我见过无数这样的问题,其中接受的答案建议使用ActionController::Base.helpers.asset_path("favicon.ico"). 没关系,但是,当我在生产中尝试它时,我得到一个指向我的生产服务器的 URL,而不是指向 S3。

我在生产 HAML 中添加了一段测试代码来演示该问题:

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

...生成 HTML:

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

所以,我认为ActionController::Base.helpers.image_path不是解决问题的正确方法。

我也看到很多答案说view_context应该使用。但是,当我需要 URL 时,我没有控制器实例,所以这种方法也不适合我。

更多背景(如果您有兴趣)

我想要实现的是从 S3 提供 Paperclip 默认图像。

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

我不想硬编码指向我的 S3 存储桶的 URL,因为我想在开发时从本地机器提供文件(如此处建议:https ://github.com/thoughtbot/回形针/问题/1092

4

1 回答 1

1

看起来像这里描述的问题:https://github.com/rails/rails/issues/10051并且似乎在 Rails 4 中通过https://github.com/rails/rails/pull/12622修复。

第一个讨论描述了使用 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
于 2014-12-22T21:56:56.473 回答