asset_tag_helper.rb 25.4 KB
Newer Older
1 2
require 'active_support/core_ext/array/extract_options'
require 'active_support/core_ext/hash/keys'
3 4
require 'action_view/helpers/asset_tag_helpers/javascript_tag_helpers'
require 'action_view/helpers/asset_tag_helpers/stylesheet_tag_helpers'
5
require 'action_view/helpers/asset_tag_helpers/asset_paths'
6
require 'action_view/helpers/tag_helper'
7 8

module ActionView
9
  # = Action View Asset Tag Helpers
10
  module Helpers #:nodoc:
11
    # This module provides methods for generating HTML that links views to assets such
12
    # as images, javascripts, stylesheets, and feeds. These methods do not verify
P
Pratik Naik 已提交
13 14 15
    # the assets exist before linking to them:
    #
    #   image_tag("rails.png")
16
    #   # => <img alt="Rails" src="/images/rails.png?1230601161" />
P
Pratik Naik 已提交
17
    #   stylesheet_link_tag("application")
18
    #   # => <link href="/stylesheets/application.css?1232285206" media="screen" rel="stylesheet" />
19 20
    #
    # === Using asset hosts
P
Pratik Naik 已提交
21
    #
22
    # By default, Rails links to these assets on the current host in the public
P
Pratik Naik 已提交
23 24 25 26
    # folder, but you can direct Rails to link to assets from a dedicated asset
    # server by setting ActionController::Base.asset_host in the application
    # configuration, typically in <tt>config/environments/production.rb</tt>.
    # For example, you'd define <tt>assets.example.com</tt> to be your asset
27 28
    # host this way, inside the <tt>configure</tt> block of your environment-specific
    # configuration files or <tt>config/application.rb</tt>:
29
    #
30
    #   config.action_controller.asset_host = "assets.example.com"
P
Pratik Naik 已提交
31 32 33
    #
    # Helpers take that into account:
    #
34
    #   image_tag("rails.png")
P
Pratik Naik 已提交
35
    #   # => <img alt="Rails" src="http://assets.example.com/images/rails.png?1230601161" />
36
    #   stylesheet_link_tag("application")
37
    #   # => <link href="http://assets.example.com/stylesheets/application.css?1232285206" media="screen" rel="stylesheet" />
38
    #
P
Pratik Naik 已提交
39 40 41 42 43 44 45
    # Browsers typically open at most two simultaneous connections to a single
    # host, which means your assets often have to wait for other assets to finish
    # downloading. You can alleviate this by using a <tt>%d</tt> wildcard in the
    # +asset_host+. For example, "assets%d.example.com". If that wildcard is
    # present Rails distributes asset requests among the corresponding four hosts
    # "assets0.example.com", ..., "assets3.example.com". With this trick browsers
    # will open eight simultaneous connections rather than two.
46 47
    #
    #   image_tag("rails.png")
P
Pratik Naik 已提交
48
    #   # => <img alt="Rails" src="http://assets0.example.com/images/rails.png?1230601161" />
49
    #   stylesheet_link_tag("application")
50
    #   # => <link href="http://assets2.example.com/stylesheets/application.css?1232285206" media="screen" rel="stylesheet" />
51
    #
P
Pratik Naik 已提交
52 53 54
    # To do this, you can either setup four actual hosts, or you can use wildcard
    # DNS to CNAME the wildcard to a single asset host. You can read more about
    # setting up your DNS CNAME records from your ISP.
55
    #
56
    # Note: This is purely a browser performance optimization and is not meant
57 58
    # for server load balancing. See http://www.die.net/musings/page_load_time/
    # for background.
59
    #
P
Pratik Naik 已提交
60 61
    # Alternatively, you can exert more control over the asset host by setting
    # +asset_host+ to a proc like this:
62
    #
P
Pratik Naik 已提交
63
    #   ActionController::Base.asset_host = Proc.new { |source|
64
    #     "http://assets#{Digest::MD5.hexdigest(source).to_i(16) % 2 + 1}.example.com"
P
Pratik Naik 已提交
65
    #   }
66
    #   image_tag("rails.png")
M
Marius Nuennerich 已提交
67
    #   # => <img alt="Rails" src="http://assets1.example.com/images/rails.png?1230601161" />
68
    #   stylesheet_link_tag("application")
69
    #   # => <link href="http://assets2.example.com/stylesheets/application.css?1232285206" media="screen" rel="stylesheet" />
