url_helper.rb 27.7 KB
Newer Older
1
require 'action_view/helpers/javascript_helper'
2
require 'active_support/core_ext/array/access'
J
Jeremy Kemper 已提交
3
require 'active_support/core_ext/hash/keys'
4

D
Initial  
David Heinemeier Hansson 已提交
5
module ActionView
6
  module Helpers #:nodoc:
7
    # Provides a set of methods for making links and getting URLs that
8 9
    # depend on the routing subsystem (see ActionController::Routing).
    # This allows you to use the same format for links in views
10
    # and controllers.
D
Initial  
David Heinemeier Hansson 已提交
11
    module UrlHelper
12
      include JavaScriptHelper
13

14 15
      # Need to map default url options to controller one.
      def default_url_options(*args) #:nodoc:
16
        controller.send(:default_url_options, *args)
17 18
      end

19
      # Returns the URL for the set of +options+ provided. This takes the
P
Pratik Naik 已提交
20
      # same options as +url_for+ in Action Controller (see the
P
Pratik Naik 已提交
21 22 23
      # documentation for <tt>ActionController::Base#url_for</tt>). Note that by default
      # <tt>:only_path</tt> is <tt>true</tt> so you'll get the relative "/controller/action"
      # instead of the fully qualified URL like "http://example.com/controller/action".
24
      #
P
Pratik Naik 已提交
25
      # When called from a view, +url_for+ returns an HTML escaped url. If you
26
      # need an unescaped url, pass <tt>:escape => false</tt> in the +options+.
27 28
      #
      # ==== Options
P
Pratik Naik 已提交
29 30 31
      # * <tt>:anchor</tt> - Specifies the anchor name to be appended to the path.
      # * <tt>:only_path</tt> - If true, returns the relative URL (omitting the protocol, host name, and port) (<tt>true</tt> by default unless <tt>:host</tt> is specified).
      # * <tt>:trailing_slash</tt> - If true, adds a trailing slash, as in "/archive/2005/". Note that this
32
      #   is currently not recommended since it breaks caching.
P
Pratik Naik 已提交
33 34 35 36 37
      # * <tt>:host</tt> - Overrides the default (current) host if provided.
      # * <tt>:protocol</tt> - Overrides the default (current) protocol if provided.
      # * <tt>:user</tt> - Inline HTTP authentication (only plucked out if <tt>:password</tt> is also present).
      # * <tt>:password</tt> - Inline HTTP authentication (only plucked out if <tt>:user</tt> is also present).
      # * <tt>:escape</tt> - Determines whether the returned URL will be HTML escaped or not (<tt>true</tt> by default).
38
      #
39 40 41 42
      # ==== Relying on named routes
      #
      # If you instead of a hash pass a record (like an Active Record or Active Resource) as the options parameter,
      # you'll trigger the named route for that record. The lookup will happen on the name of the class. So passing
P
Pratik Naik 已提交
43 44
      # a Workshop object will attempt to use the +workshop_path+ route. If you have a nested route, such as
      # +admin_workshop_path+ you'll have to call that explicitly (it's impossible for +url_for+ to guess that route).
45
      #
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
      # ==== Examples
      #   <%= url_for(:action => 'index') %>
      #   # => /blog/
      #
      #   <%= url_for(:action => 'find', :controller => 'books') %>
      #   # => /books/find
      #
      #   <%= url_for(:action => 'login', :controller => 'members', :only_path => false, :protocol => 'https') %>
      #   # => https://www.railsapplication.com/members/login/
      #
      #   <%= url_for(:action => 'play', :anchor => 'player') %>
      #   # => /messages/play/#player
      #
      #   <%= url_for(:action => 'checkout', :anchor => 'tax&ship') %>
      #   # => /testing/jump/#tax&amp;ship
      #
      #   <%= url_for(:action => 'checkout', :anchor => 'tax&ship', :escape => false) %>
      #   # => /testing/jump/#tax&ship
