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

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

      # Returns the URL for the set of +options+ provided. This takes the
P
Pratik Naik 已提交
14
      # same options as +url_for+ in Action Controller (see the
P
Pratik Naik 已提交
15 16 17
      # 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".
18
      #
P
Pratik Naik 已提交
19
      # When called from a view, +url_for+ returns an HTML escaped url. If you
20
      # need an unescaped url, pass <tt>:escape => false</tt> in the +options+.
21 22
      #
      # ==== Options
P
Pratik Naik 已提交
23 24 25
      # * <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
26
      #   is currently not recommended since it breaks caching.
P
Pratik Naik 已提交
27 28 29 30 31
      # * <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).
32
      #
33 34 35 36
      # ==== 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 已提交
37 38
      # 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).
39
      #
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
      # ==== 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
58 59 60 61 62 63 64 65
      #
      #   <%= 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
66 67 68 69 70 71 72 73 74 75 76
      #
      #   <%= 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()
77
      def url_for(options = {})
78
        options ||= {}
79 80 81 82
        url = case options
        when String
          escape = true
          options
83
        when Hash
84
          options = { :only_path => options[:host].nil? }.update(options.symbolize_keys)
85
          escape  = options.key?(:escape) ? options.delete(:escape) : true
86 87 88 89
          @controller.send(:url_for, options)
        when :back
          escape = false
          @controller.request.env["HTTP_REFERER"] || 'javascript:history.back()'
90 91
        else
          escape = false
92
          polymorphic_path(options)
93
        end
94

95
        escape ? escape_once(url) : url
D
Initial  
David Heinemeier Hansson 已提交
96 97
      end

98 99
      # 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 已提交
100
      # +url_for+. It's also possible to pass a string instead
101
      # of an options hash to get a link tag that uses the value of the string as the
P
Pratik Naik 已提交
102
      # href for the link, or use <tt>:back</tt> to link to the referrer - a JavaScript back
P
Pratik Naik 已提交
103
      # link will be used in place of a referrer if none exists. If +nil+ is passed as
104
      # a name, the link itself will become the name.
105
      #
106 107 108 109 110 111 112
      # ==== Signatures
      #
      #   link_to(name, options = {}, html_options = nil)
      #   link_to(options = {}, html_options = nil) do
      #     # name
      #   end
      #
113
      # ==== Options
P
Pratik Naik 已提交
114
      # * <tt>:confirm => 'question?'</tt> - This will add a JavaScript confirm
115
      #   prompt with the question specified. If the user accepts, the link is
116
      #   processed normally, otherwise no action is taken.
P
Pratik Naik 已提交
117
      # * <tt>:popup => true || array of window options</tt> - This will force the
118 119
      #   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 已提交
120
      #   that are passed to the <tt>window.open</tt> JavaScript call.
P
Pratik Naik 已提交
121
      # * <tt>:method => symbol of HTTP verb</tt> - This modifier will dynamically
122
      #   create an HTML form and immediately submit the form for processing using
123 124
      #   the HTTP verb specified. Useful for having links perform a POST operation
      #   in dangerous actions like deleting a record (which search bots can follow
125
      #   while spidering your site). Supported verbs are <tt>:post</tt>, <tt>:delete</tt> and <tt>:put</tt>.
126
      #   Note that if the user has JavaScript disabled, the request will fall back
P
Pratik Naik 已提交
127 128 129 130
      #   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>.
131
      # * The +html_options+ will accept a hash of html attributes for the link tag.
132
      #
133
      # You can mix and match the +html_options+ with the exception of
P
Pratik Naik 已提交
134 135
      # <tt>:popup</tt> and <tt>:method</tt> which will raise an
      # <tt>ActionView::ActionViewError</tt> exception.
136
      #
137
      # ==== Examples
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
      # 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>
154 155
      #
      # Similarly,
156 157 158 159 160 161 162 163 164
      #
      #   link_to "Profiles", profiles_path
      #   # => <a href="/profiles">Profiles</a>
      #
      # is better than
      #
      #   link_to "Profiles", :controller => "profiles"
      #   # => <a href="/profiles">Profiles</a>
      #
165 166 167
      # 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 已提交
168
      #     <strong><%= @profile.name %></strong> -- <span>Check it out!</span>
169
      #   <% end %>
P
Pratik Naik 已提交
170 171 172
      #   # => <a href="/profiles/1">
      #          <strong>David</strong> -- <span>Check it out!</span>
      #        </a>
173
      #
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
      # 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 已提交
