Changeset 7106
- Timestamp:
- 06/23/07 17:49:18 (2 years ago)
- Files:
-
- trunk/actionpack/lib/action_view/helpers/asset_tag_helper.rb (modified) (16 diffs)
- trunk/actionpack/lib/action_view/helpers/benchmark_helper.rb (modified) (1 diff)
- trunk/actionpack/lib/action_view/helpers/cache_helper.rb (modified) (1 diff)
- trunk/actionpack/lib/action_view/helpers/capture_helper.rb (modified) (2 diffs)
- trunk/actionpack/lib/action_view/helpers/date_helper.rb (modified) (14 diffs)
- trunk/actionpack/lib/action_view/helpers/form_tag_helper.rb (modified) (7 diffs)
- trunk/actionpack/lib/action_view/helpers/number_helper.rb (modified) (6 diffs)
- trunk/actionpack/lib/action_view/helpers/tag_helper.rb (modified) (5 diffs)
- trunk/actionpack/lib/action_view/helpers/text_helper.rb (modified) (17 diffs)
Legend:
- Unmodified
- Added
- Removed
- Modified
- Copied
- Moved
trunk/actionpack/lib/action_view/helpers/asset_tag_helper.rb
r6354 r7106 5 5 module ActionView 6 6 module Helpers #:nodoc: 7 # Provides methods for linking an HTML page together with other assets such 8 # as images, javascripts, stylesheets, and feeds. You can direct Rails to 9 # link to assets from a dedicated assets server by setting ActionController::Base.asset_host 10 # in your environment.rb. These methods do not verify the assets exist before 11 # linking to them. 7 # This module provides methods for generating HTML that links views to assets such 8 # as images, javascripts, stylesheets, and feeds. These methods do not verify 9 # the assets exist before linking to them. 10 # 11 # === Using asset hosts 12 # By default, Rails links to these assets on the current host in the public 13 # folder, but you can direct Rails to link to assets from a dedicated assets server by 14 # setting ActionController::Base.asset_host in your environment.rb. For example, 15 # let's say your asset host is assets.example.com. 12 16 # 13 17 # ActionController::Base.asset_host = "assets.example.com" … … 17 21 # => <link href="http://assets.example.com/stylesheets/application.css" media="screen" rel="Stylesheet" type="text/css" /> 18 22 # 19 # Since browsers typically open at most two connections to a single host, 20 # your assets often wait in single file for their turn to load. 21 # 22 # Use a %d wildcard in asset_host (asset%d.myapp.com) to automatically 23 # distribute asset requests among four hosts (asset0-asset3.myapp.com) 24 # so browsers will open eight connections rather than two. Use wildcard 25 # DNS to CNAME the wildcard to your real asset host. 26 # 27 # Note: this is purely a browser performance optimization and is not meant 23 # This is useful since browsers typically open at most two connections to a single host, 24 # which means your assets often wait in single file for their turn to load. You can 25 # alleviate this by using a %d wildcard in <tt>asset_host</tt> (for example, "assets%d.example.com") 26 # to automatically distribute asset requests among four hosts (e.g., assets0.example.com through assets3.example.com) 27 # so browsers will open eight connections rather than two. 28 # 29 # image_tag("rails.png") 30 # => <img src="http://assets0.example.com/images/rails.png" alt="Rails" /> 31 # stylesheet_include_tag("application") 32 # => <link href="http://assets3.example.com/stylesheets/application.css" media="screen" rel="Stylesheet" type="text/css" /> 33 # 34 # To do this, you can either setup four actual hosts, or you can use wildcard DNS to CNAME 35 # the wildcard to a single asset host. You can read more about setting up your DNS CNAME records from 36 # your ISP. 37 # 38 # Note: This is purely a browser performance optimization and is not meant 28 39 # for server load balancing. See http://www.die.net/musings/page_load_time/ 29 40 # for background. … … 38 49 # +url_options+. You can modify the LINK tag itself in +tag_options+. 39 50 # 40 # TagOptions:51 # ==== Options: 41 52 # * <tt>:rel</tt> - Specify the relation of this link, defaults to "alternate" 42 53 # * <tt>:type</tt> - Override the auto-generated mime type 43 54 # * <tt>:title</tt> - Specify the title of the link, defaults to the +type+ 44 55 # 56 # ==== Examples 45 57 # auto_discovery_link_tag # => 46 # <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.cur enthost.com/controller/action" />58 # <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.currenthost.com/controller/action" /> 47 59 # auto_discovery_link_tag(:atom) # => 48 # <link rel="alternate" type="application/atom+xml" title="ATOM" href="http://www.cur enthost.com/controller/action" />60 # <link rel="alternate" type="application/atom+xml" title="ATOM" href="http://www.currenthost.com/controller/action" /> 49 61 # auto_discovery_link_tag(:rss, {:action => "feed"}) # => 50 # <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.cur enthost.com/controller/feed" />62 # <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.currenthost.com/controller/feed" /> 51 63 # auto_discovery_link_tag(:rss, {:action => "feed"}, {:title => "My RSS"}) # => 52 # <link rel="alternate" type="application/rss+xml" title="My RSS" href="http://www.curenthost.com/controller/feed" /> 64 # <link rel="alternate" type="application/rss+xml" title="My RSS" href="http://www.currenthost.com/controller/feed" /> 65 # auto_discovery_link_tag(:rss, {:controller => "news", :action => "feed"}) # => 66 # <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.currenthost.com/news/feed" /> 67 # auto_discovery_link_tag(:rss, "http://www.example.com/feed.rss", {:title => "Example RSS"}) # => 68 # <link rel="alternate" type="application/rss+xml" title="Example RSS" href="http://www.example.com/feed" /> 53 69 def auto_discovery_link_tag(type = :rss, url_options = {}, tag_options = {}) 54 70 tag( … … 66 82 # Used internally by javascript_include_tag to build the script path. 67 83 # 84 # ==== Examples 68 85 # javascript_path "xmlhr" # => /javascripts/xmlhr.js 69 86 # javascript_path "dir/xmlhr.js" # => /javascripts/dir/xmlhr.js 70 87 # javascript_path "/dir/xmlhr" # => /dir/xmlhr.js 88 # javascript_path "http://www.railsapplication.com/js/xmlhr" # => http://www.railsapplication.com/js/xmlhr.js 89 # javascript_path "http://www.railsapplication.com/js/xmlhr.js" # => http://www.railsapplication.com/js/xmlhr.js 71 90 def javascript_path(source) 72 91 compute_public_path(source, 'javascripts', 'js') … … 86 105 # html attributes of the script tag by passing a hash as the last argument. 87 106 # 107 # ==== Examples 88 108 # javascript_include_tag "xmlhr" # => 109 # <script type="text/javascript" src="/javascripts/xmlhr.js"></script> 110 # 111 # javascript_include_tag "xmlhr.js" # => 89 112 # <script type="text/javascript" src="/javascripts/xmlhr.js"></script> 90 113 # … … 92 115 # <script type="text/javascript" src="/javascripts/common.javascript"></script> 93 116 # <script type="text/javascript" src="/elsewhere/cools.js"></script> 117 # 118 # javascript_include_tag "http://www.railsapplication.com/xmlhr" # => 119 # <script type="text/javascript" src="http://www.railsapplication.com/xmlhr.js"></script> 120 # 121 # javascript_include_tag "http://www.railsapplication.com/xmlhr.js" # => 122 # <script type="text/javascript" src="http://www.railsapplication.com/xmlhr.js"></script> 94 123 # 95 124 # javascript_include_tag :defaults # => … … 97 126 # <script type="text/javascript" src="/javascripts/effects.js"></script> 98 127 # ... 99 # <script type="text/javascript" src="/javascripts/application.js"></script> *see below128 # <script type="text/javascript" src="/javascripts/application.js"></script> <!-- * see below --> 100 129 # 101 130 # * = The application.js file is only referenced if it exists 102 131 # 103 # You can also include all javascripts in the javascripts directory using :all as the source: 132 # Though it's not really recommended practice, if you need to extend the default JavaScript set for any reason 133 # (e.g., you're going to be using a certain .js file in every action), then take a look at the register_javascript_include_default method. 134 # 135 # You can also include all javascripts in the javascripts directory using <tt>:all</tt> as the source: 104 136 # 105 137 # javascript_include_tag :all # => … … 111 143 # <script type="text/javascript" src="/javascripts/checkout.js"></script> 112 144 # 113 # Note that the default javascript files will be included first. So Prototype and Scriptaculous are available for114 # all subsequently included files. They145 # Note that the default javascript files will be included first. So Prototype and Scriptaculous are available to 146 # all subsequently included files. 115 147 # 116 148 # == Caching multiple javascripts into one 117 149 # 118 # You can also cache multiple javascripts into one file, which requires less HTTP connections and can better be150 # You can also cache multiple javascripts into one file, which requires less HTTP connections to download and can better be 119 151 # compressed by gzip (leading to faster transfers). Caching will only happen if ActionController::Base.perform_caching 120 # is set to true (which is the case by default for the Rails production environment, but not for the development 121 # environment). Examples: 122 # 152 # is set to <tt>true</tt> (which is the case by default for the Rails production environment, but not for the development 153 # environment). 154 # 155 # ==== Examples 123 156 # javascript_include_tag :all, :cache => true # when ActionController::Base.perform_caching is false => 124 157 # <script type="text/javascript" src="/javascripts/prototype.js"></script> … … 169 202 # Register one or more additional JavaScript files to be included when 170 203 # <tt>javascript_include_tag :defaults</tt> is called. This method is 171 # only intended to be called from plugin initialization to register additional204 # typically intended to be called from plugin initialization to register additional 172 205 # .js files that the plugin installed in <tt>public/javascripts</tt>. 173 206 def self.register_javascript_include_default(*sources) … … 184 217 # Used internally by stylesheet_link_tag to build the stylesheet path. 185 218 # 219 # ==== Examples 186 220 # stylesheet_path "style" # => /stylesheets/style.css 187 221 # stylesheet_path "dir/style.css" # => /stylesheets/dir/style.css 188 222 # stylesheet_path "/dir/style.css" # => /dir/style.css 223 # stylesheet_path "http://www.railsapplication.com/css/style" # => http://www.railsapplication.com/css/style.css 224 # stylesheet_path "http://www.railsapplication.com/css/style.js" # => http://www.railsapplication.com/css/style.css 189 225 def stylesheet_path(source) 190 226 compute_public_path(source, 'stylesheets', 'css') … … 195 231 # You can modify the link attributes by passing a hash as the last argument. 196 232 # 233 # ==== Examples 197 234 # stylesheet_link_tag "style" # => 198 235 # <link href="/stylesheets/style.css" media="screen" rel="Stylesheet" type="text/css" /> 199 236 # 237 # stylesheet_link_tag "style.css" # => 238 # <link href="/stylesheets/style.css" media="screen" rel="Stylesheet" type="text/css" /> 239 # 240 # stylesheet_link_tag "http://www.railsapplication.com/style.css" # => 241 # <link href="http://www.railsapplication.com/style.css" media="screen" rel="Stylesheet" type="text/css" /> 242 # 200 243 # stylesheet_link_tag "style", :media => "all" # => 201 244 # <link href="/stylesheets/style.css" media="all" rel="Stylesheet" type="text/css" /> 245 # 246 # stylesheet_link_tag "style", :media => "print" # => 247 # <link href="/stylesheets/style.css" media="print" rel="Stylesheet" type="text/css" /> 202 248 # 203 249 # stylesheet_link_tag "random.styles", "/css/stylish" # => … … 219 265 # environment). Examples: 220 266 # 267 # ==== Examples 221 268 # stylesheet_link_tag :all, :cache => true # when ActionController::Base.perform_caching is false => 222 269 # <link href="/stylesheets/style1.css" media="screen" rel="Stylesheet" type="text/css" /> … … 272 319 # a filename without an extension is deprecated. 273 320 # 321 # ==== Examples 274 322 # image_path("edit.png") # => /images/edit.png 275 323 # image_path("icons/edit.png") # => /images/icons/edit.png 276 324 # image_path("/icons/edit.png") # => /icons/edit.png 325 # image_path("http://www.railsapplication.com/img/edit.png") # => http://www.railsapplication.com/img/edit.png 277 326 def image_path(source) 278 327 unless (source.split("/").last || source).include?(".") || source.blank? … … 290 339 # path or a file that exists in your public images directory. Note that 291 340 # specifying a filename without the extension is now deprecated in Rails. 292 # You can add html attributes using the +options+. The +options+ supports 341 # 342 # ==== Options 343 # You can add HTML attributes using the +options+. The +options+ supports 293 344 # two additional keys for convienence and conformance: 294 345 # … … 299 350 # value is not in the correct format. 300 351 # 352 # ==== Examples 301 353 # image_tag("icon.png") # => 302 354 # <img src="/images/icon.png" alt="Icon" /> … … 305 357 # image_tag("/icons/icon.gif", :size => "16x16") # => 306 358 # <img src="/icons/icon.gif" width="16" height="16" alt="Icon" /> 359 # image_tag("/icons/icon.gif", :height => '32', :width => '32') # => 360 # <img alt="Icon" height="32" src="/icons/icon.gif" width="32" /> 361 # image_tag("/icons/icon.gif", :class => "menu_icon") # => 362 # <img alt="Icon" class="menu_icon" src="/icons/icon.gif" /> 307 363 def image_tag(source, options = {}) 308 364 options.symbolize_keys! trunk/actionpack/lib/action_view/helpers/benchmark_helper.rb
r1719 r7106 3 3 module ActionView 4 4 module Helpers 5 # This helper offers a method to measure the execution time of a block 6 # in a template. 5 7 module BenchmarkHelper 6 # Measures the execution time of a block in a template and reports the result to the log. Example: 8 # Allows you to measure the execution time of a block 9 # in a template and records the result to the log. Wrap this block around 10 # expensive operations or possible bottlenecks to get a time reading 11 # for the operation. For example, let's say you thought your file 12 # processing method was taking too long; you could wrap it in a benchmark block. 7 13 # 8 # <% benchmark " Notes section" do %>9 # <%= expensive_ notes_operation %>14 # <% benchmark "Process data files" do %> 15 # <%= expensive_files_operation %> 10 16 # <% end %> 11 17 # 12 # Will add something like "Notes section (0.34523)" to the log. 18 # That would add something like "Process data files (0.34523)" to the log, 19 # which you can then use to compare timings when optimizing your code. 13 20 # 14 21 # You may give an optional logger level as the second argument 15 # (:debug, :info, :warn, :error) . The defaultis :info.22 # (:debug, :info, :warn, :error); the default value is :info. 16 23 def benchmark(message = "Benchmarking", level = :info) 17 24 if @logger trunk/actionpack/lib/action_view/helpers/cache_helper.rb
r473 r7106 1 1 module ActionView 2 2 module Helpers 3 # This helper to exposes a method for caching of view fragments. 3 4 # See ActionController::Caching::Fragments for usage instructions. 4 5 module CacheHelper 6 # A method for caching fragments of a view rather than an entire 7 # action or page. This technique is useful caching pieces like 8 # menus, lists of news topics, static HTML fragments, and so on. 9 # This method takes a block that contains the content you wish 10 # to cache. See ActionController::Caching::Fragments for more 11 # information. 12 # 13 # ==== Examples 14 # If you wanted to cache a navigation menu, you could do the 15 # following. 16 # 17 # <% cache do %> 18 # <%= render :partial => "menu" %> 19 # <% end %> 20 # 21 # You can also cache static content... 22 # 23 # <% cache do %> 24 # <p>Hello users! Welcome to our website!</p> 25 # <% end %> 26 # 27 # ...and static content mixed with RHTML content. 28 # 29 # <% cache do %> 30 # Topics: 31 # <%= render :partial => "topics", :collection => @topic_list %> 32 # <i>Topics listed alphabetically</i> 33 # <% end %> 5 34 def cache(name = {}, &block) 6 35 @controller.cache_erb_fragment(block, name) trunk/actionpack/lib/action_view/helpers/capture_helper.rb
r6178 r7106 1 1 module ActionView 2 2 module Helpers 3 # Capture lets you extract parts of code which 4 # can be used in other points of the template or even layout file. 5 # 6 # == Capturing a block into an instance variable 7 # 8 # <% @script = capture do %> 9 # [some html...] 10 # <% end %> 11 # 12 # == Add javascript to header using content_for 13 # 14 # content_for("name") is a wrapper for capture which will 15 # make the fragment available by name to a yielding layout or template. 16 # 17 # layout.erb: 18 # 19 # <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> 20 # <head> 21 # <title>layout with js</title> 22 # <script type="text/javascript"> 23 # <%= yield :script %> 24 # </script> 25 # </head> 26 # <body> 27 # <%= yield %> 28 # </body> 29 # </html> 30 # 31 # view.erb 32 # 33 # This page shows an alert box! 34 # 35 # <% content_for("script") do %> 36 # alert('hello world') 37 # <% end %> 38 # 39 # Normal view text 3 # CaptureHelper exposes methods to let you extract generated markup which 4 # can be used in other parts of a template or layout file. 5 # It provides a method to capture blocks into variables through capture and 6 # a way to capture a block of code for use in a layout through content_for. 40 7 module CaptureHelper 41 # Capture allows you to extract a part of the template into an 42 # instance variable. You can use this instance variable anywhere 43 # in your templates and even in your layout. 8 # The capture method allows you to extract a part of the template into a 9 # variable. You can then use this value anywhere in your templates or layout. 44 10 # 45 # Example of capture being used in a .erb page: 11 # ==== Examples 12 # The capture method can be used in RHTML (ERb) templates... 46 13 # 47 14 # <% @greeting = capture do %> 48 # Welcome To my shiny new web page! 15 # Welcome to my shiny new web page! The date and time is 16 # <%= Time.now %> 49 17 # <% end %> 50 18 # 51 # Example of capture being used in a .builder page:19 # ...and Builder (RXML) templates. 52 20 # 53 # @ greeting= capture do54 # 'Welcome To my shiny new web page!'21 # @timestamp = capture do 22 # "The current timestamp is #{Time.now}." 55 23 # end 24 # 25 # You can then use the content as a variable anywhere else. For 26 # example: 27 # 28 # <html> 29 # <head><title><%= @greeting %></title></head> 30 # <body> 31 # <b><%= @greeting %></b> 32 # </body></html> 33 # 56 34 def capture(*args, &block) 57 35 # execute the block … … 69 47 end 70 48 71 # Calling content_for stores the block of markup for later use.72 # Subsequently, you can make calls to it by name with <tt>yield</tt>73 # in another template or in the layout.49 # Calling content_for stores the block of markup in an identifier for later use. 50 # You can make subsequent calls to the stored content in another template or in the layout 51 # by calling it by name with <tt>yield</tt>. 74 52 # 75 # Example:53 # ==== Examples 76 54 # 77 # <% content_for(" header") do %>78 # alert(' hello world')55 # <% content_for("authorized") do %> 56 # alert('You are not authorized for that!') 79 57 # <% end %> 80 58 # 81 # You can use yield :headeranywhere in your templates.59 # You can then use <tt>yield :authorized</tt> anywhere in your templates. 82 60 # 83 # <%= yield :header %> 61 # <%= yield :authorized if current_user == nil %> 62 # 63 # You can also use these variables in a layout. For example: 64 # 65 # <!-- This is the layout --> 66 # <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> 67 # <head> 68 # <title>My Website</title> 69 # <%= yield :script %> 70 # </head> 71 # <body> 72 # <%= yield %> 73 # </body> 74 # </html> 75 # 76 # And now we'll create a view that has a content_for call that 77 # creates the <tt>script</tt> identifier. 78 # 79 # <!-- This is our view --> 80 # Please login! 81 # 82 # <% content_for("script") do %> 83 # <script type="text/javascript">alert('You are not authorized for this action!')</script> 84 # <% end %> 85 # 86 # Then in another view you may want to do something like this: 87 # 88 # <%= link_to_remote 'Logout', :action => 'logout' %> 89 # 90 # <% content_for("script") do %> 91 # <%= javascript_include_tag :defaults %> 92 # <% end %> 93 # 94 # That will include Prototype and Scriptaculous into the page; this technique 95 # is useful if you'll only be using these scripts on a few views. 84 96 # 85 97 # NOTE: Beware that content_for is ignored in caches. So you shouldn't use it trunk/actionpack/lib/action_view/helpers/date_helper.rb
r7027 r7106 38 38 # 60-89 secs # => 1 minute 39 39 # 40 # Examples: 41 # 40 # ==== Examples 42 41 # from_time = Time.now 43 # distance_of_time_in_words(from_time, from_time + 50.minutes) # => about 1 hour 44 # distance_of_time_in_words(from_time, from_time + 15.seconds) # => less than a minute 45 # distance_of_time_in_words(from_time, from_time + 15.seconds, true) # => less than 20 seconds 42 # distance_of_time_in_words(from_time, from_time + 50.minutes) # => about 1 hour 43 # distance_of_time_in_words(from_time, 50.minutes.from_now) # => about 1 hour 44 # distance_of_time_in_words(from_time, from_time + 15.seconds) # => less than a minute 45 # distance_of_time_in_words(from_time, from_time + 15.seconds, true) # => less than 20 seconds 46 # distance_of_time_in_words(from_time, 3.years.from_now) # => over 3 years 47 # distance_of_time_in_words(from_time, from_time + 60.hours) # => about 3 days 48 # distance_of_time_in_words(from_time, from_time + 45.seconds, true) # => less than a minute 49 # distance_of_time_in_words(from_time, from_time - 45.seconds, true) # => less than a minute 50 # distance_of_time_in_words(from_time, 76.seconds.from_now) # => 1 minute 51 # distance_of_time_in_words(from_time, from_time + 1.year + 3.days) # => about 1 years 52 # distance_of_time_in_words(from_time, from_time + 4.years + 15.days + 30.minutes + 5.seconds) # => over 4 years 53 # 54 # to_time = Time.now + 6.years + 19.days 55 # distance_of_time_in_words(from_time, to_time, true) # => over 6 years 56 # distance_of_time_in_words(to_time, from_time, true) # => over 6 years 57 # distance_of_time_in_words(Time.now, Time.now) # => less than a minute 46 58 # 47 59 # Note: Rails calculates one year as 365.25 days. … … 77 89 78 90 # Like distance_of_time_in_words, but where <tt>to_time</tt> is fixed to <tt>Time.now</tt>. 91 # 92 # ==== Examples 93 # time_ago_in_words(3.minutes.from_now) # => 3 minutes 94 # time_ago_in_words(Time.now - 15.hours) # => 15 hours 95 # time_ago_in_words(Time.now) # => less than a minute 96 # 97 # from_time = Time.now - 3.days - 14.minutes - 25.seconds # => 3 days 79 98 def time_ago_in_words(from_time, include_seconds = false) 80 99 distance_of_time_in_words(from_time, Time.now, include_seconds) … … 97 116 # NOTE: Discarded selects will default to 1. So if no month select is available, January will be assumed. 98 117 # 99 # Examples:100 # 118 # ==== Examples 119 # # Generates a date select that when POSTed is stored in the post variable, in the written_on attribute 101 120 # date_select("post", "written_on") 121 # 122 # # Generates a date select that when POSTed is stored in the post variable, in the written_on attribute, 123 # # with the year in the year drop down box starting at 1995. 102 124 # date_select("post", "written_on", :start_year => 1995) 125 # 126 # # Generates a date select that when POSTed is stored in the post variable, in the written_on attribute, 127 # # with the year in the year drop down box starting at 1995, numbers used for months instead of words, 128 # # and without a day select box. 103 129 # date_select("post", "written_on", :start_year => 1995, :use_month_numbers => true, 104 130 # :discard_day => true, :include_blank => true) 131 # 132 # # Generates a date select that when POSTed is stored in the post variable, in the written_on attribute 133 # # with the fields ordered as day, month, year rather than month, day, year. 105 134 # date_select("post", "written_on", :order => [:day, :month, :year]) 106 # date_select("user", "birthday", :order => [:month, :day]) 107 # 135 # 136 # # Generates a date select that when POSTed is stored in the user variable, in the birthday attribute 137 # # lacking a year field. 138 # date_select("user", "birthday", :order => [:month, :day]) 139 # 140 # # Generates a date select that when POSTed is stored in the user variable, in the birthday attribute 141 # # which is initially set to the date 3 days from the current date 108 142 # date_select("post", "written_on", :default => 3.days.from_now) 143 # 144 # # Generates a date select that when POSTed is stored in the credit_card variable, in the bill_due attribute 145 # # that will have a default day of 20. 109 146 # date_select("credit_card", "bill_due", :default => { :day => 20 }) 110 147 # … … 120 157 # time-based attribute (identified by +method+) on an object assigned to the template (identified by +object+). 121 158 # You can include the seconds with <tt>:include_seconds</tt>. 122 # Examples: 123 # 159 # 160 # ==== Examples 161 # # Creates a time select tag that, when POSTed, will be stored in the post variable in the sunrise attribute 124 162 # time_select("post", "sunrise") 163 # 164 # # Creates a time select tag that, when POSTed, will be stored in the order variable in the submitted attribute 165 # time_select("order", "submitted") 166 # 167 # # Creates a time select tag that, when POSTed, will be stored in the mail variable in the sent_at attribute 168 # time_select("mail", "sent_at") 169 # 170 # # Creates a time select tag with a seconds field that, when POSTed, will be stored in the post variables in 171 # # the sunrise attribute. 125 172 # time_select("post", "start_time", :include_seconds => true) 173 # 174 # # Creates a time select tag with a seconds field that, when POSTed, will be stored in the entry variables in 175 # # the submission_time attribute. 176 # time_select("entry", "submission_time", :include_seconds => true) 126 177 # 127 178 # The selects are prepared for multi-parameter assignment to an Active Record object. … … 136 187 # attribute (identified by +method+) on an object assigned to the template (identified by +object+). Examples: 137 188 # 189 # ==== Examples 190 # # Generates a datetime select that, when POSTed, will be stored in the post variable in the written_on attribute 138 191 # datetime_select("post", "written_on") 192 # 193 # # Generates a datetime select with a year select that starts at 1995 that, when POSTed, will be stored in the 194 # # post variable in the written_on attribute. 139 195 # datetime_select("post", "written_on", :start_year => 1995) 196 # 197 # # Generates a datetime select with a default value of 3 days from the current time that, when POSTed, will be stored in the 198 # # trip variable in the departing attribute. 199 # datetime_select("trip", "departing", :default => 3.days.from_now) 200 # 201 # # Generates a datetime select that discards the type that, when POSTed, will be stored in the post variable as the written_on 202 # # attribute. 203 # datetime_select("post", "written_on", :discard_type => true) 140 204 # 141 205 # The selects are prepared for multi-parameter assignment to an Active Record object. … … 149 213 # will be appened onto the <tt>:order</tt> passed in. You can also add <tt>:date_separator</tt> and <tt>:time_separator</tt> 150 214 # keys to the +options+ to control visual display of the elements. 151 def select_datetime(datetime = Time.now, options = {}) 215 # 216 # ==== Examples 217 # my_date_time = Time.now + 4.days 218 # 219 # # Generates a datetime select that defaults to the datetime in my_date_time (four days after today) 220 # select_datetime(my_date_time) 221 # 222 # # Generates a datetime select that defaults to today (no specified datetime) 223 # select_datetime() 224 # 225 # # Generates a datetime select that defaults to the datetime in my_date_time (four days after today) 226 # # with the fields ordered year, month, day rather then month, day, year. 227 # select_datetime(my_date_time, :order => [:year, :month, :day]) 228 # 229 # # Generates a datetime select that defaults to the datetime in my_date_time (four days after today) 230 # # with a '/' between each date field. 231 # select_datetime(my_date_time, :date_separator => '/') 232 # 233 # # Generates a datetime select that discards the type of the field and defaults to the datetime in 234 # # my_date_time (four days after today) 235 # select_datetime(my_date_time, :discard_type => true) 236 # 237 # # Generates a datetime select that defaults to the datetime in my_date_time (four days after today) 238 # # prefixed with 'payday' rather than 'date' 239 # select_datetime(my_date_time, :prefix => 'payday') 240 # 241 def select_datetime(datetime = Time.now, options = {}) 152 242 separator = options[:datetime_separator] || '' 153 243 select_date(datetime, options) + separator + select_time(datetime, options) … … 158 248 # symbols <tt>:year</tt>, <tt>:month</tt> and <tt>:day</tt> in the desired order. If you do not supply a Symbol, it 159 249 # will be appened onto the <tt>:order</tt> passed in. 250 # 251 # ==== Examples 252 # my_date = Time.today + 6.days 253 # 254 # # Generates a date select that defaults to the date in my_date (six days after today) 255 # select_date(my_date) 256 # 257 # # Generates a date select that defaults to today (no specified date) 258 # select_date() 259 # 260 # # Generates a date select that defaults to the date in my_date (six days after today) 261 # # with the fields ordered year, month, day rather then month, day, year. 262 # select_date(my_date, :order => [:year, :month, :day]) 263 # 264 # # Generates a date select that discards the type of the field and defaults to the date in 265 # # my_date (six days after today) 266 # select_datetime(my_date_time, :discard_type => true) 267 # 268 # # Generates a date select that defaults to the datetime in my_date (six days after today) 269 # # prefixed with 'payday' rather than 'date' 270 # select_datetime(my_date_time, :prefix => 'payday') 271 # 160 272 def select_date(date = Date.today, options = {}) 161 273 options[:order] ||= [] … … 170 282 171 283 # Returns a set of html select-tags (one for hour and minute) 172 # You can set <tt>:add_separator</tt> key to format the output. 284 # You can set <tt>:time_separator</tt> key to format the output, and 285 # the <tt>:include_seconds</tt> option to include an input for seconds. 286 # 287 # ==== Examples 288 # my_time = Time.now + 5.days + 7.hours + 3.minutes + 14.seconds 289 # 290 # # Generates a time select that defaults to the time in my_time 291 # select_time(my_time) 292 # 293 # # Generates a time select that defaults to the current time (no specified time) 294 # select_time() 295 # 296 # # Generates a time select that defaults to the time in my_time, 297 # # which has fields separated by ':' 298 # select_time(my_time, :time_separator => ':') 299 # 300 # # Generates a time select that defaults to the time in my_time, 301 # # that also includes an input for seconds 302 # select_time(my_time, :include_seconds => true) 303 # 304 # # Generates a time select that defaults to the time in my_time, that has fields 305 # # separated by ':' and includes an input for seconds 306 # select_time(my_time, :time_separator => ':', :include_seconds => true) 307 # 173 308 def select_time(datetime = Time.now, options = {}) 174 309 separator = options[:time_separator] || '' … … 179 314 # The <tt>second</tt> can also be substituted for a second number. 180 315 # Override the field name using the <tt>:field_name</tt> option, 'second' by default. 316 # 317 # ==== Examples 318 # my_time = Time.now + 16.minutes 319 # 320 # # Generates a select field for seconds that defaults to the seconds for the time in my_time 321 # select_second(my_time) 322 # 323 # # Generates a select field for seconds that defaults to the number given 324 # select_second(33) 325 # 326 # # Generates a select field for seconds that defaults to the seconds for the time in my_time 327 # # that is named 'interval' rather than 'second' 328 # select_second(my_time, :field_name => 'interval') 329 # 181 330 def select_second(datetime, options = {}) 182 331 val = datetime ? (datetime.kind_of?(Fixnum) ? datetime : datetime.sec) : '' … … 199 348 # The <tt>minute</tt> can also be substituted for a minute number. 200 349 # Override the field name using the <tt>:field_name</tt> option, 'minute' by default. 350 # 351 # ==== Examples 352 # my_time = Time.now + 6.hours 353 # 354 # # Generates a select field for minutes that defaults to the minutes for the time in my_time 355 # select_minute(my_time) 356 # 357 # # Generates a select field for minutes that defaults to the number given 358 # select_minute(14) 359 # 360 # # Generates a select field for minutes that defaults to the minutes for the time in my_time 361 # # that is named 'stride' rather than 'second' 362 # select_minute(my_time, :field_name => 'stride') 363 # 201 364 def select_minute(datetime, options = {}) 202 365 val = datetime ? (datetime.kind_of?(Fixnum) ? datetime : datetime.min) : '' … … 218 381 # The <tt>hour</tt> can also be substituted for a hour number. 219 382 # Override the field name using the <tt>:field_name</tt> option, 'hour' by default. 383 # 384 # ==== Examples 385 # my_time = Time.now + 6.hours 386 # 387 # # Generates a select field for minutes that defaults to the minutes for the time in my_time 388 # select_minute(my_time) 389 # 390 # # Generates a select field for minutes that defaults to the number given 391 # select_minute(14) 392 # 393 # # Generates a select field for minutes that defaults to the minutes for the time in my_time 394 # # that is named 'stride' rather than 'second' 395 # select_minute(my_time, :field_name => 'stride') 396 # 220 397 def select_hour(datetime, options = {}) 221 398 val = datetime ? (datetime.kind_of?(Fixnum) ? datetime : datetime.hour) : '' … … 237 414 # The <tt>date</tt> can also be substituted for a hour number. 238 415 # Override the field name using the <tt>:field_name</tt> option, 'day' by default. 416 # 417 # ==== Examples 418 # my_date = Time.today + 2.days 419 # 420 # # Generates a select field for days that defaults to the day for the date in my_date 421 # select_day(my_time) 422 # 423 # # Generates a select field for days that defaults to the number given 424 # select_day(5) 425 # 426 # # Generates a select field for days that defaults to the day for the date in my_date 427 # # that is named 'due' rather than 'day' 428 # select_day(my_time, :field_name => 'due') 429 # 239 430 def select_day(date, options = {}) 240 431 val = date ? (date.kind_of?(Fixnum) ? date : date.day) : '' … … 259 450 # set the <tt>:add_month_numbers</tt> key in +options+ to true. If you would prefer to show month names as abbreviations, 260 451 # set the <tt>:use_short_month</tt> key in +options+ to true. If you want to use your own month names, set the 261 # <tt>:use_month_names</tt> key in +options+ to an array of 12 month names. 262 # 263 # Examples: 264 # 265 # select_month(Date.today) # Will use keys like "January", "March" 266 # select_month(Date.today, :use_month_numbers => true) # Will use keys like "1", "3" 267 # select_month(Date.today, :add_month_numbers => true) # Will use keys like "1 - January", "3 - March" 268 # select_month(Date.today, :use_short_month => true) # Will use keys like "Jan", "Mar" 269 # select_month(Date.today, :use_month_names => %w(Januar Februar Marts ...)) # Will use keys like "Januar", "Marts" 270 # 271 # Override the field name using the <tt>:field_name</tt> option, 'month' by default. 452 # <tt>:use_month_names</tt> key in +options+ to an array of 12 month names. Override the field name using the 453 # <tt>:field_name</tt> option, 'month' by default. 454 # 455 # ==== Examples 456 # # Generates a select field for months that defaults to the current month that 457 # # will use keys like "January", "March". 458 # select_month(Date.today) 459 # 460 # # Generates a select field for months that defaults to the current month that 461 # # is named "start" rather than "month" 462 # select_month(Date.today, :field_name => 'start') 463 # 464 # # Generates a select field for months that defaults to the current month that 465 # # will use keys like "1", "3". 466 # select_month(Date.today, :use_month_numbers => true) 467 # 468 # # Generates a select field for months that defaults to the current month that 469 # # will use keys like "1 - January", "3 - March". 470 # select_month(Date.today, :add_month_numbers => true) 471 # 472 # # Generates a select field for months that defaults to the current month that 473 # # will use keys like "Jan", "Mar". 474 # select_month(Date.today, :use_short_month => true) 475 # 476 # # Generates a select field for months that defaults to the current month that 477 # # will use keys like "Januar", "Marts." 478 # select_month(Date.today, :use_month_names => %w(Januar Februar Marts ...)) 479 # 272 480 def select_month(date, options = {}) 273 481 val = date ? (date.kind_of?(Fixnum) ? date : date.month) : '' … … 299 507 # can be changed using the <tt>:start_year</tt> and <tt>:end_year</tt> keys in the +options+. Both ascending and descending year 300 508 # lists are supported by making <tt>:start_year</tt> less than or greater than <tt>:end_year</tt>. The <tt>date</tt> can also be 301 # substituted for a year given as a number. Example: 302 # 303 # select_year(Date.today, :start_year => 1992, :end_year => 2007) # ascending year values 304 # select_year(Date.today, :start_year => 2005, :end_year => 1900) # descending year values 509 # substituted for a year given as a number. Override the field name using the <tt>:field_name</tt> option, 'year' by default. 510 # 511 # ==== Examples 512 # # Generates a select field for years that defaults to the current year that 513 # # has ascending year values 514 # select_year(Date.today, :start_year => 1992, :end_year => 2007) 515 # 516 # # Generates a select field for years that defaults to the current year that 517 # # is named 'birth' rather than 'year' 518 # select_year(Date.today, :field_name => 'birth') 519 # 520 # # Generates a select field for years that defaults to the current year that 521 # # has descending year values 522 # select_year(Date.today, :start_year => 2005, :end_year => 1900) 523 # 524 # # Generates a select field for years that defaults to the year 2006 that 525 # # has ascending year values 305 526 # select_year(2006, :start_year => 2000, :end_year => 2010) 306 527 # 307 # Override the field name using the <tt>:field_name</tt> option, 'year' by default.308 528 def select_year(date, options = {}) 309 529 val = date ? (date.kind_of?(Fixnum) ? date : date.year) : '' trunk/actionpack/lib/action_view/helpers/form_tag_helper.rb
r7105 r7106 4 4 module ActionView 5 5 module Helpers 6 # Provides a number of methods for creating form tags that doesn't rely on conventions with anobject assigned to the template like7 # FormHelper does. With the FormTagHelper, you provide the names and values yourself.6 # Provides a number of methods for creating form tags that doesn't rely on an ActiveRecord object assigned to the template like 7 # FormHelper does. Instead, you provide the names and values manually. 8 8 # 9 # NOTE: The html options disabled, readonly, and multiple can all be treated as booleans. So specifying <tt>:disabled => true</tt>10 # will give <tt>disabled="disabled"</tt>.9 # NOTE: The HTML options <tt>disabled</tt>, <tt>readonly</tt>, and <tt>multiple</tt> can all be treated as booleans. So specifying 10 # <tt>:disabled => true</tt> will give <tt>disabled="disabled"</tt>. 11 11 module FormTagHelper 12 12 # Starts a form tag that points the action to an url configured with <tt>url_for_options</tt> just like 13 13 # ActionController::Base#url_for. The method for the form defaults to POST. 14 14 # 15 # Examples: 16 # * <tt>form_tag('/posts') => <form action="/posts" method="post"></tt> 17 # * <tt>form_tag('/posts/1', :method => :put) => <form action="/posts/1" method="put"></tt> 18 # * <tt>form_tag('/upload', :multipart => true) => <form action="/upload" method="post" enctype="multipart/form-data"></tt> 19 # 20 # ERb example: 21 # <% form_tag '/posts' do -%> 22 # <div><%= submit_tag 'Save' %></div> 23 # <% end -%> 24 # 25 # Will output: 26 # <form action="/posts" method="post"><div><input type="submit" name="submit" value="Save" /></div></form> 27 # 28 # Options: 15 # ==== Options 29 16 # * <tt>:multipart</tt> - If set to true, the enctype is set to "multipart/form-data". 30 17 # * <tt>:method</tt> - The method to use when submitting the form, usually either "get" or "post". 31 18 # If "put", "delete", or another verb is used, a hidden input with name _method 32 19 # is added to simulate the verb over post. 20 # * A list of parameters to feed to the URL the form will be posted to. 21 # 22 # ==== Examples 23 # form_tag('/posts') 24 # # => <form action="/posts" method="post"> 25 # 26 # form_tag('/posts/1', :method => :put) 27 # # => <form action="/posts/1" method="put"> 28 # 29 # form_tag('/upload', :multipart => true) 30 # # => <form action="/upload" method="post" enctype="multipart/form-data"> 31 # 32 # <% form_tag '/posts' do -%> 33 # <div><%= submit_tag 'Save' %></div> 34 # <% end -%> 35 # # => <form action="/posts" method="post"><div><input type="submit" name="submit" value="Save" /></div></form> 33 36 def form_tag(url_for_options = {}, options = {}, *parameters_for_url, &block) 34 37 html_options = html_options_for_form(url_for_options, options, *parameters_for_url) … … 40 43 end 41 44 42 43 45 # Creates a dropdown selection box, or if the <tt>:multiple</tt> option is set to true, a multiple 44 46 # choice selection box. 45 47 # 46 48 # Helpers::FormOptions can be used to create common select boxes such as countries, time zones, or 47 # associated records. 48 # 49 # <tt>option_tags</tt> is a string containing the option tags for the select box: 50 # # Outputs <select id="people" name="people"><option>David</option></select> 49 # associated records. <tt>option_tags</tt> is a string containing the option tags for the select box. 50 # 51 # ==== Options 52 # * <tt>:multiple</tt> - If set to true the selection will allow multiple choices. 53 # * <tt>:disabled</tt> - If set to true, the user will not be able to use this input. 54 # * Any other key creates standard HTML attributes for the tag. 55 # 56 # ==== Examples 51 57 # select_tag "people", "<option>David</option>" 52 # 53 # Options: 54 # * <tt>:multiple</tt> - If set to true the selection will allow multiple choices. 58 # # => <select id="people" name="people"><option>David</option></select> 59 # 60 # select_tag "count", "<option>1</option><option>2</option><option>3</option><option>4</option>" 61 # # => <select id="count" name="count"><option>1</option><option>2</option> 62 # # <option>3</option><option>4</option></select> 63 # 64 # select_tag "colors", "<option>Red</option><option>Green</option><option>Blue</option>", :multiple => true 65 # # => <select id="colors" multiple="multiple" name="colors"><option>Red</option> 66 # # <option>Green</option><option>Blue</option></select> 67 # 68 # select_tag "locations", "<option>Home</option><option selected="selected">Work</option><option>Out</option>" 69 # # => <select id="locations" name="locations"><option>Home</option><option selected='selected'>Work</option> 70 # # <option>Out</option></select> 71 # 72 # select_tag "access", "<option>Read</option><option>Write</option>", :multiple => true, :class => 'form_input' 73 # # => <select class="form_input" id="access" multiple="multiple" name="access"><option>Read</option> 74 # # <option>Write</option></select> 75 # 76 # select_tag "destination", "<option>NYC</option><option>Paris</option><option>Rome</option>", :disabled => true 77 # # => <select disabled="disabled" id="destination" name="destination"><option>NYC</option> 78 # # <option>Paris</option><option>Rome</option></select> 55 79 def select_tag(name, option_tags = nil, options = {}) 56 80 content_tag :select, option_tags, { "name" => name, "id" => name }.update(options.stringify_keys) 57 81 end 58 82 59 # Creates a standard text field. 60 # 61 # Options: 83 # Creates a standard text field; use these text fields to input smaller chunks of text like a username 84 # or a search query. 85 # 86 # ==== Options 62 87 # * <tt>:disabled</tt> - If set to true, the user will not be able to use this input. 63 88 # * <tt>:size</tt> - The number of visible characters that will fit in the input. 64 89 # * <tt>:maxlength</tt> - The maximum number of characters that the browser will allow the user to enter. 90 # * Any other key creates standard HTML attributes for the tag. 65 91 # 66 # A hash of standard HTML options for the tag. 92 # ==== Examples 93 # text_field_tag 'name' 94 # # => <input id="name" name="name" type="text" /> 95 # 96 # text_field_tag 'query', 'Enter your search query here' 97 # # => <input id="query" name="query" type="text" value="Enter your search query here" /> 98 # 99 # text_field_tag 'request', nil, :class => 'special_input' 100 # # => <input class="special_input" id="request" name="request" type="text" /> 101 # 102 # text_field_tag 'address', '', :size => 75 103 # # => <input id="address" name="address" size="75" type="text" value="" /> 104 # 105 # text_field_tag 'zip', nil, :maxlength => 5 106 # # => <input id="zip" maxlength="5" name="zip" type="text" /> 107 # 108 # text_field_tag 'payment_amount', '$0.00', :disabled => true 109 # # => <input disabled="disabled" id="payment_amount" name="payment_amount" type="text" value="$0.00" /> 110 # 111 # text_field_tag 'ip', '0.0.0.0', :maxlength => 15, :size => 20, :class => "ip-input" 112 # # => <input class="ip-input" id="ip" maxlength="15" name="ip" size="20" type="text" value="0.0.0.0" /> 67 113 def text_field_tag(name, value = nil, options = {}) 68 114 tag :input, { "type" => "text", "name" => name, "id" => name, "value" => value }.update(options.stringify_keys) 69 115 end 70 116 71 # Creates a hidden field. 72 # 73 # Takes the same options as text_field_tag 117 # Creates a hidden form input field used to transmit data that would be lost due to HTTP's statelessness or 118 # data that should be hidden from the user. 119 # 120 # ==== Options 121 # * Creates standard HTML attributes for the tag. 122 # 123 # ==== Examples 124 # hidden_field_tag 'tags_list' 125 # # => <input id="tags_list" name="tags_list" type="hidden" /> 126 # 127 # hidden_field_tag 'token', 'VUBJKB23UIVI1UU1VOBVI@' 128 # # => <input id="token" name="token" type="hidden" value="VUBJKB23UIVI1UU1VOBVI@" /> 129 # 130 # hidden_field_tag 'collected_input', '', :onchange => "alert('Input collected!')" 131 # # => <input id="collected_input" name="collected_input" onchange="alert('Input collected!')" 132 # # type="hidden" value="" /> 74 133 def hidden_field_tag(name, value = nil, options = {}) 75 134 text_field_tag(name, value, options.stringify_keys.update("type" => "hidden")) 76 135 end 77 136 78 # Creates a file upload field. 79 # 80 # If you are using file uploads then you will also need to set the multipart option for the form:137 # Creates a file upload field. If you are using file uploads then you will also need 138 # to set the multipart option for the form tag: 139 # 81 140 # <%= form_tag { :action => "post" }, { :multipart => true } %> 82 141 # <label for="file">File to Upload</label> <%= file_field_tag "file" %> … … 86 145 # The specified URL will then be passed a File object containing the selected file, or if the field 87 146 # was left blank, a StringIO object. 147 # 148 # ==== Options 149 # * Creates standard HTML attributes for the tag. 150 # * <tt>:disabled</tt> - If set to true, the user will not be able to use this input. 151 # 152 # ==== Examples 153 # file_field_tag 'attachment' 154 # # => <input id="attachment" name="attachment" type="file" /> 155 # 156 # file_field_tag 'avatar', :class => 'profile-input' 157 # # => <input class="profile-input" id="avatar" name="avatar" type="file" /> 158 # 159 # file_field_tag 'picture', :disabled => true 160 # # => <input disabled="disabled" id="picture" name="picture" type="file" /> 161 # 162 # file_field_tag 'resume', :value => '~/resume.doc' 163 # # => <input id="resume" name="resume" type="file" value="~/resume.doc" /> 164 # 165 # file_field_tag 'user_pic', :accept => 'image/png,image/gif,image/jpeg' 166 # # => <input accept="image/png,image/gif,image/jpeg" id="user_pic" name="user_pic" type="file" /> 167 # 168 # file_field_tag 'file', :accept => 'text/html', :class => 'upload', :value => 'index.html' 169 # # => <input accept="text/html" class="upload" id="file" name="file" type="file" value="index.html" /> 88 170 def file_field_tag(name, options = {}) 89 171 text_field_tag(name, nil, options.update("type" => "file")) 90 172 end 91 173 92 # Creates a password field. 93 # 94 # Takes the same options as text_field_tag 174 # Creates a password field, a masked text field that will hide the users input behind a mask character. 175 # 176 # ==== Options 177 # * <tt>:disabled</tt> - If set to true, the user will not be able to use this input. 178 # * <tt>:size</tt> - The number of visible characters that will fit in the input. 179 # * <tt>:maxlength</tt> - The maximum number of characters that the browser will allow the user to enter. 180 # * Any other key creates standard HTML attributes for the tag. 181 # 182 # ==== Examples 183 # password_field_tag 'pass' 184 # # => <input id="pass" name="pass" type="password" /> 185 # 186 # password_field_tag 'secret', 'Your secret here' 187 # # => <input id="secret" name="secret" type="password" value="Your secret here" /> 188 # 189 # password_field_tag 'masked', nil, :class => 'masked_input_field' 190 # # => <input class="masked_input_field" id="masked" name="masked" type="password" /> 191 # 192 # password_field_tag 'token', '', :size => 15 193 # # => <input id="token" name="token" size="15" type="password" value="" /> 194 # 195 # password_field_tag 'key', nil, :maxlength => 16 196 # # => <input id="key" maxlength="16" name="key" type="password" /> 197 # 198 # password_field_tag 'confirm_pass', nil, :disabled => true 199 # # => <input disabled="disabled" id="confirm_pass" name="confirm_pass" type="password" /> 200 # 201 # password_field_tag 'pin', '1234', :maxlength => 4, :size => 6, :class => "pin-input" 202 # # => <input class="pin-input" id="pin" maxlength="4" name="pin" size="6" type="password" value="1234" /> 95 203 def password_field_tag(name = "password", value = nil, options = {}) 96 204 text_field_tag(name, value, options.update("type" => "password")) 97 205 end 98 206 99 # Creates a text input area. 100 # 101 # Options: 102 # * <tt>:size</tt> - A string specifying the dimensions of the textarea. 103 # # Outputs <textarea name="body" id="body" cols="25" rows="10"></textarea> 104 # <%= text_area_tag "body", nil, :size => "25x10" %> 207 # Creates a text input area; use a textarea for longer text inputs such as blog posts or descriptions. 208 # 209 # ==== Options 210 # * <tt>:size</tt> - A string specifying the dimensions of the textarea using dimensions (e.g., "25x10"). 211 # * <tt>:rows</tt> - Specify the number of rows in the textarea 212 # * <tt>:cols</tt> - Specify the number of columns in the textarea 213 # * <tt>:disabled</tt> - If set to true, the user will not be able to use this input. 214 # * Any other key creates standard HTML attributes for the tag. 215 # 216 # ==== Examples 217 # text_area_tag 'post' 218 # # => <textarea id="post" name="post"></textarea> 219 # 220 # text_area_tag 'bio', @user.bio 221 # # => <textarea id="bio" name="bio">This is my biography.</textarea> 222 # 223 # text_area_tag 'body', nil, :rows => 10, :cols => 25 224 # # => <textarea cols="25" id="body" name="body" rows="10"></textarea> 225 # 226 # text_area_tag 'body', nil, :size => "25x10" 227 # # => <textarea name="body" id="body" cols="25" rows="10"></textarea> 228 # 229 # text_area_tag 'description', "Description goes here.", :disabled => true 230 # # => <textarea disabled="disabled" id="description" name="description">Description goes here.</textarea> 231 # 232 # text_area_tag 'comment', nil, :class => 'comment_input' 233 # # => <textarea class="comment_input" id="comment" name="comment"></textarea> 105 234 def text_area_tag(name, content = nil, options = {}) 106 235 options.stringify_keys! … … 113 242 end 114 243 115 # Creates a check box. 244 # Creates a check box form input tag. 245 # 246 # ==== Options 247 # * <tt>:disabled</tt> - If set to true, the user will not be able to use this input. 248 # * Any other key creates standard HTML options for the tag. 249 # 250 # ==== Examples 251 # check_box_tag 'accept' 252 # # => <input id="accept" name="accept" type="checkbox" value="1" /> 253 # 254 # check_box_tag 'rock', 'rock music' 255 # # => <input id="rock" name="rock" type="checkbox" value="rock music" /> 256 # 257 # check_box_tag 'receive_email', 'yes', true 258 # # => <input checked="checked" id="receive_email" name="receive_email" type="checkbox" value="yes" /> 259 # 260 # check_box_tag 'tos', 'yes', false, :class => 'accept_tos' 261 # # => <input class="accept_tos" id="tos" name="tos" type="checkbox" value="yes" /> 262 # 263 # check_box_tag 'eula', 'accepted', false, :disabled => true 264 # # => <input disabled="disabled" id="eula" name="eula" type="checkbox" value="accepted" /> 116 265 def check_box_tag(name, value = "1", checked = false, options = {}) 117 266 html_options = { "type" => "checkbox", "name" => name, "id" => name, "value" => value }.update(options.stringify_keys) … … 120 269 end 121 270 122 # Creates a radio button. 271 # Creates a radio button; use groups of radio buttons named the same to allow users to 272 # select from a group of options. 273 # 274 # ==== Options 275 # * <tt>:disabled</tt> - If set to true, the user will not be able to use this input. 276 # * Any other key creates standard HTML options for the tag. 277 # 278 # ==== Examples 279 # radio_button_tag 'gender', 'male' 280 # # => <input id="gender_male" name="gender" type="radio" value="male" /> 281 # 282 # radio_button_tag 'receive_updates', 'no', true 283 # # => <input checked="checked" id="receive_updates_no" name="receive_updates" type="radio" value="no" /> 284 # 285 # radio_button_tag 'time_slot', "3:00 p.m.", false, :disabled => true 286 # # => <input disabled="disabled" id="time_slot_300_pm" name="time_slot" type="radio" value="3:00 p.m." /> 287 # 288 # radio_button_tag 'color', "green", true, :class => "color_input" 289 # # => <input checked="checked" class="color_input" id="color_green" name="color" type="radio" value="green" /> 123 290 def radio_button_tag(name, value, checked = false, options = {}) 124 291 pretty_tag_value = value.to_s.gsub(/\s/, "_").gsub(/(?!-)\W/, "").downcase … … 129 296 end 130 297 131 # Creates a submit button with the text <tt>value</tt> as the caption. If options contains a pair with the key of <tt>:disable_with</tt>, 132 # then the value will be used to rename a disabled version of the submit button. 133 # 134 # Options: 135 # * <tt>:disable_with</tt> - When specified the button will be disabled when clicked and the <tt>value</tt> will be replaced with the 136 # the string provided. 137 # # Outputs <input name="commit" onclick="this.disabled=true;this.value='Saving...';this.form.submit();" type="submit" value="Send" /> 138 # <%= submit_tag 'Send', :disable_with => 'Saving...' %> 298 # Creates a submit button with the text <tt>value</tt> as the caption. 299 # 300 # ==== Options 301 # * <tt>:disabled</tt> - If set to true, the user will not be able to use this input. 302 # * <tt>:disable_with</tt> - Value of this parameter will be used as the value for a disabled version 303 # of the submit button when the form is submitted. 304 # * Any other key creates standard HTML options for the tag. 305 # 306 # ==== Examples 307 # submit_tag 308 # # => <input name="commit" type="submit" value="Save changes" /> 309 # 310 # submit_tag "Edit this article" 311 # # => <input name="commit" type="submit" value="Edit this article" /> 312 # 313 # submit_tag "Save edits", :disabled => true 314 # # => <input disabled="disabled" name="commit" type="submit" value="Save edits" /> 315 # 316 # submit_tag "Complete sale", :disable_with => "Please wait..." 317 # # => <input name="commit" onclick="this.disabled=true;this.value='Please wait...';this.form.submit();" 318 # # type="submit" value="Complete sale" /> 319 # 320 # submit_tag nil, :class => "form_submit" 321 # # => <input class="form_submit" name="commit" type="submit" /> 322 # 323 # submit_tag "Edit", :disable_width => "Editing...", :class => 'edit-button' 324 # # => <input class="edit-button" disable_width="Editing..." name="commit" type="submit" value="Edit" /> 139 325 def submit_tag(value = "Save changes", options = {}) 140 326 options.stringify_keys! … … 158 344 # 159 345 # <tt>source</tt> is passed to AssetTagHelper#image_path 346 # 347 # ==== Options 348 # * <tt>:disabled</tt> - If set to true, the user will not be able to use this input. 349 # * Any other key creates standard HTML options for the tag. 350 # 351 # ==== Examples 352 # image_submit_tag("login.png") 353 # # => <input src="/images/login.png" type="image" /> 354 # 355 # image_submit_tag("purchase.png"), :disabled => true 356 # # => <input disabled="disabled" src="/images/purchase.png" type="image" /> 357 # 358 # image_submit_tag("search.png"), :class => 'search-button' 359 # # => <input class="search-button" src="/images/search.png" type="image" /> 360 # 361 # image_submit_tag("agree.png"), :disabled => true, :class => "agree-disagree-button" 362 # # => <input class="agree-disagree-button" disabled="disabled" src="/images/agree.png" type="image" /> 160 363 def image_submit_tag(source, options = {}) 161 364 tag :input, { "type" => "image", "src" => image_path(source) }.update(options.stringify_keys) trunk/actionpack/lib/action_view/helpers/number_helper.rb
r6407 r7106 5 5 # precision, positional notation, and file size. 6 6 module NumberHelper 7 # Formats a +number+ into a US phone number . You can customize the format7 # Formats a +number+ into a US phone number (e.g., (555) 123-9876). You can customize the format 8 8 # in the +options+ hash. 9 # 10 # ==== Options 9 11 # * <tt>:area_code</tt> - Adds parentheses around the area code. 10 # * <tt>:delimiter</tt> - Specifies the delimiter to use , defaults to "-".12 # * <tt>:delimiter</tt> - Specifies the delimiter to use (defaults to "-"). 11 13 # * <tt>:extension</tt> - Specifies an extension to add to the end of the 12 # generated number 14 # generated number. 13 15 # * <tt>:country_code</tt> - Sets the country code for the phone number. 14 16 # 15 # number_to_phone(1235551234) => 123-555-1234 16 # number_to_phone(1235551234, :area_code => true) => (123) 555-1234 17 # number_to_phone(1235551234, :delimiter => " ") => 123 555 1234 18 # number_to_phone(1235551234, :area_code => true, :extension => 555) => (123) 555-1234 x 555 19 # number_to_phone(1235551234, :country_code => 1) 17 # ==== Examples 18 # number_to_phone(1235551234) # => 123-555-1234 19 # number_to_phone(1235551234, :area_code => true) # => (123) 555-1234 20 # number_to_phone(1235551234, :delimiter => " ") # => 123 555 1234 21 # number_to_phone(1235551234, :area_code => true, :extension => 555) # => (123) 555-1234 x 555 22 # number_to_phone(1235551234, :country_code => 1) # => +1-123-555-1234 23 # 24 # number_to_phone(1235551234, :country_code => 1, :extension => 1343, :delimeter => ".") 25 # => +1.123.555.1234 x 1343 20 26 def number_to_phone(number, options = {}) 21 27 number = number.to_s.strip unless number.nil? … … 41 47 end 42 48 43 # Formats a +number+ into a currency string . You can customize the format49 # Formats a +number+ into a currency string (e.g., $13.65). You can customize the format 44 50 # in the +options+ hash. 45 # * <tt>:precision</tt> - Sets the level of precision, defaults to 246 # * <tt>:unit</tt> - Sets the denomination of the currency, defaults to "$"47 # * <tt>:separator</tt> - Sets the separator between the units, defaults to "."48 # * <tt>:delimiter</tt> - Sets the thousands delimiter, defaults to ","49 51 # 50 # number_to_currency(1234567890.50) => $1,234,567,890.50 51 # number_to_currency(1234567890.506) => $1,234,567,890.51 52 # number_to_currency(1234567890.506, :precision => 3) => $1,234,567,890.506 52 # ==== Options 53 # * <tt>:precision</tt> - Sets the level of precision (defaults to 2). 54 # * <tt>:unit</tt> - Sets the denomination of the currency (defaults to "$"). 55 # * <tt>:separator</tt> - Sets the separator between the units (defaults to "."). 56 # * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults to ","). 57 # 58 # ==== Examples 59 # number_to_currency(1234567890.50) # => $1,234,567,890.50 60 # number_to_currency(1234567890.506) # => $1,234,567,890.51 61 # number_to_currency(1234567890.506, :precision => 3) # => $1,234,567,890.506 62 # 53 63 # number_to_currency(1234567890.50, :unit => "£", :separator => ",", :delimiter => "") 54 # => £1234567890,5064 # # => £1234567890,50 55 65 def number_to_currency(number, options = {}) 56 66 options = options.stringify_keys … … 68 78 end 69 79 70 # Formats a +number+ as a percentage string . You can customize the80 # Formats a +number+ as a percentage string (e.g., 65%). You can customize the 71 81 # format in the +options+ hash. 72 # * <tt>:precision</tt> - Sets the level of precision, defaults to 373 # * <tt>:separator</tt> - Sets the separator between the units, defaults to "."74 82 # 75 # number_to_percentage(100) => 100.000% 76 # number_to_percentage(100, {:precision => 0}) => 100% 77 # number_to_percentage(302.0574, {:precision => 2}) => 302.06% 83 # ==== Options 84 # * <tt>:precision</tt> - Sets the level of precision (defaults to 3). 85 # * <tt>:separator</tt> - Sets the separator between the units (defaults to "."). 86 # 87 # ==== Examples 88 # number_to_percentage(100) # => 100.000% 89 # number_to_percentage(100, :precision => 0) # => 100% 90 # 91 # number_to_percentage(302.24398923423, :precision => 5) 92 # # => 302.24399% 78 93 def number_to_percentage(number, options = {}) 79 94 options = options.stringify_keys … … 94 109 end 95 110 96 # Formats a +number+ with grouped thousands using +delimiter+ . You111 # Formats a +number+ with grouped thousands using +delimiter+ (e.g., 12,324). You 97 112 # can customize the format using optional <em>delimiter</em> and <em>separator</em> parameters. 98 # * <tt>delimiter</tt> - Sets the thousands delimiter, defaults to ","99 # * <tt>separator</tt> - Sets the separator between the units, defaults to "."100 113 # 101 # number_with_delimiter(12345678) => 12,345,678 102 # number_with_delimiter(12345678.05) => 12,345,678.05 103 # number_with_delimiter(12345678, ".") => 12.345.678 114 # ==== Options 115 # * <tt>delimiter</tt> - Sets the thousands delimiter (defaults to ","). 116 # * <tt>separator</tt> - Sets the separator between the units (defaults to "."). 117 # 118 # ==== Examples 119 # number_with_delimiter(12345678) # => 12,345,678 120 # number_with_delimiter(12345678.05) # => 12,345,678.05 121 # number_with_delimiter(12345678, ".") # => 12.345.678 122 # 123 # number_with_delimiter(98765432.98, " ", ",") 124 # # => 98 765 432,98 104 125 def number_with_delimiter(number, delimiter=",", separator=".") 105 126 begin … … 112 133 end 113 134 114 # Formats a +number+ with the specified level of +precision+ . The default135 # Formats a +number+ with the specified level of +precision+ (e.g., 112.32 has a precision of 2). The default 115 136 # level of precision is 3. 116 137 # 117 # number_with_precision(111.2345) => 111.235 118 # number_with_precision(111.2345, 2) => 111.24 138 # ==== Examples 139 # number_with_precision(111.2345) # => 111.235 140 # number_with_precision(111.2345, 2) # => 111.24 141 # number_with_precision(13, 5) # => 13.00000 142 # number_with_precision(389.32314, 0) # => 389 119 143 def number_with_precision(number, precision=3) 120 144 "%01.#{precision}f" % number … … 123 147 end 124 148 125 # Formats the bytes in +size+ into a more understandable representation. 126 # Useful for reporting file sizes to users. This method returns nil if 149 # Formats the bytes in +size+ into a more understandable representation 150 # (e.g., giving it 1500 yields 1.5 KB). This method is useful for 151 # reporting file sizes to users. This method returns nil if 127 152 # +size+ cannot be converted into a number. You can change the default 128 # precision of 1 in+precision+.153 # precision of 1 using the precision parameter +precision+. 129 154 # 130 # number_to_human_size(123) => 123 Bytes 131 # number_to_human_size(1234) => 1.2 KB 132 # number_to_human_size(12345) => 12.1 KB 133 # number_to_human_size(1234567) => 1.2 MB 134 # number_to_human_size(1234567890) => 1.1 GB 135 # number_to_human_size(1234567890123) => 1.1 TB 136 # number_to_human_size(1234567, 2) => 1.18 MB 155 # ==== Examples 156 # number_to_human_size(123) # => 123 Bytes 157 # number_to_human_size(1234) # => 1.2 KB 158 # number_to_human_size(12345) # => 12.1 KB 159 # number_to_human_size(1234567) # => 1.2 MB 160 # number_to_human_size(1234567890) # => 1.1 GB 161 # number_to_human_size(1234567890123) # => 1.1 TB 162 # number_to_human_size(1234567, 2) # => 1.18 MB 163 # number_to_human_size(483989, 0) # => 4 MB 137 164 def number_to_human_size(size, precision=1) 138 165 size = Kernel.Float(size) trunk/actionpack/lib/action_view/helpers/tag_helper.rb
r6652 r7106 4 4 module ActionView 5 5 module Helpers #:nodoc: 6 # Use thesemethods to generate HTML tags programmatically when you can't use6 # Provides methods to generate HTML tags programmatically when you can't use 7 7 # a Builder. By default, they output XHTML compliant tags. 8 8 module TagHelper … … 12 12 # compliant. Setting +open+ to true will create an open tag compatible 13 13 # with HTML 4.0 and below. Add HTML attributes by passing an attributes 14 # hash to +options+. For attributes with no value like (disabled and 15 # readonly), give it a value of true in the +options+ hash. You can use 14 # hash to +options+. 15 # 16 # ==== Options 17 # The +options+ hash is used with attributes with no value like (<tt>disabled</tt> and 18 # <tt>readonly</tt>), which you can give a value of true in the +options+ hash. You can use 16 19 # symbols or strings for the attribute names. 17 20 # 21 # ==== Examples 18 22 # tag("br") 19 # # => <br /> 23 # # => <br /> 24 # 20 25 # tag("br", nil, true) 21 # # => <br> 26 # # => <br> 27 # 22 28 # tag("input", { :type => 'text', :disabled => true }) 23 # # => <input type="text" disabled="disabled" /> 29 # # => <input type="text" disabled="disabled" /> 30 # 31 # tag("img", { :src => "open.png" }) 32 # # => <img src="open.png" /> 24 33 def tag(name, options = nil, open = false) 25 34 "<#{name}#{tag_options(options) if options}" + (open ? ">" : " />") … … 27 36 28 37 # Returns an HTML block tag of type +name+ surrounding the +content+. Add 29 # HTML attributes by passing an attributes hash to +options+. For attributes30 # with no value like (disabled and readonly), give it a value of true in31 # the +options+ hash. You can use symbols or strings for the attribute names.38 # HTML attributes by passing an attributes hash to +options+. 39 # Instead of passing the content as an argument, you can also use a block 40 # in which case, you pass your +options+ as the second parameter. 32 41 # 42 # ==== Options 43 # The +options+ hash is used with attributes with no value like (<tt>disabled</tt> and 44 # <tt>readonly</tt>), which you can give a value of true in the +options+ hash. You can use 45 # symbols or strings for the attribute names. 46 # 47 # ==== Examples 33 48 # content_tag(:p, "Hello world!") 34 49 # # => <p>Hello world!</p> … … 37 52 # content_tag("select", options, :multiple => true) 38 53 # # => <select multiple="multiple">...options...</select> 39 #40 # Instead of passing the content as an argument, you can also use a block41 # in which case, you pass your +options+ as the second parameter.42 54 # 43 55 # <% content_tag :div, :class => "strong" do -%> … … 62 74 # <tt><![CDATA[</tt> and end with (and may not contain) the string <tt>]]></tt>. 63 75 # 76 # ==== Examples 64 77 # cdata_section("<hello world>") 65 # # => <![CDATA[<hello world>]]> 78 # # => <![CDATA[<hello world>]]> 79 # 80 # cdata_section(File.read("hello_world.txt")) 81 # # => <![CDATA[<hello from a text file]]> 66 82 def cdata_section(content) 67 83 "<![CDATA[#{content}]]>" 68 84 end 69 85 70 # Returns the escaped+html+ without affecting existing escaped entities.86 # Returns an escaped version of +html+ without affecting existing escaped entities. 71 87 # 88 # ==== Examples 72 89 # escape_once("1 > 2 & 3") 73 # # => "1 < 2 & 3" 90 # # => "1 < 2 & 3" 91 # 92 # escape_once("<< Accept & Checkout") 93 # # => "<< Accept & Checkout" 74 94 def escape_once(html) 75 95 fix_double_escape(html_escape(html.to_s)) trunk/actionpack/lib/action_view/helpers/text_helper.rb
r6493 r7106 4 4 module ActionView 5 5 module Helpers #:nodoc: 6 # The TextHelper Module provides a set of methods for filtering, formatting7 # and transforming strings thatcan reduce the amount of inline Ruby code in6 # The TextHelper module provides a set of methods for filtering, formatting 7 # and transforming strings, which can reduce the amount of inline Ruby code in 8 8 # your views. These helper methods extend ActionView making them callable 9 # within your template files as shown in the following example which truncates 10 # the title of each post to 10 characters. 11 # 12 # <% @posts.each do |post| %> 13 # # post == 'This is my title' 14 # Title: <%= truncate(post.title, 10) %> 15 # <% end %> 16 # => Title: This is my... 9 # within your template files. 17 10 module TextHelper 18 11 # The preferred method of outputting text in your views is to use the 19 12 # <%= "text" %> eRuby syntax. The regular _puts_ and _print_ methods 20 13 # do not operate as expected in an eRuby code block. If you absolutely must 21 # output text within a code block, you can use the concat method. 22 # 23 # <% concat "hello", binding %> 24 # is equivalent to using: 25 # <%= "hello" %> 14 # output text within a non-output code block (i.e., <% %>), you can use the concat method. 15 # 16 # ==== Examples 17 # <% 18 # concat "hello", binding 19 # # is the equivalent of <%= "hello" %> 20 # 21 # if (logged_in == true): 22 # concat "Logged in!", binding 23 # else 24 # concat link_to('login', :action => login), binding 25 # end 26 # # will either display "Logged in!" or a login link 27 # %> 26 28 def concat(string, binding) 27 29 eval(ActionView::Base.erb_variable, binding) << string … … 29 31 30 32 # If +text+ is longer than +length+, +text+ will be truncated to the length of 31 # +length+ and the last three characters will be replaced with the +truncate_string+. 32 # 33 # +length+ (defaults to 30) and the last three characters will be replaced with the +truncate_string+ 34 # (defaults to "..."). 35 # 36 # ==== Examples 33 37 # truncate("Once upon a time in a world far far away", 14) 34 # => Once upon a... 38 # # => Once upon a... 39 # 40 # truncate("Once upon a time in a world far far away") 41 # # => Once upon a time in a world f... 42 # 43 # truncate("And they found that many people were sleeping better.", 25, "(clipped)") 44 # # => And they found that many (clipped) 45 # 46 # truncate("And they found that many people were sleeping better.", 15, "... (continued)") 47 # # => And they found... (continued) 35 48 def truncate(text, length = 30, truncate_string = "...") 36 49 if text.nil? then return end … … 41 54 # Highlights one or more +phrases+ everywhere in +text+ by inserting it into 42 55 # a +highlighter+ string. The highlighter can be specialized by passing +highlighter+ 43 # as a single-quoted string with \1 where the phrase is to be inserted. 44 # 56 # as a single-quoted string with \1 where the phrase is to be inserted (defaults to 57 # '<strong class="highlight">\1</strong>') 58 # 59 # ==== Examples 45 60 # highlight('You searched for: rails', 'rails') 46 61 # # => You searched for: <strong class="highlight">rails</strong> 47 62 # 63 # highlight('You searched for: ruby, rails, dhh', 'actionpack') 64 # # => You searched for: ruby, rails, dhh 65 # 48 66 # highlight('You searched for: rails', ['for', 'rails'], '<em>\1</em>') 49 67 # # => You searched <em>for</em>: <em>rails</em> 68 # 69 # highlight('You searched for: rails', 'rails', "<a href='search?q=\1'>\1</a>") 70 # # => You searched for: <a href='search?q=rails>rails</a> 50 71 def highlight(text, phrases, highlighter = '<strong class="highlight">\1</strong>') 51 72 if text.blank? || phrases.blank? … … 58 79 59 80 # Extracts an excerpt from +text+ that matches the first instance of +phrase+. 60 # The +radius+ expands the excerpt on each side of +phrase+ by the number of characters61 # defined in +radius+ . If the excerpt radius overflows the beginning or end of the +text+,81 # The +radius+ expands the excerpt on each side of the first occurance of +phrase+ by the number of characters 82 # defined in +radius+ (which defaults to 100). If the excerpt radius overflows the beginning or end of the +text+, 62 83 # then the +excerpt_string+ will be prepended/appended accordingly. If the +phrase+ 63 84 # isn't found, nil is returned. 64 85 # 86 # ==== Examples 65 87 # excerpt('This is an example', 'an', 5) 66 # => "...s is an examp..."88 # # => "...s is an examp..." 67 89 # 68 90 # excerpt('This is an example', 'is', 5) 69 # => "This is an..." 91 # # => "This is an..." 92 # 93 # excerpt('This is an example', 'is') 94 # # => "This is an example" 95 # 96 # excerpt('This next thing is an example', 'ex', 2) 97 # # => "...next t..." 98 # 99 # excerpt('This is also an example', 'an', 8, '<chop> ') 100 # # => "<chop> is also an example" 70 101 def excerpt(text, phrase, radius = 100, excerpt_string = "...") 71 102 if text.nil? || phrase.nil? then return end … … 90 121 # it will just add an 's' to the +singular+ word. 91 122 # 92 # pluralize(1, 'person') => 1 person 93 # pluralize(2, 'person') => 2 people 94 # pluralize(3, 'person', 'users') => 3 users 123 # ==== Examples 124 # pluralize(1, 'person') 125 # # => 1 person 126 # 127 # pluralize(2, 'person') 128 # # => 2 people 129 # 130 # pluralize(3, 'person', 'users') 131 # # => 3 users 132 # 133 # pluralize(0, 'person') 134 # # => 0 people 95 135 def pluralize(count, singular, plural = nil) 96 136 "#{count || 0} " + if count == 1 || count == '1' … … 106 146 107 147 # Wraps the +text+ into lines no longer than +line_width+ width. This method 108 # breaks on the first whitespace character that does not exceed +line_width+. 109 # 148 # breaks on the first whitespace character that does not exceed +line_width+ 149 # (which is 80 by default). 150 # 151 # ==== Examples 110 152 # word_wrap('Once upon a time', 4) 111 # => Once\nupon\na\ntime 153 # # => Once\nupon\na\ntime 154 # 155 # word_wrap('Once upon a time', 8) 156 # # => Once upon\na time 157 # 158 # word_wrap('Once upon a time') 159 # # => Once upon a time 160 # 161 # word_wrap('Once upon a time', 1) 162 # # => Once\nupon\na\ntime 112 163 def word_wrap(text, line_width = 80) 113 164 text.gsub(/\n/, "\n\n").gsub(/(.{1,#{line_width}})(\s+|$)/, "\\1\n").strip … … 117 168 require_library_or_gem "redcloth" unless Object.const_defined?(:RedCloth) 118 169 119 # Returns the text with all the Textile codes turned into HTML tags. 170 # Returns the text with all the Textile[http://www.textism.com/tools/textile] codes turned into HTML tags. 171 # 172 # You can learn more about Textile's syntax at its website[http://www.textism.com/tools/textile]. 120 173 # <i>This method is only available if RedCloth[http://whytheluckystiff.net/ruby/redcloth/] 121 174 # is available</i>. 175 # 176 # ==== Examples 177 # textilize("*This is Textile!* Rejoice!") 178 # # => "<p><strong>This is Textile!</strong> Rejoice!</p>" 179 # 180 # textilize("I _love_ ROR(Ruby on Rails)!") 181 # # => "<p>I <em>love</em> <acronym title="Ruby on Rails">ROR</acronym>!</p>" 182 # 183 # textilize("h2. Textile makes markup -easy- simple!") 184 # # => "<h2>Textile makes markup <del>easy</del> simple!</h2>" 185 # 186 # textilize("Visit the Rails website "here":http://www.rubyonrails.org/.) 187 # # => "<p>Visit the Rails website <a href="http://www.rubyonrails.org/">here</a>.</p>" 122 188 def textilize(text) 123 189 if text.blank? … … 132 198 # Returns the text with all the Textile codes turned into HTML tags, 133 199 # but without the bounding <p> tag that RedCloth adds. 200 # 201 # You can learn more about Textile's syntax at its website[http://www.textism.com/tools/textile]. 134 202 # <i>This method is only available if RedCloth[http://whytheluckystiff.net/ruby/redcloth/] 135 203 # is available</i>. 204 # 205 # ==== Examples 206 # textilize_without_paragraph("*This is Textile!* Rejoice!") 207 # # => "<strong>This is Textile!</strong> Rejoice!" 208 # 209 # textilize_without_paragraph("I _love_ ROR(Ruby on Rails)!") 210 # # => "I <em>love</em> <acronym title="Ruby on Rails">ROR</acronym>!" 211 # 212 # textilize_without_paragraph("h2. Textile makes markup -easy- simple!") 213 # # => "<h2>Textile makes markup <del>easy</del> simple!</h2>" 214 # 215 # textilize_without_paragraph("Visit the Rails website "here":http://www.rubyonrails.org/.) 216 # # => "Visit the Rails website <a href="http://www.rubyonrails.org/">here</a>." 136 217 def textilize_without_paragraph(text) 137 218 textiled = textilize(text) … … 150 231 # <i>This method is only available if BlueCloth[http://www.deveiate.org/projects/BlueCloth] 151 232 # is available</i>. 233 # 234 # ==== Examples 235 # markdown("We are using __Markdown__ now!") 236 # # => "<p>We are using <strong>Markdown</strong> now!</p>" 237 # 238 # markdown("We like to _write_ `code`, not just _read_ it!") 239 # # => "<p>We like to <em>write</em> <code>code</code>, not just <em>read</em> it!</p>" 240 # 241 # markdown("The [Markdown website](http://daringfireball.net/projects/markdown/) has more information.") 242 # # => "<p>The <a href="http://daringfireball.net/projects/markdown/">Markdown website</a> 243 # # has more information.</p>" 244 # 245 # markdown('') 246 # # => '<p><img src="http://rubyonrails.com/images/rails.png" alt="The ROR logo" title="Ruby on Rails" /></p>' 152 247 def markdown(text) 153 248 text.blank? ? "" : BlueCloth.new(text).to_html … … 162 257 # considered as a linebreak and a <tt><br /></tt> tag is appended. This 163 258 # method does not remove the newlines from the +text+. 259 # 260 # ==== Examples 261 # my_text = """Here is some basic text... 262 # ...with a line break.""" 263 # 264 # simple_format(my_text) 265 # # => "<p>Here is some basic text...<br />...with a line break.</p>" 266 # 267 # more_text = """We want to put a paragraph... 268 # 269 # ...right there.""" 270 # 271 # simple_format(more_text) 272 # # => "<p>We want to put a paragraph...</p><p>...right there.</p>" 164 273 def simple_format(text) 165 274 content_tag 'p', text.to_s. … … 169 278 end 170 279 171 # Turns all urls and email addresses into clickable links. The +link+ parameter172 # will limit what should be linked. You can add htmlattributes to the links using280 # Turns all URLs and e-mail addresses into clickable links. The +link+ parameter 281 # will limit what should be linked. You can add HTML attributes to the links using 173 282 # +href_options+. Options for +link+ are <tt>:all</tt> (default), 174 # <tt>:email_addresses</tt>, and <tt>:urls</tt>. 175 # 176 # auto_link("Go to http://www.rubyonrails.org and say hello to david@loudthinking.com") => 177 # Go to <a href="http://www.rubyonrails.org">http://www.rubyonrails.org</a> and 178 # say hello to <a href="mailto:david@loudthinking.com">david@loudthinking.com</a> 179 # 180 # If a block is given, each url and email address is yielded and the 181 # result is used as the link text. 182 # 183 # auto_link(post.body, :all, :target => '_blank') do |text| 283 # <tt>:email_addresses</tt>, and <tt>:urls</tt>. If a block is given, each URL and 284 # e-mail address is yielded and the result is used as the link text. 285 # 286 # ==== Examples 287 # auto_link("Go to http://www.rubyonrails.org and say hello to david@loudthinking.com") 288 # # => "Go to <a href="http://www.rubyonrails.org">http://www.rubyonrails.org</a> and 289 # # say hello to <a href="mailto:david@loudthinking.com">david@loudthinking.com</a>" 290 # 291 # auto_link("Visit http://www.loudthinking.com/ or e-mail david@loudthinking.com", :urls) 292 # # => "Visit <a href=\"http://www.loudthinking.com/\">http://www.loudthinking.com/</a> 293 # # or e-mail david@loudthinking.com" 294 # 295 # auto_link("Visit http://www.loudthinking.com/ or e-mail david@loudthinking.com", :email_addresses) 296 # # => "Visit http://www.loudthinking.com/ or e-mail <a href=\"mailto:david@loudthinking.com\">david@loudthinking.com</a>" 297 # 298 # post_body = "Welcome to my new blog at http://www.myblog.com/. Please e-mail me at me@email.com." 299 # auto_link(post_body, :all, :target => '_blank') do |text| 184 300 # truncate(text, 15) 185 301 # end 302 # # => "Welcome to my new blog at <a href=\"http://www.myblog.com/\" target=\"_blank\">http://www.m...</a>. 303 # Please e-mail me at <a href=\"mailto:me@email.com\">me@email.com</a>." 304 # 186 305 def auto_link(text, link = :all, href_options = {}, &block) 187 306 return '' if text.blank? … … 193 312 end 194 313 195 # Strips link tags from +text+ leaving just the link label. 196 # 314 # Strips all link tags from +text+ leaving just the link text. 315 # 316 # ==== Examples 197 317 # strip_links('<a href="http://www.rubyonrails.org">Ruby on Rails</a>') 198 # => Ruby on Rails 318 # # => Ruby on Rails 319 # 320 # strip_links('Please e-mail me at <a href="mailto:me@email.com">me@email.com</a>.') 321 # # => Please e-mail me at me@email.com. 322 # 323 # strip_links('Blog: <a href="http://www.myblog.com/" class="nav" target=\"_blank\">Visit</a>.') 324 # # => Blog: Visit 199 325 def strip_links(text) 200 326 text.gsub(/<a\b.*?>(.*?)<\/a>/mi, '\1') … … 205 331 206 332 # Sanitizes the +html+ by converting <form> and <script> tags into regular 207 # text, and removing all "on xxx" attributes (so that arbitrary Javascript208 # cannot be executed ). It also removes href= and src=attributes that start with333 # text, and removing all "on*" (e.g., onClick) attributes so that arbitrary Javascript 334 # cannot be executed. It also removes <tt>href</tt> and <tt>src</tt> attributes that start with 209 335 # "javascript:". You can modify what gets sanitized by defining VERBOTEN_TAGS 210 336 # and VERBOTEN_ATTRS before this Module is loaded. 211 337 # 338 # ==== Examples 212 339 # sanitize('<script> do_nasty_stuff() </script>') 213 # => <script> do_nasty_stuff() </script> 340 # # => <script> do_nasty_stuff() </script> 341 # 214 342 # sanitize('<a href="javascript: sucker();">Click here for $100</a>') 215 # => <a>Click here for $100</a> 343 # # => <a>Click here for $100</a> 344 # 345 # sanitize('<a href="#" onClick="kill_all_humans();">Click here!!!</a>') 346 # # => <a href="#">Click here!!!</a> 347 # 348 # sanitize('<img src="javascript:suckers_run_this();" />') 349 # # => <img /> 216 350 def sanitize(html) 217 351 # only do this if absolutely necessary … … 249 383 # html-scanner tokenizer and so its HTML parsing ability is limited by 250 384 # that of html-scanner. 385 # 386 # ==== Examples 387 # strip_tags("Strip <i>these</i> tags!") 388 # # => Strip these tags! 389 # 390 # strip_tags("<b>Bold</b> no more! <a href='more.html'>See more here</a>...") 391 # # => Bold no more! See more here... 392 # 393 # strip_tags("<div id='top-bar'>Welcome to my website!</div>") 394 # # => Welcome to my website! 251 395 def strip_tags(html) 252 396 return html if html.blank? … … 270 414 # Creates a Cycle object whose _to_s_ method cycles through elements of an 271 415 # array every time it is called. This can be used for example, to alternate 272 # classes for table rows: 273 # 416 # classes for table rows. You can use named cycles to allow nesting in loops. 417 # Passing a Hash as the last parameter with a <tt>:name</tt> key will create a 418 # named cycle. You can manually reset a cycle by calling reset_cycle and passing the 419 # name of the cycle. 420 # 421 # ==== Examples 422 # # Alternate CSS classes for even and odd numbers... 423 # @items = [1,2,3,4] 424 # <table> 274 425 # <% @items.each do |item| %> 275 426 # <tr class="<%= cycle("even", "odd") -%>"> … … 277 428 # </tr> 278 429 # <% end %> 279 # 280 # You can use named cycles to allow nesting in loops. Passing a Hash as 281 # the last parameter with a <tt>:name</tt> key will create a named cycle. 282 # You can manually reset a cycle by calling reset_cycle and passing the 283 # name of the cycle. 284 # 430 # </table> 431 # 432 # 433 # # Cycle CSS classes for rows, and text colors for values within each row 434 # @items = x = [{:first => 'Robert', :middle => 'Daniel', :last => 'James'}, 435 # {:first => 'Emily', :middle => 'Shannon', :maiden => 'Pike', :last => 'Hicks'}, 436 # {:first => 'June', :middle => 'Dae', :last => 'Jones'}] 285 437 # <% @items.each do |item| %> 286 438 # <tr class="<%= cycle("even", "odd", :name => "row_class") 287 439 # <td> 288 440 # <% item.values.each do |value| %> 441 # <!-- Create a named cycle "colors" --> 289 442 # <span style="color:<%= cycle("red", "green", "blue", :name => "colors") -%>"> 290 # value443 # <%= value %> 291 444 # </span> 292 445 # <% end %> … … 313 466 # Resets a cycle so that it starts from the first element the next time 314 467 # it is called. Pass in +name+ to reset a named cycle. 468 # 469 # ==== Example 470 # # Alternate CSS classes for even and odd numbers... 471 # @items = [[1,2,3,4], [5,6,3], [3,4,5,6,7,4]] 472 # <table> 473 # <% @items.each do |item| %> 474 # <tr class="<%= cycle("even", "odd") -%>"> 475 # <% item.each do |value| %> 476 # <span style="color:<%= cycle("#333", "#666", "#999", :name => "colors") -%>"> 477 # <%= value %> 478 # </span> 479 # <% end %> 480 # 481 # <% reset_cycle("colors") %> 482 # </tr> 483 # <% end %> 484 # </table> 315 485 def reset_cycle(name = "default") 316 486 cycle = get_cycle(name)