64 65 66 67 68 69 70 71
      #
      #   <%= url_for(Workshop.new) %>
      #   # relies on Workshop answering a new_record? call (and in this case returning true)
      #   # => /workshops
      #
      #   <%= url_for(@workshop) %>
      #   # calls @workshop.to_s
      #   # => /workshops/5
72 73 74 75 76 77 78 79 80 81 82
      #
      #   <%= url_for("http://www.example.com") %>
      #   # => http://www.example.com
      #
      #   <%= url_for(:back) %>
      #   # if request.env["HTTP_REFERER"] is set to "http://www.example.com"
      #   # => http://www.example.com
      #
      #   <%= url_for(:back) %>
      #   # if request.env["HTTP_REFERER"] is not set or is blank
      #   # => javascript:history.back()
83
      def url_for(options = {})
84
        options ||= {}
85 86 87 88
        url = case options
        when String
          escape = true
          options
89
        when Hash
90
          options = { :only_path => options[:host].nil? }.update(options.symbolize_keys)
91
          escape  = options.key?(:escape) ? options.delete(:escape) : false
92
          controller.send(:url_for, options)
93 94
        when :back
          escape = false
95
          controller.request.env["HTTP_REFERER"] || 'javascript:history.back()'
96 97
        else
          escape = false
98
          polymorphic_path(options)
99
        end
100

101
        escape ? escape_once(url).html_safe! : url
D
Initial  
David Heinemeier Hansson 已提交
102 103
      end

104 105
      # Creates a link tag of the given +name+ using a URL created by the set
      # of +options+. See the valid options in the documentation for
P
Pratik Naik 已提交
106
      # +url_for+. It's also possible to pass a string instead
107
      # of an options hash to get a link tag that uses the value of the string as the
P
Pratik Naik 已提交
108
      # href for the link, or use <tt>:back</tt> to link to the referrer - a JavaScript back
P
Pratik Naik 已提交
109
      # link will be used in place of a referrer if none exists. If +nil+ is passed as
110
      # a name, the link itself will become the name.
111
      #
112 113 114 115 116 117 118
      # ==== Signatures
      #
      #   link_to(name, options = {}, html_options = nil)
      #   link_to(options = {}, html_options = nil) do
      #     # name
      #   end
      #
119
      # ==== Options
P
Pratik Naik 已提交
120
      # * <tt>:confirm => 'question?'</tt> - This will add a JavaScript confirm
121
      #   prompt with the question specified. If the user accepts, the link is
122
      #   processed normally, otherwise no action is taken.
P
Pratik Naik 已提交
123
      # * <tt>:popup => true || array of window options</tt> - This will force the
124 125
      #   link to open in a popup window. By passing true, a default browser window
      #   will be opened with the URL. You can also specify an array of options
P
Pratik Naik 已提交
126
      #   that are passed to the <tt>window.open</tt> JavaScript call.
P
Pratik Naik 已提交
127
      # * <tt>:method => symbol of HTTP verb</tt> - This modifier will dynamically
128
      #   create an HTML form and immediately submit the form for processing using
129 130
      #   the HTTP verb specified. Useful for having links perform a POST operation
      #   in dangerous actions like deleting a record (which search bots can follow
131
      #   while spidering your site). Supported verbs are <tt>:post</tt>, <tt>:delete</tt> and <tt>:put</tt>.
132
      #   Note that if the user has JavaScript disabled, the request will fall back
P
Pratik Naik 已提交
133 134 135 136
      #   to using GET. If <tt>:href => '#'</tt> is used and the user has JavaScript
      #   disabled clicking the link will have no effect. If you are relying on the
      #   POST behavior, you should check for it in your controller's action by using
      #   the request object's methods for <tt>post?</tt>, <tt>delete?</tt> or <tt>put?</tt>.
137
      # * The +html_options+ will accept a hash of html attributes for the link tag.
