PageRenderTime 50ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/actionpack/lib/action_view/helpers/url_helper.rb

https://github.com/ghar/rails
Ruby | 681 lines | 188 code | 43 blank | 450 comment | 38 complexity | d0301563c47fb437677a9083e66f2910 MD5 | raw file
  1. require 'action_view/helpers/javascript_helper'
  2. require 'active_support/core_ext/array/access'
  3. require 'active_support/core_ext/hash/keys'
  4. require 'active_support/core_ext/string/output_safety'
  5. require 'action_dispatch'
  6. module ActionView
  7. # = Action View URL Helpers
  8. module Helpers #:nodoc:
  9. # Provides a set of methods for making links and getting URLs that
  10. # depend on the routing subsystem (see ActionDispatch::Routing).
  11. # This allows you to use the same format for links in views
  12. # and controllers.
  13. module UrlHelper
  14. # This helper may be included in any class that includes the
  15. # URL helpers of a routes (routes.url_helpers). Some methods
  16. # provided here will only work in the context of a request
  17. # (link_to_unless_current, for instance), which must be provided
  18. # as a method called #request on the context.
  19. extend ActiveSupport::Concern
  20. include ActionDispatch::Routing::UrlFor
  21. include TagHelper
  22. def _routes_context
  23. controller
  24. end
  25. # Need to map default url options to controller one.
  26. # def default_url_options(*args) #:nodoc:
  27. # controller.send(:default_url_options, *args)
  28. # end
  29. #
  30. def url_options
  31. return super unless controller.respond_to?(:url_options)
  32. controller.url_options
  33. end
  34. # Returns the URL for the set of +options+ provided. This takes the
  35. # same options as +url_for+ in Action Controller (see the
  36. # documentation for <tt>ActionController::Base#url_for</tt>). Note that by default
  37. # <tt>:only_path</tt> is <tt>true</tt> so you'll get the relative "/controller/action"
  38. # instead of the fully qualified URL like "http://example.com/controller/action".
  39. #
  40. # ==== Options
  41. # * <tt>:anchor</tt> - Specifies the anchor name to be appended to the path.
  42. # * <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).
  43. # * <tt>:trailing_slash</tt> - If true, adds a trailing slash, as in "/archive/2005/". Note that this
  44. # is currently not recommended since it breaks caching.
  45. # * <tt>:host</tt> - Overrides the default (current) host if provided.
  46. # * <tt>:protocol</tt> - Overrides the default (current) protocol if provided.
  47. # * <tt>:user</tt> - Inline HTTP authentication (only plucked out if <tt>:password</tt> is also present).
  48. # * <tt>:password</tt> - Inline HTTP authentication (only plucked out if <tt>:user</tt> is also present).
  49. #
  50. # ==== Relying on named routes
  51. #
  52. # Passing a record (like an Active Record or Active Resource) instead of a Hash as the options parameter will
  53. # trigger the named route for that record. The lookup will happen on the name of the class. So passing a
  54. # Workshop object will attempt to use the +workshop_path+ route. If you have a nested route, such as
  55. # +admin_workshop_path+ you'll have to call that explicitly (it's impossible for +url_for+ to guess that route).
  56. #
  57. # ==== Examples
  58. # <%= url_for(:action => 'index') %>
  59. # # => /blog/
  60. #
  61. # <%= url_for(:action => 'find', :controller => 'books') %>
  62. # # => /books/find
  63. #
  64. # <%= url_for(:action => 'login', :controller => 'members', :only_path => false, :protocol => 'https') %>
  65. # # => https://www.example.com/members/login/
  66. #
  67. # <%= url_for(:action => 'play', :anchor => 'player') %>
  68. # # => /messages/play/#player
  69. #
  70. # <%= url_for(:action => 'jump', :anchor => 'tax&ship') %>
  71. # # => /testing/jump/#tax&ship
  72. #
  73. # <%= url_for(Workshop.new) %>
  74. # # relies on Workshop answering a persisted? call (and in this case returning false)
  75. # # => /workshops
  76. #
  77. # <%= url_for(@workshop) %>
  78. # # calls @workshop.to_param which by default returns the id
  79. # # => /workshops/5
  80. #
  81. # # to_param can be re-defined in a model to provide different URL names:
  82. # # => /workshops/1-workshop-name
  83. #
  84. # <%= url_for("http://www.example.com") %>
  85. # # => http://www.example.com
  86. #
  87. # <%= url_for(:back) %>
  88. # # if request.env["HTTP_REFERER"] is set to "http://www.example.com"
  89. # # => http://www.example.com
  90. #
  91. # <%= url_for(:back) %>
  92. # # if request.env["HTTP_REFERER"] is not set or is blank
  93. # # => javascript:history.back()
  94. def url_for(options = {})
  95. options ||= {}
  96. case options
  97. when String
  98. options
  99. when Hash
  100. options = options.symbolize_keys.reverse_merge!(:only_path => options[:host].nil?)
  101. super
  102. when :back
  103. controller.request.env["HTTP_REFERER"] || 'javascript:history.back()'
  104. else
  105. polymorphic_path(options)
  106. end
  107. end
  108. # Creates a link tag of the given +name+ using a URL created by the set of +options+.
  109. # See the valid options in the documentation for +url_for+. It's also possible to
  110. # pass a String instead of an options hash, which generates a link tag that uses the
  111. # value of the String as the href for the link. Using a <tt>:back</tt> Symbol instead
  112. # of an options hash will generate a link to the referrer (a JavaScript back link
  113. # will be used in place of a referrer if none exists). If +nil+ is passed as the name
  114. # the value of the link itself will become the name.
  115. #
  116. # ==== Signatures
  117. #
  118. # link_to(body, url, html_options = {})
  119. # # url is a String; you can use URL helpers like
  120. # # posts_path
  121. #
  122. # link_to(body, url_options = {}, html_options = {})
  123. # # url_options, except :confirm or :method,
  124. # # is passed to url_for
  125. #
  126. # link_to(options = {}, html_options = {}) do
  127. # # name
  128. # end
  129. #
  130. # link_to(url, html_options = {}) do
  131. # # name
  132. # end
  133. #
  134. # ==== Options
  135. # * <tt>:confirm => 'question?'</tt> - This will allow the unobtrusive JavaScript
  136. # driver to prompt with the question specified. If the user accepts, the link is
  137. # processed normally, otherwise no action is taken.
  138. # * <tt>:method => symbol of HTTP verb</tt> - This modifier will dynamically
  139. # create an HTML form and immediately submit the form for processing using
  140. # the HTTP verb specified. Useful for having links perform a POST operation
  141. # in dangerous actions like deleting a record (which search bots can follow
  142. # while spidering your site). Supported verbs are <tt>:post</tt>, <tt>:delete</tt> and <tt>:put</tt>.
  143. # Note that if the user has JavaScript disabled, the request will fall back
  144. # to using GET. If <tt>:href => '#'</tt> is used and the user has JavaScript
  145. # disabled clicking the link will have no effect. If you are relying on the
  146. # POST behavior, you should check for it in your controller's action by using
  147. # the request object's methods for <tt>post?</tt>, <tt>delete?</tt> or <tt>put?</tt>.
  148. # * <tt>:remote => true</tt> - This will allow the unobtrusive JavaScript
  149. # driver to make an Ajax request to the URL in question instead of following
  150. # the link. The drivers each provide mechanisms for listening for the
  151. # completion of the Ajax request and performing JavaScript operations once
  152. # they're complete
  153. #
  154. # ==== Examples
  155. # Because it relies on +url_for+, +link_to+ supports both older-style controller/action/id arguments
  156. # and newer RESTful routes. Current Rails style favors RESTful routes whenever possible, so base
  157. # your application on resources and use
  158. #
  159. # link_to "Profile", profile_path(@profile)
  160. # # => <a href="/profiles/1">Profile</a>
  161. #
  162. # or the even pithier
  163. #
  164. # link_to "Profile", @profile
  165. # # => <a href="/profiles/1">Profile</a>
  166. #
  167. # in place of the older more verbose, non-resource-oriented
  168. #
  169. # link_to "Profile", :controller => "profiles", :action => "show", :id => @profile
  170. # # => <a href="/profiles/show/1">Profile</a>
  171. #
  172. # Similarly,
  173. #
  174. # link_to "Profiles", profiles_path
  175. # # => <a href="/profiles">Profiles</a>
  176. #
  177. # is better than
  178. #
  179. # link_to "Profiles", :controller => "profiles"
  180. # # => <a href="/profiles">Profiles</a>
  181. #
  182. # You can use a block as well if your link target is hard to fit into the name parameter. ERB example:
  183. #
  184. # <%= link_to(@profile) do %>
  185. # <strong><%= @profile.name %></strong> -- <span>Check it out!</span>
  186. # <% end %>
  187. # # => <a href="/profiles/1">
  188. # <strong>David</strong> -- <span>Check it out!</span>
  189. # </a>
  190. #
  191. # Classes and ids for CSS are easy to produce:
  192. #
  193. # link_to "Articles", articles_path, :id => "news", :class => "article"
  194. # # => <a href="/articles" class="article" id="news">Articles</a>
  195. #
  196. # Be careful when using the older argument style, as an extra literal hash is needed:
  197. #
  198. # link_to "Articles", { :controller => "articles" }, :id => "news", :class => "article"
  199. # # => <a href="/articles" class="article" id="news">Articles</a>
  200. #
  201. # Leaving the hash off gives the wrong link:
  202. #
  203. # link_to "WRONG!", :controller => "articles", :id => "news", :class => "article"
  204. # # => <a href="/articles/index/news?class=article">WRONG!</a>
  205. #
  206. # +link_to+ can also produce links with anchors or query strings:
  207. #
  208. # link_to "Comment wall", profile_path(@profile, :anchor => "wall")
  209. # # => <a href="/profiles/1#wall">Comment wall</a>
  210. #
  211. # link_to "Ruby on Rails search", :controller => "searches", :query => "ruby on rails"
  212. # # => <a href="/searches?query=ruby+on+rails">Ruby on Rails search</a>
  213. #
  214. # link_to "Nonsense search", searches_path(:foo => "bar", :baz => "quux")
  215. # # => <a href="/searches?foo=bar&amp;baz=quux">Nonsense search</a>
  216. #
  217. # The two options specific to +link_to+ (<tt>:confirm</tt> and <tt>:method</tt>) are used as follows:
  218. #
  219. # link_to "Visit Other Site", "http://www.rubyonrails.org/", :confirm => "Are you sure?"
  220. # # => <a href="http://www.rubyonrails.org/" data-confirm="Are you sure?"">Visit Other Site</a>
  221. #
  222. # link_to("Destroy", "http://www.example.com", :method => :delete, :confirm => "Are you sure?")
  223. # # => <a href='http://www.example.com' rel="nofollow" data-method="delete" data-confirm="Are you sure?">Destroy</a>
  224. def link_to(*args, &block)
  225. if block_given?
  226. options = args.first || {}
  227. html_options = args.second
  228. link_to(capture(&block), options, html_options)
  229. else
  230. name = args[0]
  231. options = args[1] || {}
  232. html_options = args[2]
  233. html_options = convert_options_to_data_attributes(options, html_options)
  234. url = url_for(options)
  235. href = html_options['href']
  236. tag_options = tag_options(html_options)
  237. href_attr = "href=\"#{ERB::Util.html_escape(url)}\"" unless href
  238. "<a #{href_attr}#{tag_options}>#{ERB::Util.html_escape(name || url)}</a>".html_safe
  239. end
  240. end
  241. # Generates a form containing a single button that submits to the URL created
  242. # by the set of +options+. This is the safest method to ensure links that
  243. # cause changes to your data are not triggered by search bots or accelerators.
  244. # If the HTML button does not work with your layout, you can also consider
  245. # using the +link_to+ method with the <tt>:method</tt> modifier as described in
  246. # the +link_to+ documentation.
  247. #
  248. # By default, the generated form element has a class name of <tt>button_to</tt>
  249. # to allow styling of the form itself and its children. This can be changed
  250. # using the <tt>:form_class</tt> modifier within +html_options+. You can control
  251. # the form submission and input element behavior using +html_options+.
  252. # This method accepts the <tt>:method</tt> and <tt>:confirm</tt> modifiers
  253. # described in the +link_to+ documentation. If no <tt>:method</tt> modifier
  254. # is given, it will default to performing a POST operation. You can also
  255. # disable the button by passing <tt>:disabled => true</tt> in +html_options+.
  256. # If you are using RESTful routes, you can pass the <tt>:method</tt>
  257. # to change the HTTP verb used to submit the form.
  258. #
  259. # ==== Options
  260. # The +options+ hash accepts the same options as +url_for+.
  261. #
  262. # There are a few special +html_options+:
  263. # * <tt>:method</tt> - Symbol of HTTP verb. Supported verbs are <tt>:post</tt>, <tt>:get</tt>,
  264. # <tt>:delete</tt> and <tt>:put</tt>. By default it will be <tt>:post</tt>.
  265. # * <tt>:disabled</tt> - If set to true, it will generate a disabled button.
  266. # * <tt>:confirm</tt> - This will use the unobtrusive JavaScript driver to
  267. # prompt with the question specified. If the user accepts, the link is
  268. # processed normally, otherwise no action is taken.
  269. # * <tt>:remote</tt> - If set to true, will allow the Unobtrusive JavaScript drivers to control the
  270. # submit behavior. By default this behavior is an ajax submit.
  271. # * <tt>:form_class</tt> - This controls the class of the form within which the submit button will
  272. # be placed
  273. #
  274. # ==== Examples
  275. # <%= button_to "New", :action => "new" %>
  276. # # => "<form method="post" action="/controller/new" class="button_to">
  277. # # <div><input value="New" type="submit" /></div>
  278. # # </form>"
  279. #
  280. #
  281. # <%= button_to "New", :action => "new", :form_class => "new-thing" %>
  282. # # => "<form method="post" action="/controller/new" class="new-thing">
  283. # # <div><input value="New" type="submit" /></div>
  284. # # </form>"
  285. #
  286. #
  287. # <%= button_to "Delete Image", { :action => "delete", :id => @image.id },
  288. # :confirm => "Are you sure?", :method => :delete %>
  289. # # => "<form method="post" action="/images/delete/1" class="button_to">
  290. # # <div>
  291. # # <input type="hidden" name="_method" value="delete" />
  292. # # <input data-confirm='Are you sure?' value="Delete" type="submit" />
  293. # # </div>
  294. # # </form>"
  295. #
  296. #
  297. # <%= button_to('Destroy', 'http://www.example.com', :confirm => 'Are you sure?',
  298. # :method => "delete", :remote => true, :disable_with => 'loading...') %>
  299. # # => "<form class='button_to' method='post' action='http://www.example.com' data-remote='true'>
  300. # # <div>
  301. # # <input name='_method' value='delete' type='hidden' />
  302. # # <input value='Destroy' type='submit' disable_with='loading...' data-confirm='Are you sure?' />
  303. # # </div>
  304. # # </form>"
  305. # #
  306. def button_to(name, options = {}, html_options = {})
  307. html_options = html_options.stringify_keys
  308. convert_boolean_attributes!(html_options, %w( disabled ))
  309. method_tag = ''
  310. if (method = html_options.delete('method')) && %w{put delete}.include?(method.to_s)
  311. method_tag = tag('input', :type => 'hidden', :name => '_method', :value => method.to_s)
  312. end
  313. form_method = method.to_s == 'get' ? 'get' : 'post'
  314. form_class = html_options.delete('form_class') || 'button_to'
  315. remote = html_options.delete('remote')
  316. request_token_tag = ''
  317. if form_method == 'post' && protect_against_forgery?
  318. request_token_tag = tag(:input, :type => "hidden", :name => request_forgery_protection_token.to_s, :value => form_authenticity_token)
  319. end
  320. url = options.is_a?(String) ? options : self.url_for(options)
  321. name ||= url
  322. html_options = convert_options_to_data_attributes(options, html_options)
  323. html_options.merge!("type" => "submit", "value" => name)
  324. ("<form method=\"#{form_method}\" action=\"#{ERB::Util.html_escape(url)}\" #{"data-remote=\"true\"" if remote} class=\"#{ERB::Util.html_escape(form_class)}\"><div>" +
  325. method_tag + tag("input", html_options) + request_token_tag + "</div></form>").html_safe
  326. end
  327. # Creates a link tag of the given +name+ using a URL created by the set of
  328. # +options+ unless the current request URI is the same as the links, in
  329. # which case only the name is returned (or the given block is yielded, if
  330. # one exists). You can give +link_to_unless_current+ a block which will
  331. # specialize the default behavior (e.g., show a "Start Here" link rather
  332. # than the link's text).
  333. #
  334. # ==== Examples
  335. # Let's say you have a navigation menu...
  336. #
  337. # <ul id="navbar">
  338. # <li><%= link_to_unless_current("Home", { :action => "index" }) %></li>
  339. # <li><%= link_to_unless_current("About Us", { :action => "about" }) %></li>
  340. # </ul>
  341. #
  342. # If in the "about" action, it will render...
  343. #
  344. # <ul id="navbar">
  345. # <li><a href="/controller/index">Home</a></li>
  346. # <li>About Us</li>
  347. # </ul>
  348. #
  349. # ...but if in the "index" action, it will render:
  350. #
  351. # <ul id="navbar">
  352. # <li>Home</li>
  353. # <li><a href="/controller/about">About Us</a></li>
  354. # </ul>
  355. #
  356. # The implicit block given to +link_to_unless_current+ is evaluated if the current
  357. # action is the action given. So, if we had a comments page and wanted to render a
  358. # "Go Back" link instead of a link to the comments page, we could do something like this...
  359. #
  360. # <%=
  361. # link_to_unless_current("Comment", { :controller => "comments", :action => "new" }) do
  362. # link_to("Go back", { :controller => "posts", :action => "index" })
  363. # end
  364. # %>
  365. def link_to_unless_current(name, options = {}, html_options = {}, &block)
  366. link_to_unless current_page?(options), name, options, html_options, &block
  367. end
  368. # Creates a link tag of the given +name+ using a URL created by the set of
  369. # +options+ unless +condition+ is true, in which case only the name is
  370. # returned. To specialize the default behavior (i.e., show a login link rather
  371. # than just the plaintext link text), you can pass a block that
  372. # accepts the name or the full argument list for +link_to_unless+.
  373. #
  374. # ==== Examples
  375. # <%= link_to_unless(@current_user.nil?, "Reply", { :action => "reply" }) %>
  376. # # If the user is logged in...
  377. # # => <a href="/controller/reply/">Reply</a>
  378. #
  379. # <%=
  380. # link_to_unless(@current_user.nil?, "Reply", { :action => "reply" }) do |name|
  381. # link_to(name, { :controller => "accounts", :action => "signup" })
  382. # end
  383. # %>
  384. # # If the user is logged in...
  385. # # => <a href="/controller/reply/">Reply</a>
  386. # # If not...
  387. # # => <a href="/accounts/signup">Reply</a>
  388. def link_to_unless(condition, name, options = {}, html_options = {}, &block)
  389. if condition
  390. if block_given?
  391. block.arity <= 1 ? capture(name, &block) : capture(name, options, html_options, &block)
  392. else
  393. name
  394. end
  395. else
  396. link_to(name, options, html_options)
  397. end
  398. end
  399. # Creates a link tag of the given +name+ using a URL created by the set of
  400. # +options+ if +condition+ is true, otherwise only the name is
  401. # returned. To specialize the default behavior, you can pass a block that
  402. # accepts the name or the full argument list for +link_to_unless+ (see the examples
  403. # in +link_to_unless+).
  404. #
  405. # ==== Examples
  406. # <%= link_to_if(@current_user.nil?, "Login", { :controller => "sessions", :action => "new" }) %>
  407. # # If the user isn't logged in...
  408. # # => <a href="/sessions/new/">Login</a>
  409. #
  410. # <%=
  411. # link_to_if(@current_user.nil?, "Login", { :controller => "sessions", :action => "new" }) do
  412. # link_to(@current_user.login, { :controller => "accounts", :action => "show", :id => @current_user })
  413. # end
  414. # %>
  415. # # If the user isn't logged in...
  416. # # => <a href="/sessions/new/">Login</a>
  417. # # If they are logged in...
  418. # # => <a href="/accounts/show/3">my_username</a>
  419. def link_to_if(condition, name, options = {}, html_options = {}, &block)
  420. link_to_unless !condition, name, options, html_options, &block
  421. end
  422. # Creates a mailto link tag to the specified +email_address+, which is
  423. # also used as the name of the link unless +name+ is specified. Additional
  424. # HTML attributes for the link can be passed in +html_options+.
  425. #
  426. # +mail_to+ has several methods for hindering email harvesters and customizing
  427. # the email itself by passing special keys to +html_options+.
  428. #
  429. # ==== Options
  430. # * <tt>:encode</tt> - This key will accept the strings "javascript" or "hex".
  431. # Passing "javascript" will dynamically create and encode the mailto link then
  432. # eval it into the DOM of the page. This method will not show the link on
  433. # the page if the user has JavaScript disabled. Passing "hex" will hex
  434. # encode the +email_address+ before outputting the mailto link.
  435. # * <tt>:replace_at</tt> - When the link +name+ isn't provided, the
  436. # +email_address+ is used for the link label. You can use this option to
  437. # obfuscate the +email_address+ by substituting the @ sign with the string
  438. # given as the value.
  439. # * <tt>:replace_dot</tt> - When the link +name+ isn't provided, the
  440. # +email_address+ is used for the link label. You can use this option to
  441. # obfuscate the +email_address+ by substituting the . in the email with the
  442. # string given as the value.
  443. # * <tt>:subject</tt> - Preset the subject line of the email.
  444. # * <tt>:body</tt> - Preset the body of the email.
  445. # * <tt>:cc</tt> - Carbon Copy addition recipients on the email.
  446. # * <tt>:bcc</tt> - Blind Carbon Copy additional recipients on the email.
  447. #
  448. # ==== Examples
  449. # mail_to "me@domain.com"
  450. # # => <a href="mailto:me@domain.com">me@domain.com</a>
  451. #
  452. # mail_to "me@domain.com", "My email", :encode => "javascript"
  453. # # => <script type="text/javascript">eval(decodeURIComponent('%64%6f%63...%27%29%3b'))</script>
  454. #
  455. # mail_to "me@domain.com", "My email", :encode => "hex"
  456. # # => <a href="mailto:%6d%65@%64%6f%6d%61%69%6e.%63%6f%6d">My email</a>
  457. #
  458. # mail_to "me@domain.com", nil, :replace_at => "_at_", :replace_dot => "_dot_", :class => "email"
  459. # # => <a href="mailto:me@domain.com" class="email">me_at_domain_dot_com</a>
  460. #
  461. # mail_to "me@domain.com", "My email", :cc => "ccaddress@domain.com",
  462. # :subject => "This is an example email"
  463. # # => <a href="mailto:me@domain.com?cc=ccaddress@domain.com&subject=This%20is%20an%20example%20email">My email</a>
  464. def mail_to(email_address, name = nil, html_options = {})
  465. email_address = ERB::Util.html_escape(email_address)
  466. html_options = html_options.stringify_keys
  467. encode = html_options.delete("encode").to_s
  468. extras = %w{ cc bcc body subject }.map { |item|
  469. option = html_options.delete(item) || next
  470. "#{item}=#{Rack::Utils.escape(option).gsub("+", "%20")}"
  471. }.compact
  472. extras = extras.empty? ? '' : '?' + ERB::Util.html_escape(extras.join('&'))
  473. email_address_obfuscated = email_address.to_str
  474. email_address_obfuscated.gsub!(/@/, html_options.delete("replace_at")) if html_options.key?("replace_at")
  475. email_address_obfuscated.gsub!(/\./, html_options.delete("replace_dot")) if html_options.key?("replace_dot")
  476. case encode
  477. when "javascript"
  478. string = ''
  479. html = content_tag("a", name || email_address_obfuscated.html_safe, html_options.merge("href" => "mailto:#{email_address}#{extras}".html_safe))
  480. html = escape_javascript(html.to_str)
  481. "document.write('#{html}');".each_byte do |c|
  482. string << sprintf("%%%x", c)
  483. end
  484. "<script type=\"#{Mime::JS}\">eval(decodeURIComponent('#{string}'))</script>".html_safe
  485. when "hex"
  486. email_address_encoded = email_address_obfuscated.unpack('C*').map {|c|
  487. sprintf("&#%d;", c)
  488. }.join
  489. string = 'mailto:'.unpack('C*').map { |c|
  490. sprintf("&#%d;", c)
  491. }.join + email_address.unpack('C*').map { |c|
  492. char = c.chr
  493. char =~ /\w/ ? sprintf("%%%x", c) : char
  494. }.join
  495. content_tag "a", name || email_address_encoded.html_safe, html_options.merge("href" => "#{string}#{extras}".html_safe)
  496. else
  497. content_tag "a", name || email_address_obfuscated.html_safe, html_options.merge("href" => "mailto:#{email_address}#{extras}".html_safe)
  498. end
  499. end
  500. # True if the current request URI was generated by the given +options+.
  501. #
  502. # ==== Examples
  503. # Let's say we're in the <tt>/shop/checkout?order=desc</tt> action.
  504. #
  505. # current_page?(:action => 'process')
  506. # # => false
  507. #
  508. # current_page?(:controller => 'shop', :action => 'checkout')
  509. # # => true
  510. #
  511. # current_page?(:controller => 'shop', :action => 'checkout', :order => 'asc')
  512. # # => false
  513. #
  514. # current_page?(:action => 'checkout')
  515. # # => true
  516. #
  517. # current_page?(:controller => 'library', :action => 'checkout')
  518. # # => false
  519. #
  520. # Let's say we're in the <tt>/shop/checkout?order=desc&page=1</tt> action.
  521. #
  522. # current_page?(:action => 'process')
  523. # # => false
  524. #
  525. # current_page?(:controller => 'shop', :action => 'checkout')
  526. # # => true
  527. #
  528. # current_page?(:controller => 'shop', :action => 'checkout', :order => 'desc', :page => '1')
  529. # # => true
  530. #
  531. # current_page?(:controller => 'shop', :action => 'checkout', :order => 'desc', :page => '2')
  532. # # => false
  533. #
  534. # current_page?(:controller => 'shop', :action => 'checkout', :order => 'desc')
  535. # # => false
  536. #
  537. # current_page?(:action => 'checkout')
  538. # # => true
  539. #
  540. # current_page?(:controller => 'library', :action => 'checkout')
  541. # # => false
  542. #
  543. # Let's say we're in the <tt>/products</tt> action with method POST in case of invalid product.
  544. #
  545. # current_page?(:controller => 'product', :action => 'index')
  546. # # => false
  547. #
  548. def current_page?(options)
  549. unless request
  550. raise "You cannot use helpers that need to determine the current " \
  551. "page unless your view context provides a Request object " \
  552. "in a #request method"
  553. end
  554. return false unless request.get?
  555. url_string = url_for(options)
  556. # We ignore any extra parameters in the request_uri if the
  557. # submitted url doesn't have any either. This lets the function
  558. # work with things like ?order=asc
  559. if url_string.index("?")
  560. request_uri = request.fullpath
  561. else
  562. request_uri = request.path
  563. end
  564. if url_string =~ /^\w+:\/\//
  565. url_string == "#{request.protocol}#{request.host_with_port}#{request_uri}"
  566. else
  567. url_string == request_uri
  568. end
  569. end
  570. private
  571. def convert_options_to_data_attributes(options, html_options)
  572. if html_options
  573. html_options = html_options.stringify_keys
  574. html_options['data-remote'] = 'true' if link_to_remote_options?(options) || link_to_remote_options?(html_options)
  575. disable_with = html_options.delete("disable_with")
  576. confirm = html_options.delete('confirm')
  577. method = html_options.delete('method')
  578. html_options["data-disable-with"] = disable_with if disable_with
  579. html_options["data-confirm"] = confirm if confirm
  580. add_method_to_attributes!(html_options, method) if method
  581. html_options
  582. else
  583. link_to_remote_options?(options) ? {'data-remote' => 'true'} : {}
  584. end
  585. end
  586. def link_to_remote_options?(options)
  587. options.is_a?(Hash) && options.key?('remote') && options.delete('remote')
  588. end
  589. def add_method_to_attributes!(html_options, method)
  590. if method && method.to_s.downcase != "get" && html_options["rel"] !~ /nofollow/
  591. html_options["rel"] = "#{html_options["rel"]} nofollow".strip
  592. end
  593. html_options["data-method"] = method
  594. end
  595. def options_for_javascript(options)
  596. if options.empty?
  597. '{}'
  598. else
  599. "{#{options.keys.map { |k| "#{k}:#{options[k]}" }.sort.join(', ')}}"
  600. end
  601. end
  602. def array_or_string_for_javascript(option)
  603. if option.kind_of?(Array)
  604. "['#{option.join('\',\'')}']"
  605. elsif !option.nil?
  606. "'#{option}'"
  607. end
  608. end
  609. # Processes the +html_options+ hash, converting the boolean
  610. # attributes from true/false form into the form required by
  611. # HTML/XHTML. (An attribute is considered to be boolean if
  612. # its name is listed in the given +bool_attrs+ array.)
  613. #
  614. # More specifically, for each boolean attribute in +html_options+
  615. # given as:
  616. #
  617. # "attr" => bool_value
  618. #
  619. # if the associated +bool_value+ evaluates to true, it is
  620. # replaced with the attribute's name; otherwise the attribute is
  621. # removed from the +html_options+ hash. (See the XHTML 1.0 spec,
  622. # section 4.5 "Attribute Minimization" for more:
  623. # http://www.w3.org/TR/xhtml1/#h-4.5)
  624. #
  625. # Returns the updated +html_options+ hash, which is also modified
  626. # in place.
  627. #
  628. # Example:
  629. #
  630. # convert_boolean_attributes!( html_options,
  631. # %w( checked disabled readonly ) )
  632. def convert_boolean_attributes!(html_options, bool_attrs)
  633. bool_attrs.each { |x| html_options[x] = x if html_options.delete(x) }
  634. html_options
  635. end
  636. end
  637. end
  638. end