200
      # The three options specific to +link_to+ (<tt>:confirm</tt>, <tt>:popup</tt>, and <tt>:method</tt>) are used as follows:
201
      #
202
      #   link_to "Visit Other Site", "http://www.rubyonrails.org/", :confirm => "Are you sure?"
203 204
      #   # => <a href="http://www.rubyonrails.org/" onclick="return confirm('Are you sure?');">Visit Other Site</a>
      #
205
      #   link_to "Help", { :action => "help" }, :popup => true
206 207
      #   # => <a href="/testing/help/" onclick="window.open(this.href);return false;">Help</a>
      #
208 209
      #   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>
210
      #
211
      #   link_to "Delete Image", @image, :confirm => "Are you sure?", :method => :delete
212
      #   # => <a href="/images/9" onclick="if (confirm('Are you sure?')) { var f = document.createElement('form');
213
      #        f.style.display = 'none'; this.parentNode.appendChild(f); f.method = 'POST'; f.action = this.href;
214
      #        var m = document.createElement('input'); m.setAttribute('type', 'hidden'); m.setAttribute('name', '_method');
P
Pratik Naik 已提交
215 216 217
      #        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>
218 219 220 221 222 223
      def link_to(*args, &block)
        if block_given?
          options      = args.first || {}
          html_options = args.second
          concat(link_to(capture(&block), options, html_options))
        else
224 225 226
          name         = args[0]
          options      = args[1] || {}
          html_options = args[2]
227

228
          url = url_for(options)
229 230 231 232 233 234

          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)
235
          else
236
            tag_options = nil
237
          end
238

239 240
          href_attr = "href=\"#{url}\"" unless href
          "<a #{href_attr}#{tag_options}>#{name || url}</a>"
D
Initial  
David Heinemeier Hansson 已提交
241 242 243
        end
      end

244 245 246 247
      # 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 已提交
248 249
      # using the +link_to+ method with the <tt>:method</tt> modifier as described in
      # the +link_to+ documentation.
250
      #
P
Pratik Naik 已提交
251
      # The generated form element has a class name of <tt>button-to</tt>
252 253 254
      # 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 已提交
255
      # described in the +link_to+ documentation. If no <tt>:method</tt> modifier
256
      # is given, it will default to performing a POST operation. You can also
257 258 259
      # 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.
260
      #
261
      # ==== Options
P
Pratik Naik 已提交
262
      # The +options+ hash accepts the same options as url_for.
263
      #
264
      # There are a few special +html_options+:
P
Pratik Naik 已提交
265 266 267
      # * <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
268 269
      #   prompt with the question specified. If the user accepts, the link is
      #   processed normally, otherwise no action is taken.
270
      #
271 272 273 274 275
      # ==== Examples
      #   <%= button_to "New", :action => "new" %>
      #   # => "<form method="post" action="/controller/new" class="button-to">
      #   #      <div><input value="New" type="submit" /></div>
      #   #    </form>"
276
      #
277 278 279 280 281 282 283 284 285
      #   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>"
286 287
      def button_to(name, options = {}, html_options = {})
        html_options = html_options.stringify_keys
288
        convert_boolean_attributes!(html_options, %w( disabled ))
289 290 291 292 293 294 295

        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'
296

297
        request_token_tag = ''
298
        if form_method == 'post' && protect_against_forgery?
299 300
          request_token_tag = tag(:input, :type => "hidden", :name => request_forgery_protection_token.to_s, :value => form_authenticity_token)
        end
301

302 303 304
        if confirm = html_options.delete("confirm")
          html_options["onclick"] = "return #{confirm_javascript_function(confirm)};"
        end
305

306
        url = options.is_a?(String) ? options : self.url_for(options)
307
        name ||= url
308

309
        html_options.merge!("type" => "submit", "value" => name)
310

311
        "<form method=\"#{form_method}\" action=\"#{escape_once url}\" class=\"button-to\"><div>" +
312
          method_tag + tag("input", html_options) + request_token_tag + "</div></form>"
313 314
      end

315

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

358
      # Creates a link tag of the given +name+ using a URL created by the set of
359
      # +options+ unless +condition+ is true, in which case only the name is
360 361
      # 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 已提交
362
      # accepts the name or the full argument list for +link_to_unless+.
363
      #
364
      # ==== Examples
365
      #   <%= link_to_unless(@current_user.nil?, "Reply", { :action => "reply" }) %>
366 367
      #   # If the user is logged in...
      #   # => <a href="/controller/reply/">Reply</a>
368
      #
369
      #   <%=