138
      #
139
      # You can mix and match the +html_options+ with the exception of
P
Pratik Naik 已提交
140 141
      # <tt>:popup</tt> and <tt>:method</tt> which will raise an
      # <tt>ActionView::ActionViewError</tt> exception.
142
      #
143
      # ==== Examples
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
      # Because it relies on +url_for+, +link_to+ supports both older-style controller/action/id arguments
      # and newer RESTful routes.  Current Rails style favors RESTful routes whenever possible, so base
      # your application on resources and use
      #
      #   link_to "Profile", profile_path(@profile)
      #   # => <a href="/profiles/1">Profile</a>
      #
      # or the even pithier
      #
      #   link_to "Profile", @profile
      #   # => <a href="/profiles/1">Profile</a>
      #
      # in place of the older more verbose, non-resource-oriented
      #
      #   link_to "Profile", :controller => "profiles", :action => "show", :id => @profile
      #   # => <a href="/profiles/show/1">Profile</a>
160 161
      #
      # Similarly,
162 163 164 165 166 167 168 169 170
      #
      #   link_to "Profiles", profiles_path
      #   # => <a href="/profiles">Profiles</a>
      #
      # is better than
      #
      #   link_to "Profiles", :controller => "profiles"
      #   # => <a href="/profiles">Profiles</a>
      #
171 172 173
      # You can use a block as well if your link target is hard to fit into the name parameter. ERb example:
      #
      #   <% link_to(@profile) do %>
P
Pratik Naik 已提交
174
      #     <strong><%= @profile.name %></strong> -- <span>Check it out!</span>
175
      #   <% end %>
P
Pratik Naik 已提交
176 177 178
      #   # => <a href="/profiles/1">
      #          <strong>David</strong> -- <span>Check it out!</span>
      #        </a>
179
      #
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
      # Classes and ids for CSS are easy to produce:
      #
      #   link_to "Articles", articles_path, :id => "news", :class => "article"
      #   # => <a href="/articles" class="article" id="news">Articles</a>
      #
      # Be careful when using the older argument style, as an extra literal hash is needed:
      #
      #   link_to "Articles", { :controller => "articles" }, :id => "news", :class => "article"
      #   # => <a href="/articles" class="article" id="news">Articles</a>
      #
      # Leaving the hash off gives the wrong link:
      #
      #   link_to "WRONG!", :controller => "articles", :id => "news", :class => "article"
      #   # => <a href="/articles/index/news?class=article">WRONG!</a>
      #
      # +link_to+ can also produce links with anchors or query strings:
      #
      #   link_to "Comment wall", profile_path(@profile, :anchor => "wall")
      #   # => <a href="/profiles/1#wall">Comment wall</a>
      #
      #   link_to "Ruby on Rails search", :controller => "searches", :query => "ruby on rails"
      #   # => <a href="/searches?query=ruby+on+rails">Ruby on Rails search</a>
      #
      #   link_to "Nonsense search", searches_path(:foo => "bar", :baz => "quux")
      #   # => <a href="/searches?foo=bar&amp;baz=quux">Nonsense search</a>
      #
P
Pratik Naik 已提交
206
      # The three options specific to +link_to+ (<tt>:confirm</tt>, <tt>:popup</tt>, and <tt>:method</tt>) are used as follows:
207
      #
208
      #   link_to "Visit Other Site", "http://www.rubyonrails.org/", :confirm => "Are you sure?"
209 210
      #   # => <a href="http://www.rubyonrails.org/" onclick="return confirm('Are you sure?');">Visit Other Site</a>
      #
211
      #   link_to "Help", { :action => "help" }, :popup => true
212 213
      #   # => <a href="/testing/help/" onclick="window.open(this.href);return false;">Help</a>
      #
214 215
      #   link_to "View Image", @image, :popup => ['new_window_name', 'height=300,width=600']
      #   # => <a href="/images/9" onclick="window.open(this.href,'new_window_name','height=300,width=600');return false;">View Image</a>