P
Pratik Naik 已提交
70 71
    #
    # The example above generates "http://assets1.example.com" and
72
    # "http://assets2.example.com". This option is useful for example if
P
Pratik Naik 已提交
73
    # you need fewer/more than four hosts, custom host names, etc.
74
    #
P
Pratik Naik 已提交
75 76 77
    # As you see the proc takes a +source+ parameter. That's a string with the
    # absolute path of the asset with any extensions and timestamps in place,
    # for example "/images/rails.png?1230601161".
78 79 80 81 82 83 84 85 86
    #
    #    ActionController::Base.asset_host = Proc.new { |source|
    #      if source.starts_with?('/images')
    #        "http://images.example.com"
    #      else
    #        "http://assets.example.com"
    #      end
    #    }
    #   image_tag("rails.png")
P
Pratik Naik 已提交
87
    #   # => <img alt="Rails" src="http://images.example.com/images/rails.png?1230601161" />
88
    #   stylesheet_link_tag("application")
89
    #   # => <link href="http://assets.example.com/stylesheets/application.css?1232285206" media="screen" rel="stylesheet" />
90
    #
P
Pratik Naik 已提交
91 92 93 94 95 96
    # Alternatively you may ask for a second parameter +request+. That one is
    # particularly useful for serving assets from an SSL-protected page. The
    # example proc below disables asset hosting for HTTPS connections, while
    # still sending assets for plain HTTP requests from asset hosts. If you don't
    # have SSL certificates for each of the asset hosts this technique allows you
    # to avoid warnings in the client about mixed media.
97 98 99 100 101 102 103 104 105
    #
    #   ActionController::Base.asset_host = Proc.new { |source, request|
    #     if request.ssl?
    #       "#{request.protocol}#{request.host_with_port}"
    #     else
    #       "#{request.protocol}assets.example.com"
    #     end
    #   }
    #
P
Pratik Naik 已提交
106 107
    # You can also implement a custom asset host object that responds to +call+
    # and takes either one or two parameters just like the proc.
108 109 110 111 112
    #
    #   config.action_controller.asset_host = AssetHostingWithMinimumSsl.new(
    #     "http://asset%d.example.com", "https://asset1.example.com"
    #   )
    #
113
    # === Customizing the asset path
114
    #
P
Pratik Naik 已提交
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
    # By default, Rails appends asset's timestamps to all asset paths. This allows
    # you to set a cache-expiration date for the asset far into the future, but
    # still be able to instantly invalidate it by simply updating the file (and
    # hence updating the timestamp, which then updates the URL as the timestamp
    # is part of that, which in turn busts the cache).
    #
    # 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 advantage of this
    # feature. Here's an example for Apache:
    #
    #   # Asset Expiration
    #   ExpiresActive On
    #   <FilesMatch "\.(ico|gif|jpe?g|png|js|css)$">
    #     ExpiresDefault "access plus 1 year"
    #   </FilesMatch>
    #
    # Also note that in order for this to work, all your application servers must
    # return the same timestamps. This means that they must have their clocks
    # synchronized. If one of them drifts out of sync, you'll see different
    # timestamps at random and the cache won't work. In that case the browser
    # will request the same assets over and over again even thought they didn't
    # change. You can use something like Live HTTP Headers for Firefox to verify
    # that the cache is indeed working.
138 139 140 141 142 143 144 145 146 147 148
    #
    # This strategy works well enough for most server setups and requires the
    # least configuration, but if you deploy several application servers at
    # different times - say to handle a temporary spike in load - then the
    # asset time stamps will be out of sync. In a setup like this you may want
    # to set the way that asset paths are generated yourself.
    #
    # Altering the asset paths that Rails generates can be done in two ways.
    # The easiest is to define the RAILS_ASSET_ID environment variable. The
    # contents of this variable will always be used in preference to
    # calculated timestamps. A more complex but flexible way is to set
149
    # <tt>ActionController::Base.config.asset_path</tt> to a proc
150 151 152 153 154 155
    # that takes the unmodified asset path and returns the path needed for
    # your asset caching to work. Typically you'd do something like this in
    # <tt>config/environments/production.rb</tt>:
    #
    #   # Normally you'd calculate RELEASE_NUMBER at startup.
    #   RELEASE_NUMBER = 12345
156
    #   config.action_controller.asset_path = proc { |asset_path|
