Froze rails gems
[depot.git] / vendor / rails / actionpack / lib / action_view / helpers / asset_tag_helper.rb
1 require 'cgi'
2 require 'action_view/helpers/url_helper'
3 require 'action_view/helpers/tag_helper'
4
5 module ActionView
6 module Helpers #:nodoc:
7 # This module provides methods for generating HTML that links views to assets such
8 # as images, javascripts, stylesheets, and feeds. These methods do not verify
9 # the assets exist before linking to them.
10 #
11 # === Using asset hosts
12 # By default, Rails links to these assets on the current host in the public
13 # folder, but you can direct Rails to link to assets from a dedicated assets server by
14 # setting ActionController::Base.asset_host in your <tt>config/environment.rb</tt>. For example,
15 # let's say your asset host is <tt>assets.example.com</tt>.
16 #
17 # ActionController::Base.asset_host = "assets.example.com"
18 # image_tag("rails.png")
19 # => <img src="http://assets.example.com/images/rails.png" alt="Rails" />
20 # stylesheet_link_tag("application")
21 # => <link href="http://assets.example.com/stylesheets/application.css" media="screen" rel="stylesheet" type="text/css" />
22 #
23 # This is useful since browsers typically open at most two connections to a single host,
24 # which means your assets often wait in single file for their turn to load. You can
25 # alleviate this by using a <tt>%d</tt> wildcard in <tt>asset_host</tt> (for example, "assets%d.example.com")
26 # to automatically distribute asset requests among four hosts (e.g., "assets0.example.com" through "assets3.example.com")
27 # so browsers will open eight connections rather than two.
28 #
29 # image_tag("rails.png")
30 # => <img src="http://assets0.example.com/images/rails.png" alt="Rails" />
31 # stylesheet_link_tag("application")
32 # => <link href="http://assets3.example.com/stylesheets/application.css" media="screen" rel="stylesheet" type="text/css" />
33 #
34 # To do this, you can either setup 4 actual hosts, or you can use wildcard DNS to CNAME
35 # the wildcard to a single asset host. You can read more about setting up your DNS CNAME records from
36 # your ISP.
37 #
38 # Note: This is purely a browser performance optimization and is not meant
39 # for server load balancing. See http://www.die.net/musings/page_load_time/
40 # for background.
41 #
42 # Alternatively, you can exert more control over the asset host by setting <tt>asset_host</tt> to a proc
43 # that takes a single source argument. This is useful if you are unable to setup 4 actual hosts or have
44 # fewer/more than 4 hosts. The example proc below generates http://assets1.example.com and
45 # http://assets2.example.com randomly.
46 #
47 # ActionController::Base.asset_host = Proc.new { |source| "http://assets#{rand(2) + 1}.example.com" }
48 # image_tag("rails.png")
49 # => <img src="http://assets2.example.com/images/rails.png" alt="Rails" />
50 # stylesheet_link_tag("application")
51 # => <link href="http://assets1.example.com/stylesheets/application.css" media="screen" rel="stylesheet" type="text/css" />
52 #
53 # The proc takes a <tt>source</tt> parameter (which is the path of the source asset) and an optional
54 # <tt>request</tt> parameter (which is an entire instance of an <tt>ActionController::AbstractRequest</tt>
55 # subclass). This can be used to generate a particular asset host depending on the asset path and the particular
56 # request.
57 #
58 # ActionController::Base.asset_host = Proc.new { |source|
59 # if source.starts_with?('/images')
60 # "http://images.example.com"
61 # else
62 # "http://assets.example.com"
63 # end
64 # }
65 # image_tag("rails.png")
66 # => <img src="http://images.example.com/images/rails.png" alt="Rails" />
67 # stylesheet_link_tag("application")
68 # => <link href="http://assets.example.com/stylesheets/application.css" media="screen" rel="stylesheet" type="text/css" />
69 #
70 # The optional <tt>request</tt> parameter to the proc is useful in particular for serving assets from an
71 # SSL-protected page. The example proc below disables asset hosting for HTTPS connections, while still sending
72 # assets for plain HTTP requests from asset hosts. This is useful for avoiding mixed media warnings when serving
73 # non-HTTP assets from HTTPS web pages when you don't have an SSL certificate for each of the asset hosts.
74 #
75 # ActionController::Base.asset_host = Proc.new { |source, request|
76 # if request.ssl?
77 # "#{request.protocol}#{request.host_with_port}"
78 # else
79 # "#{request.protocol}assets.example.com"
80 # end
81 # }
82 #
83 # === Using asset timestamps
84 #
85 # By default, Rails will append all asset paths with that asset's timestamp. This allows you to set a cache-expiration date for the
86 # asset far into the future, but still be able to instantly invalidate it by simply updating the file (and hence updating the timestamp,
87 # which then updates the URL as the timestamp is part of that, which in turn busts the cache).
88 #
89 # It's the responsibility of the web server you use to set the far-future expiration date on cache assets that you need to take
90 # advantage of this feature. Here's an example for Apache:
91 #
92 # # Asset Expiration
93 # ExpiresActive On
94 # <FilesMatch "\.(ico|gif|jpe?g|png|js|css)$">
95 # ExpiresDefault "access plus 1 year"
96 # </FilesMatch>
97 #
98 # Also note that in order for this to work, all your application servers must return the same timestamps. This means that they must
99 # have their clocks synchronized. If one of them drift out of sync, you'll see different timestamps at random and the cache won't
100 # work. Which means that the browser will request the same assets over and over again even thought they didn't change. You can use
101 # something like Live HTTP Headers for Firefox to verify that the cache is indeed working (and that the assets are not being
102 # requested over and over).
103 module AssetTagHelper
104 ASSETS_DIR = defined?(Rails.public_path) ? Rails.public_path : "public"
105 JAVASCRIPTS_DIR = "#{ASSETS_DIR}/javascripts"
106 STYLESHEETS_DIR = "#{ASSETS_DIR}/stylesheets"
107 JAVASCRIPT_DEFAULT_SOURCES = ['prototype', 'effects', 'dragdrop', 'controls'].freeze unless const_defined?(:JAVASCRIPT_DEFAULT_SOURCES)
108
109 # Returns a link tag that browsers and news readers can use to auto-detect
110 # an RSS or ATOM feed. The +type+ can either be <tt>:rss</tt> (default) or
111 # <tt>:atom</tt>. Control the link options in url_for format using the
112 # +url_options+. You can modify the LINK tag itself in +tag_options+.
113 #
114 # ==== Options:
115 # * <tt>:rel</tt> - Specify the relation of this link, defaults to "alternate"
116 # * <tt>:type</tt> - Override the auto-generated mime type
117 # * <tt>:title</tt> - Specify the title of the link, defaults to the +type+
118 #
119 # ==== Examples
120 # auto_discovery_link_tag # =>
121 # <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.currenthost.com/controller/action" />
122 # auto_discovery_link_tag(:atom) # =>
123 # <link rel="alternate" type="application/atom+xml" title="ATOM" href="http://www.currenthost.com/controller/action" />
124 # auto_discovery_link_tag(:rss, {:action => "feed"}) # =>
125 # <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.currenthost.com/controller/feed" />
126 # auto_discovery_link_tag(:rss, {:action => "feed"}, {:title => "My RSS"}) # =>
127 # <link rel="alternate" type="application/rss+xml" title="My RSS" href="http://www.currenthost.com/controller/feed" />
128 # auto_discovery_link_tag(:rss, {:controller => "news", :action => "feed"}) # =>
129 # <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.currenthost.com/news/feed" />
130 # auto_discovery_link_tag(:rss, "http://www.example.com/feed.rss", {:title => "Example RSS"}) # =>
131 # <link rel="alternate" type="application/rss+xml" title="Example RSS" href="http://www.example.com/feed" />
132 def auto_discovery_link_tag(type = :rss, url_options = {}, tag_options = {})
133 tag(
134 "link",
135 "rel" => tag_options[:rel] || "alternate",
136 "type" => tag_options[:type] || Mime::Type.lookup_by_extension(type.to_s).to_s,
137 "title" => tag_options[:title] || type.to_s.upcase,
138 "href" => url_options.is_a?(Hash) ? url_for(url_options.merge(:only_path => false)) : url_options
139 )
140 end
141
142 # Computes the path to a javascript asset in the public javascripts directory.
143 # If the +source+ filename has no extension, .js will be appended.
144 # Full paths from the document root will be passed through.
145 # Used internally by javascript_include_tag to build the script path.
146 #
147 # ==== Examples
148 # javascript_path "xmlhr" # => /javascripts/xmlhr.js
149 # javascript_path "dir/xmlhr.js" # => /javascripts/dir/xmlhr.js
150 # javascript_path "/dir/xmlhr" # => /dir/xmlhr.js
151 # javascript_path "http://www.railsapplication.com/js/xmlhr" # => http://www.railsapplication.com/js/xmlhr.js
152 # javascript_path "http://www.railsapplication.com/js/xmlhr.js" # => http://www.railsapplication.com/js/xmlhr.js
153 def javascript_path(source)
154 JavaScriptTag.new(self, @controller, source).public_path
155 end
156 alias_method :path_to_javascript, :javascript_path # aliased to avoid conflicts with a javascript_path named route
157
158 # Returns an html script tag for each of the +sources+ provided. You
159 # can pass in the filename (.js extension is optional) of javascript files
160 # that exist in your public/javascripts directory for inclusion into the
161 # current page or you can pass the full path relative to your document
162 # root. To include the Prototype and Scriptaculous javascript libraries in
163 # your application, pass <tt>:defaults</tt> as the source. When using
164 # <tt>:defaults</tt>, if an application.js file exists in your public
165 # javascripts directory, it will be included as well. You can modify the
166 # html attributes of the script tag by passing a hash as the last argument.
167 #
168 # ==== Examples
169 # javascript_include_tag "xmlhr" # =>
170 # <script type="text/javascript" src="/javascripts/xmlhr.js"></script>
171 #
172 # javascript_include_tag "xmlhr.js" # =>
173 # <script type="text/javascript" src="/javascripts/xmlhr.js"></script>
174 #
175 # javascript_include_tag "common.javascript", "/elsewhere/cools" # =>
176 # <script type="text/javascript" src="/javascripts/common.javascript"></script>
177 # <script type="text/javascript" src="/elsewhere/cools.js"></script>
178 #
179 # javascript_include_tag "http://www.railsapplication.com/xmlhr" # =>
180 # <script type="text/javascript" src="http://www.railsapplication.com/xmlhr.js"></script>
181 #
182 # javascript_include_tag "http://www.railsapplication.com/xmlhr.js" # =>
183 # <script type="text/javascript" src="http://www.railsapplication.com/xmlhr.js"></script>
184 #
185 # javascript_include_tag :defaults # =>
186 # <script type="text/javascript" src="/javascripts/prototype.js"></script>
187 # <script type="text/javascript" src="/javascripts/effects.js"></script>
188 # ...
189 # <script type="text/javascript" src="/javascripts/application.js"></script>
190 #
191 # * = The application.js file is only referenced if it exists
192 #
193 # Though it's not really recommended practice, if you need to extend the default JavaScript set for any reason
194 # (e.g., you're going to be using a certain .js file in every action), then take a look at the register_javascript_include_default method.
195 #
196 # You can also include all javascripts in the javascripts directory using <tt>:all</tt> as the source:
197 #
198 # javascript_include_tag :all # =>
199 # <script type="text/javascript" src="/javascripts/prototype.js"></script>
200 # <script type="text/javascript" src="/javascripts/effects.js"></script>
201 # ...
202 # <script type="text/javascript" src="/javascripts/application.js"></script>
203 # <script type="text/javascript" src="/javascripts/shop.js"></script>
204 # <script type="text/javascript" src="/javascripts/checkout.js"></script>
205 #
206 # Note that the default javascript files will be included first. So Prototype and Scriptaculous are available to
207 # all subsequently included files.
208 #
209 # If you want Rails to search in all the subdirectories under javascripts, you should explicitly set <tt>:recursive</tt>:
210 #
211 # javascript_include_tag :all, :recursive => true
212 #
213 # == Caching multiple javascripts into one
214 #
215 # You can also cache multiple javascripts into one file, which requires less HTTP connections to download and can better be
216 # compressed by gzip (leading to faster transfers). Caching will only happen if ActionController::Base.perform_caching
217 # is set to <tt>true</tt> (which is the case by default for the Rails production environment, but not for the development
218 # environment).
219 #
220 # ==== Examples
221 # javascript_include_tag :all, :cache => true # when ActionController::Base.perform_caching is false =>
222 # <script type="text/javascript" src="/javascripts/prototype.js"></script>
223 # <script type="text/javascript" src="/javascripts/effects.js"></script>
224 # ...
225 # <script type="text/javascript" src="/javascripts/application.js"></script>
226 # <script type="text/javascript" src="/javascripts/shop.js"></script>
227 # <script type="text/javascript" src="/javascripts/checkout.js"></script>
228 #
229 # javascript_include_tag :all, :cache => true # when ActionController::Base.perform_caching is true =>
230 # <script type="text/javascript" src="/javascripts/all.js"></script>
231 #
232 # javascript_include_tag "prototype", "cart", "checkout", :cache => "shop" # when ActionController::Base.perform_caching is false =>
233 # <script type="text/javascript" src="/javascripts/prototype.js"></script>
234 # <script type="text/javascript" src="/javascripts/cart.js"></script>
235 # <script type="text/javascript" src="/javascripts/checkout.js"></script>
236 #
237 # javascript_include_tag "prototype", "cart", "checkout", :cache => "shop" # when ActionController::Base.perform_caching is true =>
238 # <script type="text/javascript" src="/javascripts/shop.js"></script>
239 #
240 # The <tt>:recursive</tt> option is also available for caching:
241 #
242 # javascript_include_tag :all, :cache => true, :recursive => true
243 def javascript_include_tag(*sources)
244 options = sources.extract_options!.stringify_keys
245 cache = options.delete("cache")
246 recursive = options.delete("recursive")
247
248 if ActionController::Base.perform_caching && cache
249 joined_javascript_name = (cache == true ? "all" : cache) + ".js"
250 joined_javascript_path = File.join(JAVASCRIPTS_DIR, joined_javascript_name)
251
252 unless File.exists?(joined_javascript_path)
253 JavaScriptSources.create(self, @controller, sources, recursive).write_asset_file_contents(joined_javascript_path)
254 end
255 javascript_src_tag(joined_javascript_name, options)
256 else
257 JavaScriptSources.create(self, @controller, sources, recursive).expand_sources.collect { |source|
258 javascript_src_tag(source, options)
259 }.join("\n")
260 end
261 end
262
263 # Register one or more javascript files to be included when <tt>symbol</tt>
264 # is passed to <tt>javascript_include_tag</tt>. This method is typically intended
265 # to be called from plugin initialization to register javascript files
266 # that the plugin installed in <tt>public/javascripts</tt>.
267 #
268 # ActionView::Helpers::AssetTagHelper.register_javascript_expansion :monkey => ["head", "body", "tail"]
269 #
270 # javascript_include_tag :monkey # =>
271 # <script type="text/javascript" src="/javascripts/head.js"></script>
272 # <script type="text/javascript" src="/javascripts/body.js"></script>
273 # <script type="text/javascript" src="/javascripts/tail.js"></script>
274 def self.register_javascript_expansion(expansions)
275 JavaScriptSources.expansions.merge!(expansions)
276 end
277
278 # Register one or more stylesheet files to be included when <tt>symbol</tt>
279 # is passed to <tt>stylesheet_link_tag</tt>. This method is typically intended
280 # to be called from plugin initialization to register stylesheet files
281 # that the plugin installed in <tt>public/stylesheets</tt>.
282 #
283 # ActionView::Helpers::AssetTagHelper.register_stylesheet_expansion :monkey => ["head", "body", "tail"]
284 #
285 # stylesheet_link_tag :monkey # =>
286 # <link href="/stylesheets/head.css" media="screen" rel="stylesheet" type="text/css" />
287 # <link href="/stylesheets/body.css" media="screen" rel="stylesheet" type="text/css" />
288 # <link href="/stylesheets/tail.css" media="screen" rel="stylesheet" type="text/css" />
289 def self.register_stylesheet_expansion(expansions)
290 StylesheetSources.expansions.merge!(expansions)
291 end
292
293 # Register one or more additional JavaScript files to be included when
294 # <tt>javascript_include_tag :defaults</tt> is called. This method is
295 # typically intended to be called from plugin initialization to register additional
296 # .js files that the plugin installed in <tt>public/javascripts</tt>.
297 def self.register_javascript_include_default(*sources)
298 JavaScriptSources.expansions[:defaults].concat(sources)
299 end
300
301 def self.reset_javascript_include_default #:nodoc:
302 JavaScriptSources.expansions[:defaults] = JAVASCRIPT_DEFAULT_SOURCES.dup
303 end
304
305 # Computes the path to a stylesheet asset in the public stylesheets directory.
306 # If the +source+ filename has no extension, <tt>.css</tt> will be appended.
307 # Full paths from the document root will be passed through.
308 # Used internally by +stylesheet_link_tag+ to build the stylesheet path.
309 #
310 # ==== Examples
311 # stylesheet_path "style" # => /stylesheets/style.css
312 # stylesheet_path "dir/style.css" # => /stylesheets/dir/style.css
313 # stylesheet_path "/dir/style.css" # => /dir/style.css
314 # stylesheet_path "http://www.railsapplication.com/css/style" # => http://www.railsapplication.com/css/style.css
315 # stylesheet_path "http://www.railsapplication.com/css/style.js" # => http://www.railsapplication.com/css/style.css
316 def stylesheet_path(source)
317 StylesheetTag.new(self, @controller, source).public_path
318 end
319 alias_method :path_to_stylesheet, :stylesheet_path # aliased to avoid conflicts with a stylesheet_path named route
320
321 # Returns a stylesheet link tag for the sources specified as arguments. If
322 # you don't specify an extension, <tt>.css</tt> will be appended automatically.
323 # You can modify the link attributes by passing a hash as the last argument.
324 #
325 # ==== Examples
326 # stylesheet_link_tag "style" # =>
327 # <link href="/stylesheets/style.css" media="screen" rel="stylesheet" type="text/css" />
328 #
329 # stylesheet_link_tag "style.css" # =>
330 # <link href="/stylesheets/style.css" media="screen" rel="stylesheet" type="text/css" />
331 #
332 # stylesheet_link_tag "http://www.railsapplication.com/style.css" # =>
333 # <link href="http://www.railsapplication.com/style.css" media="screen" rel="stylesheet" type="text/css" />
334 #
335 # stylesheet_link_tag "style", :media => "all" # =>
336 # <link href="/stylesheets/style.css" media="all" rel="stylesheet" type="text/css" />
337 #
338 # stylesheet_link_tag "style", :media => "print" # =>
339 # <link href="/stylesheets/style.css" media="print" rel="stylesheet" type="text/css" />
340 #
341 # stylesheet_link_tag "random.styles", "/css/stylish" # =>
342 # <link href="/stylesheets/random.styles" media="screen" rel="stylesheet" type="text/css" />
343 # <link href="/css/stylish.css" media="screen" rel="stylesheet" type="text/css" />
344 #
345 # You can also include all styles in the stylesheets directory using <tt>:all</tt> as the source:
346 #
347 # stylesheet_link_tag :all # =>
348 # <link href="/stylesheets/style1.css" media="screen" rel="stylesheet" type="text/css" />
349 # <link href="/stylesheets/styleB.css" media="screen" rel="stylesheet" type="text/css" />
350 # <link href="/stylesheets/styleX2.css" media="screen" rel="stylesheet" type="text/css" />
351 #
352 # If you want Rails to search in all the subdirectories under stylesheets, you should explicitly set <tt>:recursive</tt>:
353 #
354 # stylesheet_link_tag :all, :recursive => true
355 #
356 # == Caching multiple stylesheets into one
357 #
358 # You can also cache multiple stylesheets into one file, which requires less HTTP connections and can better be
359 # compressed by gzip (leading to faster transfers). Caching will only happen if ActionController::Base.perform_caching
360 # is set to true (which is the case by default for the Rails production environment, but not for the development
361 # environment). Examples:
362 #
363 # ==== Examples
364 # stylesheet_link_tag :all, :cache => true # when ActionController::Base.perform_caching is false =>
365 # <link href="/stylesheets/style1.css" media="screen" rel="stylesheet" type="text/css" />
366 # <link href="/stylesheets/styleB.css" media="screen" rel="stylesheet" type="text/css" />
367 # <link href="/stylesheets/styleX2.css" media="screen" rel="stylesheet" type="text/css" />
368 #
369 # stylesheet_link_tag :all, :cache => true # when ActionController::Base.perform_caching is true =>
370 # <link href="/stylesheets/all.css" media="screen" rel="stylesheet" type="text/css" />
371 #
372 # stylesheet_link_tag "shop", "cart", "checkout", :cache => "payment" # when ActionController::Base.perform_caching is false =>
373 # <link href="/stylesheets/shop.css" media="screen" rel="stylesheet" type="text/css" />
374 # <link href="/stylesheets/cart.css" media="screen" rel="stylesheet" type="text/css" />
375 # <link href="/stylesheets/checkout.css" media="screen" rel="stylesheet" type="text/css" />
376 #
377 # stylesheet_link_tag "shop", "cart", "checkout", :cache => "payment" # when ActionController::Base.perform_caching is true =>
378 # <link href="/stylesheets/payment.css" media="screen" rel="stylesheet" type="text/css" />
379 #
380 # The <tt>:recursive</tt> option is also available for caching:
381 #
382 # stylesheet_link_tag :all, :cache => true, :recursive => true
383 def stylesheet_link_tag(*sources)
384 options = sources.extract_options!.stringify_keys
385 cache = options.delete("cache")
386 recursive = options.delete("recursive")
387
388 if ActionController::Base.perform_caching && cache
389 joined_stylesheet_name = (cache == true ? "all" : cache) + ".css"
390 joined_stylesheet_path = File.join(STYLESHEETS_DIR, joined_stylesheet_name)
391
392 unless File.exists?(joined_stylesheet_path)
393 StylesheetSources.create(self, @controller, sources, recursive).write_asset_file_contents(joined_stylesheet_path)
394 end
395 stylesheet_tag(joined_stylesheet_name, options)
396 else
397 StylesheetSources.create(self, @controller, sources, recursive).expand_sources.collect { |source|
398 stylesheet_tag(source, options)
399 }.join("\n")
400 end
401 end
402
403 # Computes the path to an image asset in the public images directory.
404 # Full paths from the document root will be passed through.
405 # Used internally by +image_tag+ to build the image path.
406 #
407 # ==== Examples
408 # image_path("edit") # => /images/edit
409 # image_path("edit.png") # => /images/edit.png
410 # image_path("icons/edit.png") # => /images/icons/edit.png
411 # image_path("/icons/edit.png") # => /icons/edit.png
412 # image_path("http://www.railsapplication.com/img/edit.png") # => http://www.railsapplication.com/img/edit.png
413 def image_path(source)
414 ImageTag.new(self, @controller, source).public_path
415 end
416 alias_method :path_to_image, :image_path # aliased to avoid conflicts with an image_path named route
417
418 # Returns an html image tag for the +source+. The +source+ can be a full
419 # path or a file that exists in your public images directory.
420 #
421 # ==== Options
422 # You can add HTML attributes using the +options+. The +options+ supports
423 # three additional keys for convenience and conformance:
424 #
425 # * <tt>:alt</tt> - If no alt text is given, the file name part of the
426 # +source+ is used (capitalized and without the extension)
427 # * <tt>:size</tt> - Supplied as "{Width}x{Height}", so "30x45" becomes
428 # width="30" and height="45". <tt>:size</tt> will be ignored if the
429 # value is not in the correct format.
430 # * <tt>:mouseover</tt> - Set an alternate image to be used when the onmouseover
431 # event is fired, and sets the original image to be replaced onmouseout.
432 # This can be used to implement an easy image toggle that fires on onmouseover.
433 #
434 # ==== Examples
435 # image_tag("icon") # =>
436 # <img src="/images/icon" alt="Icon" />
437 # image_tag("icon.png") # =>
438 # <img src="/images/icon.png" alt="Icon" />
439 # image_tag("icon.png", :size => "16x10", :alt => "Edit Entry") # =>
440 # <img src="/images/icon.png" width="16" height="10" alt="Edit Entry" />
441 # image_tag("/icons/icon.gif", :size => "16x16") # =>
442 # <img src="/icons/icon.gif" width="16" height="16" alt="Icon" />
443 # image_tag("/icons/icon.gif", :height => '32', :width => '32') # =>
444 # <img alt="Icon" height="32" src="/icons/icon.gif" width="32" />
445 # image_tag("/icons/icon.gif", :class => "menu_icon") # =>
446 # <img alt="Icon" class="menu_icon" src="/icons/icon.gif" />
447 # image_tag("mouse.png", :mouseover => "/images/mouse_over.png") # =>
448 # <img src="/images/mouse.png" onmouseover="this.src='/images/mouse_over.png'" onmouseout="this.src='/images/mouse.png'" alt="Mouse" />
449 # image_tag("mouse.png", :mouseover => image_path("mouse_over.png")) # =>
450 # <img src="/images/mouse.png" onmouseover="this.src='/images/mouse_over.png'" onmouseout="this.src='/images/mouse.png'" alt="Mouse" />
451 def image_tag(source, options = {})
452 options.symbolize_keys!
453
454 options[:src] = path_to_image(source)
455 options[:alt] ||= File.basename(options[:src], '.*').split('.').first.to_s.capitalize
456
457 if size = options.delete(:size)
458 options[:width], options[:height] = size.split("x") if size =~ %r{^\d+x\d+$}
459 end
460
461 if mouseover = options.delete(:mouseover)
462 options[:onmouseover] = "this.src='#{image_path(mouseover)}'"
463 options[:onmouseout] = "this.src='#{image_path(options[:src])}'"
464 end
465
466 tag("img", options)
467 end
468
469 private
470 def javascript_src_tag(source, options)
471 content_tag("script", "", { "type" => Mime::JS, "src" => path_to_javascript(source) }.merge(options))
472 end
473
474 def stylesheet_tag(source, options)
475 tag("link", { "rel" => "stylesheet", "type" => Mime::CSS, "media" => "screen", "href" => html_escape(path_to_stylesheet(source)) }.merge(options), false, false)
476 end
477
478 module ImageAsset
479 DIRECTORY = 'images'.freeze
480
481 def directory
482 DIRECTORY
483 end
484
485 def extension
486 nil
487 end
488 end
489
490 module JavaScriptAsset
491 DIRECTORY = 'javascripts'.freeze
492 EXTENSION = 'js'.freeze
493
494 def public_directory
495 JAVASCRIPTS_DIR
496 end
497
498 def directory
499 DIRECTORY
500 end
501
502 def extension
503 EXTENSION
504 end
505 end
506
507 module StylesheetAsset
508 DIRECTORY = 'stylesheets'.freeze
509 EXTENSION = 'css'.freeze
510
511 def public_directory
512 STYLESHEETS_DIR
513 end
514
515 def directory
516 DIRECTORY
517 end
518
519 def extension
520 EXTENSION
521 end
522 end
523
524 class AssetTag
525 extend ActiveSupport::Memoizable
526
527 Cache = {}
528 CacheGuard = Mutex.new
529
530 ProtocolRegexp = %r{^[-a-z]+://}.freeze
531
532 def initialize(template, controller, source, include_host = true)
533 # NOTE: The template arg is temporarily needed for a legacy plugin
534 # hook that is expected to call rewrite_asset_path on the
535 # template. This should eventually be removed.
536 @template = template
537 @controller = controller
538 @source = source
539 @include_host = include_host
540 @cache_key = if controller.respond_to?(:request)
541 [self.class.name,controller.request.protocol,
542 ActionController::Base.asset_host,
543 ActionController::Base.relative_url_root,
544 source, include_host]
545 else
546 [self.class.name,ActionController::Base.asset_host, source, include_host]
547 end
548 end
549
550 def public_path
551 compute_public_path(@source)
552 end
553 memoize :public_path
554
555 def asset_file_path
556 File.join(ASSETS_DIR, public_path.split('?').first)
557 end
558 memoize :asset_file_path
559
560 def contents
561 File.read(asset_file_path)
562 end
563
564 def mtime
565 File.mtime(asset_file_path)
566 end
567
568 private
569 def request
570 @controller.request
571 end
572
573 def request?
574 @controller.respond_to?(:request)
575 end
576
577 # Add the the extension +ext+ if not present. Return full URLs otherwise untouched.
578 # Prefix with <tt>/dir/</tt> if lacking a leading +/+. Account for relative URL
579 # roots. Rewrite the asset path for cache-busting asset ids. Include
580 # asset host, if configured, with the correct request protocol.
581 def compute_public_path(source)
582 if source =~ ProtocolRegexp
583 source += ".#{extension}" if missing_extension?(source)
584 source = prepend_asset_host(source)
585 source
586 else
587 CacheGuard.synchronize do
588 Cache[@cache_key] ||= begin
589 source += ".#{extension}" if missing_extension?(source) || file_exists_with_extension?(source)
590 source = "/#{directory}/#{source}" unless source[0] == ?/
591 source = rewrite_asset_path(source)
592 source = prepend_relative_url_root(source)
593 source = prepend_asset_host(source)
594 source
595 end
596 end
597 end
598 end
599
600 def missing_extension?(source)
601 extension && File.extname(source).blank?
602 end
603
604 def file_exists_with_extension?(source)
605 extension && File.exist?(File.join(ASSETS_DIR, directory, "#{source}.#{extension}"))
606 end
607
608 def prepend_relative_url_root(source)
609 relative_url_root = ActionController::Base.relative_url_root
610 if request? && @include_host && source !~ %r{^#{relative_url_root}/}
611 "#{relative_url_root}#{source}"
612 else
613 source
614 end
615 end
616
617 def prepend_asset_host(source)
618 if @include_host && source !~ ProtocolRegexp
619 host = compute_asset_host(source)
620 if request? && !host.blank? && host !~ ProtocolRegexp
621 host = "#{request.protocol}#{host}"
622 end
623 "#{host}#{source}"
624 else
625 source
626 end
627 end
628
629 # Pick an asset host for this source. Returns +nil+ if no host is set,
630 # the host if no wildcard is set, the host interpolated with the
631 # numbers 0-3 if it contains <tt>%d</tt> (the number is the source hash mod 4),
632 # or the value returned from invoking the proc if it's a proc.
633 def compute_asset_host(source)
634 if host = ActionController::Base.asset_host
635 if host.is_a?(Proc)
636 case host.arity
637 when 2
638 host.call(source, request)
639 else
640 host.call(source)
641 end
642 else
643 (host =~ /%d/) ? host % (source.hash % 4) : host
644 end
645 end
646 end
647
648 # Use the RAILS_ASSET_ID environment variable or the source's
649 # modification time as its cache-busting asset id.
650 def rails_asset_id(source)
651 if asset_id = ENV["RAILS_ASSET_ID"]
652 asset_id
653 else
654 path = File.join(ASSETS_DIR, source)
655
656 if File.exist?(path)
657 File.mtime(path).to_i.to_s
658 else
659 ''
660 end
661 end
662 end
663
664 # Break out the asset path rewrite in case plugins wish to put the asset id
665 # someplace other than the query string.
666 def rewrite_asset_path(source)
667 if @template.respond_to?(:rewrite_asset_path)
668 # DEPRECATE: This way to override rewrite_asset_path
669 @template.send(:rewrite_asset_path, source)
670 else
671 asset_id = rails_asset_id(source)
672 if asset_id.blank?
673 source
674 else
675 "#{source}?#{asset_id}"
676 end
677 end
678 end
679 end
680
681 class ImageTag < AssetTag
682 include ImageAsset
683 end
684
685 class JavaScriptTag < AssetTag
686 include JavaScriptAsset
687 end
688
689 class StylesheetTag < AssetTag
690 include StylesheetAsset
691 end
692
693 class AssetCollection
694 extend ActiveSupport::Memoizable
695
696 Cache = {}
697 CacheGuard = Mutex.new
698
699 def self.create(template, controller, sources, recursive)
700 CacheGuard.synchronize do
701 key = [self, sources, recursive]
702 Cache[key] ||= new(template, controller, sources, recursive).freeze
703 end
704 end
705
706 def initialize(template, controller, sources, recursive)
707 # NOTE: The template arg is temporarily needed for a legacy plugin
708 # hook. See NOTE under AssetTag#initialize for more details
709 @template = template
710 @controller = controller
711 @sources = sources
712 @recursive = recursive
713 end
714
715 def write_asset_file_contents(joined_asset_path)
716 FileUtils.mkdir_p(File.dirname(joined_asset_path))
717 File.open(joined_asset_path, "w+") { |cache| cache.write(joined_contents) }
718 mt = latest_mtime
719 File.utime(mt, mt, joined_asset_path)
720 end
721
722 private
723 def determine_source(source, collection)
724 case source
725 when Symbol
726 collection[source] || raise(ArgumentError, "No expansion found for #{source.inspect}")
727 else
728 source
729 end
730 end
731
732 def validate_sources!
733 @sources.collect { |source| determine_source(source, self.class.expansions) }.flatten
734 end
735
736 def all_asset_files
737 path = [public_directory, ('**' if @recursive), "*.#{extension}"].compact
738 Dir[File.join(*path)].collect { |file|
739 file[-(file.size - public_directory.size - 1)..-1].sub(/\.\w+$/, '')
740 }.sort
741 end
742
743 def tag_sources
744 expand_sources.collect { |source| tag_class.new(@template, @controller, source, false) }
745 end
746
747 def joined_contents
748 tag_sources.collect { |source| source.contents }.join("\n\n")
749 end
750
751 # Set mtime to the latest of the combined files to allow for
752 # consistent ETag without a shared filesystem.
753 def latest_mtime
754 tag_sources.map { |source| source.mtime }.max
755 end
756 end
757
758 class JavaScriptSources < AssetCollection
759 include JavaScriptAsset
760
761 EXPANSIONS = { :defaults => JAVASCRIPT_DEFAULT_SOURCES.dup }
762
763 def self.expansions
764 EXPANSIONS
765 end
766
767 APPLICATION_JS = "application".freeze
768 APPLICATION_FILE = "application.js".freeze
769
770 def expand_sources
771 if @sources.include?(:all)
772 assets = all_asset_files
773 ((defaults.dup & assets) + assets).uniq!
774 else
775 expanded_sources = validate_sources!
776 expanded_sources << APPLICATION_JS if include_application?
777 expanded_sources
778 end
779 end
780 memoize :expand_sources
781
782 private
783 def tag_class
784 JavaScriptTag
785 end
786
787 def defaults
788 determine_source(:defaults, self.class.expansions)
789 end
790
791 def include_application?
792 @sources.include?(:defaults) && File.exist?(File.join(JAVASCRIPTS_DIR, APPLICATION_FILE))
793 end
794 end
795
796 class StylesheetSources < AssetCollection
797 include StylesheetAsset
798
799 EXPANSIONS = {}
800
801 def self.expansions
802 EXPANSIONS
803 end
804
805 def expand_sources
806 @sources.first == :all ? all_asset_files : validate_sources!
807 end
808 memoize :expand_sources
809
810 private
811 def tag_class
812 StylesheetTag
813 end
814 end
815 end
816 end
817 end