216
      #
217
      #   link_to "Delete Image", @image, :confirm => "Are you sure?", :method => :delete
218
      #   # => <a href="/images/9" onclick="if (confirm('Are you sure?')) { var f = document.createElement('form');
219
      #        f.style.display = 'none'; this.parentNode.appendChild(f); f.method = 'POST'; f.action = this.href;
220
      #        var m = document.createElement('input'); m.setAttribute('type', 'hidden'); m.setAttribute('name', '_method');
P
Pratik Naik 已提交
221 222 223
      #        m.setAttribute('value', 'delete');var s = document.createElement('input'); s.setAttribute('type', 'hidden');
      #        s.setAttribute('name', 'authenticity_token'); s.setAttribute('value', 'Q/ttlxPYZ6R77B+vZ1sBkhj21G2isO9dpE6UtOHBApg=');
      #        f.appendChild(s)f.appendChild(m);f.submit(); };return false;">Delete Image</a>
224 225 226 227
      def link_to(*args, &block)
        if block_given?
          options      = args.first || {}
          html_options = args.second
228
          concat(link_to(capture(&block), options, html_options).html_safe!)
229
        else
230 231 232
          name         = args[0]
          options      = args[1] || {}
          html_options = args[2]
233

234
          url = url_for(options)
235 236 237 238 239 240

          if html_options
            html_options = html_options.stringify_keys
            href = html_options['href']
            convert_options_to_javascript!(html_options, url)
            tag_options = tag_options(html_options)
241
          else
242
            tag_options = nil
243
          end
244

245
          href_attr = "href=\"#{url}\"" unless href
246
          "<a #{href_attr}#{tag_options}>#{ERB::Util.h(name || url)}</a>".html_safe!
D
Initial  
David Heinemeier Hansson 已提交
247 248 249
        end
      end

250 251 252 253
      # Generates a form containing a single button that submits to the URL created
      # by the set of +options+. This is the safest method to ensure links that
      # cause changes to your data are not triggered by search bots or accelerators.
      # If the HTML button does not work with your layout, you can also consider
P
Pratik Naik 已提交
254 255
      # using the +link_to+ method with the <tt>:method</tt> modifier as described in
      # the +link_to+ documentation.
256
      #
P
Pratik Naik 已提交
257
      # The generated form element has a class name of <tt>button-to</tt>
258 259 260
      # to allow styling of the form itself and its children. You can control
      # the form submission and input element behavior using +html_options+.
      # This method accepts the <tt>:method</tt> and <tt>:confirm</tt> modifiers
P
Pratik Naik 已提交
261
      # described in the +link_to+ documentation. If no <tt>:method</tt> modifier
262
      # is given, it will default to performing a POST operation. You can also
263 264 265
      # disable the button by passing <tt>:disabled => true</tt> in +html_options+.
      # If you are using RESTful routes, you can pass the <tt>:method</tt>
      # to change the HTTP verb used to submit the form.
266
      #
267
      # ==== Options
P
Pratik Naik 已提交
268
      # The +options+ hash accepts the same options as url_for.
269
      #
270
      # There are a few special +html_options+:
P
Pratik Naik 已提交
271 272 273
      # * <tt>:method</tt> - Specifies the anchor name to be appended to the path.
      # * <tt>:disabled</tt> - Specifies the anchor name to be appended to the path.
      # * <tt>:confirm</tt> - This will add a JavaScript confirm
274 275
      #   prompt with the question specified. If the user accepts, the link is
      #   processed normally, otherwise no action is taken.
276
      #
277 278 279 280 281
      # ==== Examples
      #   <%= button_to "New", :action => "new" %>
      #   # => "<form method="post" action="/controller/new" class="button-to">
      #   #      <div><input value="New" type="submit" /></div>
      #   #    </form>"
282
      #