157 158 159
    #     "/release-#{RELEASE_NUMBER}#{asset_path}"
    #   }
    #
160
    # This example would cause the following behavior on all servers no
161 162 163 164 165
    # matter when they were deployed:
    #
    #   image_tag("rails.png")
    #   # => <img alt="Rails" src="/release-12345/images/rails.png" />
    #   stylesheet_link_tag("application")
166
    #   # => <link href="/release-12345/stylesheets/application.css?1232285206" media="screen" rel="stylesheet" />
167
    #
168
    # Changing the asset_path does require that your web servers have
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
    # knowledge of the asset template paths that you rewrite to so it's not
    # suitable for out-of-the-box use. To use the example given above you
    # could use something like this in your Apache VirtualHost configuration:
    #
    #   <LocationMatch "^/release-\d+/(images|javascripts|stylesheets)/.*$">
    #     # Some browsers still send conditional-GET requests if there's a
    #     # Last-Modified header or an ETag header even if they haven't
    #     # reached the expiry date sent in the Expires header.
    #     Header unset Last-Modified
    #     Header unset ETag
    #     FileETag None
    #
    #     # Assets requested using a cache-busting filename should be served
    #     # only once and then cached for a really long time. The HTTP/1.1
    #     # spec frowns on hugely-long expiration times though and suggests
    #     # that assets which never expire be served with an expiration date
    #     # 1 year from access.
    #     ExpiresActive On
    #     ExpiresDefault "access plus 1 year"
    #   </LocationMatch>
    #
    #   # We use cached-busting location names with the far-future expires
    #   # headers to ensure that if a file does change it can force a new
    #   # request. The actual asset filenames are still the same though so we
    #   # need to rewrite the location from the cache-busting location to the
    #   # real asset location so that we can serve it.
    #   RewriteEngine On
    #   RewriteRule ^/release-\d+/(images|javascripts|stylesheets)/(.*)$ /$1/$2 [L]
197
    module AssetTagHelper
198
      include TagHelper
199 200
      include JavascriptTagHelpers
      include StylesheetTagHelpers
201
      # Returns a link tag that browsers and news readers can use to auto-detect
T
Tom Stuart 已提交
202
      # an RSS or Atom feed. The +type+ can either be <tt>:rss</tt> (default) or
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
      # <tt>:atom</tt>. Control the link options in url_for format using the
      # +url_options+. You can modify the LINK tag itself in +tag_options+.
      #
      # ==== Options
      # * <tt>:rel</tt>  - Specify the relation of this link, defaults to "alternate"
      # * <tt>:type</tt>  - Override the auto-generated mime type
      # * <tt>:title</tt>  - Specify the title of the link, defaults to the +type+
      #
      # ==== Examples
      #  auto_discovery_link_tag # =>
      #     <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.currenthost.com/controller/action" />
      #  auto_discovery_link_tag(:atom) # =>
      #     <link rel="alternate" type="application/atom+xml" title="ATOM" href="http://www.currenthost.com/controller/action" />
      #  auto_discovery_link_tag(:rss, {:action => "feed"}) # =>
      #     <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.currenthost.com/controller/feed" />
      #  auto_discovery_link_tag(:rss, {:action => "feed"}, {:title => "My RSS"}) # =>
      #     <link rel="alternate" type="application/rss+xml" title="My RSS" href="http://www.currenthost.com/controller/feed" />
      #  auto_discovery_link_tag(:rss, {:controller => "news", :action => "feed"}) # =>
      #     <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.currenthost.com/news/feed" />
      #  auto_discovery_link_tag(:rss, "http://www.example.com/feed.rss", {:title => "Example RSS"}) # =>
      #     <link rel="alternate" type="application/rss+xml" title="Example RSS" href="http://www.example.com/feed" />
      def auto_discovery_link_tag(type = :rss, url_options = {}, tag_options = {})
        tag(
          "link",
          "rel"   => tag_options[:rel] || "alternate",
          "type"  => tag_options[:type] || Mime::Type.lookup_by_extension(type.to_s).to_s,
          "title" => tag_options[:title] || type.to_s.upcase,
          "href"  => url_options.is_a?(Hash) ? url_for(url_options.merge(:only_path => false)) : url_options
        )
      end

      #   <%= favicon_link_tag %>
      #
      # generates
      #
238
      #   <link href="/assets/favicon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon" />
239 240 241
      #
      # You may specify a different file in the first argument:
      #
