Class: SmartAsset

Inherits:
Object
  • Object
show all
Defined in:
lib/smart_asset.rb,
lib/smart_asset/helper.rb,
lib/smart_asset/adapters/rails3.rb,
lib/smart_asset/adapters/stasis.rb,
lib/smart_asset/adapters/sinatra.rb

Defined Under Namespace

Modules: Adapters, Helper Classes: SmartAssetRailtie, Stasis

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.append_randomObject

Returns the value of attribute append_random.



15
16
17
# File 'lib/smart_asset.rb', line 15

def append_random
  @append_random
end

.asset_counterObject

Returns the value of attribute asset_counter.



15
16
17
# File 'lib/smart_asset.rb', line 15

def asset_counter
  @asset_counter
end

.asset_hostObject

Returns the value of attribute asset_host.



15
16
17
# File 'lib/smart_asset.rb', line 15

def asset_host
  @asset_host
end

.cacheObject

Returns the value of attribute cache.



15
16
17
# File 'lib/smart_asset.rb', line 15

def cache
  @cache
end

.configObject

Returns the value of attribute config.



15
16
17
# File 'lib/smart_asset.rb', line 15

def config
  @config
end

.destObject

Returns the value of attribute dest.



15
16
17
# File 'lib/smart_asset.rb', line 15

def dest
  @dest
end

.envObject

Returns the value of attribute env.



15
16
17
# File 'lib/smart_asset.rb', line 15

def env
  @env
end

.envsObject

Returns the value of attribute envs.



15
16
17
# File 'lib/smart_asset.rb', line 15

def envs
  @envs
end

.pubObject

Returns the value of attribute pub.



15
16
17
# File 'lib/smart_asset.rb', line 15

def pub
  @pub
end

.rootObject

Returns the value of attribute root.



15
16
17
# File 'lib/smart_asset.rb', line 15

def root
  @root
end

.sourcesObject

Returns the value of attribute sources.



15
16
17
# File 'lib/smart_asset.rb', line 15

def sources
  @sources
end

Class Method Details

.binary(root, relative_config = nil) ⇒ Object



17
18
19
20
21
# File 'lib/smart_asset.rb', line 17

def binary(root, relative_config=nil)
  load_config root, relative_config
  compress 'javascripts'
  compress 'stylesheets'
end

.compress(type) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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
113
114
115
116
117
118
119
120
121
# File 'lib/smart_asset.rb', line 23

def compress(type)
  dest = @dest[type]
  dir = "#{@pub}/#{@sources[type]}"
  ext = ext_from_type(type)
  packages = []
  time_cache = {}

  change = Change.new(dir)
  change.d
  states = change.send(:states)
  
  FileUtils.mkdir_p dest
  
  (@config[type] || {}).each do |package, files|
    next if ENV['PACKAGE'] && ENV['PACKAGE'] != package
    if files
      # Generate file hashes
      hashes = files.inject([]) do |array, file|
        path = "#{file}.#{ext}"
        if states[path]
          array << "#{states[path][:size]}#{states[path][:hash]}"
        end
        array
      end
      next if hashes.empty?
      
      # Modified hash
      hash = Digest::SHA1.hexdigest(hashes.join)[0..7]
      
      # Package path
      package = "#{dest}/#{hash}_#{package}.#{ext}"
      
      # If package file exists
      if File.exists?(package)
        packages << package
      else
        data = []
        
        # Join files in package
        files.each do |file|
          if File.exists?(source = "#{dir}/#{file}.#{ext}")
            data << File.read(source)
          end
        end
        
        # Don't create new compressed file if no data
        data = data.join("\n")
        next if data.strip.empty?
        
        # Compress joined files
        tmp = "#{dest}/tmp.#{ext}"
        File.open(tmp, 'w') { |f| f.write(data) }
        puts "\nCreating #{package}..."

        # Binary paths
        bin      = File.expand_path(File.dirname(__FILE__) + '/../bin')
        compiler = bin + '/compiler.jar'
        yui      = bin + '/yui.jar'
        
        if ext == 'js'
          warning = ENV['WARN'] ? nil : " --warning_level QUIET"
          cmd = "java -jar #{compiler} --js #{tmp} --js_output_file #{package}#{warning}"
        elsif ext == 'css'
          warning = ENV['WARN'] ? " -v" : nil
          cmd = "java -jar #{yui} #{tmp} -o #{package}#{warning}"
        end

        puts cmd if ENV['DEBUG']
        cmd_output = `#{cmd}`

        raise "Error running `#{cmd}`:\n#{cmd_output}"  unless $?.success?
        
        FileUtils.rm(tmp) unless ENV['DEBUG']
        
        # Fix YUI compression issue
        if ext == 'css'
          if RUBY_PLATFORM.downcase.include?('darwin')
            `sed -i '' 's/ and(/ and (/g' #{package}`
          else
            `sed -i 's/ and(/ and (/g' #{package}`
          end
        end
        
        # Package created
        packages << package
      end
    end
  end
  
  # Remove old/unused packages
  (Dir["#{dest}/#{"[^_]"*8}_*.#{ext}"] - packages).each do |path|
    FileUtils.rm path
  end
  
  # Delete legacy files
  Dir["#{dest}/*.yml", "#{dest}/#{"[0-9]"*14}_*.{css,js}"].each do |path|
    FileUtils.rm path
  end