283 284 285 286 287 288 289 290 291
      #   button_to "Delete Image", { :action => "delete", :id => @image.id },
      #             :confirm => "Are you sure?", :method => :delete
      #   # => "<form method="post" action="/images/delete/1" class="button-to">
      #   #      <div>
      #   #        <input type="hidden" name="_method" value="delete" />
      #   #        <input onclick="return confirm('Are you sure?');"
      #   #              value="Delete" type="submit" />
      #   #      </div>
      #   #    </form>"
292 293
      def button_to(name, options = {}, html_options = {})
        html_options = html_options.stringify_keys
294
        convert_boolean_attributes!(html_options, %w( disabled ))
295 296 297 298 299 300 301

        method_tag = ''
        if (method = html_options.delete('method')) && %w{put delete}.include?(method.to_s)
          method_tag = tag('input', :type => 'hidden', :name => '_method', :value => method.to_s)
        end

        form_method = method.to_s == 'get' ? 'get' : 'post'
302

303
        request_token_tag = ''
304
        if form_method == 'post' && protect_against_forgery?
305 306
          request_token_tag = tag(:input, :type => "hidden", :name => request_forgery_protection_token.to_s, :value => form_authenticity_token)
        end
307

308

309
        url = options.is_a?(String) ? options : self.url_for(options)
310
        name ||= url
311 312
     
        convert_options_to_javascript!(html_options, url)
313

314
        html_options.merge!("type" => "submit", "value" => name)
315

316 317
        ("<form method=\"#{form_method}\" action=\"#{escape_once url}\" class=\"button-to\"><div>" +
          method_tag + tag("input", html_options) + request_token_tag + "</div></form>").html_safe!
318 319
      end

320

321
      # Creates a link tag of the given +name+ using a URL created by the set of
322
      # +options+ unless the current request URI is the same as the links, in
323
      # which case only the name is returned (or the given block is yielded, if
P
Pratik Naik 已提交
324
      # one exists).  You can give +link_to_unless_current+ a block which will
325 326 327 328 329
      # specialize the default behavior (e.g., show a "Start Here" link rather
      # than the link's text).
      #
      # ==== Examples
      # Let's say you have a navigation menu...
330 331 332 333 334 335
      #
      #   <ul id="navbar">
      #     <li><%= link_to_unless_current("Home", { :action => "index" }) %></li>
      #     <li><%= link_to_unless_current("About Us", { :action => "about" }) %></li>
      #   </ul>
      #
336
      # If in the "about" action, it will render...
337 338 339 340 341
      #
      #   <ul id="navbar">
      #     <li><a href="/controller/index">Home</a></li>
      #     <li>About Us</li>
      #   </ul>
342
      #
343
      # ...but if in the "index" action, it will render:
344 345
      #
      #   <ul id="navbar">
346
      #     <li>Home</li>
347 348 349
      #     <li><a href="/controller/about">About Us</a></li>
      #   </ul>
      #
P
Pratik Naik 已提交
350
      # The implicit block given to +link_to_unless_current+ is evaluated if the current
351
      # action is the action given.  So, if we had a comments page and wanted to render a
352
      # "Go Back" link instead of a link to the comments page, we could do something like this...
353 354
      #
      #    <%=
355
      #        link_to_unless_current("Comment", { :controller => 'comments', :action => 'new}) do
356 357
      #           link_to("Go back", { :controller => 'posts', :action => 'index' })
      #        end
358
      #     %>
359 360
      def link_to_unless_current(name, options = {}, html_options = {}, &block)
        link_to_unless current_page?(options), name, options, html_options, &block
361 362
      end

363
      # Creates a link tag of the given +name+ using a URL created by the set of
364
      # +options+ unless +condition+ is true, in which case only the name is
365 366
      # returned. To specialize the default behavior (i.e., show a login link rather
      # than just the plaintext link text), you can pass a block that