242
      #   <%= favicon_link_tag '/myicon.ico' %>
243 244 245
      #
      # That's passed to +path_to_image+ as is, so it gives
      #
246
      #   <link href="/myicon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon" />
247 248 249 250 251 252 253 254 255
      #
      # The helper accepts an additional options hash where you can override "rel" and "type".
      #
      # For example, Mobile Safari looks for a different LINK tag, pointing to an image that
      # will be used if you add the page to the home screen of an iPod Touch, iPhone, or iPad.
      # The following call would generate such a tag:
      #
      #   <%= favicon_link_tag 'mb-icon.png', :rel => 'apple-touch-icon', :type => 'image/png' %>
      #
256
      def favicon_link_tag(source='favicon.ico', options={})
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
        tag('link', {
          :rel  => 'shortcut icon',
          :type => 'image/vnd.microsoft.icon',
          :href => path_to_image(source)
        }.merge(options.symbolize_keys))
      end

      # Computes the path to an image asset in the public images directory.
      # Full paths from the document root will be passed through.
      # Used internally by +image_tag+ to build the image path:
      #
      #   image_path("edit")                                         # => "/images/edit"
      #   image_path("edit.png")                                     # => "/images/edit.png"
      #   image_path("icons/edit.png")                               # => "/images/icons/edit.png"
      #   image_path("/icons/edit.png")                              # => "/icons/edit.png"
272
      #   image_path("http://www.example.com/img/edit.png")          # => "http://www.example.com/img/edit.png"
273 274 275 276 277
      #
      # If you have images as application resources this method may conflict with their named routes.
      # The alias +path_to_image+ is provided to avoid that. Rails uses the alias internally, and
      # plugin authors are encouraged to do so.
      def image_path(source)
278
        asset_paths.compute_public_path(source, 'images')
279 280 281
      end
      alias_method :path_to_image, :image_path # aliased to avoid conflicts with an image_path named route

282 283 284 285 286 287 288
      # Computes the full URL to an image asset in the public images directory.
      # This will use +image_path+ internally, so most of their behaviors will be the same.
      def image_url(source)
        URI.join(current_host, path_to_image(source)).to_s
      end
      alias_method :url_to_image, :image_url # aliased to avoid conflicts with an image_url named route

289 290 291 292 293 294 295 296 297
      # Computes the path to a video asset in the public videos directory.
      # Full paths from the document root will be passed through.
      # Used internally by +video_tag+ to build the video path.
      #
      # ==== Examples
      #   video_path("hd")                                            # => /videos/hd
      #   video_path("hd.avi")                                        # => /videos/hd.avi
      #   video_path("trailers/hd.avi")                               # => /videos/trailers/hd.avi
      #   video_path("/trailers/hd.avi")                              # => /trailers/hd.avi
298
      #   video_path("http://www.example.com/vid/hd.avi")             # => http://www.example.com/vid/hd.avi
299
      def video_path(source)
300
        asset_paths.compute_public_path(source, 'videos')
301 302 303
      end
      alias_method :path_to_video, :video_path # aliased to avoid conflicts with a video_path named route

304 305 306 307 308 309 310
      # Computes the full URL to a video asset in the public videos directory.
      # This will use +video_path+ internally, so most of their behaviors will be the same.
      def video_url(source)
        URI.join(current_host, path_to_video(source)).to_s
      end
      alias_method :url_to_video, :video_url # aliased to avoid conflicts with an video_url named route

311 312 313 314 315 316 317 318 319
      # Computes the path to an audio asset in the public audios directory.
      # Full paths from the document root will be passed through.
      # Used internally by +audio_tag+ to build the audio path.
      #
      # ==== Examples
      #   audio_path("horse")                                            # => /audios/horse
      #   audio_path("horse.wav")                                        # => /audios/horse.wav
      #   audio_path("sounds/horse.wav")                                 # => /audios/sounds/horse.wav
      #   audio_path("/sounds/horse.wav")                                # => /sounds/horse.wav
320
      #   audio_path("http://www.example.com/sounds/horse.wav")          # => http://www.example.com/sounds/horse.wav
321
      def audio_path(source)
322
        asset_paths.compute_public_path(source, 'audios')
323 324 325
      end
      alias_method :path_to_audio, :audio_path # aliased to avoid conflicts with an audio_path named route

