2 require 'action_view/helpers/url_helper'
3 require 'action_view/helpers/tag_helper'
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.
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>.
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" />
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.
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" />
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
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/
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.
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" />
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
58 # ActionController::Base.asset_host = Proc.new { |source|
59 # if source.starts_with?('/images')
60 # "http://images.example.com"
62 # "http://assets.example.com"
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" />
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.
75 # ActionController::Base.asset_host = Proc.new { |source, request|
77 # "#{request.protocol}#{request.host_with_port}"
79 # "#{request.protocol}assets.example.com"
83 # === Using asset timestamps
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).
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:
94 # <FilesMatch "\.(ico|gif|jpe?g|png|js|css)$">
95 # ExpiresDefault "access plus 1 year"
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)
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+.
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+
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
= {})
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
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.
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
156 alias_method
:path_to_javascript, :javascript_path # aliased to avoid conflicts with a javascript_path named route
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.
169 # javascript_include_tag "xmlhr" # =>
170 # <script type="text/javascript" src="/javascripts/xmlhr.js"></script>
172 # javascript_include_tag "xmlhr.js" # =>
173 # <script type="text/javascript" src="/javascripts/xmlhr.js"></script>
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>
179 # javascript_include_tag "http://www.railsapplication.com/xmlhr" # =>
180 # <script type="text/javascript" src="http://www.railsapplication.com/xmlhr.js"></script>
182 # javascript_include_tag "http://www.railsapplication.com/xmlhr.js" # =>
183 # <script type="text/javascript" src="http://www.railsapplication.com/xmlhr.js"></script>
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>
189 # <script type="text/javascript" src="/javascripts/application.js"></script>
191 # * = The application.js file is only referenced if it exists
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.
196 # You can also include all javascripts in the javascripts directory using <tt>:all</tt> as the source:
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>
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>
206 # Note that the default javascript files will be included first. So Prototype and Scriptaculous are available to
207 # all subsequently included files.
209 # If you want Rails to search in all the subdirectories under javascripts, you should explicitly set <tt>:recursive</tt>:
211 # javascript_include_tag :all, :recursive => true
213 # == Caching multiple javascripts into one
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
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>
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>
229 # javascript_include_tag :all, :cache => true # when ActionController::Base.perform_caching is true =>
230 # <script type="text/javascript" src="/javascripts/all.js"></script>
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>
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>
240 # The <tt>:recursive</tt> option is also available for caching:
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")
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
)
252 unless File
.exists
?(joined_javascript_path
)
253 JavaScriptSources
.create(self, @controller, sources
, recursive
).write_asset_file_contents(joined_javascript_path
)
255 javascript_src_tag(joined_javascript_name
, options
)
257 JavaScriptSources
.create(self, @controller, sources
, recursive
).expand_sources
.collect
{ |source
|
258 javascript_src_tag(source
, options
)
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>.
268 # ActionView::Helpers::AssetTagHelper.register_javascript_expansion :monkey => ["head", "body", "tail"]
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
)
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>.
283 # ActionView::Helpers::AssetTagHelper.register_stylesheet_expansion :monkey => ["head", "body", "tail"]
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
)
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
)
301 def self.reset_javascript_include_default
#:nodoc:
302 JavaScriptSources
.expansions
[:defaults] = JAVASCRIPT_DEFAULT_SOURCES
.dup
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.
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
319 alias_method
:path_to_stylesheet, :stylesheet_path # aliased to avoid conflicts with a stylesheet_path named route
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.
326 # stylesheet_link_tag "style" # =>
327 # <link href="/stylesheets/style.css" media="screen" rel="stylesheet" type="text/css" />
329 # stylesheet_link_tag "style.css" # =>
330 # <link href="/stylesheets/style.css" media="screen" rel="stylesheet" type="text/css" />
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" />
335 # stylesheet_link_tag "style", :media => "all" # =>
336 # <link href="/stylesheets/style.css" media="all" rel="stylesheet" type="text/css" />
338 # stylesheet_link_tag "style", :media => "print" # =>
339 # <link href="/stylesheets/style.css" media="print" rel="stylesheet" type="text/css" />
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" />
345 # You can also include all styles in the stylesheets directory using <tt>:all</tt> as the source:
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" />
352 # If you want Rails to search in all the subdirectories under stylesheets, you should explicitly set <tt>:recursive</tt>:
354 # stylesheet_link_tag :all, :recursive => true
356 # == Caching multiple stylesheets into one
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:
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" />
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" />
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" />
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" />
380 # The <tt>:recursive</tt> option is also available for caching:
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")
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
)
392 unless File
.exists
?(joined_stylesheet_path
)
393 StylesheetSources
.create(self, @controller, sources
, recursive
).write_asset_file_contents(joined_stylesheet_path
)
395 stylesheet_tag(joined_stylesheet_name
, options
)
397 StylesheetSources
.create(self, @controller, sources
, recursive
).expand_sources
.collect
{ |source
|
398 stylesheet_tag(source
, options
)
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.
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
416 alias_method
:path_to_image, :image_path # aliased to avoid conflicts with an image_path named route
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.
422 # You can add HTML attributes using the +options+. The +options+ supports
423 # three additional keys for convenience and conformance:
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.
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
!
454 options
[:src] = path_to_image(source
)
455 options
[:alt] ||= File
.basename(options
[:src], '.*').split('.').first
.to_s
.capitalize
457 if size
= options
.delete(:size)
458 options
[:width], options
[:height] = size
.split("x") if size
=~
%r
{^\d
+x\d
+$
}
461 if mouseover
= options
.delete(:mouseover)
462 options
[:onmouseover] = "this.src='#{image_path(mouseover)}'"
463 options
[:onmouseout] = "this.src='#{image_path(options[:src])}'"
470 def javascript_src_tag(source
, options
)
471 content_tag("script", "", { "type" => Mime
::JS, "src" => path_to_javascript(source
) }.merge(options
))
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)
479 DIRECTORY
= 'images'.freeze
490 module JavaScriptAsset
491 DIRECTORY
= 'javascripts'.freeze
492 EXTENSION
= 'js'.freeze
507 module StylesheetAsset
508 DIRECTORY
= 'stylesheets'.freeze
509 EXTENSION
= 'css'.freeze
525 extend ActiveSupport
::Memoizable
528 CacheGuard
= Mutex
.new
530 ProtocolRegexp
= %r
{^
[-a-z
]+://}.freeze
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.
537 @controller = controller
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
]
546 [self.class.name
,ActionController
::Base.asset_host
, source
, include_host
]
551 compute_public_path(@source)
556 File
.join(ASSETS_DIR
, public_path
.split('?').first
)
558 memoize
:asset_file_path
561 File
.read(asset_file_path
)
565 File
.mtime(asset_file_path
)
574 @controller.respond_to
?(:request)
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
)
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
)
600 def missing_extension
?(source
)
601 extension
&& File
.extname(source
).blank
?
604 def file_exists_with_extension
?(source
)
605 extension
&& File
.exist
?(File
.join(ASSETS_DIR
, directory
, "#{source}.#{extension}"))
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}"
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}"
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
638 host
.call(source
, request
)
643 (host
=~
/%d/) ? host
% (source
.hash
% 4) : host
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"]
654 path
= File
.join(ASSETS_DIR
, source
)
657 File
.mtime(path
).to_i
.to_s
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
)
671 asset_id
= rails_asset_id(source
)
675 "#{source}?#{asset_id}"
681 class ImageTag
< AssetTag
685 class JavaScriptTag
< AssetTag
686 include JavaScriptAsset
689 class StylesheetTag
< AssetTag
690 include StylesheetAsset
693 class AssetCollection
694 extend ActiveSupport
::Memoizable
697 CacheGuard
= Mutex
.new
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
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
710 @controller = controller
712 @recursive = recursive
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
) }
719 File
.utime(mt
, mt
, joined_asset_path
)
723 def determine_source(source
, collection
)
726 collection
[source
] || raise(ArgumentError
, "No expansion found for #{source.inspect}")
732 def validate_sources
!
733 @sources.collect
{ |source
| determine_source(source
, self.class.expansions
) }.flatten
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+$/, '')
744 expand_sources
.collect
{ |source
| tag_class
.new(@template, @controller, source
, false) }
748 tag_sources
.collect
{ |source
| source
.contents
}.join("\n\n")
751 # Set mtime to the latest of the combined files to allow for
752 # consistent ETag without a shared filesystem.
754 tag_sources
.map
{ |source
| source
.mtime
}.max
758 class JavaScriptSources
< AssetCollection
759 include JavaScriptAsset
761 EXPANSIONS
= { :defaults => JAVASCRIPT_DEFAULT_SOURCES
.dup
}
767 APPLICATION_JS
= "application".freeze
768 APPLICATION_FILE
= "application.js".freeze
771 if @sources.include?(:all)
772 assets
= all_asset_files
773 ((defaults
.dup
& assets
) + assets
).uniq
!
775 expanded_sources
= validate_sources
!
776 expanded_sources
<< APPLICATION_JS
if include_application
?
780 memoize
:expand_sources
788 determine_source(:defaults, self.class.expansions
)
791 def include_application
?
792 @sources.include?(:defaults) && File
.exist
?(File
.join(JAVASCRIPTS_DIR
, APPLICATION_FILE
))
796 class StylesheetSources
< AssetCollection
797 include StylesheetAsset
806 @sources.first
== :all ? all_asset_files
: validate_sources
!
808 memoize
:expand_sources