P
Pratik Naik 已提交
367
      # accepts the name or the full argument list for +link_to_unless+.
368
      #
369
      # ==== Examples
370
      #   <%= link_to_unless(@current_user.nil?, "Reply", { :action => "reply" }) %>
371 372
      #   # If the user is logged in...
      #   # => <a href="/controller/reply/">Reply</a>
373
      #
374
      #   <%=
375 376
      #      link_to_unless(@current_user.nil?, "Reply", { :action => "reply" }) do |name|
      #        link_to(name, { :controller => "accounts", :action => "signup" })
377
      #      end
378 379 380 381 382
      #   %>
      #   # If the user is logged in...
      #   # => <a href="/controller/reply/">Reply</a>
      #   # If not...
      #   # => <a href="/accounts/signup">Reply</a>
383
      def link_to_unless(condition, name, options = {}, html_options = {}, &block)
384 385
        if condition
          if block_given?
386
            block.arity <= 1 ? yield(name) : yield(name, options, html_options)
387
          else
388
            name
389
          end
D
Initial  
David Heinemeier Hansson 已提交
390
        else
391
          link_to(name, options, html_options)
392
        end
393
      end
394

395
      # Creates a link tag of the given +name+ using a URL created by the set of
396
      # +options+ if +condition+ is true, in which case only the name is
397
      # returned. To specialize the default behavior, you can pass a block that
P
Pratik Naik 已提交
398 399
      # accepts the name or the full argument list for +link_to_unless+ (see the examples
      # in +link_to_unless+).
400 401 402 403 404 405
      #
      # ==== Examples
      #   <%= link_to_if(@current_user.nil?, "Login", { :controller => "sessions", :action => "new" }) %>
      #   # If the user isn't logged in...
      #   # => <a href="/sessions/new/">Login</a>
      #
406
      #   <%=
407 408
      #      link_to_if(@current_user.nil?, "Login", { :controller => "sessions", :action => "new" }) do
      #        link_to(@current_user.login, { :controller => "accounts", :action => "show", :id => @current_user })
409
      #      end
410 411 412 413 414
      #   %>
      #   # If the user isn't logged in...
      #   # => <a href="/sessions/new/">Login</a>
      #   # If they are logged in...
      #   # => <a href="/accounts/show/3">my_username</a>
415 416
      def link_to_if(condition, name, options = {}, html_options = {}, &block)
        link_to_unless !condition, name, options, html_options, &block
D
Initial  
David Heinemeier Hansson 已提交
417 418
      end

419 420
      # Creates a mailto link tag to the specified +email_address+, which is
      # also used as the name of the link unless +name+ is specified. Additional
421
      # HTML attributes for the link can be passed in +html_options+.
422
      #
P
Pratik Naik 已提交
423
      # +mail_to+ has several methods for hindering email harvesters and customizing
424 425
      # the email itself by passing special keys to +html_options+.
      #
426
      # ==== Options
P
Pratik Naik 已提交
427 428
      # * <tt>:encode</tt> - This key will accept the strings "javascript" or "hex".
      #   Passing "javascript" will dynamically create and encode the mailto link then
429 430
      #   eval it into the DOM of the page. This method will not show the link on
      #   the page if the user has JavaScript disabled. Passing "hex" will hex
P
Pratik Naik 已提交
431 432
      #   encode the +email_address+ before outputting the mailto link.
      # * <tt>:replace_at</tt> - When the link +name+ isn't provided, the
433 434 435
      #   +email_address+ is used for the link label. You can use this option to
      #   obfuscate the +email_address+ by substituting the @ sign with the string
      #   given as the value.
P
Pratik Naik 已提交
436
      # * <tt>:replace_dot</tt> - When the link +name+ isn't provided, the
437 438 439
      #   +email_address+ is used for the link label. You can use this option to
      #   obfuscate the +email_address+ by substituting the . in the email with the
      #   string given as the value.