326 327 328 329 330 331 332
      # Computes the full URL to a audio asset in the public audios directory.
      # This will use +audio_path+ internally, so most of their behaviors will be the same.
      def audio_url(source)
        URI.join(current_host, path_to_audio(source)).to_s
      end
      alias_method :url_to_audio, :audio_url # aliased to avoid conflicts with an audio_url named route

S
Santiago Pastorino 已提交
333 334 335 336 337 338 339 340 341 342 343 344 345 346
      # Computes the path to a font asset in the public fonts directory.
      # Full paths from the document root will be passed through.
      #
      # ==== Examples
      #   font_path("font")                                           # => /fonts/font
      #   font_path("font.ttf")                                       # => /fonts/font.ttf
      #   font_path("dir/font.ttf")                                   # => /fonts/dir/font.ttf
      #   font_path("/dir/font.ttf")                                  # => /dir/font.ttf
      #   font_path("http://www.example.com/dir/font.ttf")            # => http://www.example.com/dir/font.ttf
      def font_path(source)
        asset_paths.compute_public_path(source, 'fonts')
      end
      alias_method :path_to_font, :font_path # aliased to avoid conflicts with an font_path named route

347 348 349 350 351 352 353
      # Computes the full URL to a font asset in the public fonts directory.
      # This will use +font_path+ internally, so most of their behaviors will be the same.
      def font_url(source)
        URI.join(current_host, path_to_font(source)).to_s
      end
      alias_method :url_to_font, :font_url # aliased to avoid conflicts with an font_url named route

354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
      # Returns an html image tag for the +source+. The +source+ can be a full
      # path or a file that exists in your public images directory.
      #
      # ==== Options
      # You can add HTML attributes using the +options+. The +options+ supports
      # three additional keys for convenience and conformance:
      #
      # * <tt>:alt</tt>  - If no alt text is given, the file name part of the
      #   +source+ is used (capitalized and without the extension)
      # * <tt>:size</tt> - Supplied as "{Width}x{Height}", so "30x45" becomes
      #   width="30" and height="45". <tt>:size</tt> will be ignored if the
      #   value is not in the correct format.
      # * <tt>:mouseover</tt> - Set an alternate image to be used when the onmouseover
      #   event is fired, and sets the original image to be replaced onmouseout.
      #   This can be used to implement an easy image toggle that fires on onmouseover.
      #
      # ==== Examples
      #  image_tag("icon")  # =>
      #    <img src="/images/icon" alt="Icon" />
      #  image_tag("icon.png")  # =>
      #    <img src="/images/icon.png" alt="Icon" />
      #  image_tag("icon.png", :size => "16x10", :alt => "Edit Entry")  # =>
      #    <img src="/images/icon.png" width="16" height="10" alt="Edit Entry" />
      #  image_tag("/icons/icon.gif", :size => "16x16")  # =>
      #    <img src="/icons/icon.gif" width="16" height="16" alt="Icon" />
      #  image_tag("/icons/icon.gif", :height => '32', :width => '32') # =>
      #    <img alt="Icon" height="32" src="/icons/icon.gif" width="32" />
      #  image_tag("/icons/icon.gif", :class => "menu_icon") # =>
      #    <img alt="Icon" class="menu_icon" src="/icons/icon.gif" />
      #  image_tag("mouse.png", :mouseover => "/images/mouse_over.png") # =>
      #    <img src="/images/mouse.png" onmouseover="this.src='/images/mouse_over.png'" onmouseout="this.src='/images/mouse.png'" alt="Mouse" />
      #  image_tag("mouse.png", :mouseover => image_path("mouse_over.png")) # =>
      #    <img src="/images/mouse.png" onmouseover="this.src='/images/mouse_over.png'" onmouseout="this.src='/images/mouse.png'" alt="Mouse" />
387
      def image_tag(source, options={})
388
        options = options.symbolize_keys
389 390 391 392

        src = options[:src] = path_to_image(source)

        unless src =~ /^cid:/
393
          options[:alt] = options.fetch(:alt){ image_alt(src) }
394 395 396 397 398 399 400 401 402 403 404 405 406 407
        end

        if size = options.delete(:size)
          options[:width], options[:height] = size.split("x") if size =~ %r{^\d+x\d+$}
        end

        if mouseover = options.delete(:mouseover)
          options[:onmouseover] = "this.src='#{path_to_image(mouseover)}'"
          options[:onmouseout]  = "this.src='#{src}'"
        end

        tag("img", options)
      end

408
      def image_alt(src)
