diff options
Diffstat (limited to 'railties/guides/source/action_view_overview.textile')
-rw-r--r-- | railties/guides/source/action_view_overview.textile | 143 |
1 files changed, 69 insertions, 74 deletions
diff --git a/railties/guides/source/action_view_overview.textile b/railties/guides/source/action_view_overview.textile index 8b5eda0973..cfd71ad287 100644 --- a/railties/guides/source/action_view_overview.textile +++ b/railties/guides/source/action_view_overview.textile @@ -12,9 +12,9 @@ endprologue. h3. What is Action View? -Action View and Action Controller are the two major components of Action Pack. In Rails, web requests are handled by Action Pack, which splits the work into a controller part (performing the logic) and a view part (rendering a template). Typically, Action Controller will be concerned with communicating with the database and performing CRUD actions where necessary. Action View is then responsible for compiling the response. +Action View and Action Controller are the two major components of Action Pack. In Rails, web requests are handled by Action Pack, which splits the work into a controller part (performing the logic) and a view part (rendering a template). Typically, Action Controller will be concerned with communicating with the database and performing CRUD actions where necessary. Action View is then responsible for compiling the response. -Action View templates are written using embedded Ruby in tags mingled with HTML. To avoid cluttering the templates with boilerplate code, a number of helper classes provide common behavior for forms, dates, and strings. It's also easy to add new helpers to your application as it evolves. +Action View templates are written using embedded Ruby in tags mingled with HTML. To avoid cluttering the templates with boilerplate code, a number of helper classes provide common behavior for forms, dates, and strings. It's also easy to add new helpers to your application as it evolves. Note: Some features of Action View are tied to Active Record, but that doesn't mean that Action View depends on Active Record. Action View is an independent package that can be used with any sort of backend. @@ -24,13 +24,13 @@ TODO... h3. Using Action View outside of Rails -Action View works well with Action Record, but it can also be used with other Ruby tools. We can demonstrate this by creating a small "Rack":http://rack.rubyforge.org/ application that includes Action View functionality. This may be useful, for example, if you'd like access to Action View's helpers in a Rack application. +Action View works well with Action Record, but it can also be used with other Ruby tools. We can demonstrate this by creating a small "Rack":http://rack.rubyforge.org/ application that includes Action View functionality. This may be useful, for example, if you'd like access to Action View's helpers in a Rack application. Let's start by ensuring that you have the Action Pack and Rack gems installed: <shell> -gem install actionpack -gem install rack +$ gem install actionpack +$ gem install rack </shell> Now we'll create a simple "Hello World" application that uses the +titleize+ method provided by Active Support. @@ -52,20 +52,20 @@ Rack::Handler::Mongrel.run method(:hello_world), :Port => 4567 We can see this all come together by starting up the application and then visiting +http://localhost:4567/+ <shell> -ruby hello_world.rb +$ ruby hello_world.rb </shell> -TODO needs a screenshot? I have one - not sure where to put it. +TODO needs a screenshot? I have one - not sure where to put it. -Notice how 'hello world' has been converted into 'Hello World' by the +titleize+ helper method. +Notice how 'hello world' has been converted into 'Hello World' by the +titleize+ helper method. -Action View can also be used with "Sinatra":http://www.sinatrarb.com/ in the same way. +Action View can also be used with "Sinatra":http://www.sinatrarb.com/ in the same way. Let's start by ensuring that you have the Action Pack and Sinatra gems installed: <shell> -gem install actionpack -gem install sinatra +$ gem install actionpack +$ gem install sinatra </shell> Now we'll create the same "Hello World" application in Sinatra. @@ -85,12 +85,12 @@ end Then, we can run the application: <shell> -ruby hello_world.rb +$ ruby hello_world.rb </shell> Once the application is running, you can see Sinatra and Action View working together by visiting +http://localhost:4567/+ -TODO needs a screenshot? I have one - not sure where to put it. +TODO needs a screenshot? I have one - not sure where to put it. h3. Templates, Partials and Layouts @@ -172,7 +172,7 @@ 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. +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. ActiveRecordHelper @@ -196,7 +196,7 @@ error_messages_for "post" 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. +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. <ruby> form("post") @@ -220,29 +220,29 @@ Typically, +form_for+ is used instead of +form+ because it doesn't automatically h5. input -Returns a default input tag for the type of object returned by the method. +Returns a default input tag for the type of object returned by the method. For example, if +@post+ has an attribute +title+ mapped to a +String+ column that holds "Hello World": <ruby> -input("post", "title") # => +input("post", "title") # => <input id="post_title" name="post[title]" size="30" type="text" value="Hello World" /> </ruby> h4. AssetTagHelper -This module provides methods for generating HTML that links views to assets such as images, javascripts, stylesheets, and feeds. +This module provides methods for generating HTML that links views to assets such as images, JavaScript files, stylesheets, and feeds. -By default, Rails links to these assets on the current host in the public folder, but you can direct Rails to link to assets from a dedicated assets server by setting +ActionController::Base.asset_host+ in your +config/environment.rb+. For example, let's say your asset host is +assets.example.com+: +By default, Rails links to these assets on the current host in the public folder, but you can direct Rails to link to assets from a dedicated assets server by setting +ActionController::Base.asset_host+ in the application configuration, typically in +config/environments/production.rb+. For example, let's say your asset host is +assets.example.com+: <ruby> ActionController::Base.asset_host = "assets.example.com" -image_tag("rails.png") # => <img src="http://assets.example.com/images/rails.png" alt="Rails" /> +image_tag("rails.png") # => <img src="http://assets.example.com/images/rails.png" alt="Rails" /> </ruby> 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. +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+. <ruby> ActionView::Helpers::AssetTagHelper.register_javascript_expansion :monkey => ["head", "body", "tail"] @@ -253,9 +253,6 @@ javascript_include_tag :monkey # => <script type="text/javascript" src="/javascripts/tail.js"></script> </ruby> -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+. h5. register_stylesheet_expansion @@ -281,7 +278,7 @@ auto_discovery_link_tag(:rss, "http://www.example.com/feed.rss", {:title => "RSS 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. +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. <ruby> image_path("edit.png") # => /images/edit.png @@ -289,7 +286,7 @@ image_path("edit.png") # => /images/edit.png 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. +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. <ruby> image_tag("icon.png") # => <img src="/images/icon.png" alt="Icon" /> @@ -297,35 +294,35 @@ image_tag("icon.png") # => <img src="/images/icon.png" alt="Icon" /> 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. +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. <ruby> javascript_include_tag "common" # => - <script type="text/javascript" src="/javascripts/common.js"></script> + <script type="text/javascript" src="/javascripts/common.js"></script> </ruby> -To include the Prototype and Scriptaculous javascript libraries in your application, pass +:defaults+ as the source. When using +:defaults+, if an +application.js+ file exists in your +public/javascripts+ directory, it will be included as well. +To include the Prototype and Scriptaculous JavaScript libraries in your application, pass +:defaults+ as the source. When using +:defaults+, if an +application.js+ file exists in your +public/javascripts+ directory, it will be included as well. <ruby> javascript_include_tag :defaults </ruby> -You can also include all javascripts in the javascripts directory using +:all+ as the source. +You can also include all JavaScript files in the +public/javascripts+ directory using +:all+ as the source. <ruby> javascript_include_tag :all </ruby> -You can also cache multiple javascripts into one file, which requires less HTTP connections to download and can better be compressed by gzip (leading to faster transfers). Caching will only happen if +ActionController::Base.perform_caching+ is set to true (which is the case by default for the Rails production environment, but not for the development environment). +You can also cache multiple JavaScript files into one file, which requires less HTTP connections to download and can better be compressed by gzip (leading to faster transfers). Caching will only happen if +ActionController::Base.perform_caching+ is set to true (which is the case by default for the Rails production environment, but not for the development environment). <ruby> -javascript_include_tag :all, :cache => true # => - <script type="text/javascript" src="/javascripts/all.js"></script> +javascript_include_tag :all, :cache => true # => + <script type="text/javascript" src="/javascripts/all.js"></script> </ruby> 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. +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. <ruby> javascript_path "common" # => /javascripts/common.js @@ -333,7 +330,7 @@ javascript_path "common" # => /javascripts/common.js 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. +Returns a stylesheet link tag for the sources specified as arguments. If you don't specify an extension, +.css+ will be appended automatically. <ruby> stylesheet_link_tag "application" # => @@ -346,7 +343,7 @@ You can also include all styles in the stylesheet directory using :all as the so stylesheet_link_tag :all </ruby> -You can also cache multiple stylesheets into one file, which requires less HTTP connections and can better be compressed by gzip (leading to faster transfers). Caching will only happen if ActionController::Base.perform_caching is set to true (which is the case by default for the Rails production environment, but not for the development environment). +You can also cache multiple stylesheets into one file, which requires less HTTP connections and can better be compressed by gzip (leading to faster transfers). Caching will only happen if ActionController::Base.perform_caching is set to true (which is the case by default for the Rails production environment, but not for the development environment). <ruby> stylesheet_link_tag :all, :cache => true @@ -355,7 +352,7 @@ stylesheet_link_tag :all, :cache => true 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. +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. <ruby> stylesheet_path "application" # => /stylesheets/application.css @@ -370,14 +367,14 @@ This helper makes building an ATOM feed easy. Here's a full usage example: *config/routes.rb* <ruby> -map.resources :posts +resources :posts </ruby> *app/controllers/posts_controller.rb* <ruby> def index - @posts = Post.find(:all) + @posts = Post.all respond_to do |format| format.html @@ -415,7 +412,7 @@ Allows you to measure the execution time of a block in a template and records th <ruby> <% benchmark "Process data files" do %> <%= expensive_files_operation %> -<% end %> +<% end %> </ruby> This would add something like "Process data files (0.34523)" to the log, which you can then use to compare timings when optimizing your code. @@ -428,7 +425,7 @@ A method for caching fragments of a view rather than an entire action or page. T <ruby> <% cache do %> - <%= render :partial => "shared/footer" %> + <%= render "shared/footer" %> <% end %> </ruby> @@ -442,7 +439,7 @@ The +capture+ method allows you to extract part of a template into a variable. Y <% @greeting = capture do %> <p>Welcome! The date and time is <%= Time.now %></p> <% end %> -<ruby> +</ruby> The captured variable can then be used anywhere else. @@ -455,7 +452,7 @@ The captured variable can then be used anywhere else. <%= @greeting %> </body> </html> -</ruby> +</ruby> h5. content_for @@ -484,7 +481,7 @@ For example, let's say we have a standard application layout, but also a special <% content_for :special_script do %> <script type="text/javascript">alert('Hello!')</script> -<% end %> +<% end %> </ruby> h4. DateHelper @@ -523,7 +520,7 @@ Returns a set of html select-tags (one for year, month, and day) pre-selected wi select_date(Time.today + 6.days) # Generates a date select that defaults to today (no specified date) -select_date() +select_date() </ruby> h5. select_datetime @@ -535,7 +532,7 @@ Returns a set of html select-tags (one for year, month, day, hour, and minute) p select_datetime(Time.now + 4.days) # Generates a datetime select that defaults to today (no specified datetime) -select_datetime() +select_datetime() </ruby> h5. select_day @@ -583,7 +580,7 @@ Returns a select tag with options for each of the seconds 0 through 59 with the <ruby> # Generates a select field for seconds that defaults to the seconds for the time provided -select_second(Time.now + 16.minutes) +select_second(Time.now + 16.minutes) </ruby> h5. select_time @@ -592,7 +589,7 @@ 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) +select_time(Time.now) </ruby> h5. select_year @@ -621,7 +618,7 @@ Returns a set of select tags (one for hour, minute and optionally second) pre-se <ruby> # Creates a time select tag that, when POSTed, will be stored in the order variable in the submitted attribute -time_select("order", "submitted") +time_select("order", "submitted") </ruby> h4. DebugHelper @@ -654,7 +651,7 @@ The core method of this helper, form_for, gives you the ability to create a form <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| %> +<%= form_for @person, :url => { :action => "create" } do |f| %> <%= f.text_field :first_name %> <%= f.text_field :last_name %> <%= submit_tag 'Create' %> @@ -711,7 +708,7 @@ 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]" /> +# => <input type="file" id="user_avatar" name="user[avatar]" /> </ruby> h5. form_for @@ -733,7 +730,7 @@ 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}" /> +# => <input type="hidden" id="user_token" name="user[token]" value="#{@user.token}" /> </ruby> h5. label @@ -751,7 +748,7 @@ Returns an input tag of the "password" type tailored for accessing a specified a <ruby> password_field(:login, :pass) -# => <input type="text" id="login_pass" name="login[pass]" value="#{@login.pass}" /> +# => <input type="text" id="login_pass" name="login[pass]" value="#{@login.pass}" /> </ruby> h5. radio_button @@ -812,7 +809,7 @@ end 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}) +collection_select(:post, :author_id, Author.all, :id, :name_with_initial, {:prompt => true}) </ruby> If @post.author_id is already 1, this would return: @@ -854,7 +851,7 @@ end Sample usage: -<ruby> +<ruby> option_groups_from_collection_for_select(@continents, :countries, :name, :id, :name, 3) </ruby> @@ -880,7 +877,7 @@ Note: Only the +optgroup+ and +option+ tags are returned, so you still have to w h5. options_for_select -Accepts a container (hash, array, enumerable, your type) and returns a string of option tags. +Accepts a container (hash, array, enumerable, your type) and returns a string of option tags. <ruby> options_for_select([ "VISA", "MasterCard" ]) @@ -891,7 +888,7 @@ Note: Only the +option+ tags are returned, you have to wrap this call in a regul 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. +Returns a string of option tags that have been compiled by iterating over the +collection+ and assigning 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) @@ -902,7 +899,7 @@ For example, imagine a loop iterating over each person in @project.people to gen <ruby> options_from_collection_for_select(@project.people, "id", "name") # => <option value="#{person.id}">#{person.name}</option> -</ruby> +</ruby> Note: Only the +option+ tags are returned, you have to wrap this call in a regular HTML +select+ tag. @@ -913,7 +910,7 @@ Create a select tag and a series of contained option tags for the provided objec Example with @post.person_id => 1: <ruby> -select("post", "person_id", Person.find(:all).collect {|p| [ p.name, p.id ] }, { :include_blank => true }) +select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, { :include_blank => true }) </ruby> could become: @@ -949,7 +946,7 @@ Creates a check box form input tag. <ruby> check_box_tag 'accept' -# => <input id="accept" name="accept" type="checkbox" value="1" /> +# => <input id="accept" name="accept" type="checkbox" value="1" /> </ruby> h5. field_set_tag @@ -965,7 +962,7 @@ Creates a field set for grouping HTML form elements. h5. file_field_tag -Creates a file upload field. +Creates a file upload field. If you are using file uploads then you will also need to set the multipart option for the form tag: @@ -1079,7 +1076,7 @@ h4. JavaScriptHelper Provides functionality for working with JavaScript in your views. -Rails includes the Prototype JavaScript framework and the Scriptaculous JavaScript controls and visual effects library. If you wish to use these libraries and their helpers, make sure +<%= javascript_include_tag :defaults, :cache => true %>+ is in the HEAD section of your page. This function will include the necessary JavaScript files Rails generated in the public/javascripts directory. +Rails includes the Prototype JavaScript framework and the Scriptaculous JavaScript controls and visual effects library. If you wish to use these libraries and their helpers, make sure +<%= javascript_include_tag :defaults, :cache => true %>+ is in the HEAD section of your page. This function will include the necessary JavaScript files Rails generated in the +public/javascripts+ directory. h5. button_to_function @@ -1173,7 +1170,7 @@ number_with_delimiter(12345678) # => 12,345,678 h5. number_with_precision -Formats a number with the specified level of +precision+, which defaults to 3. +Formats a number with the specified level of +precision+, which defaults to 3. <ruby> number_with_precision(111.2345) # => 111.235 @@ -1207,7 +1204,7 @@ form_remote_tag :html => { :action => url_for(:controller => "some", :action => would generate the following: <html> -<form action="/some/place" method="post" onsubmit="new Ajax.Request('', +<form action="/some/place" method="post" onsubmit="new Ajax.Request('', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)}); return false;"> </html> @@ -1293,7 +1290,7 @@ Yields a JavaScriptGenerator and returns the generated JavaScript code. Use this <ruby> update_page do |page| page.hide 'spinner' -end +end </ruby> h5. update_page_tag @@ -1395,7 +1392,7 @@ h5. remove Removes the DOM elements with the given ids from the page. <ruby> -page.remove 'person_23', 'person_9', 'person_2' +page.remove 'person_23', 'person_9', 'person_2' </ruby> h5. replace @@ -1420,7 +1417,7 @@ Returns a collection reference by finding it through a CSS pattern in the DOM. <ruby> page.select('p.welcome b').first.hide # => $$('p.welcome b').first().hide(); -</ruby> +</ruby> h5. show @@ -1440,7 +1437,7 @@ Toggles the visibility of the DOM elements with the given ids. Example: <ruby> page.toggle 'person_14', 'person_12', 'person_23' # Hides the elements -page.toggle 'person_14', 'person_12', 'person_23' # Shows the previously hidden elements +page.toggle 'person_14', 'person_12', 'person_23' # Shows the previously hidden elements </ruby> h5. visual_effect @@ -1455,11 +1452,11 @@ h3. Localized Views Action View has the ability render different templates depending on the current locale. -For example, suppose you have a Posts controller with a show action. By default, calling this action will render +app/views/posts/show.html.erb+. But if you set +I18n.locale = :de+, then +app/views/posts/show.de.html.erb+ will be rendered instead. If the localized template isn't present, the undecorated version will be used. This means you're not required to provide localized views for all cases, but they will be preferred and used if available. +For example, suppose you have a Posts controller with a show action. By default, calling this action will render +app/views/posts/show.html.erb+. But if you set +I18n.locale = :de+, then +app/views/posts/show.de.html.erb+ will be rendered instead. If the localized template isn't present, the undecorated version will be used. This means you're not required to provide localized views for all cases, but they will be preferred and used if available. You can use the same technique to localize the rescue files in your public directory. For example, setting +I18n.locale = :de+ and creating +public/500.de.html+ and +public/404.de.html+ would allow you to have localized rescue pages. -Since Rails doesn't restrict the symbols that you use to set I18n.locale, you can leverage this system to display different content depending on anything you like. For example, suppose you have some "expert" users that should see different pages from "normal" users. You could add the following to +app/controllers/application.rb+: +Since Rails doesn't restrict the symbols that you use to set I18n.locale, you can leverage this system to display different content depending on anything you like. For example, suppose you have some "expert" users that should see different pages from "normal" users. You could add the following to +app/controllers/application.rb+: <ruby> before_filter :set_expert_locale @@ -1471,11 +1468,9 @@ end Then you could create special views like +app/views/posts/show.expert.html.erb+ that would only be displayed to expert users. -You can read more about the Rails Internationalization (I18n) API "here":i18n.html. +You can read more about the Rails Internationalization (I18n) API "here":i18n.html. h3. Changelog -"Lighthouse Ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/71 - -* September 3, 2009: Continuing work by Trevor Turk, leveraging the "Action Pack docs":http://ap.rubyonrails.org/ and "What's new in Edge Rails":http://ryandaigle.com/articles/2007/8/3/what-s-new-in-edge-rails-partials-get-layouts +* September 3, 2009: Continuing work by Trevor Turk, leveraging the Action Pack docs and "What's new in Edge Rails":http://ryandaigle.com/articles/2007/8/3/what-s-new-in-edge-rails-partials-get-layouts * April 5, 2009: Starting work by Trevor Turk, leveraging Mike Gunderloy's docs |