P
Pratik Naik 已提交
440
      # * <tt>:subject</tt> - Preset the subject line of the email.
441
      # * <tt>:body</tt> - Preset the body of the email.
P
Pratik Naik 已提交
442 443
      # * <tt>:cc</tt> - Carbon Copy addition recipients on the email.
      # * <tt>:bcc</tt> - Blind Carbon Copy additional recipients on the email.
444
      #
445
      # ==== Examples
446
      #   mail_to "me@domain.com"
447
      #   # => <a href="mailto:me@domain.com">me@domain.com</a>
448
      #
449
      #   mail_to "me@domain.com", "My email", :encode => "javascript"
450
      #   # => <script type="text/javascript">eval(decodeURIComponent('%64%6f%63...%27%29%3b'))</script>
451
      #
452
      #   mail_to "me@domain.com", "My email", :encode => "hex"
453 454
      #   # => <a href="mailto:%6d%65@%64%6f%6d%61%69%6e.%63%6f%6d">My email</a>
      #
455
      #   mail_to "me@domain.com", nil, :replace_at => "_at_", :replace_dot => "_dot_", :class => "email"
456
      #   # => <a href="mailto:me@domain.com" class="email">me_at_domain_dot_com</a>
457
      #
458
      #   mail_to "me@domain.com", "My email", :cc => "ccaddress@domain.com",
459
      #            :subject => "This is an example email"
460
      #   # => <a href="mailto:me@domain.com?cc=ccaddress@domain.com&subject=This%20is%20an%20example%20email">My email</a>
D
Initial  
David Heinemeier Hansson 已提交
461
      def mail_to(email_address, name = nil, html_options = {})
462
        html_options = html_options.stringify_keys
463
        encode = html_options.delete("encode").to_s
464 465
        cc, bcc, subject, body = html_options.delete("cc"), html_options.delete("bcc"), html_options.delete("subject"), html_options.delete("body")

466
        string = ''
467
        extras = ''
468 469 470 471
        extras << "cc=#{Rack::Utils.escape(cc).gsub("+", "%20")}&" unless cc.nil?
        extras << "bcc=#{Rack::Utils.escape(bcc).gsub("+", "%20")}&" unless bcc.nil?
        extras << "body=#{Rack::Utils.escape(body).gsub("+", "%20")}&" unless body.nil?
        extras << "subject=#{Rack::Utils.escape(subject).gsub("+", "%20")}&" unless subject.nil?
472 473
        extras = "?" << extras.gsub!(/&?$/,"") unless extras.empty?

474 475
        email_address = email_address.to_s

476 477 478 479
        email_address_obfuscated = email_address.dup
        email_address_obfuscated.gsub!(/@/, html_options.delete("replace_at")) if html_options.has_key?("replace_at")
        email_address_obfuscated.gsub!(/\./, html_options.delete("replace_dot")) if html_options.has_key?("replace_dot")

480
        if encode == "javascript"
481
          "document.write('#{content_tag("a", name || email_address_obfuscated, html_options.merge({ "href" => "mailto:"+email_address+extras }))}');".each_byte do |c|
482
            string << sprintf("%%%x", c)
483
          end
484
          "<script type=\"#{Mime::JS}\">eval(decodeURIComponent('#{string}'))</script>"
485
        elsif encode == "hex"
486 487 488 489 490 491 492 493
          email_address_encoded = ''
          email_address_obfuscated.each_byte do |c|
            email_address_encoded << sprintf("&#%d;", c)
          end

          protocol = 'mailto:'
          protocol.each_byte { |c| string << sprintf("&#%d;", c) }

494 495 496
          email_address.each_byte do |c|
            char = c.chr
            string << (char =~ /\w/ ? sprintf("%%%x", c) : char)
497
          end
498
          content_tag "a", name || email_address_encoded, html_options.merge({ "href" => "#{string}#{extras}" })
499
        else