X
Xavier Noria 已提交
409
        File.basename(src, '.*').sub(/-[[:xdigit:]]{32}\z/, '').capitalize
410 411
      end

412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
      # Returns an html video tag for the +sources+. If +sources+ is a string,
      # a single video tag will be returned. If +sources+ is an array, a video
      # tag with nested source tags for each source will be returned. The
      # +sources+ can be full paths or files that exists in your public videos
      # directory.
      #
      # ==== Options
      # You can add HTML attributes using the +options+. The +options+ supports
      # two additional keys for convenience and conformance:
      #
      # * <tt>:poster</tt> - Set an image (like a screenshot) to be shown
      #   before the video loads. The path is calculated like the +src+ of +image_tag+.
      # * <tt>:size</tt> - Supplied as "{Width}x{Height}", so "30x45" becomes
      #   width="30" and height="45". <tt>:size</tt> will be ignored if the
      #   value is not in the correct format.
      #
      # ==== Examples
      #  video_tag("trailer")  # =>
      #    <video src="/videos/trailer" />
      #  video_tag("trailer.ogg")  # =>
      #    <video src="/videos/trailer.ogg" />
      #  video_tag("trailer.ogg", :controls => true, :autobuffer => true)  # =>
      #    <video autobuffer="autobuffer" controls="controls" src="/videos/trailer.ogg" />
      #  video_tag("trailer.m4v", :size => "16x10", :poster => "screenshot.png")  # =>
      #    <video src="/videos/trailer.m4v" width="16" height="10" poster="/images/screenshot.png" />
      #  video_tag("/trailers/hd.avi", :size => "16x16")  # =>
      #    <video src="/trailers/hd.avi" width="16" height="16" />
      #  video_tag("/trailers/hd.avi", :height => '32', :width => '32') # =>
      #    <video height="32" src="/trailers/hd.avi" width="32" />
441 442
      #  video_tag("trailer.ogg", "trailer.flv") # =>
      #    <video><source src="/videos/trailer.ogg" /><source src="/videos/trailer.flv" /></video>
443
      #  video_tag(["trailer.ogg", "trailer.flv"]) # =>
444
      #    <video><source src="/videos/trailer.ogg" /><source src="/videos/trailer.flv" /></video>
A
Alexey Vakhov 已提交
445
      #  video_tag(["trailer.ogg", "trailer.flv"], :size => "160x120") # =>
446 447
      #    <video height="120" width="160"><source src="/videos/trailer.ogg" /><source src="/videos/trailer.flv" /></video>
      def video_tag(*sources)
448 449
        multiple_sources_tag('video', sources) do |options|
          options[:poster] = path_to_image(options[:poster]) if options[:poster]
450

451 452
          if size = options.delete(:size)
            options[:width], options[:height] = size.split("x") if size =~ %r{^\d+x\d+$}
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
          end
        end
      end

      # Returns an html audio tag for the +source+.
      # The +source+ can be full path or file that exists in
      # your public audios directory.
      #
      # ==== Examples
      #  audio_tag("sound")  # =>
      #    <audio src="/audios/sound" />
      #  audio_tag("sound.wav")  # =>
      #    <audio src="/audios/sound.wav" />
      #  audio_tag("sound.wav", :autoplay => true, :controls => true)  # =>
      #    <audio autoplay="autoplay" controls="controls" src="/audios/sound.wav" />
468 469 470
      #  audio_tag("sound.wav", "sound.mid")  # =>
      #    <audio><source src="/audios/sound.wav" /><source src="/audios/sound.mid" /></audio>
      def audio_tag(*sources)
471
        multiple_sources_tag('audio', sources)
472 473
      end

474 475 476
      private

        def asset_paths
477
          @asset_paths ||= AssetTagHelper::AssetPaths.new(config, controller)
478
        end
479 480

        def multiple_sources_tag(type, sources)
481
          options = sources.extract_options!.symbolize_keys
482 483 484 485 486 487 488 489 490 491
          sources.flatten!

          yield options if block_given?

          if sources.size > 1
            content_tag(type, options) do
              safe_join sources.map { |source| tag("source", :src => send("path_to_#{type}", source)) }
            end
          else
            options[:src] = send("path_to_#{type}", sources.first)
492
            content_tag(type, nil, options)
493 494
          end
        end
495 496 497 498

        def current_host
          url_for(:only_path => false)
        end
499 500
    end
  end
501
end