Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

Changeset 7106

Show
Ignore:
Timestamp:
06/23/07 17:49:18 (2 years ago)
Author:
david
Message:

Massive documentation update for all helpers (closes #8223, #8177, #8175, #8108, #7977, #7972, #7971, #7969) [jeremymcanally]

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • trunk/actionpack/lib/action_view/helpers/asset_tag_helper.rb

    r6354 r7106  
    55module ActionView 
    66  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.  
    1216    # 
    1317    #   ActionController::Base.asset_host = "assets.example.com" 
     
    1721    #     => <link href="http://assets.example.com/stylesheets/application.css" media="screen" rel="Stylesheet" type="text/css" /> 
    1822    # 
    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 
    2839    # for server load balancing. See http://www.die.net/musings/page_load_time/ 
    2940    # for background. 
     
    3849      # +url_options+. You can modify the LINK tag itself in +tag_options+. 
    3950      # 
    40       # Tag Options: 
     51      # ==== Options: 
    4152      # * <tt>:rel</tt>  - Specify the relation of this link, defaults to "alternate" 
    4253      # * <tt>:type</tt>  - Override the auto-generated mime type 
    4354      # * <tt>:title</tt>  - Specify the title of the link, defaults to the +type+ 
    4455      # 
     56      # ==== Examples 
    4557      #  auto_discovery_link_tag # => 
    46       #     <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.curenthost.com/controller/action" /> 
     58      #     <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.currenthost.com/controller/action" /> 
    4759      #  auto_discovery_link_tag(:atom) # => 
    48       #     <link rel="alternate" type="application/atom+xml" title="ATOM" href="http://www.curenthost.com/controller/action" /> 
     60      #     <link rel="alternate" type="application/atom+xml" title="ATOM" href="http://www.currenthost.com/controller/action" /> 
    4961      #  auto_discovery_link_tag(:rss, {:action => "feed"}) # => 
    50       #     <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.curenthost.com/controller/feed" /> 
     62      #     <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.currenthost.com/controller/feed" /> 
    5163      #  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" /> 
    5369      def auto_discovery_link_tag(type = :rss, url_options = {}, tag_options = {}) 
    5470        tag( 
     
    6682      # Used internally by javascript_include_tag to build the script path. 
    6783      # 
     84      # ==== Examples 
    6885      #   javascript_path "xmlhr" # => /javascripts/xmlhr.js 
    6986      #   javascript_path "dir/xmlhr.js" # => /javascripts/dir/xmlhr.js 
    7087      #   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 
    7190      def javascript_path(source) 
    7291        compute_public_path(source, 'javascripts', 'js') 
     
    86105      # html attributes of the script tag by passing a hash as the last argument. 
    87106      # 
     107      # ==== Examples 
    88108      #   javascript_include_tag "xmlhr" # => 
     109      #     <script type="text/javascript" src="/javascripts/xmlhr.js"></script> 
     110      # 
     111      #   javascript_include_tag "xmlhr.js" # => 
    89112      #     <script type="text/javascript" src="/javascripts/xmlhr.js"></script> 
    90113      # 
     
    92115      #     <script type="text/javascript" src="/javascripts/common.javascript"></script> 
    93116      #     <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> 
    94123      # 
    95124      #   javascript_include_tag :defaults # => 
     
    97126      #     <script type="text/javascript" src="/javascripts/effects.js"></script> 
    98127      #     ... 
    99       #     <script type="text/javascript" src="/javascripts/application.js"></script> *see below 
     128      #     <script type="text/javascript" src="/javascripts/application.js"></script> <!-- * see below --> 
    100129      # 
    101130      # * = The application.js file is only referenced if it exists 
    102131      # 
    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: 
    104136      # 
    105137      #   javascript_include_tag :all # => 
     
    111143      #     <script type="text/javascript" src="/javascripts/checkout.js"></script> 
    112144      # 
    113       # Note that the default javascript files will be included first. So Prototype and Scriptaculous are available for 
    114       # all subsequently included files. They 
     145      # Note that the default javascript files will be included first. So Prototype and Scriptaculous are available to 
     146      # all subsequently included files. 
    115147      # 
    116148      # == Caching multiple javascripts into one 
    117149      # 
    118       # You can also cache multiple javascripts into one file, which requires less HTTP connections and can better be 
     150      # You can also cache multiple javascripts into one file, which requires less HTTP connections to download and can better be 
    119151      # 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 
    123156      #   javascript_include_tag :all, :cache => true # when ActionController::Base.perform_caching is false => 
    124157      #     <script type="text/javascript" src="/javascripts/prototype.js"></script> 
     
    169202      # Register one or more additional JavaScript files to be included when 
    170203      # <tt>javascript_include_tag :defaults</tt> is called. This method is 
    171       # only intended to be called from plugin initialization to register additional 
     204      # typically intended to be called from plugin initialization to register additional 
    172205      # .js files that the plugin installed in <tt>public/javascripts</tt>. 
    173206      def self.register_javascript_include_default(*sources) 
     
    184217      # Used internally by stylesheet_link_tag to build the stylesheet path. 
    185218      # 
     219      # ==== Examples 
    186220      #   stylesheet_path "style" # => /stylesheets/style.css 
    187221      #   stylesheet_path "dir/style.css" # => /stylesheets/dir/style.css 
    188222      #   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 
    189225      def stylesheet_path(source) 
    190226        compute_public_path(source, 'stylesheets', 'css') 
     
    195231      # You can modify the link attributes by passing a hash as the last argument. 
    196232      # 
     233      # ==== Examples 
    197234      #   stylesheet_link_tag "style" # => 
    198235      #     <link href="/stylesheets/style.css" media="screen" rel="Stylesheet" type="text/css" /> 
    199236      # 
     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      # 
    200243      #   stylesheet_link_tag "style", :media => "all" # => 
    201244      #     <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" /> 
    202248      # 
    203249      #   stylesheet_link_tag "random.styles", "/css/stylish" # => 
     
    219265      # environment). Examples: 
    220266      # 
     267      # ==== Examples 
    221268      #   stylesheet_link_tag :all, :cache => true # when ActionController::Base.perform_caching is false => 
    222269      #     <link href="/stylesheets/style1.css"  media="screen" rel="Stylesheet" type="text/css" /> 
     
    272319      # a filename without an extension is deprecated. 
    273320      # 
     321      # ==== Examples 
    274322      #   image_path("edit.png")  # => /images/edit.png 
    275323      #   image_path("icons/edit.png")  # => /images/icons/edit.png 
    276324      #   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 
    277326      def image_path(source) 
    278327        unless (source.split("/").last || source).include?(".") || source.blank? 
     
    290339      # path or a file that exists in your public images directory. Note that 
    291340      # 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 
    293344      # two additional keys for convienence and conformance: 
    294345      # 
     
    299350      #   value is not in the correct format. 
    300351      # 
     352      # ==== Examples 
    301353      #  image_tag("icon.png")  # => 
    302354      #    <img src="/images/icon.png" alt="Icon" /> 
     
    305357      #  image_tag("/icons/icon.gif", :size => "16x16")  # => 
    306358      #    <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" /> 
    307363      def image_tag(source, options = {}) 
    308364        options.symbolize_keys! 
  • trunk/actionpack/lib/action_view/helpers/benchmark_helper.rb

    r1719 r7106  
    33module ActionView 
    44  module Helpers 
     5    # This helper offers a method to measure the execution time of a block  
     6    # in a template. 
    57    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. 
    713      # 
    8       #  <% benchmark "Notes section" do %> 
    9       #    <%= expensive_notes_operation %> 
     14      #  <% benchmark "Process data files" do %> 
     15      #    <%= expensive_files_operation %> 
    1016      #  <% end %> 
    1117      # 
    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. 
    1320      # 
    1421      # You may give an optional logger level as the second argument 
    15       # (:debug, :info, :warn, :error).  The default is :info. 
     22      # (:debug, :info, :warn, :error); the default value is :info. 
    1623      def benchmark(message = "Benchmarking", level = :info) 
    1724        if @logger 
  • trunk/actionpack/lib/action_view/helpers/cache_helper.rb

    r473 r7106  
    11module ActionView 
    22  module Helpers 
     3    # This helper to exposes a method for caching of view fragments. 
    34    # See ActionController::Caching::Fragments for usage instructions. 
    45    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 %> 
    534      def cache(name = {}, &block) 
    635        @controller.cache_erb_fragment(block, name) 
  • trunk/actionpack/lib/action_view/helpers/capture_helper.rb

    r6178 r7106  
    11module ActionView 
    22  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. 
    407    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.  
    4410      #  
    45       # Example of capture being used in a .erb page: 
     11      # ==== Examples 
     12      # The capture method can be used in RHTML (ERb) templates... 
    4613      #  
    4714      #   <% @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 %> 
    4917      #   <% end %> 
    5018      # 
    51       # Example of capture being used in a .builder page: 
     19      # ...and Builder (RXML) templates. 
    5220      #  
    53       #   @greeting = capture do 
    54       #     'Welcome To my shiny new web page!' 
     21      #   @timestamp = capture do 
     22      #     "The current timestamp is #{Time.now}." 
    5523      #   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      # 
    5634      def capture(*args, &block) 
    5735        # execute the block 
     
    6947      end 
    7048       
    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>. 
    7452      #  
    75       # Example: 
     53      # ==== Examples 
    7654      #  
    77       #   <% content_for("header") do %> 
    78       #     alert('hello world') 
     55      #   <% content_for("authorized") do %> 
     56      #     alert('You are not authorized for that!') 
    7957      #   <% end %> 
    8058      # 
    81       # You can use yield :header anywhere in your templates. 
     59      # You can then use <tt>yield :authorized</tt> anywhere in your templates. 
    8260      # 
    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. 
    8496      # 
    8597      # 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  
    3838      # 60-89 secs      # => 1 minute 
    3939      # 
    40       # Examples: 
    41       # 
     40      # ==== Examples 
    4241      #   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 
    4658      # 
    4759      # Note: Rails calculates one year as 365.25 days. 
     
    7789 
    7890      # 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 
    7998      def time_ago_in_words(from_time, include_seconds = false) 
    8099        distance_of_time_in_words(from_time, Time.now, include_seconds) 
     
    97116      # NOTE: Discarded selects will default to 1. So if no month select is available, January will be assumed. 
    98117      # 
    99       # Examples: 
    100       # 
     118      # ==== Examples 
     119      #   # Generates a date select that when POSTed is stored in the post variable, in the written_on attribute 
    101120      #   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. 
    102124      #   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.  
    103129      #   date_select("post", "written_on", :start_year => 1995, :use_month_numbers => true, 
    104130      #                                     :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. 
    105134      #   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 
    108142      #   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. 
    109146      #   date_select("credit_card", "bill_due", :default => { :day => 20 }) 
    110147      # 
     
    120157      # time-based attribute (identified by +method+) on an object assigned to the template (identified by +object+). 
    121158      # 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 
    124162      #   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.  
    125172      #   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) 
    126177      # 
    127178      # The selects are prepared for multi-parameter assignment to an Active Record object. 
     
    136187      # attribute (identified by +method+) on an object assigned to the template (identified by +object+). Examples: 
    137188      # 
     189      # ==== Examples 
     190      #   # Generates a datetime select that, when POSTed, will be stored in the post variable in the written_on attribute 
    138191      #   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. 
    139195      #   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) 
    140204      # 
    141205      # The selects are prepared for multi-parameter assignment to an Active Record object. 
     
    149213      # will be appened onto the <tt>:order</tt> passed in. You can also add <tt>:date_separator</tt> and <tt>:time_separator</tt> 
    150214      # 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 = {}) 
    152242        separator = options[:datetime_separator] || '' 
    153243        select_date(datetime, options) + separator + select_time(datetime, options) 
     
    158248      # symbols <tt>:year</tt>, <tt>:month</tt> and <tt>:day</tt> in the desired order. If you do not supply a Symbol, it 
    159249      # 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      # 
    160272      def select_date(date = Date.today, options = {}) 
    161273        options[:order] ||= [] 
     
    170282 
    171283      # 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      # 
    173308      def select_time(datetime = Time.now, options = {}) 
    174309        separator = options[:time_separator] || '' 
     
    179314      # The <tt>second</tt> can also be substituted for a second number. 
    180315      # 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      # 
    181330      def select_second(datetime, options = {}) 
    182331        val = datetime ? (datetime.kind_of?(Fixnum) ? datetime : datetime.sec) : '' 
     
    199348      # The <tt>minute</tt> can also be substituted for a minute number. 
    200349      # 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      # 
    201364      def select_minute(datetime, options = {}) 
    202365        val = datetime ? (datetime.kind_of?(Fixnum) ? datetime : datetime.min) : '' 
     
    218381      # The <tt>hour</tt> can also be substituted for a hour number. 
    219382      # 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      # 
    220397      def select_hour(datetime, options = {}) 
    221398        val = datetime ? (datetime.kind_of?(Fixnum) ? datetime : datetime.hour) : '' 
     
    237414      # The <tt>date</tt> can also be substituted for a hour number. 
    238415      # 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      # 
    239430      def select_day(date, options = {}) 
    240431        val = date ? (date.kind_of?(Fixnum) ? date : date.day) : '' 
     
    259450      # set the <tt>:add_month_numbers</tt> key in +options+ to true. If you would prefer to show month names as abbreviations, 
    260451      # 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      # 
    272480      def select_month(date, options = {}) 
    273481        val = date ? (date.kind_of?(Fixnum) ? date : date.month) : '' 
     
    299507      # can be changed using the <tt>:start_year</tt> and <tt>:end_year</tt> keys in the +options+. Both ascending and descending year 
    300508      # 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 
    305526      #   select_year(2006, :start_year => 2000, :end_year => 2010) 
    306527      # 
    307       # Override the field name using the <tt>:field_name</tt> option, 'year' by default. 
    308528      def select_year(date, options = {}) 
    309529        val = date ? (date.kind_of?(Fixnum) ? date : date.year) : '' 
  • trunk/actionpack/lib/action_view/helpers/form_tag_helper.rb

    r7105 r7106  
    44module ActionView 
    55  module Helpers 
    6     # Provides a number of methods for creating form tags that doesn't rely on conventions with an object assigned to the template like 
    7     # 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
    88    # 
    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>. 
    1111    module FormTagHelper 
    1212      # Starts a form tag that points the action to an url configured with <tt>url_for_options</tt> just like 
    1313      # ActionController::Base#url_for. The method for the form defaults to POST. 
    1414      # 
    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 
    2916      # * <tt>:multipart</tt> - If set to true, the enctype is set to "multipart/form-data". 
    3017      # * <tt>:method</tt>    - The method to use when submitting the form, usually either "get" or "post". 
    3118      #                         If "put", "delete", or another verb is used, a hidden input with name _method  
    3219      #                         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> 
    3336      def form_tag(url_for_options = {}, options = {}, *parameters_for_url, &block) 
    3437        html_options = html_options_for_form(url_for_options, options, *parameters_for_url) 
     
    4043      end 
    4144 
    42  
    4345      # Creates a dropdown selection box, or if the <tt>:multiple</tt> option is set to true, a multiple 
    4446      # choice selection box. 
    4547      # 
    4648      # 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 
    5157      #   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> 
    5579      def select_tag(name, option_tags = nil, options = {}) 
    5680        content_tag :select, option_tags, { "name" => name, "id" => name }.update(options.stringify_keys) 
    5781      end 
    5882 
    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 
    6287      # * <tt>:disabled</tt> - If set to true, the user will not be able to use this input. 
    6388      # * <tt>:size</tt> - The number of visible characters that will fit in the input. 
    6489      # * <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. 
    6591      #  
    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" /> 
    67113      def text_field_tag(name, value = nil, options = {}) 
    68114        tag :input, { "type" => "text", "name" => name, "id" => name, "value" => value }.update(options.stringify_keys) 
    69115      end 
    70116 
    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="" /> 
    74133      def hidden_field_tag(name, value = nil, options = {}) 
    75134        text_field_tag(name, value, options.stringify_keys.update("type" => "hidden")) 
    76135      end 
    77136 
    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      # 
    81140      #   <%= form_tag { :action => "post" }, { :multipart => true } %> 
    82141      #     <label for="file">File to Upload</label> <%= file_field_tag "file" %> 
     
    86145      # The specified URL will then be passed a File object containing the selected file, or if the field  
    87146      # 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" /> 
    88170      def file_field_tag(name, options = {}) 
    89171        text_field_tag(name, nil, options.update("type" => "file")) 
    90172      end 
    91173 
    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" /> 
    95203      def password_field_tag(name = "password", value = nil, options = {}) 
    96204        text_field_tag(name, value, options.update("type" => "password")) 
    97205      end 
    98206 
    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> 
    105234      def text_area_tag(name, content = nil, options = {}) 
    106235        options.stringify_keys! 
     
    113242      end 
    114243 
    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" /> 
    116265      def check_box_tag(name, value = "1", checked = false, options = {}) 
    117266        html_options = { "type" => "checkbox", "name" => name, "id" => name, "value" => value }.update(options.stringify_keys) 
     
    120269      end 
    121270 
    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" /> 
    123290      def radio_button_tag(name, value, checked = false, options = {}) 
    124291        pretty_tag_value = value.to_s.gsub(/\s/, "_").gsub(/(?!-)\W/, "").downcase 
     
    129296      end 
    130297 
    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" /> 
    139325      def submit_tag(value = "Save changes", options = {}) 
    140326        options.stringify_keys! 
     
    158344      # 
    159345      # <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" /> 
    160363      def image_submit_tag(source, options = {}) 
    161364        tag :input, { "type" => "image", "src" => image_path(source) }.update(options.stringify_keys) 
  • trunk/actionpack/lib/action_view/helpers/number_helper.rb

    r6407 r7106  
    55    # precision, positional notation, and file size. 
    66    module NumberHelper 
    7       # Formats a +number+ into a US phone number. You can customize the format 
     7      # Formats a +number+ into a US phone number (e.g., (555) 123-9876). You can customize the format 
    88      # in the +options+ hash. 
     9      # 
     10      # ==== Options 
    911      # * <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 "-")
    1113      # * <tt>:extension</tt>  - Specifies an extension to add to the end of the 
    12       #   generated number 
     14      #   generated number. 
    1315      # * <tt>:country_code</tt>  - Sets the country code for the phone number. 
    1416      # 
    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       
    2026      def number_to_phone(number, options = {}) 
    2127        number       = number.to_s.strip unless number.nil? 
     
    4147      end 
    4248 
    43       # Formats a +number+ into a currency string. You can customize the format 
     49      # Formats a +number+ into a currency string (e.g., $13.65). You can customize the format 
    4450      # in the +options+ hash. 
    45       # * <tt>:precision</tt>  -  Sets the level of precision, defaults to 2 
    46       # * <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 "," 
    4951      # 
    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      # 
    5363      #  number_to_currency(1234567890.50, :unit => "&pound;", :separator => ",", :delimiter => "") 
    54       #    => &pound;1234567890,50 
     64      #  # => &pound;1234567890,50 
    5565      def number_to_currency(number, options = {}) 
    5666        options   = options.stringify_keys 
     
    6878      end 
    6979 
    70       # Formats a +number+ as a percentage string. You can customize the 
     80      # Formats a +number+ as a percentage string (e.g., 65%). You can customize the 
    7181      # format in the +options+ hash. 
    72       # * <tt>:precision</tt>  - Sets the level of precision, defaults to 3 
    73       # * <tt>:separator</tt>  - Sets the separator between the units, defaults to "." 
    7482      # 
    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% 
    7893      def number_to_percentage(number, options = {}) 
    7994        options   = options.stringify_keys 
     
    94109      end 
    95110 
    96       # Formats a +number+ with grouped thousands using +delimiter+. You 
     111      # Formats a +number+ with grouped thousands using +delimiter+ (e.g., 12,324). You 
    97112      # 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 "." 
    100113      # 
    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 
    104125      def number_with_delimiter(number, delimiter=",", separator=".") 
    105126        begin 
     
    112133      end 
    113134 
    114       # Formats a +number+ with the specified level of +precision+. The default 
     135      # Formats a +number+ with the specified level of +precision+ (e.g., 112.32 has a precision of 2). The default 
    115136      # level of precision is 3. 
    116137      # 
    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 
    119143      def number_with_precision(number, precision=3) 
    120144        "%01.#{precision}f" % number 
     
    123147      end 
    124148 
    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 
    127152      # +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+. 
    129154      # 
    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 
    137164      def number_to_human_size(size, precision=1) 
    138165        size = Kernel.Float(size) 
  • trunk/actionpack/lib/action_view/helpers/tag_helper.rb

    r6652 r7106  
    44module ActionView 
    55  module Helpers #:nodoc: 
    6     # Use these methods to generate HTML tags programmatically when you can't use 
     6    # Provides methods to generate HTML tags programmatically when you can't use 
    77    # a Builder. By default, they output XHTML compliant tags. 
    88    module TagHelper 
     
    1212      # compliant. Setting +open+ to true will create an open tag compatible  
    1313      # 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 
    1619      # symbols or strings for the attribute names. 
    1720      # 
     21      # ==== Examples 
    1822      #   tag("br") 
    19       #    # => <br /> 
     23      #   # => <br /> 
     24      # 
    2025      #   tag("br", nil, true) 
    21       #    # => <br> 
     26      #   # => <br> 
     27      # 
    2228      #   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" /> 
    2433      def tag(name, options = nil, open = false) 
    2534        "<#{name}#{tag_options(options) if options}" + (open ? ">" : " />") 
     
    2736 
    2837      # Returns an HTML block tag of type +name+ surrounding the +content+. Add 
    29       # HTML attributes by passing an attributes hash to +options+. For attributes  
    30       # with no value like (disabled and readonly), give it a value of true in  
    31       # 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
    3241      # 
     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 
    3348      #   content_tag(:p, "Hello world!") 
    3449      #    # => <p>Hello world!</p> 
     
    3752      #   content_tag("select", options, :multiple => true) 
    3853      #    # => <select multiple="multiple">...options...</select> 
    39       # 
    40       # Instead of passing the content as an argument, you can also use a block 
    41       # in which case, you pass your +options+ as the second parameter. 
    4254      # 
    4355      #   <% content_tag :div, :class => "strong" do -%> 
     
    6274      # <tt><![CDATA[</tt> and end with (and may not contain) the string <tt>]]></tt>. 
    6375      # 
     76      # ==== Examples 
    6477      #   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]]> 
    6682      def cdata_section(content) 
    6783        "<![CDATA[#{content}]]>" 
    6884      end 
    6985 
    70       # Returns the escaped +html+ without affecting existing escaped entities. 
     86      # Returns an escaped version of +html+ without affecting existing escaped entities. 
    7187      # 
     88      # ==== Examples 
    7289      #   escape_once("1 > 2 &amp; 3") 
    73       #    # => "1 &lt; 2 &amp; 3" 
     90      #   # => "1 &lt; 2 &amp; 3" 
     91      # 
     92      #   escape_once("&lt;&lt; Accept & Checkout") 
     93      #   # => "&lt;&lt; Accept &amp; Checkout" 
    7494      def escape_once(html) 
    7595        fix_double_escape(html_escape(html.to_s)) 
  • trunk/actionpack/lib/action_view/helpers/text_helper.rb

    r6493 r7106  
    44module ActionView 
    55  module Helpers #:nodoc: 
    6     # The TextHelper Module provides a set of methods for filtering, formatting  
    7     # and transforming strings that can reduce the amount of inline Ruby code in  
     6    # 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  
    88    # 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. 
    1710    module TextHelper       
    1811      # The preferred method of outputting text in your views is to use the  
    1912      # <%= "text" %> eRuby syntax. The regular _puts_ and _print_ methods  
    2013      # 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      #   %> 
    2628      def concat(string, binding) 
    2729        eval(ActionView::Base.erb_variable, binding) << string 
     
    2931 
    3032      # 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 
    3337      #   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) 
    3548      def truncate(text, length = 30, truncate_string = "...") 
    3649        if text.nil? then return end 
     
    4154      # Highlights one or more +phrases+ everywhere in +text+ by inserting it into 
    4255      # 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 
    4560      #   highlight('You searched for: rails', 'rails')   
    4661      #   # => You searched for: <strong class="highlight">rails</strong> 
    4762      # 
     63      #   highlight('You searched for: ruby, rails, dhh', 'actionpack') 
     64      #   # => You searched for: ruby, rails, dhh  
     65      # 
    4866      #   highlight('You searched for: rails', ['for', 'rails'], '<em>\1</em>')   
    4967      #   # => 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> 
    5071      def highlight(text, phrases, highlighter = '<strong class="highlight">\1</strong>') 
    5172        if text.blank? || phrases.blank? 
     
    5879 
    5980      # 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 characters 
    61       # 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+, 
    6283      # then the +excerpt_string+ will be prepended/appended accordingly. If the +phrase+  
    6384      # isn't found, nil is returned. 
    6485      # 
     86      # ==== Examples 
    6587      #   excerpt('This is an example', 'an', 5)  
    66       #    => "...s is an examp..." 
     88      #   # => "...s is an examp..." 
    6789      # 
    6890      #   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" 
    70101      def excerpt(text, phrase, radius = 100, excerpt_string = "...") 
    71102        if text.nil? || phrase.nil? then return end 
     
    90121      # it will just add an 's' to the +singular+ word. 
    91122      # 
    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 
    95135      def pluralize(count, singular, plural = nil) 
    96136         "#{count || 0} " + if count == 1 || count == '1' 
     
    106146 
    107147      # 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 
    110152      #   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 
    112163      def word_wrap(text, line_width = 80) 
    113164        text.gsub(/\n/, "\n\n").gsub(/(.{1,#{line_width}})(\s+|$)/, "\\1\n").strip 
     
    117168        require_library_or_gem "redcloth" unless Object.const_defined?(:RedCloth) 
    118169 
    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]. 
    120173        # <i>This method is only available if RedCloth[http://whytheluckystiff.net/ruby/redcloth/] 
    121174        # 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>" 
    122188        def textilize(text) 
    123189          if text.blank? 
     
    132198        # Returns the text with all the Textile codes turned into HTML tags,  
    133199        # 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]. 
    134202        # <i>This method is only available if RedCloth[http://whytheluckystiff.net/ruby/redcloth/] 
    135203        # 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>." 
    136217        def textilize_without_paragraph(text) 
    137218          textiled = textilize(text) 
     
    150231        # <i>This method is only available if BlueCloth[http://www.deveiate.org/projects/BlueCloth] 
    151232        # 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('![The ROR logo](http://rubyonrails.com/images/rails.png "Ruby on Rails")') 
     246        #   # => '<p><img src="http://rubyonrails.com/images/rails.png" alt="The ROR logo" title="Ruby on Rails" /></p>'      
    152247        def markdown(text) 
    153248          text.blank? ? "" : BlueCloth.new(text).to_html 
     
    162257      # considered as a linebreak and a <tt><br /></tt> tag is appended. This 
    163258      # 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>" 
    164273      def simple_format(text) 
    165274        content_tag 'p', text.to_s. 
     
    169278      end 
    170279 
    171       # Turns all urls and email addresses into clickable links. The +link+ parameter  
    172       # will limit what should be linked. You can add html attributes to the links using 
     280      # 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 
    173282      # +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| 
    184300      #     truncate(text, 15) 
    185301      #   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      #    
    186305      def auto_link(text, link = :all, href_options = {}, &block) 
    187306        return '' if text.blank? 
     
    193312      end 
    194313 
    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 
    197317      #   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 
    199325      def strip_links(text) 
    200326        text.gsub(/<a\b.*?>(.*?)<\/a>/mi, '\1') 
     
    205331 
    206332      # Sanitizes the +html+ by converting <form> and <script> tags into regular 
    207       # text, and removing all "onxxx" attributes (so that arbitrary Javascript 
    208       # cannot be executed). It also removes href= and src= attributes that start with 
     333      # 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 
    209335      # "javascript:". You can modify what gets sanitized by defining VERBOTEN_TAGS 
    210336      # and VERBOTEN_ATTRS before this Module is loaded. 
    211337      # 
     338      # ==== Examples 
    212339      #   sanitize('<script> do_nasty_stuff() </script>') 
    213       #    => &lt;script> do_nasty_stuff() &lt;/script> 
     340      #   # => &lt;script> do_nasty_stuff() &lt;/script> 
     341      # 
    214342      #   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 /> 
    216350      def sanitize(html) 
    217351        # only do this if absolutely necessary 
     
    249383      # html-scanner tokenizer and so its HTML parsing ability is limited by  
    250384      # 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! 
    251395      def strip_tags(html)      
    252396        return html if html.blank? 
     
    270414      # Creates a Cycle object whose _to_s_ method cycles through elements of an 
    271415      # 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> 
    274425      #   <% @items.each do |item| %> 
    275426      #     <tr class="<%= cycle("even", "odd") -%>"> 
     
    277428      #     </tr> 
    278429      #   <% 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'}] 
    285437      #   <% @items.each do |item| %> 
    286438      #     <tr class="<%= cycle("even", "odd", :name => "row_class") 
    287439      #       <td> 
    288440      #         <% item.values.each do |value| %> 
     441      #           <!-- Create a named cycle "colors" --> 
    289442      #           <span style="color:<%= cycle("red", "green", "blue", :name => "colors") -%>"> 
    290       #             value 
     443      #             <%= value %> 
    291444      #           </span> 
    292445      #         <% end %> 
     
    313466      # Resets a cycle so that it starts from the first element the next time  
    314467      # 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> 
    315485      def reset_cycle(name = "default") 
    316486        cycle = get_cycle(name)