370 371
      #      link_to_unless(@current_user.nil?, "Reply", { :action => "reply" }) do |name|
      #        link_to(name, { :controller => "accounts", :action => "signup" })
372
      #      end
373 374 375 376 377
      #   %>
      #   # If the user is logged in...
      #   # => <a href="/controller/reply/">Reply</a>
      #   # If not...
      #   # => <a href="/accounts/signup">Reply</a>
378
      def link_to_unless(condition, name, options = {}, html_options = {}, &block)
379 380
        if condition
          if block_given?
381
            block.arity <= 1 ? yield(name) : yield(name, options, html_options)
382
          else
383
            name
384
          end
D
Initial  
David Heinemeier Hansson 已提交
385
        else
386
          link_to(name, options, html_options)
387
        end
388
      end
389

390
      # Creates a link tag of the given +name+ using a URL created by the set of
391
      # +options+ if +condition+ is true, in which case only the name is
392
      # returned. To specialize the default behavior, you can pass a block that
P
Pratik Naik 已提交
393 394
      # accepts the name or the full argument list for +link_to_unless+ (see the examples
      # in +link_to_unless+).
395 396 397 398 399 400
      #
      # ==== 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>
      #
401
      #   <%=
402 403
      #      link_to_if(@current_user.nil?, "Login", { :controller => "sessions", :action => "new" }) do
      #        link_to(@current_user.login, { :controller => "accounts", :action => "show", :id => @current_user })
404
      #      end
405 406 407 408 409
      #   %>
      #   # 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>
410 411
      def link_to_if(condition, name, options = {}, html_options = {}, &block)
        link_to_unless !condition, name, options, html_options, &block
D
Initial  
David Heinemeier Hansson 已提交
412 413
      end

414 415
      # 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
416
      # HTML attributes for the link can be passed in +html_options+.
417
      #
P
Pratik Naik 已提交
418
      # +mail_to+ has several methods for hindering email harvesters and customizing
419 420
      # the email itself by passing special keys to +html_options+.
      #
421
      # ==== Options
P
Pratik Naik 已提交
422 423
      # * <tt>:encode</tt> - This key will accept the strings "javascript" or "hex".
      #   Passing "javascript" will dynamically create and encode the mailto link then
424 425
      #   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 已提交
426 427
      #   encode the +email_address+ before outputting the mailto link.
      # * <tt>:replace_at</tt> - When the link +name+ isn't provided, the
428 429 430
      #   +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 已提交
431
      # * <tt>:replace_dot</tt> - When the link +name+ isn't provided, the
432 433 434
      #   +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 已提交
435
      # * <tt>:subject</tt> - Preset the subject line of the email.
436
      # * <tt>:body</tt> - Preset the body of the email.
P
Pratik Naik 已提交
437 438
      # * <tt>:cc</tt> - Carbon Copy addition recipients on the email.
      # * <tt>:bcc</tt> - Blind Carbon Copy additional recipients on the email.
439
      #
440
      # ==== Examples
441
      #   mail_to "me@domain.com"
442
      #   # => <a href="mailto:me@domain.com">me@domain.com</a>
443
      #
444
      #   mail_to "me@domain.com", "My email", :encode => "javascript"
445
      #   # => <script type="text/javascript">eval(decodeURIComponent('%64%6f%63...%27%29%3b'))</script>
446
      #
447
      #   mail_to "me@domain.com", "My email", :encode => "hex"
448 449
      #   # => <a href="mailto:%6d%65@%64%6f%6d%61%69%6e.%63%6f%6d">My email</a>
      #
450
      #   mail_to "me@domain.com", nil, :replace_at => "_at_", :replace_dot => "_dot_", :class => "email"
451
      #   # => <a href="mailto:me@domain.com" class="email">me_at_domain_dot_com</a>
452
      #
453
      #   mail_to "me@domain.com", "My email", :cc => "ccaddress@domain.com",
454
      #            :subject => "This is an example email"
455
      #   # => <a href="mailto:me@domain.com?cc=ccaddress@domain.com&subject=This%20is%20an%20example%20email">My email</a>
D
Initial  
David Heinemeier Hansson 已提交
456
      def mail_to(email_address, name = nil, html_options = {})
457
        html_options = html_options.stringify_keys
458
        encode = html_options.delete("encode").to_s
459 460
        cc, bcc, subject, body = html_options.delete("cc"), html_options.delete("bcc"), html_options.delete("subject"), html_options.delete("body")

461
        string = ''
