I like to share this quickly for those who are concerned about application performance. Rails has always provided a way to cache assets. It's been very simple but when we think about the "cloud" and scaling, we realized it's a pain to actually make it all work with amazon s3.

We need a command line solution or some rake tasks and asset packager plugin provides these for us.

I've updated the plugin, asset_packager for Rails 3.0.1. Click here to check it out (git).

How to install

rails plugin install git://github.com/katgironpe/asset_packager.git

One rake task to cache and upload assets

namespace :cache do
  BUCKET = 'bucketname'

  desc "start aws"
  task :aws do
    require 'aws/s3'

    AWS::S3::Base.establish_connection!(
      access_key_id: 'key',
      secret_access_key: 'secret'
    )
  end


  desc "update s3"
  task :s3=> :aws do
    prefix = ''

    files = Dir[
      "./public/stylesheets/admin_all_packaged.css",
      "./public/stylesheets/splash_all_packaged.css",
      "./public/stylesheets/all_packaged.css",
      "./public/javascripts/admin_all_packaged.js",
      "./public/javascripts/splash_all_packaged.js",
      "./public/javascripts/all_packaged.js"
    ]

    files.each do |f|
      next if File.directory?(f)
      puts f

      key = f.gsub(/\.\/public/, prefix)
      puts " -> %s" % key

      AWS::S3::S3Object.store(
        key, File.open(f), BUCKET,
        :access => :public_read, 'Cache-Control' => 'max-age=315360000'
      )
    end
  end  


  desc "cache assets and update s3 for production"
  task :production do
    Rake::Task['asset:packager:delete_all'].invoke
    Rake::Task['asset:packager:build_all'].invoke
    Rake::Task['cache:s3'].invoke

  end



end

How to use

rake cache:production 

It's sort of saying cache all assets for production.

Thanks to Marco Palinar and Cyril David for sharing a similar gist on how to upload assets to Amazon s3 through a very simple rake task.

comments powered byDisqus

Hello! I am Kat. I've been a developer for several years. When I'm not sitting down, reading and working for long hours, I am traveling to some place of interest.
If you want to reach out, you can send me an email or add me up on Google Plus.