1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

AV overview guide: helper docs progress

This commit is contained in:
Trevor Turk 2009-09-09 22:12:29 -05:00
parent 05b8c82555
commit fb74a1b3dd

View file

@ -142,13 +142,13 @@ The +post+ partial wraps the post's +body+ in a +div+ with the +id+ of the post
This example would output the following:
<ruby>
<html>
<div class='box'>
<div id='post_1'>
<p>Partial Layouts are cool!</p>
</div>
</div>
</ruby>
</html>
Note that the partial layout has access to the local +post+ variable that was passed into the +render+ call. However, unlike application-wide layouts, partial layouts still have the underscore prefix.
@ -172,11 +172,13 @@ TODO...
h3. Overview of all the helpers provided by Action View
The following is only a brief overview summary of the helpers available in Action View. It's recommended that you review the API Documentation, which covers all of the helpers in more detail, but this should serve as a good starting point.
h4. Active Record Helper
The Active Record Helper makes it easier to create forms for records kept in instance variables. You may also want to review the "Rails Form helpers guide":form_helpers.html.
+error_message_on+
h5. error_message_on
Returns a string containing the error message attached to the method on the object if one exists.
@ -184,7 +186,7 @@ Returns a string containing the error message attached to the method on the obje
error_message_on "post", "title"
</ruby>
+error_messages_for+
h5. error_messages_for
Returns a string with a DIV containing all of the error messages for the objects located as instance variables by the names given.
@ -192,7 +194,7 @@ Returns a string with a DIV containing all of the error messages for the objects
error_messages_for "post"
</ruby>
+form+
h5. form
Returns a form with inputs for all attributes of the specified Active Record object. For example, let's say we have a +@post+ with attributes named +title+ of type +String+ and +body+ of type +Text+. Calling +form+ would produce a form to creating a new post with inputs for those attributes.
@ -200,7 +202,7 @@ Returns a form with inputs for all attributes of the specified Active Record obj
form("post")
</ruby>
<ruby>
<html>
<form action='/posts/create' method='post'>
<p>
<label for="post_title">Title</label><br />
@ -212,11 +214,11 @@ form("post")
</p>
<input name="commit" type="submit" value="Create" />
</form>
</ruby>
</html>
Typically, +form_for+ is used instead of +form+ because it doesn't automatically include all of the model's attributes.
+input+
h5. input
Returns a default input tag for the type of object returned by the method.
@ -238,7 +240,7 @@ ActionController::Base.asset_host = "assets.example.com"
image_tag("rails.png") # => <img src="http://assets.example.com/images/rails.png" alt="Rails" />
</ruby>
+register_javascript_expansion+
h5. register_javascript_expansion
Register one or more javascript files to be included when symbol is passed to javascript_include_tag. This method is typically intended to be called from plugin initialization to register javascript files that the plugin installed in public/javascripts.
@ -251,11 +253,11 @@ javascript_include_tag :monkey # =>
<script type="text/javascript" src="/javascripts/tail.js"></script>
</ruby>
+register_javascript_include_default+
h5. register_javascript_include_default
Register one or more additional JavaScript files to be included when +javascript_include_tag :defaults+ is called. This method is typically intended to be called from plugin initialization to register additional +.js+ files that the plugin installed in +public/javascripts+.
+register_stylesheet_expansion+
h5. register_stylesheet_expansion
Register one or more stylesheet files to be included when symbol is passed to +stylesheet_link_tag+. This method is typically intended to be called from plugin initialization to register stylesheet files that the plugin installed in +public/stylesheets+.
@ -268,7 +270,7 @@ stylesheet_link_tag :monkey # =>
<link href="/stylesheets/tail.css" media="screen" rel="stylesheet" type="text/css" />
</ruby>
+auto_discovery_link_tag+
h5. auto_discovery_link_tag
Returns a link tag that browsers and news readers can use to auto-detect an RSS or ATOM feed.
@ -277,7 +279,7 @@ auto_discovery_link_tag(:rss, "http://www.example.com/feed.rss", {:title => "RSS
<link rel="alternate" type="application/rss+xml" title="RSS Feed" href="http://www.example.com/feed" />
</ruby>
+image_path+
h5. image_path
Computes the path to an image asset in the public images directory. Full paths from the document root will be passed through. Used internally by +image_tag+ to build the image path.
@ -285,7 +287,7 @@ Computes the path to an image asset in the public images directory. Full paths f
image_path("edit.png") # => /images/edit.png
</ruby>
+image_tag+
h5. image_tag
Returns an html image tag for the source. The source can be a full path or a file that exists in your public images directory.
@ -293,7 +295,7 @@ Returns an html image tag for the source. The source can be a full path or a fil
image_tag("icon.png") # => <img src="/images/icon.png" alt="Icon" />
</ruby>
+javascript_include_tag+
h5. javascript_include_tag
Returns an html script tag for each of the sources provided. You can pass in the filename (+.js+ extension is optional) of javascript files that exist in your +public/javascripts+ directory for inclusion into the current page or you can pass the full path relative to your document root.
@ -321,7 +323,7 @@ javascript_include_tag :all, :cache => true # =>
<script type="text/javascript" src="/javascripts/all.js"></script>
</ruby>
+javascript_path+
h5. javascript_path
Computes the path to a javascript asset in the +public/javascripts+ directory. If the source filename has no extension, +.js+ will be appended. Full paths from the document root will be passed through. Used internally by +javascript_include_tag+ to build the script path.
@ -329,7 +331,7 @@ Computes the path to a javascript asset in the +public/javascripts+ directory. I
javascript_path "common" # => /javascripts/common.js
</ruby>
+stylesheet_link_tag+
h5. stylesheet_link_tag
Returns a stylesheet link tag for the sources specified as arguments. If you don't specify an extension, +.css+ will be appended automatically.
@ -351,7 +353,7 @@ stylesheet_link_tag :all, :cache => true
<link href="/stylesheets/all.css" media="screen" rel="stylesheet" type="text/css" />
</ruby>
+stylesheet_path+
h5. stylesheet_path
Computes the path to a stylesheet asset in the public stylesheets directory. If the source filename has no extension, .css will be appended. Full paths from the document root will be passed through. Used internally by stylesheet_link_tag to build the stylesheet path.
@ -361,7 +363,7 @@ stylesheet_path "application" # => /stylesheets/application.css
h4. Atom Feed Helper
+atom_feed+
h5. atom_feed
This helper makes building an ATOM feed easy. Here's a full usage example:
@ -406,7 +408,7 @@ end
h4. Benchmark Helper
+benchmark+
h5. benchmark
Allows you to measure the execution time of a block in a template and records the result to the log. Wrap this block around expensive operations or possible bottlenecks to get a time reading for the operation.
@ -420,7 +422,7 @@ This would add something like "Process data files (0.34523)" to the log, which y
h4. Cache Helper
+cache+
h5. cache
A method for caching fragments of a view rather than an entire action or page. This technique is useful caching pieces like menus, lists of news topics, static HTML fragments, and so on. This method takes a block that contains the content you wish to cache. See +ActionController::Caching::Fragments+ for more information.
@ -432,7 +434,7 @@ A method for caching fragments of a view rather than an entire action or page. T
h4. Capture Helper
+capture+
h5. capture
The +capture+ method allows you to extract part of a template into a variable. You can then use this variable anywhere in your templates or layout.
@ -455,7 +457,7 @@ The captured variable can then be used anywhere else.
</html>
</ruby>
+content_for+
h5. content_for
Calling +content_for+ stores a block of markup in an identifier for later use. You can make subsequent calls to the stored content in other templates or the layout by passing the identifier as an argument to +yield+.
@ -485,7 +487,467 @@ For example, let's say we have a standard application layout, but also a special
<% end %>
</ruby>
TODO continue at http://ap.rubyonrails.org/ on ActionView::Helpers::DateHelper
h4. Date Helper
h5. date_select
Returns a set of select tags (one for year, month, and day) pre-selected for accessing a specified date-based attribute.
<ruby>
date_select("post", "published_on")
</ruby>
h5. datetime_select
Returns a set of select tags (one for year, month, day, hour, and minute) pre-selected for accessing a specified datetime-based attribute.
<ruby>
datetime_select("post", "published_on")
</ruby>
h5. distance_of_time_in_words
Reports the approximate distance in time between two Time or Date objects or integers as seconds. Set +include_seconds+ to true if you want more detailed approximations.
<ruby>
distance_of_time_in_words(Time.now, Time.now + 15.seconds) # => less than a minute
distance_of_time_in_words(Time.now, Time.now + 15.seconds, true) # => less than 20 seconds
</ruby>
h5. select_date
Returns a set of html select-tags (one for year, month, and day) pre-selected with the +date+ provided.
<ruby>
# Generates a date select that defaults to the date provided (six days after today)
select_date(Time.today + 6.days)
# Generates a date select that defaults to today (no specified date)
select_date()
</ruby>
h5. select_datetime
Returns a set of html select-tags (one for year, month, day, hour, and minute) pre-selected with the +datetime+ provided.
<ruby>
# Generates a datetime select that defaults to the datetime provided (four days after today)
select_datetime(Time.now + 4.days)
# Generates a datetime select that defaults to today (no specified datetime)
select_datetime()
</ruby>
h5. select_day
Returns a select tag with options for each of the days 1 through 31 with the current day selected.
<ruby>
# Generates a select field for days that defaults to the day for the date provided
select_day(Time.today + 2.days)
# Generates a select field for days that defaults to the number given
select_day(5)
</ruby>
h5. select_hour
Returns a select tag with options for each of the hours 0 through 23 with the current hour selected.
<ruby>
# Generates a select field for minutes that defaults to the minutes for the time provided
select_minute(Time.now + 6.hours)
</ruby>
h5. select_minute
Returns a select tag with options for each of the minutes 0 through 59 with the current minute selected.
<ruby>
# Generates a select field for minutes that defaults to the minutes for the time provided.
select_minute(Time.now + 6.hours)
</ruby>
h5. select_month
Returns a select tag with options for each of the months January through December with the current month selected.
<ruby>
# Generates a select field for months that defaults to the current month
select_month(Date.today)
</ruby>
h5. select_second
Returns a select tag with options for each of the seconds 0 through 59 with the current second selected.
<ruby>
# Generates a select field for seconds that defaults to the seconds for the time provided
select_second(Time.now + 16.minutes)
</ruby>
h5. select_time
Returns a set of html select-tags (one for hour and minute).
<ruby>
# Generates a time select that defaults to the time provided
select_time(Time.now)
</ruby>
h5. select_year
Returns a select tag with options for each of the five years on each side of the current, which is selected. The five year radius can be changed using the +:start_year+ and +:end_year+ keys in the +options+.
<ruby>
# Generates a select field for five years on either side of +Date.today+ that defaults to the current year
select_year(Date.today)
# Generates a select field from 1900 to 2009 that defaults to the current year
select_year(Date.today, :start_year => 1900, :end_year => 2009)
</ruby>
h5. time_ago_in_words
Like +distance_of_time_in_words+, but where +to_time+ is fixed to +Time.now+.
<ruby>
time_ago_in_words(3.minutes.from_now) # => 3 minutes
</ruby>
h5. time_select
Returns a set of select tags (one for hour, minute and optionally second) pre-selected for accessing a specified time-based attribute. The selects are prepared for multi-parameter assignment to an Active Record object.
<ruby>
# Creates a time select tag that, when POSTed, will be stored in the order variable in the submitted attribute
time_select("order", "submitted")
</ruby>
h4. Debug Helper
Returns a +pre+ tag that has object dumped by YAML. This creates a very readable way to inspect an object.
<ruby>
my_hash = {'first' => 1, 'second' => 'two', 'third' => [1,2,3]}
debug(my_hash)
</ruby>
<html>
<pre class='debug_dump'>---
first: 1
second: two
third:
- 1
- 2
- 3
</pre>
</html>
h4. Form Helper
Form helpers are designed to make working with models much easier compared to using just standard HTML elements by providing a set of methods for creating forms based on your models. This helper generates the HTML for forms, providing a method for each sort of input (e.g., text, password, select, and so on). When the form is submitted (i.e., when the user hits the submit button or form.submit is called via JavaScript), the form inputs will be bundled into the params object and passed back to the controller.
There are two types of form helpers: those that specifically work with model attributes and those that don't. This helper deals with those that work with model attributes; to see an example of form helpers that dont work with model attributes, check the ActionView::Helpers::FormTagHelper documentation.
The core method of this helper, form_for, gives you the ability to create a form for a model instance; for example, let's say that you have a model Person and want to create a new instance of it:
<ruby>
# Note: a @person variable will have been created in the controller (e.g. @person = Person.new)
<% form_for :person, @person, :url => { :action => "create" } do |f| %>
<%= f.text_field :first_name %>
<%= f.text_field :last_name %>
<%= submit_tag 'Create' %>
<% end %>
</ruby>
The HTML generated for this would be:
<html>
<form action="/persons/create" method="post">
<input id="person_first_name" name="person[first_name]" size="30" type="text" />
<input id="person_last_name" name="person[last_name]" size="30" type="text" />
<input name="commit" type="submit" value="Create" />
</form>
</html>
The params object created when this form is submitted would look like:
<ruby>
{"action"=>"create", "controller"=>"persons", "person"=>{"first_name"=>"William", "last_name"=>"Smith"}}
</ruby>
The params hash has a nested person value, which can therefore be accessed with params[:person] in the controller.
h5. check_box
Returns a checkbox tag tailored for accessing a specified attribute.
<ruby>
# Let's say that @post.validated? is 1:
check_box("post", "validated")
# => <input type="checkbox" id="post_validated" name="post[validated]" value="1" />
# <input name="post[validated]" type="hidden" value="0" />
</ruby>
h5. fields_for
Creates a scope around a specific model object like form_for, but doesnt create the form tags themselves. This makes fields_for suitable for specifying additional model objects in the same form:
<ruby>
<% form_for @person, :url => { :action => "update" } do |person_form| %>
First name: <%= person_form.text_field :first_name %>
Last name : <%= person_form.text_field :last_name %>
<% fields_for @person.permission do |permission_fields| %>
Admin? : <%= permission_fields.check_box :admin %>
<% end %>
<% end %>
</ruby>
h5. file_field
Returns an file upload input tag tailored for accessing a specified attribute.
<ruby>
file_field(:user, :avatar)
# => <input type="file" id="user_avatar" name="user[avatar]" />
</ruby>
h5. form_for
Creates a form and a scope around a specific model object that is used as a base for questioning about values for the fields.
<ruby>
<% form_for @post do |f| %>
<%= f.label :title, 'Title' %>:
<%= f.text_field :title %><br />
<%= f.label :body, 'Body' %>:
<%= f.text_area :body %><br />
<% end %>
</ruby>
h5. hidden_field
Returns a hidden input tag tailored for accessing a specified attribute.
<ruby>
hidden_field(:user, :token)
# => <input type="hidden" id="user_token" name="user[token]" value="#{@user.token}" />
</ruby>
h5. label
Returns a label tag tailored for labelling an input field for a specified attribute.
<ruby>
label(:post, :title)
# => <label for="post_title">Title</label>
</ruby>
h5. password_field
Returns an input tag of the "password" type tailored for accessing a specified attribute.
<ruby>
password_field(:login, :pass)
# => <input type="text" id="login_pass" name="login[pass]" value="#{@login.pass}" />
</ruby>
h5. radio_button
Returns a radio button tag for accessing a specified attribute.
<ruby>
# Let's say that @post.category returns "rails":
radio_button("post", "category", "rails")
radio_button("post", "category", "java")
# => <input type="radio" id="post_category_rails" name="post[category]" value="rails" checked="checked" />
# <input type="radio" id="post_category_java" name="post[category]" value="java" />
</ruby>
h5. text_area
Returns a textarea opening and closing tag set tailored for accessing a specified attribute.
<ruby>
text_area(:comment, :text, :size => "20x30")
# => <textarea cols="20" rows="30" id="comment_text" name="comment[text]">
# #{@comment.text}
# </textarea>
</ruby>
h5. text_field
Returns an input tag of the "text" type tailored for accessing a specified attribute.
<ruby>
text_field(:post, :title)
# => <input type="text" id="post_title" name="post[title]" value="#{@post.title}" />
</ruby>
h4. Form Options Helper
Provides a number of methods for turning different kinds of containers into a set of option tags.
h5. collection_select
Returns +select+ and +option+ tags for the collection of existing return values of +method+ for +object+'s class.
Example object structure for use with this method:
<ruby>
class Post < ActiveRecord::Base
belongs_to :author
end
class Author < ActiveRecord::Base
has_many :posts
def name_with_initial
"#{first_name.first}. #{last_name}"
end
end
</ruby>
Sample usage (selecting the associated Author for an instance of Post, +@post+):
<ruby>
collection_select(:post, :author_id, Author.find(:all), :id, :name_with_initial, {:prompt => true})
</ruby>
If @post.author_id is already 1, this would return:
<html>
<select name="post[author_id]">
<option value="">Please select</option>
<option value="1" selected="selected">D. Heinemeier Hansson</option>
<option value="2">D. Thomas</option>
<option value="3">M. Clark</option>
</select>
</html>
h5. country_options_for_select
Returns a string of option tags for pretty much any country in the world.
h5. country_select
Return select and option tags for the given object and method, using country_options_for_select to generate the list of option tags.
h5. option_groups_from_collection_for_select
Returns a string of +option+ tags, like +options_from_collection_for_select+, but groups them by +optgroup+ tags based on the object relationships of the arguments.
Example object structure for use with this method:
<ruby>
class Continent < ActiveRecord::Base
has_many :countries
# attribs: id, name
end
class Country < ActiveRecord::Base
belongs_to :continent
# attribs: id, name, continent_id
end
</ruby>
Sample usage:
<ruby>
option_groups_from_collection_for_select(@continents, :countries, :name, :id, :name, 3)
</ruby>
TODO check above textile output looks right
Possible output:
<html>
<optgroup label="Africa">
<option value="1">Egypt</option>
<option value="4">Rwanda</option>
...
</optgroup>
<optgroup label="Asia">
<option value="3" selected="selected">China</option>
<option value="12">India</option>
<option value="5">Japan</option>
...
</optgroup>
</html>
Note: Only the +optgroup+ and +option+ tags are returned, so you still have to wrap the output in an appropriate +select+ tag.
h5. options_for_select
Accepts a container (hash, array, enumerable, your type) and returns a string of option tags.
<ruby>
options_for_select([ "VISA", "MasterCard" ])
# => <option>VISA</option> <option>MasterCard</option>
</ruby>
Note: Only the +option+ tags are returned, you have to wrap this call in a regular HTML +select+ tag.
h5. options_from_collection_for_select
Returns a string of option tags that have been compiled by iterating over the +collection+ and assigning the the result of a call to the +value_method+ as the option value and the +text_method+ as the option text.
<ruby>
# options_from_collection_for_select(collection, value_method, text_method, selected = nil)
</ruby>
For example, imagine a loop iterating over each person in @project.people to generate an input tag:
<ruby>
options_from_collection_for_select(@project.people, "id", "name")
# => <option value="#{person.id}">#{person.name}</option>
</ruby>
Note: Only the +option+ tags are returned, you have to wrap this call in a regular HTML +select+ tag.
h5. select
Create a select tag and a series of contained option tags for the provided object and method.
Example with @post.person_id => 1:
<ruby>
select("post", "person_id", Person.find(:all).collect {|p| [ p.name, p.id ] }, { :include_blank => true })
</ruby>
could become:
<html>
<select name="post[person_id]">
<option value=""></option>
<option value="1" selected="selected">David</option>
<option value="2">Sam</option>
<option value="3">Tobias</option>
</select>
</html>
h5. time_zone_options_for_select
Returns a string of option tags for pretty much any time zone in the world.
h5. time_zone_select
Return select and option tags for the given object and method, using +time_zone_options_for_select+ to generate the list of option tags.
<ruby>
time_zone_select( "user", "time_zone")
</ruby>
TODO continue from FormTagHelper
h3. Localized Views