500
          content_tag "a", name || email_address_obfuscated, html_options.merge({ "href" => "mailto:#{email_address}#{extras}" })
501
        end
D
Initial  
David Heinemeier Hansson 已提交
502 503
      end

504 505 506
      # True if the current request URI was generated by the given +options+.
      #
      # ==== Examples
507
      # Let's say we're in the <tt>/shop/checkout?order=desc</tt> action.
508 509 510 511 512 513 514
      #
      #   current_page?(:action => 'process')
      #   # => false
      #
      #   current_page?(:controller => 'shop', :action => 'checkout')
      #   # => true
      #
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
      #   current_page?(:controller => 'shop', :action => 'checkout', :order => 'asc')
      #   # => false
      #
      #   current_page?(:action => 'checkout')
      #   # => true
      #
      #   current_page?(:controller => 'library', :action => 'checkout')
      #   # => false
      #
      # Let's say we're in the <tt>/shop/checkout?order=desc&page=1</tt> action.
      #
      #   current_page?(:action => 'process')
      #   # => false
      #
      #   current_page?(:controller => 'shop', :action => 'checkout')
      #   # => true
      #
      #   current_page?(:controller => 'shop', :action => 'checkout', :order => 'desc', :page=>'1')
      #   # => true
      #
      #   current_page?(:controller => 'shop', :action => 'checkout', :order => 'desc', :page=>'2')
      #   # => false
      #
      #   current_page?(:controller => 'shop', :action => 'checkout', :order => 'desc')
539 540
      #   # => false
      #
541 542 543 544 545
      #   current_page?(:action => 'checkout')
      #   # => true
      #
      #   current_page?(:controller => 'library', :action => 'checkout')
      #   # => false
546
      def current_page?(options)
547
        url_string = CGI.unescapeHTML(url_for(options))
548 549
        request = controller.request
        # We ignore any extra parameters in the request_uri if the
550
        # submitted url doesn't have any either.  This lets the function
551
        # work with things like ?order=asc
552 553 554 555 556
        if url_string.index("?")
          request_uri = request.request_uri
        else
          request_uri = request.request_uri.split('?').first
        end
557
        if url_string =~ /^\w+:\/\//
558
          url_string == "#{request.protocol}#{request.host_with_port}#{request_uri}"
559
        else
560
          url_string == request_uri
561
        end
562 563
      end

D
Initial  
David Heinemeier Hansson 已提交
564
      private
P
Pratik Naik 已提交
565
        # Processes the +html_options+ hash, converting the boolean
566 567
        # attributes from true/false form into the form required by
        # HTML/XHTML.  (An attribute is considered to be boolean if
P
Pratik Naik 已提交
568
        # its name is listed in the given +bool_attrs+ array.)
569
        #
P
Pratik Naik 已提交
570
        # More specifically, for each boolean attribute in +html_options+
571 572
        # given as:
        #
P
Pratik Naik 已提交
573
        #   "attr" => bool_value
574
        #
P
Pratik Naik 已提交
575
        # if the associated +bool_value+ evaluates to true, it is
576
        # replaced with the attribute's name; otherwise the attribute is
P
Pratik Naik 已提交
577
        # removed from the +html_options+ hash.  (See the XHTML 1.0 spec,
578 579 580
        # section 4.5 "Attribute Minimization" for more:
        # http://www.w3.org/TR/xhtml1/#h-4.5)
        #
P
Pratik Naik 已提交
581
        # Returns the updated +html_options+ hash, which is also modified
582 583 584 585 586 587 588 589 590 591
        # in place.
        #
        # Example:
        #
        #   convert_boolean_attributes!( html_options,
        #                                %w( checked disabled readonly ) )
        def convert_boolean_attributes!(html_options, bool_attrs)
          bool_attrs.each { |x| html_options[x] = x if html_options.delete(x) }
          html_options
        end
D
Initial  
David Heinemeier Hansson 已提交
592 593
    end
  end
594
end