开发者

Rails: Images on one server, CSS and Javascript on another

I am working on a rails app that has a bunch (hundreds) of images that are hosted on an S3 server. To have helpers like image_tag point here I had to add this to by config/env开发者_开发百科ironments/development.rb test.rb and production.rb:

config.action_controller.asset_host = "http://mybucket.s3.amazonaws.com"

However, this also means that it looks there for CSS and Javascript. This is a huge pain because each time I change the CSS I have to re-upload it to Amazon.

So.. Is there an easy way I can make my app look to Amazon for images, but locally for CSS/Javascript?

(I'm using Rails 3.0)


You can pass a Proc object to config.action_controller.asset_host and have it determine the result programmatically at runtime.

config.action_controller.asset_host = Proc.new do |source|
  case source
  when /^\/(images|videos|audios)/
    "http://mybucket.s3.amazonaws.com"
  else
    "http://mydomain.com"
  end
end

but left as it is, this would give you http://mybucket.s3.amazonaws.com/images/whatever.png when you use image_tag :whatever.

If you want to modify the path as well, you can do something very similar with config.action_controller.asset_path

config.action_controller.asset_path = Proc.new do |path|
  path.sub /^\/(images|videos|audios)/, ""
end

which would give you http://mybucket.s3.amazonaws.com/whatever.png combined with the former.


There's nothing stopping you from passing full url to image_tag: image_tag("#{IMAGE_ROOT}/icon.png").

But to me moving static images (icons, backgrounds, etc) to S3 and leaving stylesheets/js files on rails sounds kinda inconsistent. You could either move them all to S3 or setup Apache for caching (if you're afraid users pulling big images will create too much overhead for Rails).

BTW, you don't have to put config.action_controller... into config files for all three environments: placing that line just in config/environment.rb will have the same effect.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