基于asset_id修改,aset_sync也许是更好的选择
Uploads static assets to Aliyun OSS with unique identifiers encoded into the path of the asset.
Only works with Rails 3.x because Rails 3 makes doing this sort of thing a lot easier and
that is all I needed it for.
This library takes standard Rails asset paths such as /stylesheets/main.css?1288717704
and converts them
into http://my_bucket.oss.aliyuncs.com/stylesheets/main-id-95df8d9bf5237ad08df3115ee74dcb10.css
.
It uses an MD5 hash of the file contents to produce the id so the same asset will always have the same ID.
In my quest to achieve a Google Page Speed score of 100, this library achieves the following:
- Assets served from a cookie-less domain
- Unique identifier is not encoded into a query parameter (so it is cacheable by proxy servers)
- All assets have far-future expires headers for caching
- Assets have the Cache-Control: public header for caching
- CSS and javascript is GZipped and the correct headers are added
As an added bonus, all your assets are available over https://
as well.
Add the gem to your Gemfile
gem "asset_oss"
Configure config/environments/production.rb
to use Aliyun OSS as the asset host
and to use the id-stamped asset paths in helpers
config.action_controller.asset_host = Proc.new do |source|
'http://my_bucket.oss.aliyuncs.com'
end
config.action_controller.asset_path = Proc.new do |source|
AssetOSS::Asset.fingerprint(source)
end
Add your Aliyun OSS configuration details to config/asset_oss.yml
production:
access_key_id: 'MY_ACCESS_KEY'
secret_access_key: 'MY_ACCESS_SECRET'
bucket: "my_live_bucket"
Optionally create a rake task in lib/tasks/asset_oss.rake
to
perform the upload for use in your deploy scripts
namespace :asset do
namespace :oss do
desc "uploads the current assets to aliyun oss with stamped ids"
task :upload do
Aliyun::OSS::DEFAULT_HOST.replace "oss-internal.aliyuncs.com"
AssetOSS::Asset.asset_paths += ['assets'] # Configure additional asset paths
AssetOSS::OSS.upload
end
end
end
If you want to use the SSL host in your configuration you can do so in config/environments/production.rb
config.action_controller.asset_host = Proc.new do |source|
request.ssl? 'https://my_bucket.oss.aliyuncs.com' : 'http://my_bucket.oss.aliyuncs.com'
end
By default any relative CSS images that match files on the filesystem are converted to AssetOSS paths as well.
For aliyun oss, if you don’t specify a prefix
it will use the http://
bucket URL by default. You can override this in config/asset_oss.yml
. For example if you wanted to use the https://
url:
production:
host: 'oss-internal.aliyuncs.com'
access_key_id: 'MY_ACCESS_KEY'
secret_access_key: 'MY_ACCESS_SECRET'
bucket: "my_live_bucket"
prefix: "https://my_bucket.oss.aliyuncs.com"