end

.load_config(root, relative_config = nil) ⇒ Object



123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
# File 'lib/smart_asset.rb', line 123

def load_config(root, relative_config=nil)
  relative_config ||= 'config/assets.yml'
  @root = File.expand_path(root)

  return unless File.file?("#{@root}/#{relative_config}")

  @cache = nil
  @config = YAML::load(File.read("#{@root}/#{relative_config}"))
  
  # Default values
  if @config['append_random'].nil?
    @config['append_random'] = {}
  end
  if @config['append_random'].is_a?(::Hash) && @config['append_random']['development'].nil?
    @config['append_random']['development'] = true
  end
  
  @config['asset_host_count'] ||= 4
  @config['asset_host'] ||= ActionController::Base.asset_host rescue nil
  @config['environments'] ||= %w(production)
  @config['public'] ||= 'public'
  
  @config['destination'] ||= {}
  @config['destination']['javascripts'] ||= 'javascripts/packaged'
  @config['destination']['stylesheets'] ||= 'stylesheets/packaged'
  
  @config['sources'] ||= {}
  @config['sources']['javascripts'] ||= "javascripts"
  @config['sources']['stylesheets'] ||= "stylesheets"
  
  # Convert from asset packager syntax
  %w(javascripts stylesheets).each do |type|
    if @config[type].respond_to?(:pop)
      @config[type] = @config[type].inject({}) do |hash, package|
        hash.merge! package
      end
    end
  end
  
  # Class variables
  @append_random = 
    if @config['append_random'].is_a?(::Hash)
      @config['append_random'][@env]
    else
      @config['append_random']
    end
  
  @asset_host = @config['asset_host']
  @envs = @config['environments']
  @sources = @config['sources']
  
  @pub = File.expand_path("#{@root}/#{@config['public']}")
  @dest = %w(javascripts stylesheets).inject({}) do |hash, type|
    hash[type] = "#{@pub}/#{@config['destination'][type]}"
    hash
  end
end

.paths(type, match) ⇒ Object



181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
# File 'lib/smart_asset.rb', line 181

def paths(type, match)
  match = match.to_s
  
  @cache ||= {}
  @cache[type] ||= {}
  
  if @cache[type][match]
    return @cache[type][match]
  end
  
  dest = @dest[type]
  ext = ext_from_type type
  
  if @envs.include?(@env.to_s)
    @cache[type][match] =
      if result = Dir["#{dest}/#{"[^_]"*8}_#{match}.#{ext}"].first
        [ result.gsub(@pub, '') ]
      else
        []
      end
  elsif @config && @config[type]
    result = @config[type].collect do |package, files|
      if package.to_s == match
        files.collect do |file|
          file = "/#{@sources[type]}/#{file}.#{ext}"
          file if File.exists?("#{@pub}/#{file}")
        end
      end
    end
    result.flatten.compact.uniq
  end
end

.prepend_asset_host(path) ⇒ Object



214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
# File 'lib/smart_asset.rb', line 214

def prepend_asset_host(path)
  if @asset_host.respond_to?(:keys)
    host = @asset_host[@env.to_s]
  else
    host = @asset_host
  end
  
  if host    
    if !@asset_counter || @asset_counter == @config['asset_host_count']
      @asset_counter = 0
    end
  
    count = @asset_counter.to_s
    @asset_counter += 1
  
    host.gsub('%d', count) + path
  else
    path
  end
end