asset_sync-1.0.0/0000755000004100000410000000000012250226601013707 5ustar www-datawww-dataasset_sync-1.0.0/Rakefile0000644000004100000410000000245112250226601015356 0ustar www-datawww-data#!/usr/bin/env rake begin require 'bundler/setup' require 'appraisal' rescue LoadError puts 'You must `gem install bundler` and `bundle install` to run rake tasks' end require 'bundler/gem_tasks' require 'rspec/core/rake_task' namespace :spec do RSpec::Core::RakeTask.new(:unit) do |spec| spec.pattern = 'spec/unit/*_spec.rb' spec.rspec_opts = ['--backtrace'] rbx = defined?(RUBY_ENGINE) && RUBY_ENGINE == 'rbx' jruby = defined?(RUBY_ENGINE) && RUBY_ENGINE == 'jruby' if RUBY_VERSION == '1.8.7' && !(rbx || jruby) spec.rcov = true spec.rcov_opts = %w{--exclude gems\/,spec\/} end end RSpec::Core::RakeTask.new(:integration) do |spec| spec.pattern = 'spec/integration/*_spec.rb' spec.rspec_opts = ['--backtrace'] end desc "run spec:unit and spec:integration tasks" task :all do Rake::Task['spec:unit'].execute # Travis CI does not expose encrypted ENV variables for pull requests, so # do not run integration specs # http://about.travis-ci.org/docs/user/build-configuration/#Set-environment-variables # pull_request = ENV['TRAVIS_PULL_REQUEST'] == 'true' ci_build = ENV['TRAVIS'] == 'true' if !ci_build || (ci_build && pull_request) Rake::Task['spec:integration'].execute end end end task :default => 'spec:all' asset_sync-1.0.0/Gemfile0000644000004100000410000000042512250226601015203 0ustar www-datawww-datasource 'https://rubygems.org' gemspec gem 'rcov', :platforms => :mri_18, :group => [:development, :test] gem 'simplecov', :platforms => [:jruby, :mri_19, :ruby_19, :mri_20, :rbx], :group => [:development, :test], :require => false gem 'jruby-openssl', :platform => :jruby asset_sync-1.0.0/spec/0000755000004100000410000000000012250226601014641 5ustar www-datawww-dataasset_sync-1.0.0/spec/spec_helper.rb0000644000004100000410000000276012250226601017464 0ustar www-datawww-datarequire 'rubygems' require 'bundler' begin require 'simplecov' SimpleCov.start do add_filter 'spec' end rescue LoadError # SimpleCov ain't available - continue end begin Bundler.setup(:default, :development) rescue Bundler::BundlerError => e $stderr.puts e.message $stderr.puts "Run `bundle install` to install missing gems" exit e.status_code end $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) $LOAD_PATH.unshift(File.dirname(__FILE__)) require 'asset_sync' require 'rspec' RSpec.configure do |config| config.mock_framework = :rspec end shared_context "mock without Rails" do before(:each) do if defined? Rails Object.send(:remove_const, :Rails) end AssetSync.stub(:log) end end shared_context "mock Rails" do before(:each) do unless defined? Rails Rails = double 'Rails' end Rails.stub(:env).and_return('test') Rails.stub :application => double('application') Rails.application.stub :config => double('config') Rails.application.config.stub :assets => ActiveSupport::OrderedOptions.new Rails.application.config.assets.prefix = '/assets' AssetSync.stub(:log) end end shared_context "mock Rails without_yml" do include_context "mock Rails" before(:each) do set_rails_root('without_yml') Rails.stub(:public_path).and_return(Rails.root.join('public').to_s) end end def set_rails_root(path) Rails.stub(:root).and_return(Pathname.new(File.join(File.dirname(__FILE__), 'fixtures', path))) end asset_sync-1.0.0/spec/fixtures/0000755000004100000410000000000012250226601016512 5ustar www-datawww-dataasset_sync-1.0.0/spec/fixtures/with_invalid_yml/0000755000004100000410000000000012250226601022054 5ustar www-datawww-dataasset_sync-1.0.0/spec/fixtures/with_invalid_yml/config/0000755000004100000410000000000012250226601023321 5ustar www-datawww-dataasset_sync-1.0.0/spec/fixtures/with_invalid_yml/config/asset_sync.yml0000644000004100000410000000070712250226601026223 0ustar www-datawww-datadefaults: &defaults fog_provider= "AWS" aws_access_key_id: "xxxx" aws_secret_access_key: "zzzz" region: "eu-west-1" development: <<: *defaults fog_directory: "rails_app_development" existing_remote_files: keep test: <<: *defaults fog_directory: "rails_app_test" existing_remote_files: keep production: <<: *defaults fog_directory: "rails_app_production" existing_remote_files: delete hybrid: <<: *defaults enabled: false asset_sync-1.0.0/spec/fixtures/aws_with_yml/0000755000004100000410000000000012250226601021220 5ustar www-datawww-dataasset_sync-1.0.0/spec/fixtures/aws_with_yml/config/0000755000004100000410000000000012250226601022465 5ustar www-datawww-dataasset_sync-1.0.0/spec/fixtures/aws_with_yml/config/asset_sync.yml0000644000004100000410000000074212250226601025366 0ustar www-datawww-datadefaults: &defaults fog_provider: "AWS" aws_access_key_id: "xxxx" aws_secret_access_key: "zzzz" region: "eu-west-1" run_on_precompile: false development: <<: *defaults fog_directory: "rails_app_development" existing_remote_files: keep test: <<: *defaults fog_directory: "rails_app_test" existing_remote_files: keep production: <<: *defaults fog_directory: "rails_app_production" existing_remote_files: delete hybrid: <<: *defaults enabled: false asset_sync-1.0.0/spec/fixtures/google_with_yml/0000755000004100000410000000000012250226601021702 5ustar www-datawww-dataasset_sync-1.0.0/spec/fixtures/google_with_yml/config/0000755000004100000410000000000012250226601023147 5ustar www-datawww-dataasset_sync-1.0.0/spec/fixtures/google_with_yml/config/asset_sync.yml0000644000004100000410000000064012250226601026045 0ustar www-datawww-datadefaults: &defaults fog_provider: "Google" google_storage_access_key_id: 'xxxx' google_storage_secret_access_key: 'zzzz' development: <<: *defaults fog_directory: "rails_app_development" existing_remote_files: keep test: <<: *defaults fog_directory: "rails_app_test" existing_remote_files: keep production: <<: *defaults fog_directory: "rails_app_production" existing_remote_files: delete asset_sync-1.0.0/spec/fixtures/rackspace_with_yml/0000755000004100000410000000000012250226601022362 5ustar www-datawww-dataasset_sync-1.0.0/spec/fixtures/rackspace_with_yml/config/0000755000004100000410000000000012250226601023627 5ustar www-datawww-dataasset_sync-1.0.0/spec/fixtures/rackspace_with_yml/config/asset_sync.yml0000644000004100000410000000064012250226601026525 0ustar www-datawww-datadefaults: &defaults fog_provider: "Rackspace" rackspace_username: "xxxx" rackspace_api_key: "zzzz" region: "eu-west-1" development: <<: *defaults fog_directory: "rails_app_development" existing_remote_files: keep test: <<: *defaults fog_directory: "rails_app_test" existing_remote_files: keep production: <<: *defaults fog_directory: "rails_app_production" existing_remote_files: delete asset_sync-1.0.0/spec/integration/0000755000004100000410000000000012250226601017164 5ustar www-datawww-dataasset_sync-1.0.0/spec/integration/aws_integration_spec.rb0000644000004100000410000000363112250226601023723 0ustar www-datawww-datarequire File.dirname(__FILE__) + '/../spec_helper' def bucket(name) options = { :provider => 'AWS', :aws_access_key_id => ENV['AWS_ACCESS_KEY_ID'], :aws_secret_access_key => ENV['AWS_SECRET_ACCESS_KEY'] } connection = Fog::Storage.new(options) connection.directories.get(ENV['FOG_DIRECTORY'], :prefix => name) end def execute(command) app_path = File.expand_path("../../dummy_app", __FILE__) Dir.chdir app_path `#{command}` end describe "AssetSync" do before(:each) do @prefix = SecureRandom.hex(6) end let(:app_js_regex){ /#{@prefix}\/application-[a-zA-Z0-9]*.js$/ } let(:app_js_gz_regex){ /#{@prefix}\/application-[a-zA-Z0-9]*.js.gz$/ } let(:files){ bucket(@prefix).files } after(:each) do @directory = bucket(@prefix) @directory.files.each do |f| f.destroy end end it "sync" do execute "rake ASSET_SYNC_PREFIX=#{@prefix} assets:precompile" # bucket(@prefix).files.size.should == 5 files = bucket(@prefix).files app_js_path = files.select{ |f| f.key =~ app_js_regex }.first app_js_gz_path = files.select{ |f| f.key =~ app_js_gz_regex }.first app_js = files.get( app_js_path.key ) app_js.content_type.should == "text/javascript" app_js_gz = files.get( app_js_gz_path.key ) app_js_gz.content_type.should == "text/javascript" app_js_gz.content_encoding.should == "gzip" end it "sync with enabled=false" do execute "rake ASSET_SYNC_PREFIX=#{@prefix} ASSET_SYNC_ENABLED=false assets:precompile" bucket(@prefix).files.size.should == 0 end it "sync with gzip_compression=true" do execute "rake ASSET_SYNC_PREFIX=#{@prefix} ASSET_SYNC_GZIP_COMPRESSION=true assets:precompile" # bucket(@prefix).files.size.should == 3 app_js_path = files.select{ |f| f.key =~ app_js_regex }.first app_js = files.get( app_js_path.key ) app_js.content_type.should == "text/javascript" end end asset_sync-1.0.0/spec/dummy_app/0000755000004100000410000000000012250226601016634 5ustar www-datawww-dataasset_sync-1.0.0/spec/dummy_app/Rakefile0000644000004100000410000000214412250226601020302 0ustar www-datawww-datarequire 'rubygems' # require "rake" ENV['RAILS_ROOT'] = File.dirname(__FILE__) # Set up gems listed in the Gemfile. ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE']) # require 'rails/all' require "action_controller/railtie" require "sprockets/railtie" if defined?(Bundler) Bundler.require(*Rails.groups(:assets => %w(development test))) end module AssetSyncTest class Application < Rails::Application config.encoding = "utf-8" config.filter_parameters += [:password] config.eager_load = false config.assets.enabled = true config.assets.version = '1.0' config.secret_token = 'bf196b4383deefa4e0120a6ef1d9af1cc45f5c4ebd04405' config.session_store :cookie_store, :key => '_asset_sync_test_session', :secret => 'xxxx' config.active_support.deprecation = :log config.assets.compress = true config.assets.digest = true config.assets.prefix = ENV['ASSET_SYNC_PREFIX'] end end AssetSyncTest::Application.initialize! AssetSyncTest::Application.load_tasks # Rake::Task['assets:precompile:all'].invoke asset_sync-1.0.0/spec/dummy_app/app/0000755000004100000410000000000012250226601017414 5ustar www-datawww-dataasset_sync-1.0.0/spec/dummy_app/app/assets/0000755000004100000410000000000012250226601020716 5ustar www-datawww-dataasset_sync-1.0.0/spec/dummy_app/app/assets/javascripts/0000755000004100000410000000000012250226601023247 5ustar www-datawww-dataasset_sync-1.0.0/spec/dummy_app/app/assets/javascripts/application.js0000644000004100000410000000002512250226601026105 0ustar www-datawww-dataconsole.log("hello");asset_sync-1.0.0/spec/unit/0000755000004100000410000000000012250226601015620 5ustar www-datawww-dataasset_sync-1.0.0/spec/unit/google_spec.rb0000644000004100000410000001006112250226601020431 0ustar www-datawww-datarequire File.dirname(__FILE__) + '/../spec_helper' describe AssetSync do include_context "mock Rails without_yml" describe 'with initializer' do before(:each) do AssetSync.config = AssetSync::Config.new AssetSync.configure do |config| config.fog_provider = 'Google' config.google_storage_access_key_id = 'aaaa' config.google_storage_secret_access_key = 'bbbb' config.fog_directory = 'mybucket' config.existing_remote_files = "keep" end end it "should configure provider as Google" do AssetSync.config.fog_provider.should == 'Google' AssetSync.config.should be_google end it "should should keep existing remote files" do AssetSync.config.existing_remote_files?.should == true end it "should configure google_storage_access_key_id" do AssetSync.config.google_storage_access_key_id.should == "aaaa" end it "should configure google_storage_secret_access_key" do AssetSync.config.google_storage_secret_access_key.should == "bbbb" end it "should configure fog_directory" do AssetSync.config.fog_directory.should == "mybucket" end it "should configure existing_remote_files" do AssetSync.config.existing_remote_files.should == "keep" end it "should default gzip_compression to false" do AssetSync.config.gzip_compression.should be_false end it "should default manifest to false" do AssetSync.config.manifest.should be_false end end describe 'from yml' do before(:each) do set_rails_root('google_with_yml') AssetSync.config = AssetSync::Config.new end it "should configure google_storage_access_key_id" do AssetSync.config.google_storage_access_key_id.should == "xxxx" end it "should configure google_storage_secret_access_key" do AssetSync.config.google_storage_secret_access_key.should == "zzzz" end it "should configure google_storage_access_key" do AssetSync.config.fog_directory.should == "rails_app_test" end it "should configure google_storage_access_key" do AssetSync.config.existing_remote_files.should == "keep" end it "should default gzip_compression to false" do AssetSync.config.gzip_compression.should be_false end it "should default manifest to false" do AssetSync.config.manifest.should be_false end end describe 'with no configuration' do before(:each) do AssetSync.config = AssetSync::Config.new end it "should be invalid" do expect{ AssetSync.sync }.to raise_error() end end describe 'with fail_silent configuration' do before(:each) do AssetSync.stub(:stderr).and_return(StringIO.new) AssetSync.config = AssetSync::Config.new AssetSync.configure do |config| config.fail_silently = true end end it "should not raise an invalid exception" do expect{ AssetSync.sync }.not_to raise_error() end end describe 'with gzip_compression enabled' do before(:each) do AssetSync.config = AssetSync::Config.new AssetSync.config.gzip_compression = true end it "config.gzip? should be true" do AssetSync.config.gzip?.should be_true end end describe 'with manifest enabled' do before(:each) do AssetSync.config = AssetSync::Config.new AssetSync.config.manifest = true end it "config.manifest should be true" do AssetSync.config.manifest.should be_true end it "config.manifest_path should default to public/assets.." do AssetSync.config.manifest_path.should =~ /public\/assets\/manifest.yml/ end it "config.manifest_path should default to public/assets.." do Rails.application.config.assets.manifest = "/var/assets" AssetSync.config.manifest_path.should == "/var/assets/manifest.yml" end it "config.manifest_path should default to public/custom_assets.." do Rails.application.config.assets.prefix = 'custom_assets' AssetSync.config.manifest_path.should =~ /public\/custom_assets\/manifest.yml/ end end end asset_sync-1.0.0/spec/unit/railsless_spec.rb0000644000004100000410000000375412250226601021171 0ustar www-datawww-datarequire File.dirname(__FILE__) + '/../spec_helper' describe AssetSync do include_context "mock without Rails" describe 'with initializer' do before(:each) do AssetSync.config = AssetSync::Config.new AssetSync.configure do |config| config.fog_provider = 'AWS' config.aws_access_key_id = 'aaaa' config.aws_secret_access_key = 'bbbb' config.fog_directory = 'mybucket' config.fog_region = 'eu-west-1' config.existing_remote_files = "keep" config.prefix = "assets" config.public_path = Pathname("./public") end end it "should have prefix of assets" do AssetSync.config.prefix.should == "assets" end it "should have prefix of assets" do AssetSync.config.public_path.to_s.should == "./public" end it "should default AssetSync to enabled" do AssetSync.config.enabled?.should be_true AssetSync.enabled?.should be_true end it "should configure provider as AWS" do AssetSync.config.fog_provider.should == 'AWS' AssetSync.config.should be_aws end it "should should keep existing remote files" do AssetSync.config.existing_remote_files?.should == true end it "should configure aws_access_key" do AssetSync.config.aws_access_key_id.should == "aaaa" end it "should configure aws_secret_access_key" do AssetSync.config.aws_secret_access_key.should == "bbbb" end it "should configure aws_access_key" do AssetSync.config.fog_directory.should == "mybucket" end it "should configure fog_region" do AssetSync.config.fog_region.should == "eu-west-1" end it "should configure existing_remote_files" do AssetSync.config.existing_remote_files.should == "keep" end it "should default gzip_compression to false" do AssetSync.config.gzip_compression.should be_false end it "should default manifest to false" do AssetSync.config.manifest.should be_false end end end asset_sync-1.0.0/spec/unit/rackspace_spec.rb0000644000004100000410000000477112250226601021124 0ustar www-datawww-datarequire File.dirname(__FILE__) + '/../spec_helper' describe AssetSync do include_context "mock Rails" describe 'using Rackspace with initializer' do before(:each) do set_rails_root('without_yml') AssetSync.config = AssetSync::Config.new AssetSync.configure do |config| config.fog_provider = 'Rackspace' config.fog_directory = 'mybucket' config.fog_region = 'dunno' config.rackspace_username = 'aaaa' config.rackspace_api_key = 'bbbb' config.existing_remote_files = 'keep' end end it "should configure provider as Rackspace" do AssetSync.config.fog_provider.should == 'Rackspace' AssetSync.config.should be_rackspace end it "should keep existing remote files" do AssetSync.config.existing_remote_files?.should == true end it "should configure rackspace_username" do AssetSync.config.rackspace_username.should == "aaaa" end it "should configure rackspace_api_key" do AssetSync.config.rackspace_api_key.should == "bbbb" end it "should configure fog_directory" do AssetSync.config.fog_directory.should == "mybucket" end it "should configure fog_region" do AssetSync.config.fog_region.should == "dunno" end it "should configure existing_remote_files" do AssetSync.config.existing_remote_files.should == "keep" end it "should configure existing_remote_files" do AssetSync.config.existing_remote_files.should == "keep" end it "should default rackspace_auth_url to false" do AssetSync.config.rackspace_auth_url.should be_false end end describe 'using Rackspace from yml' do before(:each) do set_rails_root('rackspace_with_yml') AssetSync.config = AssetSync::Config.new end it "should keep existing remote files" do AssetSync.config.existing_remote_files?.should == true end it "should configure rackspace_username" do AssetSync.config.rackspace_username.should == "xxxx" end it "should configure rackspace_api_key" do AssetSync.config.rackspace_api_key.should == "zzzz" end it "should configure fog_directory" do AssetSync.config.fog_directory.should == "rails_app_test" end it "should configure fog_region" do AssetSync.config.fog_region.should == "eu-west-1" end it "should configure existing_remote_files" do AssetSync.config.existing_remote_files.should == "keep" end end end asset_sync-1.0.0/spec/unit/multi_mime_spec.rb0000644000004100000410000000216012250226601021317 0ustar www-datawww-datarequire File.dirname(__FILE__) + '/../spec_helper' describe AssetSync::MultiMime do before(:each) do Object.send(:remove_const, :Rails) if defined?(Rails) Object.send(:remove_const, :Mime) if defined?(Mime) Object.send(:remove_const, :Rack) if defined?(Rack) end after(:each) do Object.send(:remove_const, :Rails) if defined?(Rails) Object.send(:remove_const, :Mime) if defined?(Mime) Object.send(:remove_const, :Rack) if defined?(Rack) end after(:all) do require 'mime/types' end describe 'Mime::Type' do it 'should detect mime type' do pending "Fails on Travis CI only as of https://travis-ci.org/rumblelabs/asset_sync/builds/4188196" require 'rails' AssetSync::MultiMime.lookup('css').should == "text/css" end end describe 'Rack::Mime' do it 'should detect mime type' do require 'rack/mime' AssetSync::MultiMime.lookup('css').should == "text/css" end end describe 'MIME::Types' do it 'should detect mime type' do require 'mime/types' AssetSync::MultiMime.lookup('css').should == "text/css" end end endasset_sync-1.0.0/spec/unit/asset_sync_spec.rb0000644000004100000410000001505512250226601021340 0ustar www-datawww-datarequire File.dirname(__FILE__) + '/../spec_helper' describe AssetSync do include_context "mock Rails without_yml" describe 'with initializer' do before(:each) do AssetSync.config = AssetSync::Config.new AssetSync.configure do |config| config.fog_provider = 'AWS' config.aws_access_key_id = 'aaaa' config.aws_secret_access_key = 'bbbb' config.fog_directory = 'mybucket' config.fog_region = 'eu-west-1' config.existing_remote_files = "keep" end end it "should default to running on precompile" do AssetSync.config.run_on_precompile.should be_true end it "should default AssetSync to enabled" do AssetSync.config.enabled?.should be_true AssetSync.enabled?.should be_true end it "should configure provider as AWS" do AssetSync.config.fog_provider.should == 'AWS' AssetSync.config.should be_aws end it "should should keep existing remote files" do AssetSync.config.existing_remote_files?.should == true end it "should configure aws_access_key" do AssetSync.config.aws_access_key_id.should == "aaaa" end it "should configure aws_secret_access_key" do AssetSync.config.aws_secret_access_key.should == "bbbb" end it "should configure aws_access_key" do AssetSync.config.fog_directory.should == "mybucket" end it "should configure fog_region" do AssetSync.config.fog_region.should == "eu-west-1" end it "should configure existing_remote_files" do AssetSync.config.existing_remote_files.should == "keep" end it "should default gzip_compression to false" do AssetSync.config.gzip_compression.should be_false end it "should default manifest to false" do AssetSync.config.manifest.should be_false end it "should default log_silently to true" do AssetSync.config.log_silently.should be_true end it "should default cdn_distribution_id to nil" do AssetSync.config.cdn_distribution_id.should be_nil end it "should default invalidate to empty array" do AssetSync.config.invalidate.should == [] end end describe 'from yml' do before(:each) do set_rails_root('aws_with_yml') AssetSync.config = AssetSync::Config.new end it "should default AssetSync to enabled" do AssetSync.config.enabled?.should be_true AssetSync.enabled?.should be_true end it "should configure run_on_precompile" do AssetSync.config.run_on_precompile.should be_false end it "should configure aws_access_key_id" do AssetSync.config.aws_access_key_id.should == "xxxx" end it "should configure aws_secret_access_key" do AssetSync.config.aws_secret_access_key.should == "zzzz" end it "should configure fog_directory" do AssetSync.config.fog_directory.should == "rails_app_test" end it "should configure fog_region" do AssetSync.config.fog_region.should == "eu-west-1" end it "should configure existing_remote_files" do AssetSync.config.existing_remote_files.should == "keep" end it "should default gzip_compression to false" do AssetSync.config.gzip_compression.should be_false end it "should default manifest to false" do AssetSync.config.manifest.should be_false end end describe 'from yml, exporting to a mobile hybrid development directory' do before(:each) do Rails.env.replace('hybrid') set_rails_root('aws_with_yml') AssetSync.config = AssetSync::Config.new end it "should be disabled" do expect{ AssetSync.sync }.not_to raise_error() end after(:each) do Rails.env.replace('test') end end describe 'with no configuration' do before(:each) do AssetSync.config = AssetSync::Config.new end it "should be invalid" do expect{ AssetSync.sync }.to raise_error() end end describe "with no other configuration than enabled = false" do before(:each) do AssetSync.config = AssetSync::Config.new AssetSync.configure do |config| config.enabled = false end end it "should do nothing, without complaining" do expect{ AssetSync.sync }.not_to raise_error() end end describe 'with fail_silent configuration' do before(:each) do AssetSync.stub(:stderr).and_return(@stderr = StringIO.new) AssetSync.config = AssetSync::Config.new AssetSync.configure do |config| config.fail_silently = true end end it "should not raise an invalid exception" do expect{ AssetSync.sync }.not_to raise_error() end it "should output a warning to stderr" do AssetSync.sync @stderr.string.should =~ /can't be blank/ end end describe 'with disabled config' do before(:each) do AssetSync.stub(:stderr).and_return(@stderr = StringIO.new) AssetSync.config = AssetSync::Config.new AssetSync.configure do |config| config.enabled = false end end it "should not raise an invalid exception" do lambda{ AssetSync.sync }.should_not raise_error() end end describe 'with gzip_compression enabled' do before(:each) do AssetSync.config = AssetSync::Config.new AssetSync.config.gzip_compression = true end it "config.gzip? should be true" do AssetSync.config.gzip?.should be_true end end describe 'with manifest enabled' do before(:each) do AssetSync.config = AssetSync::Config.new AssetSync.config.manifest = true end it "config.manifest should be true" do AssetSync.config.manifest.should be_true end it "config.manifest_path should default to public/assets.." do AssetSync.config.manifest_path.should =~ /public\/assets\/manifest.yml/ end it "config.manifest_path should default to public/assets.." do Rails.application.config.assets.manifest = "/var/assets" AssetSync.config.manifest_path.should == "/var/assets/manifest.yml" end it "config.manifest_path should default to public/custom_assets.." do Rails.application.config.assets.prefix = 'custom_assets' AssetSync.config.manifest_path.should =~ /public\/custom_assets\/manifest.yml/ end end describe 'with invalid yml' do before(:each) do set_rails_root('with_invalid_yml') AssetSync.config = AssetSync::Config.new end it "config should be invalid" do AssetSync.config.valid?.should be_false end it "should raise a config invalid error" do expect{ AssetSync.sync }.to raise_error() end end end asset_sync-1.0.0/spec/unit/storage_spec.rb0000644000004100000410000001476612250226601020641 0ustar www-datawww-datarequire File.dirname(__FILE__) + '/../spec_helper' describe AssetSync::Storage do include_context "mock Rails without_yml" describe '#upload_files' do before(:each) do @local_files = ["local_image2.jpg", "local_image1.jpg", "local_stylesheet1.css", "local_stylesheet2.css"] @remote_files = ["local_image.jpg", "local_stylesheet1.css"] @config = AssetSync::Config.new end it 'should overwrite all remote files if set to ignore' do @config.existing_remote_files = 'ignore' storage = AssetSync::Storage.new(@config) storage.stub(:local_files).and_return(@local_files) File.stub(:file?).and_return(true) # Pretend they all exist @local_files.each do |file| storage.should_receive(:upload_file).with(file) end storage.upload_files end it 'should allow force overwriting of specific files' do @config.always_upload = ['local_image.jpg'] storage = AssetSync::Storage.new(@config) storage.stub(:local_files).and_return(@local_files) storage.stub(:get_remote_files).and_return(@remote_files) File.stub(:file?).and_return(true) # Pretend they all exist (@local_files - @remote_files + storage.always_upload_files).each do |file| storage.should_receive(:upload_file).with(file) end storage.upload_files end it 'should allow to ignore files' do @config.ignored_files = ['local_image1.jpg', /local_stylesheet\d\.css/] storage = AssetSync::Storage.new(@config) storage.stub(:local_files).and_return(@local_files) storage.stub(:get_remote_files).and_return(@remote_files) File.stub(:file?).and_return(true) # Pretend they all exist (@local_files - @remote_files - storage.ignored_files + storage.always_upload_files).each do |file| storage.should_receive(:upload_file).with(file) end storage.upload_files end it 'should upload updated non-fingerprinted files' do @local_files = [ 'public/image.png', 'public/image-82389298328.png', 'public/image-a8389f9h324.png', 'public/application.js', 'public/application-b3389d983k1.js', 'public/application-ac387d53f31.js', 'public', ] @remote_files = [ 'public/image.png', 'public/image-a8389f9h324.png', 'public/application.js', 'public/application-b3389d983k1.js', ] storage = AssetSync::Storage.new(@config) storage.stub(:local_files).and_return(@local_files) storage.stub(:get_remote_files).and_return(@remote_files) File.stub(:file?).and_return(true) # Pretend they all exist updated_nonfingerprinted_files = [ 'public/image.png', 'public/application.js', ] (@local_files - @remote_files + updated_nonfingerprinted_files).each do |file| storage.should_receive(:upload_file).with(file) end storage.upload_files end it 'should correctly set expire date' do local_files = ['file1.jpg', 'file1-1234567890abcdef1234567890abcdef.jpg'] local_files += ['dir1/dir2/file2.jpg', 'dir1/dir2/file2-1234567890abcdef1234567890abcdef.jpg'] remote_files = [] storage = AssetSync::Storage.new(@config) storage.stub(:local_files).and_return(local_files) storage.stub(:get_remote_files).and_return(remote_files) File.stub(:file?).and_return(true) File.stub(:open).and_return(nil) def check_file(file) case file[:key] when 'file1.jpg' when 'dir1/dir2/file2.jpg' !file.should_not include(:cache_control, :expires) when 'file1-1234567890abcdef1234567890abcdef.jpg' when 'dir1/dir2/file2-1234567890abcdef1234567890abcdef.jpg' file.should include(:cache_control, :expires) else fail end end files = double() local_files.count.times do files.should_receive(:create) { |file| check_file(file) } end storage.stub_chain(:bucket, :files).and_return(files) storage.upload_files end it "shoud invalidate files" do @config.cdn_distribution_id = "1234" @config.invalidate = ['local_image1.jpg'] @config.fog_provider = 'AWS' storage = AssetSync::Storage.new(@config) storage.stub(:local_files).and_return(@local_files) storage.stub(:get_remote_files).and_return(@remote_files) storage.stub(:upload_file).and_return(true) mock_cdn = mock Fog::CDN.should_receive(:new).and_return(mock_cdn) mock_cdn.should_receive(:post_invalidation).with("1234", ["/assets/local_image1.jpg"]).and_return(stub({:body => {:id => '1234'}})) storage.upload_files end end describe '#upload_file' do before(:each) do # Object#remove_const does not remove the loaded # file from the $" variable Object.send(:remove_const, :MIME) if defined?(MIME) mime_types = $".grep(/mime\/types/).first $".delete(mime_types) require 'mime/types' @config = AssetSync::Config.new end it 'accepts custom headers per file' do @config.custom_headers = { "local_image2.jpg" => { :cache_control => 'max-age=0' } } storage = AssetSync::Storage.new(@config) storage.stub(:local_files).and_return(@local_files) storage.stub(:get_remote_files).and_return(@remote_files) File.stub(:open).and_return('file') # Pretend they all exist bucket = double files = double storage.stub(:bucket).and_return(bucket) bucket.stub(:files).and_return(files) files.should_receive(:create) do |argument| argument[:cache_control].should == 'max-age=0' end storage.upload_file('assets/local_image2.jpg') end it 'accepts custom headers with a regular expression' do @config.custom_headers = { ".*\.jpg" => { :cache_control => 'max-age=0' } } storage = AssetSync::Storage.new(@config) storage.stub(:local_files).and_return(@local_files) storage.stub(:get_remote_files).and_return(@remote_files) File.stub(:open).and_return('file') # Pretend they all exist bucket = mock files = mock storage.stub(:bucket).and_return(bucket) bucket.stub(:files).and_return(files) files.should_receive(:create) do |argument| argument[:cache_control].should == 'max-age=0' end storage.upload_file('assets/some_longer_path/local_image2.jpg') end after(:each) do Object.send(:remove_const, :MIME) if defined?(MIME) end end end asset_sync-1.0.0/.travis.yml0000644000004100000410000000204512250226601016021 0ustar www-datawww-datalanguage: ruby rvm: - 1.9.2 - 1.9.3 - jruby-19mode - rbx-19mode - ruby-head - jruby-head gemfile: - gemfiles/rails_3.1.gemfile - gemfiles/rails_3.2.gemfile before_install: - gem install bundler env: global: - FOG_DIRECTORY=asset-sync-travis - FOG_PROVIDER=AWS - secure: "dy8Fqlg3b1ZMK1BY5z6NMQLbzAVd7GWVYY0MeCQALz76zRac0z8MyU8hkv6h\nozFry7DSdbGehGT9foOnkWTwzGzf1rzdd5cmWrUPk1wDTRgMM9SrwodPj1TU\nzsq2EFx0a79vADQN8JXkpLC1YD6kEb9aWkTxrIT9KBgw+J5H32o=" - secure: "Hmx7D7/p2LlA2ya/xBIz21s/8MLIQCjvfYB7RWBNlWk1PfqRLAz8wX6TUVWy\nfAFktMjLnpRLRYO7AgQS4jcfQ/k0HYK9IXzqXzeI00TNm0Vwp0TCXhawiOFT\nSvUMhs2/1vRfjN0HOJ75XlWRhJzV/G5rOMiafAZLsVzN/0iiB8g=" matrix: include: - rvm: 1.9.3 gemfile: gemfiles/rails_4.0.gemfile - rvm: jruby-19mode gemfile: gemfiles/rails_4.0.gemfile - rvm: rbx-19mode gemfile: gemfiles/rails_4.0.gemfile - rvm: 2.0.0 gemfile: gemfiles/rails_3.2.gemfile - rvm: 2.0.0 gemfile: gemfiles/rails_4.0.gemfile allow_failures: - rvm: ruby-head - rvm: jruby-head asset_sync-1.0.0/lib/0000755000004100000410000000000012250226601014455 5ustar www-datawww-dataasset_sync-1.0.0/lib/asset_sync/0000755000004100000410000000000012250226601016630 5ustar www-datawww-dataasset_sync-1.0.0/lib/asset_sync/engine.rb0000644000004100000410000000525212250226601020426 0ustar www-datawww-datamodule AssetSync class Engine < Rails::Engine engine_name "asset_sync" initializer "asset_sync config", :group => :all do |app| app_initializer = Rails.root.join('config', 'initializers', 'asset_sync.rb').to_s app_yaml = Rails.root.join('config', 'asset_sync.yml').to_s if File.exists?( app_initializer ) AssetSync.log "AssetSync: using #{app_initializer}" load app_initializer elsif !File.exists?( app_initializer ) && !File.exists?( app_yaml ) AssetSync.log "AssetSync: using default configuration from built-in initializer" AssetSync.configure do |config| config.fog_provider = ENV['FOG_PROVIDER'] if ENV.has_key?('FOG_PROVIDER') config.fog_directory = ENV['FOG_DIRECTORY'] if ENV.has_key?('FOG_DIRECTORY') config.fog_region = ENV['FOG_REGION'] if ENV.has_key?('FOG_REGION') config.aws_access_key_id = ENV['AWS_ACCESS_KEY_ID'] if ENV.has_key?('AWS_ACCESS_KEY_ID') config.aws_secret_access_key = ENV['AWS_SECRET_ACCESS_KEY'] if ENV.has_key?('AWS_SECRET_ACCESS_KEY') config.aws_reduced_redundancy = ENV['AWS_REDUCED_REDUNDANCY'] == true if ENV.has_key?('AWS_REDUCED_REDUNDANCY') config.rackspace_username = ENV['RACKSPACE_USERNAME'] if ENV.has_key?('RACKSPACE_USERNAME') config.rackspace_api_key = ENV['RACKSPACE_API_KEY'] if ENV.has_key?('RACKSPACE_API_KEY') config.google_storage_access_key_id = ENV['GOOGLE_STORAGE_ACCESS_KEY_ID'] if ENV.has_key?('GOOGLE_STORAGE_ACCESS_KEY_ID') config.google_storage_secret_access_key = ENV['GOOGLE_STORAGE_SECRET_ACCESS_KEY'] if ENV.has_key?('GOOGLE_STORAGE_SECRET_ACCESS_KEY') config.enabled = (ENV['ASSET_SYNC_ENABLED'] == 'true') if ENV.has_key?('ASSET_SYNC_ENABLED') config.existing_remote_files = ENV['ASSET_SYNC_EXISTING_REMOTE_FILES'] || "keep" config.gzip_compression = (ENV['ASSET_SYNC_GZIP_COMPRESSION'] == 'true') if ENV.has_key?('ASSET_SYNC_GZIP_COMPRESSION') config.manifest = (ENV['ASSET_SYNC_MANIFEST'] == 'true') if ENV.has_key?('ASSET_SYNC_MANIFEST') end config.prefix = ENV['ASSET_SYNC_PREFIX'] if ENV.has_key?('ASSET_SYNC_PREFIX') config.existing_remote_files = ENV['ASSET_SYNC_EXISTING_REMOTE_FILES'] || "keep" config.gzip_compression = (ENV['ASSET_SYNC_GZIP_COMPRESSION'] == 'true') if ENV.has_key?('ASSET_SYNC_GZIP_COMPRESSION') config.manifest = (ENV['ASSET_SYNC_MANIFEST'] == 'true') if ENV.has_key?('ASSET_SYNC_MANIFEST') end if File.exists?( app_yaml ) AssetSync.log "AssetSync: YAML file found #{app_yaml} settings will be merged into the configuration" end end end end asset_sync-1.0.0/lib/asset_sync/version.rb0000644000004100000410000000005112250226601020636 0ustar www-datawww-datamodule AssetSync VERSION = "1.0.0" end asset_sync-1.0.0/lib/asset_sync/config.rb0000644000004100000410000001660212250226601020427 0ustar www-datawww-datamodule AssetSync class Config include ActiveModel::Validations class Invalid < StandardError; end # AssetSync attr_accessor :existing_remote_files # What to do with your existing remote files? (keep or delete) attr_accessor :gzip_compression attr_accessor :manifest attr_accessor :fail_silently attr_accessor :log_silently attr_accessor :always_upload attr_accessor :ignored_files attr_accessor :prefix attr_accessor :public_path attr_accessor :enabled attr_accessor :custom_headers attr_accessor :run_on_precompile attr_accessor :invalidate attr_accessor :cdn_distribution_id # FOG configuration attr_accessor :fog_provider # Currently Supported ['AWS', 'Rackspace'] attr_accessor :fog_directory # e.g. 'the-bucket-name' attr_accessor :fog_region # e.g. 'eu-west-1' # Amazon AWS attr_accessor :aws_access_key_id, :aws_secret_access_key, :aws_reduced_redundancy # Rackspace attr_accessor :rackspace_username, :rackspace_api_key, :rackspace_auth_url # Google Storage attr_accessor :google_storage_secret_access_key, :google_storage_access_key_id validates :existing_remote_files, :inclusion => { :in => %w(keep delete ignore) } validates :fog_provider, :presence => true validates :fog_directory, :presence => true validates :aws_access_key_id, :presence => true, :if => :aws? validates :aws_secret_access_key, :presence => true, :if => :aws? validates :rackspace_username, :presence => true, :if => :rackspace? validates :rackspace_api_key, :presence => true, :if => :rackspace? validates :google_storage_secret_access_key, :presence => true, :if => :google? validates :google_storage_access_key_id, :presence => true, :if => :google? def initialize self.fog_region = nil self.existing_remote_files = 'keep' self.gzip_compression = false self.manifest = false self.fail_silently = false self.log_silently = true self.always_upload = [] self.ignored_files = [] self.custom_headers = {} self.enabled = true self.run_on_precompile = true self.cdn_distribution_id = nil self.invalidate = [] load_yml! if defined?(Rails) && yml_exists? end def manifest_path directory = Rails.application.config.assets.manifest || default_manifest_directory File.join(directory, "manifest.yml") end def gzip? self.gzip_compression end def existing_remote_files? ['keep', 'ignore'].include?(self.existing_remote_files) end def aws? fog_provider == 'AWS' end def aws_rrs? aws_reduced_redundancy == true end def fail_silently? fail_silently || !enabled? end def log_silently? ENV['RAILS_GROUPS'] == 'assets' || self.log_silently == false end def enabled? enabled == true end def rackspace? fog_provider == 'Rackspace' end def google? fog_provider == 'Google' end def yml_exists? defined?(Rails.root) ? File.exists?(self.yml_path) : false end def yml begin @yml ||= YAML.load(ERB.new(IO.read(yml_path)).result)[Rails.env] rescue nil || {} rescue Psych::SyntaxError @yml = {} end end def yml_path Rails.root.join("config", "asset_sync.yml").to_s end def assets_prefix # Fix for Issue #38 when Rails.config.assets.prefix starts with a slash self.prefix || Rails.application.config.assets.prefix.sub(/^\//, '') end def public_path @public_path || Rails.public_path end def load_yml! self.enabled = yml["enabled"] if yml.has_key?('enabled') self.fog_provider = yml["fog_provider"] self.fog_directory = yml["fog_directory"] self.fog_region = yml["fog_region"] self.aws_access_key_id = yml["aws_access_key_id"] self.aws_secret_access_key = yml["aws_secret_access_key"] self.aws_reduced_redundancy = yml["aws_reduced_redundancy"] self.rackspace_username = yml["rackspace_username"] self.rackspace_auth_url = yml["rackspace_auth_url"] if yml.has_key?("rackspace_auth_url") self.rackspace_api_key = yml["rackspace_api_key"] self.google_storage_secret_access_key = yml["google_storage_secret_access_key"] self.google_storage_access_key_id = yml["google_storage_access_key_id"] self.existing_remote_files = yml["existing_remote_files"] if yml.has_key?("existing_remote_files") self.gzip_compression = yml["gzip_compression"] if yml.has_key?("gzip_compression") self.manifest = yml["manifest"] if yml.has_key?("manifest") self.fail_silently = yml["fail_silently"] if yml.has_key?("fail_silently") self.always_upload = yml["always_upload"] if yml.has_key?("always_upload") self.ignored_files = yml["ignored_files"] if yml.has_key?("ignored_files") self.custom_headers = yml["custom_headers"] if yml.has_key?("custom_headers") self.run_on_precompile = yml["run_on_precompile"] if yml.has_key?("run_on_precompile") self.invalidate = yml["invalidate"] if yml.has_key?("invalidate") self.cdn_distribution_id = yml['cdn_distribution_id'] if yml.has_key?("cdn_distribution_id") # TODO deprecate the other old style config settings. FML. self.aws_access_key_id = yml["aws_access_key"] if yml.has_key?("aws_access_key") self.aws_secret_access_key = yml["aws_access_secret"] if yml.has_key?("aws_access_secret") self.fog_directory = yml["aws_bucket"] if yml.has_key?("aws_bucket") self.fog_region = yml["aws_region"] if yml.has_key?("aws_region") # TODO deprecate old style config settings self.aws_access_key_id = yml["access_key_id"] if yml.has_key?("access_key_id") self.aws_secret_access_key = yml["secret_access_key"] if yml.has_key?("secret_access_key") self.fog_directory = yml["bucket"] if yml.has_key?("bucket") self.fog_region = yml["region"] if yml.has_key?("region") self.public_path = yml["public_path"] if yml.has_key?("public_path") end def fog_options options = { :provider => fog_provider } if aws? options.merge!({ :aws_access_key_id => aws_access_key_id, :aws_secret_access_key => aws_secret_access_key }) elsif rackspace? options.merge!({ :rackspace_username => rackspace_username, :rackspace_api_key => rackspace_api_key }) options.merge!({ :rackspace_region => fog_region }) if fog_region options.merge!({ :rackspace_auth_url => rackspace_auth_url }) if rackspace_auth_url elsif google? options.merge!({ :google_storage_secret_access_key => google_storage_secret_access_key, :google_storage_access_key_id => google_storage_access_key_id }) else raise ArgumentError, "AssetSync Unknown provider: #{fog_provider} only AWS and Rackspace are supported currently." end options.merge!({:region => fog_region}) if fog_region && !rackspace? return options end private def default_manifest_directory File.join(Rails.public_path, assets_prefix) end end end asset_sync-1.0.0/lib/asset_sync/asset_sync.rb0000644000004100000410000000225712250226601021336 0ustar www-datawww-datamodule AssetSync class << self def config=(data) @config = data end def config @config ||= Config.new @config end def reset_config! remove_instance_variable :@config if defined?(@config) end def configure(&proc) @config ||= Config.new yield @config end def storage @storage ||= Storage.new(self.config) end def sync with_config do self.storage.sync end end def clean with_config do self.storage.delete_extra_remote_files end end def with_config(&block) return unless AssetSync.enabled? errors = config.valid? ? "" : config.errors.full_messages.join(', ') if !(config && config.valid?) if config.fail_silently? self.warn(errors) else raise Config::Invalid.new(errors) end else block.call end end def warn(msg) stderr.puts msg end def log(msg) stdout.puts msg if config.log_silently? end def enabled? config.enabled? end # easier to stub def stderr ; STDERR ; end def stdout ; STDOUT ; end end end asset_sync-1.0.0/lib/asset_sync/multi_mime.rb0000644000004100000410000000050512250226601021316 0ustar www-datawww-datamodule AssetSync class MultiMime def self.lookup(ext) if defined?(Mime::Type) Mime::Type.lookup_by_extension(ext) elsif defined?(Rack::Mime) ext_with_dot = ".#{ext}" Rack::Mime.mime_type(ext_with_dot) else MIME::Types.type_for(ext).first end end end endasset_sync-1.0.0/lib/asset_sync/railtie.rb0000644000004100000410000000012312250226601020602 0ustar www-datawww-dataclass Rails::Railtie::Configuration def asset_sync AssetSync.config end endasset_sync-1.0.0/lib/asset_sync/storage.rb0000644000004100000410000002042612250226601020625 0ustar www-datawww-datamodule AssetSync class Storage REGEXP_FINGERPRINTED_FILES = /^(.*)\/([^-]+)-[^\.]+\.([^\.]+)$/ class BucketNotFound < StandardError; end attr_accessor :config def initialize(cfg) @config = cfg end def connection @connection ||= Fog::Storage.new(self.config.fog_options) end def bucket # fixes: https://github.com/rumblelabs/asset_sync/issues/18 @bucket ||= connection.directories.get(self.config.fog_directory, :prefix => self.config.assets_prefix) end def log(msg) AssetSync.log(msg) end def keep_existing_remote_files? self.config.existing_remote_files? end def path self.config.public_path end def ignored_files files = [] Array(self.config.ignored_files).each do |ignore| case ignore when Regexp files += self.local_files.select do |file| file =~ ignore end when String files += self.local_files.select do |file| file.split('/').last == ignore end else log "Error: please define ignored_files as string or regular expression. #{ignore} (#{ignore.class}) ignored." end end files.uniq end def local_files @local_files ||= get_local_files.uniq end def always_upload_files self.config.always_upload.map { |f| File.join(self.config.assets_prefix, f) } end def files_with_custom_headers self.config.custom_headers.inject({}) { |h,(k, v)| h[File.join(self.config.assets_prefix, k)] = v; h; } end def files_to_invalidate self.config.invalidate.map { |filename| File.join("/", self.config.assets_prefix, filename) } end def get_local_files if self.config.manifest if ActionView::Base.respond_to?(:assets_manifest) log "Using: Rails 4.0 manifest access" manifest = Sprockets::Manifest.new(ActionView::Base.assets_manifest.environment, ActionView::Base.assets_manifest.dir) return manifest.assets.values.map { |f| File.join(self.config.assets_prefix, f) } elsif File.exists?(self.config.manifest_path) log "Using: Manifest #{self.config.manifest_path}" yml = YAML.load(IO.read(self.config.manifest_path)) return yml.map do |original, compiled| # Upload font originals and compiled if original =~ /^.+(eot|svg|ttf|woff)$/ [original, compiled] else compiled end end.flatten.map { |f| File.join(self.config.assets_prefix, f) }.uniq! else log "Warning: Manifest could not be found" end end log "Using: Directory Search of #{path}/#{self.config.assets_prefix}" Dir.chdir(path) do Dir["#{self.config.assets_prefix}/**/**"] end end def get_remote_files raise BucketNotFound.new("#{self.config.fog_provider} Bucket: #{self.config.fog_directory} not found.") unless bucket # fixes: https://github.com/rumblelabs/asset_sync/issues/16 # (work-around for https://github.com/fog/fog/issues/596) files = [] bucket.files.each { |f| files << f.key } return files end def delete_file(f, remote_files_to_delete) if remote_files_to_delete.include?(f.key) log "Deleting: #{f.key}" f.destroy end end def delete_extra_remote_files log "Fetching files to flag for delete" remote_files = get_remote_files # fixes: https://github.com/rumblelabs/asset_sync/issues/19 from_remote_files_to_delete = remote_files - local_files - ignored_files - always_upload_files log "Flagging #{from_remote_files_to_delete.size} file(s) for deletion" # Delete unneeded remote files bucket.files.each do |f| delete_file(f, from_remote_files_to_delete) end end def upload_file(f) # TODO output files in debug logs as asset filename only. one_year = 31557600 ext = File.extname(f)[1..-1] mime = MultiMime.lookup(ext) file = { :key => f, :body => File.open("#{path}/#{f}"), :public => true, :content_type => mime } if /-[0-9a-fA-F]{32}$/.match(File.basename(f,File.extname(f))) file.merge!({ :cache_control => "public, max-age=#{one_year}", :expires => CGI.rfc1123_date(Time.now + one_year) }) end # overwrite headers if applicable, you probably shouldn't specific key/body, but cache-control headers etc. if files_with_custom_headers.has_key? f file.merge! files_with_custom_headers[f] log "Overwriting #{f} with custom headers #{files_with_custom_headers[f].to_s}" elsif key = self.config.custom_headers.keys.detect {|k| f.match(Regexp.new(k))} headers = {} self.config.custom_headers[key].each do |key, value| headers[key.to_sym] = value end file.merge! headers log "Overwriting matching file #{f} with custom headers #{headers.to_s}" end gzipped = "#{path}/#{f}.gz" ignore = false if config.gzip? && File.extname(f) == ".gz" # Don't bother uploading gzipped assets if we are in gzip_compression mode # as we will overwrite file.css with file.css.gz if it exists. log "Ignoring: #{f}" ignore = true elsif config.gzip? && File.exists?(gzipped) original_size = File.size("#{path}/#{f}") gzipped_size = File.size(gzipped) if gzipped_size < original_size percentage = ((gzipped_size.to_f/original_size.to_f)*100).round(2) file.merge!({ :key => f, :body => File.open(gzipped), :content_encoding => 'gzip' }) log "Uploading: #{gzipped} in place of #{f} saving #{percentage}%" else percentage = ((original_size.to_f/gzipped_size.to_f)*100).round(2) log "Uploading: #{f} instead of #{gzipped} (compression increases this file by #{percentage}%)" end else if !config.gzip? && File.extname(f) == ".gz" # set content encoding for gzipped files this allows cloudfront to properly handle requests with Accept-Encoding # http://docs.amazonwebservices.com/AmazonCloudFront/latest/DeveloperGuide/ServingCompressedFiles.html uncompressed_filename = f[0..-4] ext = File.extname(uncompressed_filename)[1..-1] mime = MultiMime.lookup(ext) file.merge!({ :content_type => mime, :content_encoding => 'gzip' }) end log "Uploading: #{f}" end if config.aws? && config.aws_rrs? file.merge!({ :storage_class => 'REDUCED_REDUNDANCY' }) end file = bucket.files.create( file ) unless ignore end def upload_files # get a fresh list of remote files remote_files = ignore_existing_remote_files? ? [] : get_remote_files # fixes: https://github.com/rumblelabs/asset_sync/issues/19 local_files_to_upload = local_files - ignored_files - remote_files + always_upload_files local_files_to_upload = (local_files_to_upload + get_non_fingerprinted(local_files_to_upload)).uniq # Upload new files local_files_to_upload.each do |f| next unless File.file? "#{path}/#{f}" # Only files. upload_file f end if self.config.cdn_distribution_id && files_to_invalidate.any? log "Invalidating Files" cdn ||= Fog::CDN.new(self.config.fog_options.except(:region)) data = cdn.post_invalidation(self.config.cdn_distribution_id, files_to_invalidate) log "Invalidation id: #{data.body["Id"]}" end end def sync # fixes: https://github.com/rumblelabs/asset_sync/issues/19 log "AssetSync: Syncing." upload_files delete_extra_remote_files unless keep_existing_remote_files? log "AssetSync: Done." end private def ignore_existing_remote_files? self.config.existing_remote_files == 'ignore' end def get_non_fingerprinted(files) files.map do |file| match_data = file.match(REGEXP_FINGERPRINTED_FILES) match_data && "#{match_data[1]}/#{match_data[2]}.#{match_data[3]}" end.compact end end end asset_sync-1.0.0/lib/generators/0000755000004100000410000000000012250226601016626 5ustar www-datawww-dataasset_sync-1.0.0/lib/generators/asset_sync/0000755000004100000410000000000012250226601021001 5ustar www-datawww-dataasset_sync-1.0.0/lib/generators/asset_sync/templates/0000755000004100000410000000000012250226601022777 5ustar www-datawww-dataasset_sync-1.0.0/lib/generators/asset_sync/templates/asset_sync.yml0000644000004100000410000000255012250226601025677 0ustar www-datawww-datadefaults: &defaults <%- if aws? -%> fog_provider: 'AWS' aws_access_key_id: "<%= aws_access_key_id %>" aws_secret_access_key: "<%= aws_secret_access_key %>" # To use AWS reduced redundancy storage. # aws_reduced_redundancy: true <%- elsif google? -%> fog_provider: 'Google' google_storage_access_key_id: "<%= google_storage_access_key_id %>" google_storage_secret_access_key: "<%= google_storage_secret_access_key %>" <%- elsif rackspace? -%> fog_provider: 'Rackspace' rackspace_username: "<%= rackspace_username %>" rackspace_api_key: "<%= rackspace_api_key %>" # if you need to change rackspace_auth_url (e.g. if you need to use Rackspace London) # rackspace_auth_url: "https://lon.identity.api.rackspacecloud.com/v2.0" <%- end -%> fog_directory: "<%= app_name %>-assets" # You may need to specify what region your storage bucket is in # fog_region: "eu-west-1" existing_remote_files: keep # To delete existing remote files. # existing_remote_files: delete # Automatically replace files with their equivalent gzip compressed version # gzip_compression: true # Fail silently. Useful for environments such as Heroku # fail_silently: true development: <<: *defaults enabled: false test: <<: *defaults enabled: false staging: <<: *defaults fog_directory: "<%= app_name %>-staging-assets" production: <<: *defaults asset_sync-1.0.0/lib/generators/asset_sync/templates/asset_sync.rb0000644000004100000410000000305212250226601025477 0ustar www-datawww-dataAssetSync.configure do |config| <%- if aws? -%> config.fog_provider = 'AWS' config.aws_access_key_id = ENV['AWS_ACCESS_KEY_ID'] config.aws_secret_access_key = ENV['AWS_SECRET_ACCESS_KEY'] # To use AWS reduced redundancy storage. # config.aws_reduced_redundancy = true <%- elsif google? -%> config.fog_provider = 'Google' config.google_storage_access_key_id = ENV['GOOGLE_STORAGE_ACCESS_KEY_ID'] config.google_storage_secret_access_key = ENV['GOOGLE_STORAGE_SECRET_ACCESS_KEY'] <%- elsif rackspace? -%> config.fog_provider = 'Rackspace' config.rackspace_username = ENV['RACKSPACE_USERNAME'] config.rackspace_api_key = ENV['RACKSPACE_API_KEY'] # if you need to change rackspace_auth_url (e.g. if you need to use Rackspace London) # config.rackspace_auth_url = "lon.auth.api.rackspacecloud.com" <%- end -%> config.fog_directory = ENV['FOG_DIRECTORY'] # Invalidate a file on a cdn after uploading files # config.cdn_distribution_id = "12345" # config.invalidate = ['file1.js'] # Increase upload performance by configuring your region # config.fog_region = 'eu-west-1' # # Don't delete files from the store # config.existing_remote_files = "keep" # # Automatically replace files with their equivalent gzip compressed version # config.gzip_compression = true # # Use the Rails generated 'manifest.yml' file to produce the list of files to # upload instead of searching the assets directory. # config.manifest = true # # Fail silently. Useful for environments such as Heroku # config.fail_silently = true end asset_sync-1.0.0/lib/generators/asset_sync/install_generator.rb0000644000004100000410000000333712250226601025050 0ustar www-datawww-datarequire 'rails/generators' module AssetSync class InstallGenerator < Rails::Generators::Base desc "Install a config/asset_sync.yml and the asset:precompile rake task enhancer" # Commandline options can be defined here using Thor-like options: class_option :use_yml, :type => :boolean, :default => false, :desc => "Use YML file instead of Rails Initializer" class_option :provider, :type => :string, :default => "AWS", :desc => "Generate with support for 'AWS', 'Rackspace', or 'Google'" def self.source_root @source_root ||= File.join(File.dirname(__FILE__), 'templates') end def aws? options[:provider] == 'AWS' end def google? options[:provider] == 'Google' end def rackspace? options[:provider] == 'Rackspace' end def aws_access_key_id "<%= ENV['AWS_ACCESS_KEY_ID'] %>" end def aws_secret_access_key "<%= ENV['AWS_SECRET_ACCESS_KEY'] %>" end def google_storage_access_key_id "<%= ENV['GOOGLE_STORAGE_ACCESS_KEY_ID'] %>" end def google_storage_secret_access_key "<%= ENV['GOOGLE_STORAGE_SECRET_ACCESS_KEY'] %>" end def rackspace_username "<%= ENV['RACKSPACE_USERNAME'] %>" end def rackspace_api_key "<%= ENV['RACKSPACE_API_KEY'] %>" end def app_name @app_name ||= Rails.application.is_a?(Rails::Application) && Rails.application.class.name.sub(/::Application$/, "").downcase end def generate_config if options[:use_yml] template "asset_sync.yml", "config/asset_sync.yml" end end def generate_initializer unless options[:use_yml] template "asset_sync.rb", "config/initializers/asset_sync.rb" end end end end asset_sync-1.0.0/lib/tasks/0000755000004100000410000000000012250226601015602 5ustar www-datawww-dataasset_sync-1.0.0/lib/tasks/asset_sync.rake0000644000004100000410000000212112250226601020615 0ustar www-datawww-datanamespace :assets do desc 'Synchronize assets to remote (assumes assets are already compiled)' task :sync => :environment do AssetSync.sync end namespace :sync do desc 'Delete out-of-sync files on remote' task :clean => :environment do AssetSync.clean end end end if Rake::Task.task_defined?("assets:precompile:nondigest") Rake::Task["assets:precompile:nondigest"].enhance do # Conditional execution needs to be inside the enhance block because the enhance block # will get executed before yaml or Rails initializers. Rake::Task["assets:sync"].invoke if defined?(AssetSync) && AssetSync.config.run_on_precompile end else Rake::Task["assets:precompile"].enhance do # rails 3.1.1 will clear out Rails.application.config if the env vars # RAILS_GROUP and RAILS_ENV are not defined. We need to reload the # assets environment in this case. # Rake::Task["assets:environment"].invoke if Rake::Task.task_defined?("assets:environment") Rake::Task["assets:sync"].invoke if defined?(AssetSync) && AssetSync.config.run_on_precompile end end asset_sync-1.0.0/lib/asset_sync.rb0000644000004100000410000000041612250226601017156 0ustar www-datawww-datarequire 'fog' require 'active_model' require 'erb' require "asset_sync/asset_sync" require 'asset_sync/config' require 'asset_sync/storage' require 'asset_sync/multi_mime' require 'asset_sync/railtie' if defined?(Rails) require 'asset_sync/engine' if defined?(Rails) asset_sync-1.0.0/asset_sync.gemspec0000644000004100000410000000246012250226601017431 0ustar www-datawww-data# -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) require "asset_sync/version" Gem::Specification.new do |s| s.name = "asset_sync" s.version = AssetSync::VERSION s.date = "2013-08-26" s.platform = Gem::Platform::RUBY s.authors = ["Simon Hamilton", "David Rice", "Phil McClure"] s.email = ["shamilton@rumblelabs.com", "me@davidjrice.co.uk", "pmcclure@rumblelabs.com"] s.homepage = "https://github.com/rumblelabs/asset_sync" s.summary = %q{Synchronises Assets in a Rails 3 application and Amazon S3/Cloudfront and Rackspace Cloudfiles} s.description = %q{After you run assets:precompile your compiled assets will be synchronised with your S3 bucket.} s.rubyforge_project = "asset_sync" s.add_dependency('fog', ">= 1.8.0") s.add_dependency('activemodel') s.add_development_dependency "rspec" s.add_development_dependency "bundler" s.add_development_dependency "jeweler" s.add_development_dependency "uglifier" s.add_development_dependency "asset_sync" s.add_development_dependency "appraisal" s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } s.require_paths = ["lib"] end asset_sync-1.0.0/gemfiles/0000755000004100000410000000000012250226601015502 5ustar www-datawww-dataasset_sync-1.0.0/gemfiles/rails_3.2.gemfile0000644000004100000410000000052212250226601020527 0ustar www-datawww-data# This file was generated by Appraisal source "https://rubygems.org" gem "rcov", :platforms=>:mri_18, :group=>[:development, :test] gem "simplecov", :platforms=>[:jruby, :mri_19, :ruby_19, :mri_20, :rbx], :group=>[:development, :test], :require=>false gem "jruby-openssl", :platform=>:jruby gem "rails", "~> 3.2.0" gemspec :path=>"../"asset_sync-1.0.0/gemfiles/rails_3.1.gemfile0000644000004100000410000000052212250226601020526 0ustar www-datawww-data# This file was generated by Appraisal source "https://rubygems.org" gem "rcov", :platforms=>:mri_18, :group=>[:development, :test] gem "simplecov", :platforms=>[:jruby, :mri_19, :ruby_19, :mri_20, :rbx], :group=>[:development, :test], :require=>false gem "jruby-openssl", :platform=>:jruby gem "rails", "~> 3.1.0" gemspec :path=>"../"asset_sync-1.0.0/gemfiles/rails_4.0.gemfile0000644000004100000410000000052212250226601020526 0ustar www-datawww-data# This file was generated by Appraisal source "https://rubygems.org" gem "rcov", :platforms=>:mri_18, :group=>[:development, :test] gem "simplecov", :platforms=>[:jruby, :mri_19, :ruby_19, :mri_20, :rbx], :group=>[:development, :test], :require=>false gem "jruby-openssl", :platform=>:jruby gem "rails", "~> 4.0.0" gemspec :path=>"../"asset_sync-1.0.0/metadata.yml0000644000004100000410000001401412250226601016212 0ustar www-datawww-data--- !ruby/object:Gem::Specification name: asset_sync version: !ruby/object:Gem::Version version: 1.0.0 prerelease: platform: ruby authors: - Simon Hamilton - David Rice - Phil McClure autorequire: bindir: bin cert_chain: [] date: 2013-08-26 00:00:00.000000000 Z dependencies: - !ruby/object:Gem::Dependency name: fog requirement: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: 1.8.0 type: :runtime prerelease: false version_requirements: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: 1.8.0 - !ruby/object:Gem::Dependency name: activemodel requirement: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: '0' type: :runtime prerelease: false version_requirements: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: '0' - !ruby/object:Gem::Dependency name: rspec requirement: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: '0' type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: '0' - !ruby/object:Gem::Dependency name: bundler requirement: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: '0' type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: '0' - !ruby/object:Gem::Dependency name: jeweler requirement: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: '0' type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: '0' - !ruby/object:Gem::Dependency name: uglifier requirement: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: '0' type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: '0' - !ruby/object:Gem::Dependency name: asset_sync requirement: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: '0' type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: '0' - !ruby/object:Gem::Dependency name: appraisal requirement: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: '0' type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: '0' description: After you run assets:precompile your compiled assets will be synchronised with your S3 bucket. email: - shamilton@rumblelabs.com - me@davidjrice.co.uk - pmcclure@rumblelabs.com executables: [] extensions: [] extra_rdoc_files: [] files: - .gitignore - .travis.yml - Appraisals - CHANGELOG.md - Gemfile - README.md - Rakefile - asset_sync.gemspec - docs/heroku.md - gemfiles/rails_3.1.gemfile - gemfiles/rails_3.2.gemfile - gemfiles/rails_4.0.gemfile - lib/asset_sync.rb - lib/asset_sync/asset_sync.rb - lib/asset_sync/config.rb - lib/asset_sync/engine.rb - lib/asset_sync/multi_mime.rb - lib/asset_sync/railtie.rb - lib/asset_sync/storage.rb - lib/asset_sync/version.rb - lib/generators/asset_sync/install_generator.rb - lib/generators/asset_sync/templates/asset_sync.rb - lib/generators/asset_sync/templates/asset_sync.yml - lib/tasks/asset_sync.rake - spec/dummy_app/Rakefile - spec/dummy_app/app/assets/javascripts/application.js - spec/fixtures/aws_with_yml/config/asset_sync.yml - spec/fixtures/google_with_yml/config/asset_sync.yml - spec/fixtures/rackspace_with_yml/config/asset_sync.yml - spec/fixtures/with_invalid_yml/config/asset_sync.yml - spec/integration/aws_integration_spec.rb - spec/spec_helper.rb - spec/unit/asset_sync_spec.rb - spec/unit/google_spec.rb - spec/unit/multi_mime_spec.rb - spec/unit/rackspace_spec.rb - spec/unit/railsless_spec.rb - spec/unit/storage_spec.rb homepage: https://github.com/rumblelabs/asset_sync licenses: [] post_install_message: rdoc_options: [] require_paths: - lib required_ruby_version: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: '0' segments: - 0 hash: -395743351028852648 required_rubygems_version: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: '0' segments: - 0 hash: -395743351028852648 requirements: [] rubyforge_project: asset_sync rubygems_version: 1.8.24 signing_key: specification_version: 3 summary: Synchronises Assets in a Rails 3 application and Amazon S3/Cloudfront and Rackspace Cloudfiles test_files: - spec/dummy_app/Rakefile - spec/dummy_app/app/assets/javascripts/application.js - spec/fixtures/aws_with_yml/config/asset_sync.yml - spec/fixtures/google_with_yml/config/asset_sync.yml - spec/fixtures/rackspace_with_yml/config/asset_sync.yml - spec/fixtures/with_invalid_yml/config/asset_sync.yml - spec/integration/aws_integration_spec.rb - spec/spec_helper.rb - spec/unit/asset_sync_spec.rb - spec/unit/google_spec.rb - spec/unit/multi_mime_spec.rb - spec/unit/rackspace_spec.rb - spec/unit/railsless_spec.rb - spec/unit/storage_spec.rb asset_sync-1.0.0/.gitignore0000644000004100000410000000024512250226601015700 0ustar www-datawww-data.DS_Store *.gem .bundle Gemfile.lock pkg/* *.swp coverage/* .env spec/dummy_app/public/* spec/dummy_app/log/* spec/dummy_app/tmp/* .rbx gemfiles/*.lock .rvmrc .idea asset_sync-1.0.0/docs/0000755000004100000410000000000012250226601014637 5ustar www-datawww-dataasset_sync-1.0.0/docs/heroku.md0000644000004100000410000000316112250226601016457 0ustar www-datawww-dataThe following issues are currently present in Heroku if you are not following the steps outlined in the main [README](http://github.com/rumblelabs/asset_sync) ## KNOWN ISSUES (IMPORTANT) We are currently trying to talk with Heroku to iron these out. 1. Will not work on heroku on an application with a *RAILS_ENV* configured as anything other than production 2. Will not work on heroku using ENV variables with the configuration as described below, you must hardcode all variables ### 1. RAILS_ENV When you see `rake assets:precompile` during deployment. Heroku is actually running something like env RAILS_ENV=production DATABASE_URL=scheme://user:pass@127.0.0.1/dbname bundle exec rake assets:precompile 2>&1 This means the *RAILS_ENV* you have set via *heroku:config* is not used. **Workaround:** you could have just one S3 bucket dedicated to assets and configure `AssetSync` to not delete existing files: AssetSync.configure do |config| ... config.fog_directory = 'app-assets' config.existing_remote_files = "keep" end ### 2. ENV varables not available Currently when heroku runs `rake assets:precompile` during deployment. It does not load your Rails application's environment config. This means using any **ENV** variables you could normally depend on are not available. For now you can just run `heroku run rake assets:precompile` after deploy. **Workaround:** you could just hardcode your AWS credentials in the initializer or yml AssetSync.configure do |config| config.aws_access_key_id = 'xxx' config.aws_secret_access_key = 'xxx' config.fog_directory = 'mybucket' end asset_sync-1.0.0/Appraisals0000644000004100000410000000024412250226601015731 0ustar www-datawww-dataappraise "rails-3.1" do gem "rails", "~> 3.1.0" end appraise "rails-3.2" do gem "rails", "~> 3.2.0" end appraise "rails-4.0" do gem "rails", "~> 4.0.0" end asset_sync-1.0.0/CHANGELOG.md0000644000004100000410000005151012250226601015522 0ustar www-datawww-data# RELEASE HISTORY ## v0.5.1 / 2012-10-22 Version 0.5.1 (David Rice ) Changes: * 5 Nominal Changes * Add a CHANGELOG.md (as generated by vclog -r -f markdown * Improve documentation on ignored_files config option * Allow failure of specs against ruby-head and jruby-head * Merge pull request #115 from demirhanaydin/patch-1 * Merge support for always providing mime_type #93 from patdeegan/master ## v0.5.0 / 2012-08-23 Version 0.5.0 (David Rice ) Changes: * 8 Nominal Changes * Merge branch 'sinatra' of github.com:rumblelabs/asset_sync into sinatra * Version 0.5.0, sinatra / rack support * Some refactoring to further remove dependency on Rails, add spec for railsless configuration * Update readme. * Add public_path and prefix config options so asset_sync can be used outside Rails. * Some refactoring to further remove dependency on Rails, add spec for railsless configuration * Merge branch 'ejholmes/sinatra' into sinatra * Version 0.4.3, removed dependency on Rails Time additions ## v0.4.3 / 2012-08-19 Version 0.4.3 (David Rice ) Changes: * 21 Nominal Changes * Refactor cache control and expiry hearder definition to use same value of one year * Merge pull request #94 from karlfreeman/time Remove Rails time dependency * Allow failures in ruby-head * Merge pull request #88 from potomak/patch-1 Fix defined? syntax * Merge pull request #95 from bbhoss/patch-1 Fix syntax error in documentation * Describe using S3 HTTPS better * Fix syntax error * remove Rails time dependency * Update readme. * Add public_path and prefix config options so asset_sync can be used outside Rails. * Fix defined? syntax * Force build on travis * Get specs running under jruby and travis /cc @headius :) * Ignore ds_store * Add jruby-openssl gem to get tests passing on jruby * test all the things * Add travis config for rbx * Merge branch 'master' of github.com:rumblelabs/asset_sync * Update README for installing on heroku, labs is no-longer a plugin * Merge pull request #75 from mscottford/master Update asset_host configuration in README to not rely on request object * Version 0.4.2, allow configuration of an array of strings or regex for files to ignore uploading. #euruko ## v0.4.2 / 2012-06-02 Version 0.4.2 (David Rice ) Changes: * 7 Nominal Changes * Remove errant puts from spec * Merge * Add option to configure ignored_files through YAML config file * Removes errant end in the asset_host config example. * Updates README to suggest a different asset_host configuration The previous version will fail in some cases because a request is not always available during asset compilation. * Fix Fog warnings when running specs. * Version 0.4.1, allow programatic disabling of AssetSync.config.enabled ## v0.4.1 / 2012-05-04 Version 0.4.1 (David Rice ) Changes: * 10 Nominal Changes * Update docs * Don't default to disabled if ASSET_SYNC_ENABLED env var is not specified. * Add option to ignore files * Add support for ASSET_SYNC_ENABLED with env vars. * Oops, should have used the accessor * Add support for enabled in the yaml config. * Add specs for AssetSync.enabled? configured through the initializer. * Make it possible to turn off AssetSync... Useful when precompiling to export to a hybrid mobile app such as PhoneGap. Would fix issue #66. * How many times will I forget to update the release date? many * Version 0.4.0, google storage support. Allow force upload of all or selected files. Travis CI enabled ## v0.4.0 / 2012-04-26 Version 0.4.0 (David Rice ) Changes: * 22 Nominal Changes * Add google storage options to built in initializer to allow config via ENV vars * Add google storage configuration to README * fix case on google provider in generator * added google storage tests * added google storage generators * add attr_accessor for google keys * add support for fog gems google storage option * Oh, travisci will build an orgs repos if you configure the webhookd. Use rumblelabs/asset_sync as build status * Merge branch 'master' into levent/feature/overwrite_specific_remote_files * Use my travis-ci build in README * Merge pull request #69 from levent/integrate_travis Integrate Travis CI * Merge branch 'integrate_travis' into feature/overwrite_specific_remote_files * Specs for uploading assets * Travis build logo * Setting up for Travis * Updated README * always_upload config option added * gitignore *.swp (for vim) * Add ability to ignore remote files * Correct name of specs * Allows specifying an array of assets to always upload to remote * Version 0.3.2, set content encoding header for .gz files ## v0.3.2 / 2012-04-18 Version 0.3.2 (David Rice ) Changes: * 11 Nominal Changes * Remove trailing comma * Merge pull request #57 from nathanhumbert/master Set Content-Encoding for gzip files when config.gzip? is not true * Merge pull request #59 from kamui/master Use Rails.public_path and Pathname#join for path concat and string interpolation * Merge pull request #55 from manuelmeurer/patch-1 Remove comments taken from another gem * Dir.chdir to path first to avoid a map call and path string slicing * add Rails.public_path stub and make Rails.root return Pathname class to match Rails behavior * Rails.root returns a Pathname, use Pathname#join instead of File.join and string interpolation * use Rails.public_path instead of concat Rails.root and 'public' * Set Content-Encoding for gzip files when config.gzip? is not true This allows a S3 bucket served via CloudFront to properly handle the Accept-Encoding request header. * Remove comments taken from another gem * Merge branch 'master' of github.com:rumblelabs/asset_sync ## v0.3.1 / 2012-03-07 Version 0.3.1 (David Rice ) Changes: * 6 Nominal Changes * Version 0.3.1, improve logging of asset_sync configuration and sync events * Remove some debugging stuffs * Improve logging during asset_sync progress. * Separate log and warn message, should not mess up heroku precompile thread as it watches STDERR for output. * Improve logging, only log to STDERR if RAILS_GROUPS=assets. * Version 0.3.0, all configuration can be managed via env variables, improve docs on configuration ## v0.3.0 / 2012-03-07 Version 0.3.0 (David Rice ) Changes: * 10 Nominal Changes * Merge pull request #50 from hampei/master made gzip_compression settable via ENV * namespaced the ENV gzip option: ASSET_SYNC_GZIP_COMPRESSION. added option to readme * made gzip_compression settable via ENV * Typo * Improve documentation * Version 0.2.12, fix the asset_sync rake task enhancement in Rails 3.2 (still supporting earlier releases) * Turns out this was an issue with Rails handling of the config.assets.digest parameter * When running rake assets:precompile this config variable is modified by Rails * So it therefore cannot be depended on to test wether to enhance the nondigest task or not * The solution is to always enhance assets:precompile:nondigest if it exists. ## v0.2.9 / 2012-01-30 Version 0.2.9 (David Rice ) Changes: * 3 Nominal Changes * Merge pull request #42 from genuitytech/master Now correctly setting config.fog_region. * Now correctly setting config.fog_region. * Version 0.2.8, improve http headers. Add far future expires and cache control, public. ## v0.2.8 / 2012-01-27 Version 0.2.8 (David Rice ) Changes: * 2 Nominal Changes * Add far future expires header * Version 0.2.7, Rails 3.2 compatibility, default Rake task improved ## v0.2.7 / 2012-01-25 Version 0.2.7 (David Rice ) Changes: * 2 Nominal Changes * Merge branch 'rails-3-2' * Version 0.2.6, Rails 3.2 compatibility, default Rake task improved ## v0.2.6 / 2012-01-25 Version 0.2.6 (David Rice ) Changes: * 3 Nominal Changes * Doc * Add Rails 3.2 compatible rake task * Fix issue #38 for when Rails.config.assets.prefix starts with a slash. ## v0.2.5 / 2012-01-10 Version 0.2.5 (David Rice ) Changes: * 1 Nominal Changes * Version 0.2.4, Support for Rails.config.assets.prefix ## v0.2.4 / 2012-01-06 Version 0.2.4 (David Rice ) Changes: * 5 Nominal Changes * Merge pull request #35 from siliconsalad/config_assets_prefix Rails.config.assets.prefix used for sync * added test with Rails.config.assets.prefix set * Rails.config.assets.prefix used for sync (instead of hardcoded 'assets' value) * specs now use shared context to mock Rails and fixed pending tests that were failing * Version 0.2.3, Rackspace London support ## v0.2.3 / 2011-12-06 Version 0.2.3 (David Rice ) Changes: * 3 Nominal Changes * Merge pull request #28 from robink/master Rackspace London support * Only merge racksace_auth_url to fog config if defined * Bump date for release ## v0.2.2 / 2011-11-29 Version 0.2.2 (David Rice ) Changes: * 10 Nominal Changes * Version 0.2.2: add fail_silently config option to avoid heroku installing the rails31_enable_runtime_asset_compilation, fixes issues #24, #29 * Further explanation of fail_silently option * Merge pull request #29 from neilmiddleton/master Allow precompile to fail quietly on heroku * Update README, and generator templates * Changes as discussed in PR#29 * Disable pre-compilation on Heroku. * Updated README and generators * Added support for specifying rackspace_auth_url (then the possibility to use Rackspace London) * Fixed typo in readme * Updated version and release date ## v0.2.12 / 2012-03-04 Version 0.2.12 (David Rice ) Changes: * 1 Nominal Changes * Version 0.2.11, minor fix to YAML loading and improved docs ## v0.2.11 / 2012-03-04 Version 0.2.11 (David Rice ) Changes: * 7 Nominal Changes * Merge pull request #48 from samsoffes/patch-1 Fix Heroku Labs plugin URL and add code coloring to readme. * Fix Heroku Labs plugin URL and add code coloring to readme. * Merge pull request #47 from dbalatero/dont_read_yml_file_every_time Cache the YML config to avoid multiple file reads. * Cache the YML config to avoid multiple file reads. * Fix documentation typos * Move old known issues about heroku ENV variables to a docs folder, write new content referencing the recommended use of user_env_compile * Version 0.2.10, fix handling of non standard Rails.config.assets.manifest path ## v0.2.10 / 2012-02-16 Version 0.2.10 (David Rice ) Changes: * 5 Nominal Changes * Add an AssetSync.log method for outputing sync config failure so we can stub it out easily in tests * Merge pull request #44 from dbalatero/fix_nonstandard_manifest_location Fixes asset_sync to correctly read manifest.yml files. * Fixes asset_sync to correctly read manifest.yml files. Rails.config.assets.manifest only points to the directory that contains the manifest.yml file: https://github.com/rails/rails/blob/226783d1e8891a38d4a61017952528970dba903d/actionpack/lib/sprockets/railtie.rb#L36 * Add hack, seems required for some applications on push to Heroku, not for others * Version 0.2.9 fix bug in internal initializer ## v0.2.1 / 2011-11-21 Version 0.2.1 (Phil ) Changes: * 4 Nominal Changes * Only configure with ENV vars if initializer and yml file do not exist * Typo in yaml, underscore need not be escaped here * Fix readme * Version 0.2.0 ## v0.2.0 / 2011-11-15 Version 0.2.0 (David Rice ) Changes: * 15 Nominal Changes * Add upgrade notice to README * Use fog directory * Merge * Fix readme * Tidy readme * Get AWS or Rackspace generators working correctly * Remove generated rake task, no need * Improve generators to generate AWS or Rackspace compatible initializer or yml * Prepare 0.2.0 for release * Convert readme and generators to new config options * Fix fog_options * Fix typo * Fix bug * Working on migrating the exposed config variables to reflect fog, add in a start on rackspace support. Write more specs, tidy up and document config * Add specs for manifest config ## v0.1.9 / 2011-11-06 Version 0.1.9 (David Rice ) Changes: * 37 Nominal Changes * Document gzip compression * Add note about gzip_compression * Add spec to test config defaults gzip_compression to false * Add gzip compression info to generated asset_sync.rb or .yml. Fix .yml example with new config settings * Update gemspec * Update docs to note that rake task is no longer generated within the app. * Add todo * Add % symbol for clarity * Output % savings when uploading gzipped files. Only use gzipped files if the compressed version is actually smaller than the original. * Tidy readme * Get AWS or Rackspace generators working correctly * Remove generated rake task, no need * Improve generators to generate AWS or Rackspace compatible initializer or yml * Prepare 0.2.0 for release * Convert readme and generators to new config options * Fix fog_options * Fix bug * Fix typo * Working on migrating the exposed config variables to reflect fog, add in a start on rackspace support. Write more specs, tidy up and document config * Add spec for gzip? config method * Reorder logic to execute quicker if gzip? compression disabled and ignore .gz uploads correctly * Ignore .gz assets if we are in gzip_compression mode * Do not set a Vary: Accept-Encoding header, S3 does not support at all * Try setting vary header a different way * Set http header Vary: Accept-Encoding when storing gzipped assets to S3 * Add todo * Refactor to computed path * Add path * Instead of overwriting the original file when processing the .gz, overwrite the original if a gz file exists to avoid any issues with whichever order files are processed in * Bump version (no release just yet) * Only handle gzip files specially if we have configured gzip_compression * Overwrite original files with gzipped equivalent, improve logging to show GZIP in action, make it a configurable option, config.gzip_compression that defaults to false * Upload GZIP compressed assets nicely to S3 with correct content type and encoding. * Refactor upload method to make enhancing nicer * Merge pull request #12 from bobbrez/master Minor correction to README for generated YAML file path. * Correcting location of generated yml in README * Comment out unnecessary logic for now ## v0.1.8 / 2011-10-17 Version 0.1.8 (David Rice ) Changes: * 4 Nominal Changes * Don't log any debugging info v0.1.8 should add a debug mode in future * Fix specs, only require asset_sync engine and railtie if Rails is initialized * Improve docs * Tidy up for release of Rails 3.1.1 support. ## v0.1.7 / 2011-10-15 Version 0.1.7 (David Rice ) Changes: * 6 Nominal Changes * Merge pull request #7 from hone/6_rails3.1.1 Rails 3.1.1 Compatability * rails 3.1.1 support * fix typo * Update the generated yml config with a staging environment, use defaults more. Engine within asset sync doesn't appear to be ran even with :group => :assets in the definition. Add railtie to allow setting config.asset_sync configuration within a rails application.rb, this and moving the initializer style of config seems to work for Rails 3.1.1, also so does purely relying on the YAML config * New version of asset_sync to work around Rails 3.1.1 issues. Test if config/initializers/asset_sync.rb exists and load that, otherwise provide a default initializer that is configurable with environment variables. Then merge in settings if config/asset_sync.yml is found. Add the asset_sync.rake in to lib/tasks so it is autoloaded and don't bother generating it anymore * Bugfix ## v0.1.6 / 2011-09-26 Version 0.1.6 (David Rice ) Changes: * 1 Nominal Changes * Fix gemfile ## v0.1.5 / 2011-09-26 Version 0.1.5 (David Rice ) Changes: * 5 Nominal Changes * Should raise storage error if AWS S3 bucket is not found. Version 0.1.5 * explain further * Merge branch 'master' of github.com:rumblelabs/asset_sync * List known issues with heroku and possible work arounds * Should raise error with no configuration ## v0.1.4 / 2011-08-30 Version 0.1.4 (David Rice ) Changes: * 2 Nominal Changes * Require dependancy of active_model, add config validation, better specs, version 0.1.4 * Tidied up read me with a DRYer use of AWS_BUCKET for asset_host. ## v0.1.3 / 2011-08-27 Version 0.1.3 (Simon Hamilton ) Changes: * 1 Nominal Changes * Bump version for release ## v0.1.2 / 2011-08-25 Version 0.1.2 (Simon Hamilton ) Changes: * 2 Nominal Changes * Removed public from cache control. May be causing a problem with uploads * Bump version for release ## v0.1.10 / 2011-11-15 Version 0.1.10 (David Rice ) Changes: * 7 Nominal Changes * Improve manifest configuration by making it a boolean option only, it will automatically use the configured manifest path if different from the default. Add documentation to readme about the new option and upgrade generated configs. * Merge pull request #20 from agworld/e26f5ca36dee1c2196653268ed6bb38c0226e4d2 Fixes issues #16, #17, #18 and #19 * fixes https://github.com/rumblelabs/asset_sync/issues/19 * Implements https://github.com/rumblelabs/asset_sync/issues/17 * fixes https://github.com/rumblelabs/asset_sync/issues/18 * fixes https://github.com/rumblelabs/asset_sync/issues/16 * Merge branch 'gzip-compression' ## v0.1.1 / 2011-08-24 Version 0.1.1 (Simon Hamilton ) Changes: * 5 Nominal Changes * Merge pull request #4 from jsmestad/patch-1 [BUGFIX] Add support for 'existing_remote_files' configuration in YAML fi * Verbose output about the delete process. * Condense logic on keep * [BUGFIX] Add support for 'existing_remote_files' configuration in YAML file. * Version 0.1.0 ready ## v0.1.0 / 2011-08-22 Version 0.1.0 (David Rice ) Changes: * 1 Nominal Changes * Merge 0.0.7 from master into new refactor branch ## v0.0.7 / 2011-08-22 Version 0.0.7 (David Rice ) Changes: * 9 Nominal Changes * Added Cache-control header (1 year, public) on uploaded files * Update README to reflect new configuration styles * Extract all file manipulation methods to a storage class, update generator templates, fix a few bugs. * Config class working, specs added, still @wip * Refactoring * Get config working and loading yml or the initializer * small additions * @wip working on extracting out a configuration class and allow config via an initializer alone, also support yml file usage for when that is useful * merge config changes ## v0.0.6 / 2011-08-06 Version 0.0.6 (Simon Hamilton ) Changes: * 1 Nominal Changes * Include ERB template rendering of yml. v0.0.5 ## v0.0.5 / 2011-08-05 Version 0.0.5 (David Rice ) Changes: * 3 Nominal Changes * now it parses the YAML file with ERB. * Set gem date for release * 0.0.4 Release ## v0.0.4 / 2011-08-05 Version 0.0.4 (David Rice ) ## v0.0.3 / 2011-07-31 Version 0.0.3 (David Rice ) Changes: * 1 Nominal Changes * Added homepage to gemspec ## v0.0.2 / 2011-07-31 Version 0.0.2 (Simon Hamilton ) Changes: * 7 Nominal Changes * Added a rails generator to install the rake task and the config. Just do "rails generate asset_sync:install" * Updated readme * Getting ready to release the gem * Revert "remove version file" This reverts commit 7ebd853947b8d5f3b6e81f96535dfce843f2c855. * remove version file * Initial commit * Initial commit ## HEAD / 2012-08-27 Current Development (David Rice) Changes: * 2 Nominal Changes * Improve documentation on ignored_files config option * Merge branch 'sinatra' asset_sync-1.0.0/README.md0000644000004100000410000004102112250226601015164 0ustar www-datawww-data[![Build Status](https://secure.travis-ci.org/rumblelabs/asset_sync.png)](http://travis-ci.org/rumblelabs/asset_sync) [![Code Climate](https://codeclimate.com/badge.png)](https://codeclimate.com/github/rumblelabs/asset_sync) # Asset Sync Synchronises Assets between Rails and S3. Asset Sync is built to run with the new Rails Asset Pipeline feature introduced in **Rails 3.1**. After you run __bundle exec rake assets:precompile__ your assets will be synchronised to your S3 bucket, optionally deleting unused files and only uploading the files it needs to. This was initially built and is intended to work on [Heroku](http://heroku.com) but can work on any platform. ## Upgrading? If you are upgrading from a version of asset_sync **< 0.2.0** (i.e. 0.1.x). All of the references to config variables have changed to reference those used in **Fog**. Ensure to backup your `asset_sync.rb` or `asset_sync.yml` files and re-run the generator. You may also then need to update your ENV configuration variables (or you can change the ones that are referenced). ## Heroku Labs (BETA) Previously there were [several issues](http://github.com/rumblelabs/asset_sync/blob/master/docs/heroku.md) with using asset_sync on Heroku as described in our [Heroku dev center article](http://devcenter.heroku.com/articles/cdn-asset-host-rails31). Now to get everything working smoothly with using **ENV** variables to configure `asset_sync` we just need to enable the [user-env-compile](http://devcenter.heroku.com/articles/labs-user-env-compile) functionality. In short: heroku labs:enable user-env-compile -a myapp Hopefully this will make it's way into the platform as standard. ## Installation Add the gem to your Gemfile ``` ruby gem 'asset_sync' ``` If you want, you can put it within your **:assets** group in your Gemfile. ``` ruby group :assets do gem 'sass-rails', '~> 3.2.3' gem 'coffee-rails', '~> 3.2.1' gem 'uglifier', '>= 1.0.3' gem 'asset_sync' end ``` This is good practice when pre-compiling your assets as it will reduce load time and server memory in production. The only caveat being, you may not be able to use a custom initializer, without perhaps wrapping it with. ``` ruby if defined?(AssetSync) ... end ``` ### Extended Installation (Faster sync with turbosprockets) It's possible to improve **asset:precompile** time if you are using Rails 3.2.x the main source of which being compilation of **non-digest** assets. [turbo-sprockets-rails3](https://github.com/ndbroadbent/turbo-sprockets-rails3) solves this by only compiling **digest** assets. Thus cutting compile time in half. > NOTE: It will be **deprecated in Rails 4** as sprockets-rails has been extracted out of Rails and will only compile **digest** assets by default. ## Configuration ### Rails Configure __config/environments/production.rb__ to use Amazon S3 as the asset host and ensure precompiling is enabled. ``` ruby #config/environments/production.rb config.action_controller.asset_host = "//#{ENV['FOG_DIRECTORY']}.s3.amazonaws.com" ``` Or, to use Google Storage Cloud, configure as this. ``` ruby #config/environments/production.rb config.action_controller.asset_host = "//#{ENV['FOG_DIRECTORY']}.storage.googleapis.com" ``` On **HTTPS**: the exclusion of any protocol in the asset host declaration above will allow browsers to choose the transport mechanism on the fly. So if your application is available under both HTTP and HTTPS the assets will be served to match. > The only caveat with this is that your S3 bucket name **must not contain any periods** so, mydomain.com.s3.amazonaws.com for example would not work under HTTPS as SSL certificates from Amazon would interpret our bucket name as **not** a subdomain of s3.amazonaws.com, but a multi level subdomain. To avoid this don't use a period in your subdomain or switch to the other style of S3 URL. ``` ruby config.action_controller.asset_host = "//s3.amazonaws.com/#{ENV['FOG_DIRECTORY']}" ``` Or ``` ruby config.action_controller.asset_host = "//storage.googleapis.com/#{ENV['FOG_DIRECTORY']}" ``` On **non default S3 bucket region**: If your bucket is set to a region that is not the default US Standard (us-east-1) you must use the first style of url ``//#{ENV['FOG_DIRECTORY']}.s3.amazonaws.com`` or amazon will return a 301 permanently moved when assets are requested. Note the caveat above about bucket names and periods. If you wish to have your assets sync to a sub-folder of your bucket instead of into the root add the following to your ``production.rb`` file ```ruby # store assets in a 'folder' instead of bucket root config.assets.prefix = "/production/assets" ```` Also, ensure the following are defined (in production.rb or application.rb) * **config.assets.digest** is set to **true**. * **config.assets.enabled** is set to **true**. Additionally, if you depend on any configuration that is setup in your `initializers` you will need to ensure that * **config.assets.initialize\_on\_precompile** is set to **true** ### AssetSync **AssetSync** supports the following methods of configuration. * [Built-in Initializer](https://github.com/rumblelabs/asset_sync/blob/master/lib/asset_sync/engine.rb) (configured through environment variables) * Rails Initializer * A YAML config file Using the **Built-in Initializer** is the default method and is supposed to be used with **environment** variables. It's the recommended approach for deployments on Heroku. If you need more control over configuration you will want to use a **custom rails initializer**. Configuration using a **YAML** file (a common strategy for Capistrano deployments) is also supported. The recommend way to configure **asset_sync** is by using **environment variables** however it's up to you, it will work fine if you hard code them too. The main reason is that then your access keys are not checked into version control. ### Built-in Initializer (Environment Variables) The Built-in Initializer will configure **AssetSync** based on the contents of your environment variables. Add your configuration details to **heroku** ``` bash heroku config:add AWS_ACCESS_KEY_ID=xxxx heroku config:add AWS_SECRET_ACCESS_KEY=xxxx heroku config:add FOG_DIRECTORY=xxxx heroku config:add FOG_PROVIDER=AWS # and optionally: heroku config:add FOG_REGION=eu-west-1 heroku config:add ASSET_SYNC_GZIP_COMPRESSION=true heroku config:add ASSET_SYNC_MANIFEST=true heroku config:add ASSET_SYNC_EXISTING_REMOTE_FILES=keep ``` Or add to a traditional unix system ``` bash export AWS_ACCESS_KEY_ID=xxxx export AWS_SECRET_ACCESS_KEY=xxxx export FOG_DIRECTORY=xxxx ``` Rackspace configuration is also supported ``` bash heroku config:add RACKSPACE_USERNAME=xxxx heroku config:add RACKSPACE_API_KEY=xxxx heroku config:add FOG_DIRECTORY=xxxx heroku config:add FOG_PROVIDER=Rackspace ``` Google Storage Cloud configuration is supported as well ``` bash heroku config:add FOG_PROVIDER=Google heroku config:add GOOGLE_STORAGE_ACCESS_KEY_ID=xxxx heroku config:add GOOGLE_STORAGE_SECRET_ACCESS_KEY=xxxx heroku config:add FOG_DIRECTORY=xxxx ``` The Built-in Initializer also sets the AssetSync default for **existing_remote_files** to **keep**. ### Custom Rails Initializer (config/initializers/asset_sync.rb) If you want to enable some of the advanced configuration options you will want to create your own initializer. Run the included Rake task to generate a starting point. rails g asset_sync:install --provider=Rackspace rails g asset_sync:install --provider=AWS The generator will create a Rails initializer at `config/initializers/asset_sync.rb`. ``` ruby AssetSync.configure do |config| config.fog_provider = 'AWS' config.fog_directory = ENV['FOG_DIRECTORY'] config.aws_access_key_id = ENV['AWS_ACCESS_KEY_ID'] config.aws_secret_access_key = ENV['AWS_SECRET_ACCESS_KEY'] # Don't delete files from the store # config.existing_remote_files = 'keep' # # Increase upload performance by configuring your region # config.fog_region = 'eu-west-1' # # Automatically replace files with their equivalent gzip compressed version # config.gzip_compression = true # # Use the Rails generated 'manifest.yml' file to produce the list of files to # upload instead of searching the assets directory. # config.manifest = true # # Fail silently. Useful for environments such as Heroku # config.fail_silently = true end ``` ### YAML (config/asset_sync.yml) Run the included Rake task to generate a starting point. rails g asset_sync:install --use-yml --provider=Rackspace rails g asset_sync:install --use-yml --provider=AWS The generator will create a YAML file at `config/asset_sync.yml`. ``` yaml defaults: &defaults fog_provider: "AWS" fog_directory: "rails-app-assets" aws_access_key_id: "<%= ENV['AWS_ACCESS_KEY_ID'] %>" aws_secret_access_key: "<%= ENV['AWS_SECRET_ACCESS_KEY'] %>" # You may need to specify what region your storage bucket is in # fog_region: "eu-west-1" existing_remote_files: keep # Existing pre-compiled assets on S3 will be kept # To delete existing remote files. # existing_remote_files: delete # To ignore existing remote files and overwrite. # existing_remote_files: ignore # Automatically replace files with their equivalent gzip compressed version # gzip_compression: true # Fail silently. Useful for environments such as Heroku # fail_silently: true # Always upload. Useful if you want to overwrite specific remote assets regardless of their existence # eg: Static files in public often reference non-fingerprinted application.css # note: You will still need to expire them from the CDN's edge cache locations # always_upload: ['application.js', 'application.css'] # Ignored files. Useful if there are some files that are created dynamically on the server and you don't want to upload on deploy. # ignored_files: ['ignore_me.js', !ruby/regexp '/ignore_some/\d{32}\.css/'] development: <<: *defaults test: <<: *defaults production: <<: *defaults ``` ### Available Configuration Options All AssetSync configuration can be modified directly using environment variables with the **Built-in initializer**. e.g. ```ruby AssetSync.config.fog_provider == ENV['FOG_PROVIDER'] ``` Simply **upcase** the ruby attribute names to get the equivalent environment variable to set. The only exception to that rule are the internal **AssetSync** config variables, they must be prepended with `ASSET_SYNC_*` e.g. ```ruby AssetSync.config.gzip_compression == ENV['ASSET_SYNC_GZIP_COMPRESSION'] ``` #### AssetSync (optional) * **existing_remote_files**: (`'keep', 'delete', 'ignore'`) what to do with previously precompiled files. **default:** `'keep'` * **gzip\_compression**: (`true, false`) when enabled, will automatically replace files that have a gzip compressed equivalent with the compressed version. **default:** `'false'` * **manifest**: (`true, false`) when enabled, will use the `manifest.yml` generated by Rails to get the list of local files to upload. **experimental**. **default:** `'false'` * **enabled**: (`true, false`) when false, will disable asset sync. **default:** `'true'` (enabled) * **ignored\_files**: an array of files to ignore e.g. `['ignore_me.js', %r(ignore_some/\d{32}\.css)]` Useful if there are some files that are created dynamically on the server and you don't want to upload on deploy **default**: `[]` #### Fog (Required) * **fog\_provider**: your storage provider *AWS* (S3) or *Rackspace* (Cloud Files) or *Google* (Google Storage) * **fog\_directory**: your bucket name #### Fog (Optional) * **fog\_region**: the region your storage bucket is in e.g. *eu-west-1* #### AWS * **aws\_access\_key\_id**: your Amazon S3 access key * **aws\_secret\_access\_key**: your Amazon S3 access secret #### Rackspace * **rackspace\_username**: your Rackspace username * **rackspace\_api\_key**: your Rackspace API Key. #### Google Storage * **google\_storage\_access\_key\_id**: your Google Storage access key * **google\_storage\_secret\_access\_key**: your Google Storage access secret #### Rackspace (Optional) * **rackspace\_auth\_url**: Rackspace auth URL, for Rackspace London use: `https://lon.identity.api.rackspacecloud.com/v2.0` ## Amazon S3 Multiple Region Support If you are using anything other than the US buckets with S3 then you'll want to set the **region**. For example with an EU bucket you could set the following environment variable. ``` bash heroku config:add FOG_REGION=eu-west-1 ``` Or via a custom initializer ``` ruby AssetSync.configure do |config| # ... config.fog_region = 'eu-west-1' end ``` Or via YAML ``` yaml production: # ... fog_region: 'eu-west-1' ``` ## Automatic gzip compression With the `gzip_compression` option enabled, when uploading your assets. If a file has a gzip compressed equivalent we will replace that asset with the compressed version and sets the correct headers for S3 to serve it. For example, if you have a file **master.css** and it was compressed to **master.css.gz** we will upload the **.gz** file to S3 in place of the uncompressed file. If the compressed file is actually larger than the uncompressed file we will ignore this rule and upload the standard uncompressed version. ## Fail Silently With the `fail_silently` option enabled, when running `rake assets:precompile` AssetSync will never throw an error due to missing configuration variables. With the new **user_env_compile** feature of Heroku (see above), this is no longer required or recommended. Yet was added for the following reasons: > With Rails 3.1 on the Heroku cedar stack, the deployment process automatically runs `rake assets:precompile`. If you are using **ENV** variable style configuration. Due to the methods with which Heroku compile slugs, there will be an error raised by asset\_sync as the environment is not available. This causes heroku to install the `rails31_enable_runtime_asset_compilation` plugin which is not necessary when using **asset_sync** and also massively slows down the first incoming requests to your app. > To prevent this part of the deploy from failing (asset_sync raising a config error), but carry on as normal set `fail_silently` to true in your configuration and ensure to run `heroku run rake assets:precompile` after deploy. ## Rake Task A rake task is included within the **asset_sync** gem to perform the sync: ``` ruby namespace :assets do desc "Synchronize assets to S3" task :sync => :environment do AssetSync.sync end end ``` If `AssetSync.config.run_on_precompile` is `true` (default), then assets will be uploaded to S3 automatically after the `assets:precompile` rake task is invoked: ``` ruby if Rake::Task.task_defined?("assets:precompile:nondigest") Rake::Task["assets:precompile:nondigest"].enhance do Rake::Task["assets:sync"].invoke if defined?(AssetSync) && AssetSync.config.run_on_precompile end else Rake::Task["assets:precompile"].enhance do Rake::Task["assets:sync"].invoke if defined?(AssetSync) && AssetSync.config.run_on_precompile end end ``` You can disable this behavior by setting `AssetSync.config.run_on_precompile = false`. ## Sinatra/Rack Support You can use the gem with any Rack application, but you must specify two additional options; `prefix` and `public_path`. ```ruby AssetSync.configure do |config| config.fog_provider = 'AWS' config.fog_directory = ENV['FOG_DIRECTORY'] config.aws_access_key_id = ENV['AWS_ACCESS_KEY_ID'] config.aws_secret_access_key = ENV['AWS_SECRET_ACCESS_KEY'] config.prefix = 'assets' config.public_path = Pathname('./public') end ``` Then manually call `AssetSync.sync` at the end of your asset precompilation task. ```ruby namespace :assets do desc 'Precompile assets' task :precompile do target = Pathname('./public/assets') manifest = Sprockets::Manifest.new(sprockets, './public/assets/manifest.json') sprockets.each_logical_path do |logical_path| if (!File.extname(logical_path).in?(['.js', '.css']) || logical_path =~ /application\.(css|js)$/) && asset = sprockets.find_asset(logical_path) filename = target.join(logical_path) FileUtils.mkpath(filename.dirname) puts "Write asset: #{filename}" asset.write_to(filename) manifest.compile(logical_path) end end AssetSync.sync end end ``` ## Todo 1. Add some before and after filters for deleting and uploading 2. Support more cloud storage providers 3. Better test coverage 4. Add rake tasks to clean old assets from a bucket ## Credits Inspired by: - [https://github.com/moocode/asset_id](https://github.com/moocode/asset_id) - [https://gist.github.com/1053855](https://gist.github.com/1053855) ## License MIT License. Copyright 2011-2013 Rumble Labs Ltd. [rumblelabs.com](http://rumblelabs.com)