aboutsummaryrefslogtreecommitdiffstats
path: root/railties/doc/guides/actionview
diff options
context:
space:
mode:
authorPratik Naik <pratiknaik@gmail.com>2008-07-16 13:00:36 +0100
committerPratik Naik <pratiknaik@gmail.com>2008-07-16 13:01:23 +0100
commit0432d151647f2178ddee79979827d552447c251f (patch)
tree7c772cd260eb051cd7b80cf91468555f03db9e11 /railties/doc/guides/actionview
parentf7d08acd5e0650658383e3d3f86d6ff5b49e9030 (diff)
downloadrails-0432d151647f2178ddee79979827d552447c251f.tar.gz
rails-0432d151647f2178ddee79979827d552447c251f.tar.bz2
rails-0432d151647f2178ddee79979827d552447c251f.zip
Merge with docrails.
Diffstat (limited to 'railties/doc/guides/actionview')
-rw-r--r--railties/doc/guides/actionview/helpers.markdown91
-rw-r--r--railties/doc/guides/actionview/partials.markdown90
2 files changed, 181 insertions, 0 deletions
diff --git a/railties/doc/guides/actionview/helpers.markdown b/railties/doc/guides/actionview/helpers.markdown
new file mode 100644
index 0000000000..c702e83ff9
--- /dev/null
+++ b/railties/doc/guides/actionview/helpers.markdown
@@ -0,0 +1,91 @@
+Helpers
+====================
+
+Helper Basics
+------------------------
+
+Helpers allow you to encapsulate rendering tasks as reusable functions. Helpers are modules, not classes, so their methods execute in the context in which they are called. They get included in a controller (typically the ApplicationController) using the helper function, like so
+
+ Class ApplicationController < ActionController::Base
+ …
+ helper :menu
+
+ def …
+ end
+ end
+
+In this way, methods in the menu helper are made available to any view or partial in your application. These methods can accept parameters, for example controller instance variables (eg; records or record collections gathered by you current controller), items from the view or partial’s locals[] hash or items from the params[] hash. You may wish to pass your controller instance variables and items from the params[] hash to the locals hash before rendering (See the section on partials). Helper methods can also accept an executable block of code.
+
+It is important to remember, though, that helpers are for rendering, and that they become available once a controller method has returned, while Rails is engaged in rendering the contents generated by a controller method. This means that helper methods are not available from within the methods of your controllers.
+
+Helpers can accomplish a variety of tasks, from formatting a complex tag for embedding content for a browser plugin (eg; Flash), to assembling a menu of options appropriate for the current context of your application, to generating sections of forms that get assembled on-the-fly.
+
+Helpers are organized around rendering tasks, so it is not necessary (nor necessarily desirable) to organize them around your application’s controllers or models. In fact, one of the benefits of helpers is that they are not connected via a rendering pipeline to specific controllers, like views and partials are. They can and should handle more generalized tasks.
+
+Here is a very simple, pseudo-example:
+
+ module MenuHelper
+ def menu(records, menu_options={})
+ item_options = menu_options.merge({<some stuff>})
+ items = records.collect |record| do
+ menu_item(record, options)
+ end
+ content_tag(“ul”, items, options)
+ end
+
+ def menu_item(record, item_options={}))
+ action = item_options[:action]
+ action ||= “show”
+ content_tag(“li”, link_to(record.title, :action => action, item_options)
+ end
+ end
+
+
+This helper will require that records passed into it have certain fields (notably :title). The helper could be written to use this as a default, allowing the field to be overwritten by an element of item_options.
+
+Look at the Rails API for examples of helpers included in Rails, eg; [`ActionView::Helpers::ActiveRecordHelper`](http://api.rubyonrails.org/classes/ActionView/Helpers/ActiveRecordHelper.html).
+
+Passing Blocks to Helper Methods
+------------------------
+
+We mentioned before that blocks can be passed to helper methods. This allows for an interesting wrinkle: a block passed to a helper method can cause it to render a partial, which can then be wrapped by the helper method’s output. This can make your helper method much more reusable. It doesn’t need to know anything about the internals about what it is rendering, it just contextualizes it for the page. You can also use the helper to modify the locals hash for the partial, based on some configuration information unique to the current controller. You could implement a flexible themes system in this way.
+
+
+Partials vs. Helpers?
+------------------------
+
+In general, the choice between using a partial vs. using a helper depends on the amount of flexibility you need. If the task is more about reacting to conditions than performing actual rendering, you may likely want a helper method. If you want to be able to call it from a variety of views, again, you may want to use a helper method. You can expect to extract helper methods out of code in views and partials during refactoring.
+
+
+Tutorial -- Calling a Helper [UNFINISHED]
+------------------------
+
+1. Create a Rails application using `rails helper_test`
+Notice the code:
+
+ class ApplicationController < ActionController::Base
+ helper :all # include all helpers, all the time
+For this tutorial, we'll keep this code, but you will likely want to exert more control over loading your helpers.
+
+2. Configure a database of your choice for the app.
+
+3. Inside of the `/app/helpers/` directory, create a new file called, `menu_helper.rb`. Write this in the file:
+
+ module MenuHelpers
+ def menu(records, item_proc=nil)
+ items = records.collect{ |record|
+ menu_item(record, item_proc)
+ }
+ content_tag("ul", items)
+ end
+
+ def menu_item(record, item_proc=nil)
+ item_url = item_proc.call(record)
+ item_url ||= { :action => :show }
+ content_tag("li", link_to(record.name, item_url))
+ end
+ end
+
+4. Create a scaffold for some object in your app, using `./script/generate scaffold widgets`.
+5. Create a database table for your widgets, with at least the fields `name` and `id`. Create a few widgets.
+6. Call the menu command twice from `index.html.erb`, once using the default action, and once supplying a Proc to generate urls. \ No newline at end of file
diff --git a/railties/doc/guides/actionview/partials.markdown b/railties/doc/guides/actionview/partials.markdown
new file mode 100644
index 0000000000..2988b933bc
--- /dev/null
+++ b/railties/doc/guides/actionview/partials.markdown
@@ -0,0 +1,90 @@
+A Guide to Using Partials
+===============================
+
+This guide elaborates on the use and function of partials in Ruby on Rails. As your Rails application grows, your view templates can start to contain a lot of duplicate view code. To manage and reduce this complexity, you can by abstract view template code into partials. Partials are reusable snippets of eRB template code stored in separate files with an underscore ('_') prefix.
+
+Partials can be located anywhere in the `app/views` directory. File extensions for partials work just like other template files, they bear an extension that denotes what kind of code they generate. For example, `_animal.html.erb` and `_animal.xml.erb` are valid filenames for partials.
+
+Partials can be inserted in eRB template code by calling the `render` method with the `:partial` option. For example:
+
+ <%= render :partial => 'foo' %>
+
+This inserts the result of evaluating the template `_foo.html.erb` into the parent template file at this location. Note that `render` assumes that the partial will be in the same directory as the calling parent template and have the same file extension. Partials can be located anywhere within the `app/views` directory. To use a partial located in a different directory then it the parent, add a '/' before it:
+
+ <%= render :partial => '/common/foo' %>
+
+Loads the partial file from the `app/views/common/_foo.html.erb` directory.
+
+Abstracting views into partials can be approached in a number of different ways, depending on the situation. Sometimes, the code that you are abstracting is a specialized view of an object or a collection of objects. Other times, you can look at partials as a reusable subroutine. We'll explore each of these approaches and when to use them as well as the syntax for calling them.
+
+Partials as a View Subroutine
+-----------------------------
+
+Using the `:locals` option, you can pass a hash of values which will be treated as local variables within the partial template.
+
+ <%= render :partial => "person", :locals => { :name => "david" } %>
+
+The variable `name` contains the value `"david"` within the `_person.html.erb` template. Passing variables in this way allows you to create modular, reusable template files. Note that if you want to make local variables that are optional in some use cases, you will have to set them to a sentinel value such as `nil` when they have not been passed. So, in the example above, if the `name` variable is optional in some use cases, you must set:
+
+ <% name ||= nil -%>
+
+So that you can later check:
+
+ <% if name -%>
+ <p>Hello, <%= name %>!</p>
+ <% end -%>
+
+Otherwise, the if statement will throw an error at runtime.
+
+Another thing to be aware of is that instance variables that are visible to the parent view template are visible to the partial. So you might be tempted to do this:
+
+ <%= render :partial => "person" %>
+
+And then within the partial:
+
+ <% if @name -%>
+ <p>Hello, <%= @name %>!</p>
+ <% end -%>
+
+The potential snag here is that if multiple templates start to rely on this partial, you will need to maintain an instance variable with the same name across all of these templates and controllers. This approach can quickly become brittle if overused.
+
+Partials as a View of an Object
+--------------------------------
+
+Another way to look at partials is to view them as mini-views of a particular object or instance variable. Use the `:object` option to pass an object assigns that object to an instance variable named after the partial itself. For example:
+
+ # Renders the partial, making @new_person available through
+ # the local variable 'person'
+ render :partial => "person", :object => @new_person
+
+If the instance variable `name` in the parent template matches the name of the partial, you can use a shortcut:
+
+ render :partial => "person"
+
+Now the value that was in `@person` in the parent template is accessible as `person` in the partial.
+
+Partials as a View of a Collection
+-----------------------------------
+
+Often it is the case that you need to display not just a single object, but a collection of objects. Rather than having to constantly nest the same partial within the same iterator code, Rails provides a syntactical shortcut using the `:collection` option:
+
+ # Renders a collection of the same partial by making each element
+ # of @winners available through the local variable "person" as it
+ # builds the complete response.
+ render :partial => "person", :collection => @winners
+
+This calls the `_person.html.erb` partial for each person in the `@winners` collection. This also creates a local variable within the partial called `partial_counter` which contains the index of the current value. So for example:
+
+ <%= partial_counter %>) <%= person -%>
+
+Where `@winners` contains three people, produces the following output:
+
+ 1) Bill
+ 2) Jeff
+ 3) Nick
+
+One last detail, you can place an arbitrary snippet of code in between the objects using the `:spacer_template` option.
+
+ # Renders the same collection of partials, but also renders the
+ # person_divider partial between each person partial.
+ render :partial => "person", :collection => @winners, :spacer_template => "person_divider"