Class: AssetS3::S3

Inherits:
Base
  • Object
show all
Defined in:
lib/asset_s3.rb

Constant Summary collapse

DEFAULT_GZIP_TYPES =
["text/css", "application/javascript"]
@@gzip_types =
DEFAULT_GZIP_TYPES

Constants inherited from Base

Base::DEFAULT_ASSET_PATHS

Class Method Summary collapse

Methods inherited from Base

absolute_path, asset_paths, asset_paths=, assets, path_prefix

Class Method Details

.cache_headersObject



65
66
67
# File 'lib/asset_s3.rb', line 65

def self.cache_headers
  {"Expires" => (Time.now + (60*60*24*365)).httpdate, "Cache-Control" => "public"} # 1 year expiry
end

.connect_to_s3Object



58
59
60
61
62
63
# File 'lib/asset_s3.rb', line 58

def self.connect_to_s3
  AWS::S3::Base.establish_connection!(
    :access_key_id => s3_config["access_key_id"],
    :secret_access_key => s3_config["secret_access_key"]
  )
end

.fingerprint(path) ⇒ Object



81
82
83
# File 'lib/asset_s3.rb', line 81

def self.fingerprint(path)
  super(path)
end

.gzip_headersObject



69
70
71
# File 'lib/asset_s3.rb', line 69

def self.gzip_headers
  {"Content-Encoding" => "gzip", "Vary" => "Accept-Encoding"}
end

.gzip_typesObject



50
51
52
# File 'lib/asset_s3.rb', line 50

def self.gzip_types
  @@gzip_types
end

.gzip_types=(types) ⇒ Object



46
47
48
# File 'lib/asset_s3.rb', line 46

def self.gzip_types=(types)
  @@gzip_types = types
end

.s3_bucketObject



77
78
79
# File 'lib/asset_s3.rb', line 77

def self.s3_bucket
  s3_config["bucket"]
end

.s3_configObject



54
55
56
# File 'lib/asset_s3.rb', line 54

def self.s3_config
  @@config ||= YAML.load_file(File.join(Rails.root, "config/asset_s3.yml"))[Rails.env] rescue nil || {}
end

.s3_permissionsObject



73
74
75
# File 'lib/asset_s3.rb', line 73

def self.s3_permissions
  :public_read
end

.upload(options = {}) ⇒ Object



85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/asset_s3.rb', line 85

def self.upload(options={})
  connect_to_s3
  assets.each do |asset|
    puts "asset_id: Uploading #{asset} as #{fingerprint(asset)}" if options[:debug]
    mime_type = MIME::Types.of(asset).first.to_s

    headers = {
      :content_type => mime_type,
      :access => s3_permissions,
    }.merge(cache_headers)

    if gzip_types.include?(mime_type)
      data = `gzip -c #{asset}`
      headers.merge!(gzip_headers)
    else
      data = File.read(asset)
    end

    puts "asset_id: headers: #{headers.inspect}" if options[:debug]

    AWS::S3::S3Object.store(
      fingerprint(asset),
      data,
      s3_bucket,
      headers
    ) unless options[:dry_run]
  end
end