462 463 464 465 466 467 468
        extras = ''
        extras << "cc=#{CGI.escape(cc).gsub("+", "%20")}&" unless cc.nil?
        extras << "bcc=#{CGI.escape(bcc).gsub("+", "%20")}&" unless bcc.nil?
        extras << "body=#{CGI.escape(body).gsub("+", "%20")}&" unless body.nil?
        extras << "subject=#{CGI.escape(subject).gsub("+", "%20")}&" unless subject.nil?
        extras = "?" << extras.gsub!(/&?$/,"") unless extras.empty?

469 470
        email_address = email_address.to_s

471 472 473 474
        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")

475
        if encode == "javascript"
476
          "document.write('#{content_tag("a", name || email_address_obfuscated, html_options.merge({ "href" => "mailto:"+email_address+extras }))}');".each_byte do |c|
477
            string << sprintf("%%%x", c)
478
          end
479
          "<script type=\"#{Mime::JS}\">eval(decodeURIComponent('#{string}'))</script>"
480
        elsif encode == "hex"
481 482 483 484 485 486 487 488
          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) }

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

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

D
Initial  
David Heinemeier Hansson 已提交
559
      private
560
        def convert_options_to_javascript!(html_options, url = '')
561 562
          confirm, popup = html_options.delete("confirm"), html_options.delete("popup")

563
          method, href = html_options.delete("method"), html_options['href']
564

565
          html_options["onclick"] = case
566
            when popup && method
567
              raise ActionView::ActionViewError, "You can't use :popup and :method in the same link"
568 569
            when confirm && popup
              "if (#{confirm_javascript_function(confirm)}) { #{popup_javascript_function(popup)} };return false;"
570
            when confirm && method
571
              "if (#{confirm_javascript_function(confirm)}) { #{method_javascript_function(method, url, href)} };return false;"
572 573
            when confirm
              "return #{confirm_javascript_function(confirm)};"
574
            when method
575
              "#{method_javascript_function(method, url, href)}return false;"
576
            when popup
577
              "#{popup_javascript_function(popup)}return false;"
578 579
            else
              html_options["onclick"]
D
Initial  
David Heinemeier Hansson 已提交
580 581
          end
        end
582

583 584
        def confirm_javascript_function(confirm)
          "confirm('#{escape_javascript(confirm)}')"
585
        end
586

587 588
        def popup_javascript_function(popup)
          popup.is_a?(Array) ? "window.open(this.href,'#{popup.first}','#{popup.last}');" : "window.open(this.href);"
589
        end
590

591 592
        def method_javascript_function(method, url = '', href = nil)
          action = (href && url.size > 0) ? "'#{url}'" : 'this.href'
593
          submit_function =
594
            "var f = document.createElement('form'); f.style.display = 'none'; " +
595
            "this.parentNode.appendChild(f); f.method = 'POST'; f.action = #{action};"
596

597 598 599 600
          unless method == :post
            submit_function << "var m = document.createElement('input'); m.setAttribute('type', 'hidden'); "
            submit_function << "m.setAttribute('name', '_method'); m.setAttribute('value', '#{method}'); f.appendChild(m);"
          end
601

602
          if protect_against_forgery?
603
            submit_function << "var s = document.createElement('input'); s.setAttribute('type', 'hidden'); "
604
            submit_function << "s.setAttribute('name', '#{request_forgery_protection_token}'); s.setAttribute('value', '#{escape_javascript form_authenticity_token}'); f.appendChild(s);"
605
          end
606
          submit_function << "f.submit();"
607 608
        end

P
Pratik Naik 已提交
609
        # Processes the +html_options+ hash, converting the boolean
610 611
        # attributes from true/false form into the form required by
        # HTML/XHTML.  (An attribute is considered to be boolean if
P
Pratik Naik 已提交
612
        # its name is listed in the given +bool_attrs+ array.)
613
        #
P
Pratik Naik 已提交
614
        # More specifically, for each boolean attribute in +html_options+
615 616
        # given as:
        #
P
Pratik Naik 已提交
617
        #   "attr" => bool_value
618
        #
P
Pratik Naik 已提交
619
        # if the associated +bool_value+ evaluates to true, it is
620
        # replaced with the attribute's name; otherwise the attribute is
P
Pratik Naik 已提交
621
        # removed from the +html_options+ hash.  (See the XHTML 1.0 spec,
622 623 624
        # section 4.5 "Attribute Minimization" for more:
        # http://www.w3.org/TR/xhtml1/#h-4.5)
        #
P
Pratik Naik 已提交
625
        # Returns the updated +html_options+ hash, which is also modified
626 627 628 629 630 631 632 633 634 635
        # 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 已提交
636 637
    end
  end
638
end