Index: actionpack/lib/action_controller/scaffolding.rb =================================================================== --- actionpack/lib/action_controller/scaffolding.rb (revision 6813) +++ actionpack/lib/action_controller/scaffolding.rb (working copy) @@ -4,17 +4,24 @@ base.extend(ClassMethods) end - # Scaffolding is a way to quickly put an Active Record class online by providing a series of standardized actions + # Scaffolding is a way to quickly build an interface to an Active Record class by providing a series of standardized actions # for listing, showing, creating, updating, and destroying objects of the class. These standardized actions come - # with both controller logic and default templates that through introspection already know which fields to display - # and which input types to use. Example: + # with both controller logic and dynamically generated default templates that, through introspection, know which fields to display + # and which input types to use. For example, let's say we wanted to use our WeblogController controller class as the interface to + # our Entry model. You would do something like this: # # class WeblogController < ActionController::Base # scaffold :entry # end # - # This tiny piece of code will add all of the following methods to the controller: + # This tiny piece of code will create methods that will generate a simple interface on the fly for manipulating instances of our Entry + # model. You'd need to navigate to http://localhost/weblog/ or http://www.yourhost.com/weblog (depending on your + # environment) to see it in action. # + # === How it works + # All of the controller logic and template code for scaffolds is generated on the fly at every request. So, behind the scenes, when + # making a request to WeblogController, all of the following methods are dynamically added to it: + # # class WeblogController < ActionController::Base # verify :method => :post, :only => [ :destroy, :create, :update ], # :redirect_to => { :action => :list } @@ -70,19 +77,64 @@ # end # end # end + # You, of course, never see this code (unless you generate the code file: see below), but it is nevertheless generated for you. The methods + # do just what they say: create creates instances of Entry, destroy destroys instances of Entry, and so on. Each method + # that needs a view (e.g., list or edit) has one generated for it when it is requested. # - # The render_scaffold method will first check to see if you've made your own template (like "weblog/show.erb" for - # the show action) and if not, then render the generic template for that action. This gives you the possibility of using the - # scaffold while you're building your specific application. Start out with a totally generic setup, then replace one template - # and one action at a time while relying on the rest of the scaffolded templates and actions. + # === The View + # The render_scaffold method will render the scaffold's view dynamically, first checking to see if you've made your + # own template (like "app/views/weblog/show.erb" for the show action). If you have, it will render that template; if you haven't, then + # it will render the generic dynamic template for that action. + # + # === Extending and replacing scaffolding + # Though it is often used as the base for Rails applications, scaffolding should always be replaced, or at the very least, extended. + # You should use a scaffold and its generic templates to get basic functionality up and running, and as you build your application, slowly + # replace the default methods and templates with your own while relying on the rest of the scaffolded templates and actions. So, using + # our example above of a blog, you could replace the create method with one that pinged an aggregator, replace + # the view for the index with our own, prettier view (in "app/views/weblog/index.erb"), and whatever you don't replace will remain scaffolded + # until you can get around to replacing it. + # + # To replace these methods, you simply redefine them. For example, if you were replacing the create method from our example, + # with one that added the date to the entry's subject and pinged an aggregator after the creation, you could do the following: + # + # class WeblogController < ActionController::Base + # scaffold :entry + # + # def create + # params[:entry][:title] = "#{params[:entry][:title]} (#{Time.now.strftime("%m/%d/%y")})" + # @entry = Entry.new(params[:entry]) + # if @entry.save + # flash[:notice] = "Entry was successfully created" + # AggregatorPinger.ping(@entry) + # redirect_to :action => "list" + # else + # render_scaffold('new') + # end + # end + # end + # + # To ween yourself off scaffolding even more, you could create a view for new (in "app/views/weblog/new.erb") and remove + # the call to render_scaffold. Repeat this process for every method until you can finally remove the call to scaffold. + # + # === Generating scaffold code files + # You can also generate static scaffolding files, which give you the same setup but instead of the code being dynamically generated + # at each request, it is dumped to file form so you can edit it at will. You can generate a scaffold by following the usage instructions + # given by executing script/generate scaffold. This can save you some keystrokes when you set yourself on replacing the scaffold, + # since much of the CRUD code can simply be extended. module ClassMethods - # Adds a swath of generic CRUD actions to the controller. The +model_id+ is automatically converted into a class name unless - # one is specifically provide through options[:class_name]. So scaffold :post would use Post as the class - # and @post/@posts for the instance variables. + # The main method for creating a scaffold, scaffold uses metaprogramming to add a swath of generic CRUD (create, read, update, delete) + # actions to the controller from which it is called. # + # The +model_id+ option is automatically converted into a class name unless one is specifically provided through + # options[:class_name]. So, scaffold :post would use Post as the class and @post/@posts for the instance + # variables, and scaffold :post, :class_name => 'BlogPost' would use BlogPost as the class and @blogpost/@blogposts + # for the instance variables. + # # It's possible to use more than one scaffold in a single controller by specifying options[:suffix] = true. This will - # make scaffold :post, :suffix => true use method names like list_post, show_post, and create_post - # instead of just list, show, and post. If suffix is used, then no index method is added. + # make scaffold :post, :suffix => true use method names like list_post, show_post, and create_post + # instead of just list, show, and post. If you added another line to say scaffold :comment, :suffix => true + # then you would have methods such as list_comment and show_comment available in the same post. If suffix + # is used, then no index method is added to the controller, but can be manually aliased or created. def scaffold(model_id, options = {}) options.assert_valid_keys(:class_name, :suffix) Index: actionpack/lib/action_controller/assertions/routing_assertions.rb =================================================================== --- actionpack/lib/action_controller/assertions/routing_assertions.rb (revision 6813) +++ actionpack/lib/action_controller/assertions/routing_assertions.rb (working copy) @@ -1,25 +1,41 @@ module ActionController module Assertions + # Suite of assertions to test routes generated by Rails and the handling of requests made to them. module RoutingAssertions - # Asserts that the routing of the given path was handled correctly and that the parsed options match. + # Asserts that the routing of the given +path+ was handled correctly and that the parsed options (given in the +expected_options+ hash) + # match +path+. Basically, it asserts that Rails recognizes the route given by +expected_options+. # - # assert_recognizes({:controller => 'items', :action => 'index'}, 'items') # check the default action - # assert_recognizes({:controller => 'items', :action => 'list'}, 'items/list') # check a specific action - # assert_recognizes({:controller => 'items', :action => 'list', :id => '1'}, 'items/list/1') # check an action with a parameter - # - # Pass a hash in the second argument to specify the request method. This is useful for routes + # Pass a hash in the second argument (+path+) to specify the request method. This is useful for routes # requiring a specific HTTP method. The hash should contain a :path with the incoming request path # and a :method containing the required HTTP verb. # # # assert that POSTing to /items will call the create action on ItemsController # assert_recognizes({:controller => 'items', :action => 'create'}, {:path => 'items', :method => :post}) # - # You can also pass in "extras" with a hash containing URL parameters that would normally be in the query string. This can be used + # You can also pass in +extras+ with a hash containing URL parameters that would normally be in the query string. This can be used # to assert that values in the query string string will end up in the params hash correctly. To test query strings you must use the # extras argument, appending the query string on the path directly will not work. For example: # # # assert that a path of '/items/list/1?view=print' returns the correct options # assert_recognizes({:controller => 'items', :action => 'list', :id => '1', :view => 'print'}, 'items/list/1', { :view => "print" }) + # + # The +message+ parameter allows you to pass in an error message that is displayed upon failure. + # + # ==== Examples + # # Check the default route (i.e., the index action) + # assert_recognizes({:controller => 'items', :action => 'index'}, 'items') + # + # # Test a specific action + # assert_recognizes({:controller => 'items', :action => 'list'}, 'items/list') + # + # # Test an action with a parameter + # assert_recognizes({:controller => 'items', :action => 'destroy', :id => '1'}, 'items/destroy/1') + # + # # Test a custom route + # assert_recognizes({:controller => 'items', :action => 'show', :id => '1'}, 'view/item1') + # + # # Check a Simply RESTful generated route + # assert_recognizes(list_items_url, 'items/list') def assert_recognizes(expected_options, path, extras={}, message=nil) if path.is_a? Hash request_method = path[:method] @@ -43,12 +59,24 @@ end end - # Asserts that the provided options can be used to generate the provided path. This is the inverse of assert_recognizes. - # For example: + # Asserts that the provided options can be used to generate the provided path. This is the inverse of #assert_recognizes. + # The +extras+ parameter is used to tell the request the names and values of additional request parameters that would be in + # a query string. The +message+ parameter allows you to specify a custom error message for assertion failures. # + # The +defaults+ parameter is unused. + # + # ==== Examples + # # Asserts that the default action is generated for a route with no action # assert_generates("/items", :controller => "items", :action => "index") + # + # # Tests that the list action is properly routed # assert_generates("/items/list", :controller => "items", :action => "list") + # + # # Tests the generation of a route with a parameter # assert_generates("/items/list/1", { :controller => "items", :action => "list", :id => "1" }) + # + # # Asserts that the generated route gives us our custom route + # assert_generates "changesets/12", { :controller => 'scm', :action => 'show_diff', :revision => "12" } def assert_generates(expected_path, options, defaults={}, extras = {}, message=nil) clean_backtrace do expected_path = "/#{expected_path}" unless expected_path[0] == ?/ @@ -67,9 +95,25 @@ end end - # Asserts that path and options match both ways; in other words, the URL generated from - # options is the same as path, and also that the options recognized from path are the same as options. This - # essentially combines assert_recognizes and assert_generates into one step. + # Asserts that path and options match both ways; in other words, it verifies that path generates + # options and then that options generates path. This essentially combines #assert_recognizes + # and #assert_generates into one step. + # + # The +extras+ hash allows you to specify options that would normally be provided as a query string to the action. The + # +message+ parameter allows you to specify a custom error message to display upon failure. + # + # ==== Examples + # # Assert a basic route: a controller with the default action (index) + # assert_routing('/home', :controller => 'home', :action => 'index') + # + # # Test a route generated with a specific controller, action, and parameter (id) + # assert_routing('/entries/show/23', :controller => 'entries', :action => 'show', id => 23) + # + # # Assert a basic route (controller + default action), with an error message if it fails + # assert_routing('/store', { :controller => 'store', :action => 'index' }, {}, {}, 'Route for store index not generated properly') + # + # # Tests a route, providing a defaults hash + # assert_routing 'controller/action/9', {:id => "9", :item => "square"}, {:controller => "controller", :action => "action"}, {}, {:item => "square"} def assert_routing(path, options, defaults={}, extras={}, message=nil) assert_recognizes(options, path, extras, message) Index: actionpack/lib/action_controller/assertions/tag_assertions.rb =================================================================== --- actionpack/lib/action_controller/assertions/tag_assertions.rb (revision 6813) +++ actionpack/lib/action_controller/assertions/tag_assertions.rb (working copy) @@ -3,6 +3,7 @@ module ActionController module Assertions + # Pair of assertions to testing elements in the HTML output of the response. module TagAssertions # Asserts that there is a tag/node/element in the body of the response # that meets all of the given conditions. The +conditions+ parameter must @@ -48,39 +49,39 @@ # * if the condition is +true+, the value must not be +nil+. # * if the condition is +false+ or +nil+, the value must be +nil+. # - # Usage: + # === Examples # - # # assert that there is a "span" tag + # # Assert that there is a "span" tag # assert_tag :tag => "span" # - # # assert that there is a "span" tag with id="x" + # # Assert that there is a "span" tag with id="x" # assert_tag :tag => "span", :attributes => { :id => "x" } # - # # assert that there is a "span" tag using the short-hand + # # Assert that there is a "span" tag using the short-hand # assert_tag :span # - # # assert that there is a "span" tag with id="x" using the short-hand + # # Assert that there is a "span" tag with id="x" using the short-hand # assert_tag :span, :attributes => { :id => "x" } # - # # assert that there is a "span" inside of a "div" + # # Assert that there is a "span" inside of a "div" # assert_tag :tag => "span", :parent => { :tag => "div" } # - # # assert that there is a "span" somewhere inside a table + # # Assert that there is a "span" somewhere inside a table # assert_tag :tag => "span", :ancestor => { :tag => "table" } # - # # assert that there is a "span" with at least one "em" child + # # Assert that there is a "span" with at least one "em" child # assert_tag :tag => "span", :child => { :tag => "em" } # - # # assert that there is a "span" containing a (possibly nested) + # # Assert that there is a "span" containing a (possibly nested) # # "strong" tag. # assert_tag :tag => "span", :descendant => { :tag => "strong" } # - # # assert that there is a "span" containing between 2 and 4 "em" tags + # # Assert that there is a "span" containing between 2 and 4 "em" tags # # as immediate children # assert_tag :tag => "span", # :children => { :count => 2..4, :only => { :tag => "em" } } # - # # get funky: assert that there is a "div", with an "ul" ancestor + # # Get funky: assert that there is a "div", with an "ul" ancestor # # and an "li" parent (with "class" = "enum"), and containing a # # "span" descendant that contains text matching /hello world/ # assert_tag :tag => "div", @@ -105,6 +106,18 @@ # Identical to #assert_tag, but asserts that a matching tag does _not_ # exist. (See #assert_tag for a full discussion of the syntax.) + # + # === Examples + # # Assert that there is not a "div" containing a "p" + # assert_no_tag :tag => "div", :descendant => { :tag => "p" } + # + # # Assert that an unordered list is empty + # assert_no_tag :tag => "ul", :descendant => { :tag => "li" } + # + # # Assert that there is not a "p" tag with between 1 to 3 "img" tags + # # as immediate children + # assert_no_tag :tag => "p", + # :children => { :count => 1..3, :only => { :tag => "img" } } def assert_no_tag(*opts) clean_backtrace do opts = opts.size > 1 ? opts.last.merge({ :tag => opts.first.to_s }) : opts.first Index: actionpack/lib/action_controller/assertions/response_assertions.rb =================================================================== --- actionpack/lib/action_controller/assertions/response_assertions.rb (revision 6813) +++ actionpack/lib/action_controller/assertions/response_assertions.rb (working copy) @@ -3,6 +3,7 @@ module ActionController module Assertions + # A small suite of assertions that test responses from Rails applications. module ResponseAssertions # Asserts that the response is one of the following types: # @@ -10,10 +11,24 @@ # * :redirect: Status code was in the 300-399 range # * :missing: Status code was 404 # * :error: Status code was in the 500-599 range + # * Your own custom explicit status number # - # You can also pass an explicit status number like assert_response(501) - # or its symbolic equivalent assert_response(:not_implemented). + # This explicit status number can be a number (like assert_response(501)) + # or its symbolic equivalent (like assert_response(:not_implemented)). # See ActionController::StatusCodes for a full list. + # + # ==== Examples + # # Makes sure we got a successful response + # assert_response(:success) # => assert_response(200) + # + # # Asserts the response was Document Not Found (404 error) + # assert_response(404) # => assert_response(:missing) + # + # # Asserts that the response was 401, with a custom error message if it was not + # assert_response(401, "Expecting 'Not Authorized,' but did not receive 401 error") + # + # # Tests that the response code was 304 to test the "unmodified view" response from Rails + # assert_response(304, "View was modified or Rails did not return the proper 'Not Modified' response") def assert_response(type, message = nil) clean_backtrace do if [ :success, :missing, :redirect, :error ].include?(type) && @response.send("#{type}?") @@ -28,9 +43,17 @@ end end - # Assert that the redirection options passed in match those of the redirect called in the latest action. This match can be partial, - # such that assert_redirected_to(:controller => "weblog") will also match the redirection of - # redirect_to(:controller => "weblog", :action => "show") and so on. + # Assert that the redirection options passed in as +options+ match those of the redirect called in the latest action. + # This match can be partial, such that assert_redirected_to(:controller => "weblog") will also match the redirection of + # redirect_to(:controller => "weblog", :action => "show") and so on. The +message+ parameter allows you to display a custom + # error message if the assertion fails. + # + # ==== Examples + # # Matches account/login, account/index, account/signup, and so on... + # assert_redirected_to(:controller => 'account') + # + # # Only matches /home/index or /home + # assert_redirected_to(:controller => 'home', action => 'index') def assert_redirected_to(options = {}, message=nil) clean_backtrace do assert_response(:redirect, message) @@ -104,6 +127,10 @@ end # Asserts that the request was rendered with the appropriate template file. + # + # ==== Examples + # assert_template('user/new') + # assert_template('store/checkout', "Checkout template is not being used") def assert_template(expected = nil, message=nil) clean_backtrace do rendered = expected ? @response.rendered_file(!expected.include?('/')) : @response.rendered_file Index: actionpack/lib/action_controller/assertions/dom_assertions.rb =================================================================== --- actionpack/lib/action_controller/assertions/dom_assertions.rb (revision 6813) +++ actionpack/lib/action_controller/assertions/dom_assertions.rb (working copy) @@ -1,7 +1,42 @@ module ActionController module Assertions + # A suite of assertions for verifying the DOM structure of the provided markup. + # These are used for testing the structure of HTML or XML strings, usually + # views or HTML snippets generated by Rails. module DomAssertions - # Test two HTML strings for equivalency (e.g., identical up to reordering of attributes) + # Test two HTML or XML strings (expected and actual) to be equivalent (i.e., + # identical up to the reordering of attributes). The message parameter allows you to + # feed in a message that is displayed upon failure (useful if you want to make a note about what + # part of the view isn't being rendered correctly). + # + # ==== Examples + # # Asserts that a link generated by Rails to the Rails website is correct + # assert_dom_equal "Rails", link_to("Rails", "http://www.rubyonrails.com") + # + # # Asserts that a link to an action is generated properly; gives a custom error message if it's not + # assert_dom_equal "Login", link_to("Login", :action => 'login'), "Login link broken" + # + # # Tests that a text area tag generated properly + # assert_dom_equal "", text_area_tag("body") + # + # # Asserts that a form tag is properly generated + # assert_dom_equal "
", + # form_tag('/posts') { submit_tag 'Save' } + # + # # Asserts that JavaScript files are included properly, even when given different paths + # assert_dom_equal "", javascript_include_tag "xhr" + # assert_dom_equal """ + # """, javascript_include_tag("corners.js", "/shared/common") + # + # # Tests for proper generation of an auto-discovery link for an action + # assert_dom_equal "", + # auto_discovery_link_tag(:rss, {:action => "feed"}, {:title => "RSS"}) + # + # # Asserts that a button to an action is generated correctly + # assert_dom_equal """
+ #
+ #
""", button_to("Go", :action => "visit", :id => 9) + # def assert_dom_equal(expected, actual, message="") clean_backtrace do expected_dom = HTML::Document.new(expected).root @@ -11,7 +46,21 @@ end end - # The negated form of +assert_dom_equivalent+. + # This is a negated form of #assert_dom_equivalent, that is, it tests that the HTML and/or XML strings are not equal. + # + # ==== Examples + # # Asserts that the image path is picked up properly for an image tag + # assert_dom_not_equal "", image_tag("/my_assets/my_image.gif") + # + # # Asserts that a link to an action recognizes the route properly + # assert_dom_not_equal "", link_to(:controller => 'home', :action => 'index') + # + # # Makes sure the custom path for a JavaScript link is correctly rendered + # assert_dom_equal "", javascript_include_tag "/shared/nav" + # + # # Tests that a custom route is recognized properly + # assert_dom_not_equal "", link_to(:controller => 'user', :action => 'home', :id => 1) # => passes + # assert_dom_equal "", link_to(:controller => 'user', :action => 'home', :id => 1) # => passes def assert_dom_not_equal(expected, actual, message="") clean_backtrace do expected_dom = HTML::Document.new(expected).root @@ -22,4 +71,4 @@ end end end -end \ No newline at end of file +end Index: actionpack/lib/action_controller/assertions/model_assertions.rb =================================================================== --- actionpack/lib/action_controller/assertions/model_assertions.rb (revision 6813) +++ actionpack/lib/action_controller/assertions/model_assertions.rb (working copy) @@ -1,7 +1,14 @@ module ActionController module Assertions module ModelAssertions - # Ensures that the passed record is valid by ActiveRecord standards and returns any error messages if it is not. + # Ensures that the record is valid by Active Record standards using the valid? method. + # It returns any error messages if it is not valid. + # + # ==== Example + # my_person = Person.find(:first) + # + # assert_valid(my_person) + # # => true def assert_valid(record) clean_backtrace do assert record.valid?, record.errors.full_messages.join("\n") @@ -9,4 +16,4 @@ end end end -end \ No newline at end of file +end Index: actionpack/lib/action_controller/assertions/selector_assertions.rb =================================================================== --- actionpack/lib/action_controller/assertions/selector_assertions.rb (revision 6813) +++ actionpack/lib/action_controller/assertions/selector_assertions.rb (working copy) @@ -13,15 +13,13 @@ end # Adds the #assert_select method for use in Rails functional - # test cases. - # - # Use #assert_select to make assertions on the response HTML of a controller + # test cases, which can be used to make assertions on the response HTML of a controller # action. You can also call #assert_select within another #assert_select to # make assertions on elements selected by the enclosing assertion. # # Use #css_select to select elements without making an assertions, either # from the response HTML or elements selected by the enclosing assertion. - # + # # In addition to HTML responses, you can make the following assertions: # * #assert_select_rjs -- Assertions on HTML content of RJS update and # insertion operations. @@ -29,7 +27,7 @@ # for example for dealing with feed item descriptions. # * #assert_select_email -- Assertions on the HTML body of an e-mail. # - # Also see HTML::Selector for learning how to use selectors. + # Also see HTML::Selector to learn how to use selectors. module SelectorAssertions # :call-seq: # css_select(selector) => array @@ -49,12 +47,26 @@ # The selector may be a CSS selector expression (+String+), an expression # with substitution values (+Array+) or an HTML::Selector object. # - # For example: + # ==== Examples + # # Selects all div tags + # divs = css_select("div") + # + # # Selects all paragraph tags and does something interesting + # pars = css_select("p") + # pars.each do |par| + # # Do something fun with paragraphs here... + # end + # + # # Selects all list items in unordered lists + # items = css_select("ul>li") + # + # # Selects all form tags and then all inputs inside the form # forms = css_select("form") # forms.each do |form| # inputs = css_select(form, "input") # ... # end + # def css_select(*args) # See assert_select to understand what's going on here. arg = args.shift @@ -105,12 +117,13 @@ # response HTML. Calling #assert_select inside an #assert_select block will # run the assertion for each element selected by the enclosing assertion. # - # For example: + # ==== Example # assert_select "ol>li" do |elements| # elements.each do |element| # assert_select element, "li" # end # end + # # Or for short: # assert_select "ol>li" do # assert_select "li" @@ -148,7 +161,7 @@ # If the method is called with a block, once all equality tests are # evaluated the block is called with an array of all matched elements. # - # === Examples + # ==== Examples # # # At least one form element # assert_select "form" @@ -342,7 +355,7 @@ # but without distinguishing whether the content is returned in an HTML # or JavaScript. # - # === Examples + # ==== Examples # # # Replacing the element foo. # # page.replace 'foo', ... @@ -454,8 +467,20 @@ # The content of each element is un-encoded, and wrapped in the root # element +encoded+. It then calls the block with all un-encoded elements. # - # === Example + # ==== Examples + # # Selects all bold tags from within the title of an ATOM feed's entries (perhaps to nab a section name prefix) + # assert_select_feed :atom, 1.0 do + # # Select each entry item and then the title item + # assert_select "entry>title" do + # # Run assertions on the encoded title elements + # assert_select_encoded do + # assert_select "b" + # end + # end + # end + # # + # # Selects all paragraph tags from within the description of an RSS feed # assert_select_feed :rss, 2.0 do # # Select description element of each feed item. # assert_select "channel>item>description" do @@ -506,11 +531,19 @@ # You must enable deliveries for this assertion to work, use: # ActionMailer::Base.perform_deliveries = true # - # === Example + # ==== Examples # - # assert_select_email do - # assert_select "h1", "Email alert" - # end + # assert_select_email do + # assert_select "h1", "Email alert" + # end + # + # assert_select_email do + # items = assert_select "ol>li" + # items.each do + # # Work with items here... + # end + # end + # def assert_select_email(&block) deliveries = ActionMailer::Base.deliveries assert !deliveries.empty?, "No e-mail in delivery list" Index: actionpack/lib/action_view/partials.rb =================================================================== --- actionpack/lib/action_view/partials.rb (revision 6813) +++ actionpack/lib/action_view/partials.rb (working copy) @@ -1,17 +1,35 @@ module ActionView - # There's also a convenience method for rendering sub templates within the current controller that depends on a single object - # (we call this kind of sub templates for partials). It relies on the fact that partials should follow the naming convention of being - # prefixed with an underscore -- as to separate them from regular templates that could be rendered on their own. + # Partials are subtemplates that are rendered within the current controller that depend on a single object that is passed in as an + # instance variable. Partials differ from normal subtemplates in that they don't have access to the parent template's environment or + # variables (but you can pass variables in). # - # In a template for Advertiser#account: + # == Partials basics + # Partials are typically used when you're rendering part of a template that relies on a single instance variable, which is passed in as a + # local variable. This variable is named for the partial's name, so if the partial is named book_info, then the instance + # variable will be called @book_info in the parent template and the local book_info in the partial. This means that + # in your view, you need to set @book_info to be whatever value you want to pass to the partial. # + # To separate them from regular templates that could be rendered on their own, partials should follow the naming convention of being + # prefixed with an underscore (_). So, for example, you would have "_login.erb" rather than "login.erb". This naming doesn't affect + # how they're called in code though, so when rendering a partial, only the name is required, not the underscore. + # + # For example, in a template for Advertiser#view_info (advertiser/view_info.erb), you may want to render the advertiser's account + # information through a partial. To do so, you could do something like the following. + # # <%= render :partial => "account" %> # # This would render "advertiser/_account.erb" and pass the instance variable @account in as a local variable +account+ to - # the template for display. + # the template for display. In the partial, then, you could use the account variable as a local. If it were a hash of values, + # it might look something like the following. # - # In another template for Advertiser#buy, we could have: + # Account name: <%= account[:name] %> + # Account number: #<%= account[:number] %> + # Owner: <%= account[:owner] %> # + # === Passing in other local variables + # In addition to the partial-named instance variable, you can also provide a hash of values to be used as local variables in the partial. + # In another part of our advertisement application, in a template for Advertiser#buy, we could have: + # # <%= render :partial => "account", :locals => { :account => @buyer } %> # # <% for ad in @advertisements %> @@ -19,31 +37,36 @@ # <% end %> # # This would first render "advertiser/_account.erb" with @buyer passed in as the local variable +account+, then render - # "advertiser/_ad.erb" and pass the local variable +ad+ to the template for display. + # "advertiser/_ad.erb" and pass the local variable +ad+ to the template for display. You can also pass more than one + # variable in as a local, since you are passing a hash in. # + # <%= render :partial => "account_info", :locals => { :project => get_project(3), :user => current_user } + # + # The above code would pass in project, user, and the instance variable account_info as locals. + # + # === Sharing partials + # Like other templates and subtemplates, two or more controllers can share a set of partials. Rendering them is similar to other + # template types, and looks something like this: + # + # <%= render :partial => "advertisement/ad", :locals => { :ad => @advertisement } %> + # + # This will render the partial "advertisement/_ad.erb" regardless of which controller this is being called from. + # # == Rendering a collection of partials # - # The example of partial use describes a familiar pattern where a template needs to iterate over an array and render a sub - # template for each of the elements. This pattern has been implemented as a single method that accepts an array and renders - # a partial by the same name as the elements contained within. So the three-lined example in "Using partials" can be rewritten - # with a single line: + # A familiar pattern for using partials is when a template needs to iterate over an array and render a sub + # template for each of the elements. As a response, this pattern has been implemented as a single method that accepts an array and renders + # a partial by the same name as the elements contained within. So, rather than using a for loop or some similar construction to iterate + # over elements, rending a partial for each one, you can use the collection parameter for the render method. # # <%= render :partial => "ad", :collection => @advertisements %> # # This will render "advertiser/_ad.erb" and pass the local variable +ad+ to the template for display. An iteration counter - # will automatically be made available to the template with a name of the form +partial_name_counter+. In the case of the - # example above, the template would be fed +ad_counter+. + # will automatically be made available to the template with a name of the form +partial_name_counter+ (for example, the above example + # template would be fed +ad_counter+), you can use that to indicate counts and so on. # - # NOTE: Due to backwards compatibility concerns, the collection can't be one of hashes. Normally you'd also just keep domain objects, - # like Active Records, in there. + # NOTE: Due to backwards compatibility concerns, the collection can't be a collection of hashes. # - # == Rendering shared partials - # - # Two controllers can share a set of partials and render them like this: - # - # <%= render :partial => "advertisement/ad", :locals => { :ad => @advertisement } %> - # - # This will render the partial "advertisement/_ad.erb" regardless of which controller this is being called from. module Partials private # Deprecated, use render :partial Index: actionpack/lib/action_view/helpers/text_helper.rb =================================================================== --- actionpack/lib/action_view/helpers/text_helper.rb (revision 6813) +++ actionpack/lib/action_view/helpers/text_helper.rb (working copy) @@ -3,35 +3,48 @@ module ActionView module Helpers #:nodoc: - # The TextHelper Module provides a set of methods for filtering, formatting - # and transforming strings that can reduce the amount of inline Ruby code in + # The TextHelper module provides a set of methods for filtering, formatting + # and transforming strings, which can reduce the amount of inline Ruby code in # your views. These helper methods extend ActionView making them callable - # within your template files as shown in the following example which truncates - # the title of each post to 10 characters. - # - # <% @posts.each do |post| %> - # # post == 'This is my title' - # Title: <%= truncate(post.title, 10) %> - # <% end %> - # => Title: This is my... + # within your template files. module TextHelper # The preferred method of outputting text in your views is to use the # <%= "text" %> eRuby syntax. The regular _puts_ and _print_ methods # do not operate as expected in an eRuby code block. If you absolutely must - # output text within a code block, you can use the concat method. + # output text within a non-output code block (i.e., <% %>), you can use the concat method. # - # <% concat "hello", binding %> - # is equivalent to using: - # <%= "hello" %> + # ==== Examples + # <% + # concat "hello", binding + # # is the equivalent of <%= "hello" %> + # + # if (logged_in == true): + # concat "Logged in!", binding + # else + # concat link_to('login', :action => login), binding + # end + # # will either display "Logged in!" or a login link + # %> def concat(string, binding) eval(ActionView::Base.erb_variable, binding) << string end # If +text+ is longer than +length+, +text+ will be truncated to the length of - # +length+ and the last three characters will be replaced with the +truncate_string+. + # +length+ (defaults to 30) and the last three characters will be replaced with the +truncate_string+ + # (defaults to "..."). # + # ==== Examples # truncate("Once upon a time in a world far far away", 14) - # => Once upon a... + # # => Once upon a... + # + # truncate("Once upon a time in a world far far away") + # # => Once upon a time in a world f... + # + # truncate("And they found that many people were sleeping better.", 25, "(clipped)") + # # => And they found that many (clipped) + # + # truncate("And they found that many people were sleeping better.", 15, "... (continued)") + # # => And they found... (continued) def truncate(text, length = 30, truncate_string = "...") if text.nil? then return end l = length - truncate_string.chars.length @@ -40,13 +53,21 @@ # Highlights one or more +phrases+ everywhere in +text+ by inserting it into # a +highlighter+ string. The highlighter can be specialized by passing +highlighter+ - # as a single-quoted string with \1 where the phrase is to be inserted. + # as a single-quoted string with \1 where the phrase is to be inserted (defaults to + # '\1') # + # ==== Examples # highlight('You searched for: rails', 'rails') # # => You searched for: rails # + # highlight('You searched for: ruby, rails, dhh', 'actionpack') + # # => You searched for: ruby, rails, dhh + # # highlight('You searched for: rails', ['for', 'rails'], '\1') # # => You searched for: rails + # + # highlight('You searched for: rails', 'rails', "\1") + # # => You searched for: \1') if text.blank? || phrases.blank? text @@ -57,16 +78,26 @@ end # Extracts an excerpt from +text+ that matches the first instance of +phrase+. - # The +radius+ expands the excerpt on each side of +phrase+ by the number of characters - # defined in +radius+. If the excerpt radius overflows the beginning or end of the +text+, + # The +radius+ expands the excerpt on each side of the first occurance of +phrase+ by the number of characters + # defined in +radius+ (which defaults to 100). If the excerpt radius overflows the beginning or end of the +text+, # then the +excerpt_string+ will be prepended/appended accordingly. If the +phrase+ # isn't found, nil is returned. # + # ==== Examples # excerpt('This is an example', 'an', 5) - # => "...s is an examp..." + # # => "...s is an examp..." # # excerpt('This is an example', 'is', 5) - # => "This is an..." + # # => "This is an..." + # + # excerpt('This is an example', 'is') + # # => "This is an example" + # + # excerpt('This next thing is an example', 'ex', 2) + # # => "...next t..." + # + # excerpt('This is also an example', 'an', 8, ' ') + # # => " is also an example" def excerpt(text, phrase, radius = 100, excerpt_string = "...") if text.nil? || phrase.nil? then return end phrase = Regexp.escape(phrase) @@ -89,9 +120,18 @@ # is loaded, it will use the Inflector to determine the plural form, otherwise # it will just add an 's' to the +singular+ word. # - # pluralize(1, 'person') => 1 person - # pluralize(2, 'person') => 2 people - # pluralize(3, 'person', 'users') => 3 users + # ==== Examples + # pluralize(1, 'person') + # # => 1 person + # + # pluralize(2, 'person') + # # => 2 people + # + # pluralize(3, 'person', 'users') + # # => 3 users + # + # pluralize(0, 'person') + # # => 0 people def pluralize(count, singular, plural = nil) "#{count || 0} " + if count == 1 || count == '1' singular @@ -105,10 +145,21 @@ end # Wraps the +text+ into lines no longer than +line_width+ width. This method - # breaks on the first whitespace character that does not exceed +line_width+. + # breaks on the first whitespace character that does not exceed +line_width+ + # (which is 80 by default). # + # ==== Examples # word_wrap('Once upon a time', 4) - # => Once\nupon\na\ntime + # # => Once\nupon\na\ntime + # + # word_wrap('Once upon a time', 8) + # # => Once upon\na time + # + # word_wrap('Once upon a time') + # # => Once upon a time + # + # word_wrap('Once upon a time', 1) + # # => Once\nupon\na\ntime def word_wrap(text, line_width = 80) text.gsub(/\n/, "\n\n").gsub(/(.{1,#{line_width}})(\s+|$)/, "\\1\n").strip end @@ -116,9 +167,24 @@ begin require_library_or_gem "redcloth" unless Object.const_defined?(:RedCloth) - # Returns the text with all the Textile codes turned into HTML tags. + # Returns the text with all the Textile[http://www.textism.com/tools/textile] codes turned into HTML tags. + # + # You can learn more about Textile's syntax at its website[http://www.textism.com/tools/textile]. # This method is only available if RedCloth[http://whytheluckystiff.net/ruby/redcloth/] # is available. + # + # ==== Examples + # textilize("*This is Textile!* Rejoice!") + # # => "

This is Textile! Rejoice!

" + # + # textilize("I _love_ ROR(Ruby on Rails)!") + # # => "

I love ROR!

" + # + # textilize("h2. Textile makes markup -easy- simple!") + # # => "

Textile makes markup easy simple!

" + # + # textilize("Visit the Rails website "here":http://www.rubyonrails.org/.) + # # => "

Visit the Rails website here.

" def textilize(text) if text.blank? "" @@ -131,8 +197,23 @@ # Returns the text with all the Textile codes turned into HTML tags, # but without the bounding

tag that RedCloth adds. + # + # You can learn more about Textile's syntax at its website[http://www.textism.com/tools/textile]. # This method is only available if RedCloth[http://whytheluckystiff.net/ruby/redcloth/] # is available. + # + # ==== Examples + # textilize_without_paragraph("*This is Textile!* Rejoice!") + # # => "This is Textile! Rejoice!" + # + # textilize_without_paragraph("I _love_ ROR(Ruby on Rails)!") + # # => "I love ROR!" + # + # textilize_without_paragraph("h2. Textile makes markup -easy- simple!") + # # => "

Textile makes markup easy simple!

" + # + # textilize_without_paragraph("Visit the Rails website "here":http://www.rubyonrails.org/.) + # # => "Visit the Rails website here." def textilize_without_paragraph(text) textiled = textilize(text) if textiled[0..2] == "

" then textiled = textiled[3..-1] end @@ -149,6 +230,20 @@ # Returns the text with all the Markdown codes turned into HTML tags. # This method is only available if BlueCloth[http://www.deveiate.org/projects/BlueCloth] # is available. + # + # ==== Examples + # markdown("We are using __Markdown__ now!") + # # => "

We are using Markdown now!

" + # + # markdown("We like to _write_ `code`, not just _read_ it!") + # # => "

We like to write code, not just read it!

" + # + # markdown("The [Markdown website](http://daringfireball.net/projects/markdown/) has more information.") + # # => "

The Markdown website + # # has more information.

" + # + # markdown('![The ROR logo](http://rubyonrails.com/images/rails.png "Ruby on Rails")') + # # => '

The ROR logo

' def markdown(text) text.blank? ? "" : BlueCloth.new(text).to_html end @@ -161,6 +256,20 @@ # paragraph and wrapped in

tags. One newline (\n) is # considered as a linebreak and a
tag is appended. This # method does not remove the newlines from the +text+. + # + # ==== Examples + # my_text = """Here is some basic text... + # ...with a line break.""" + # + # simple_format(my_text) + # # => "

Here is some basic text...
...with a line break.

" + # + # more_text = """We want to put a paragraph... + # + # ...right there.""" + # + # simple_format(more_text) + # # => "

We want to put a paragraph...

...right there.

" def simple_format(text) content_tag 'p', text.to_s. gsub(/\r\n?/, "\n"). # \r\n and \r -> \n @@ -168,21 +277,31 @@ gsub(/([^\n]\n)(?=[^\n])/, '\1
') # 1 newline -> br end - # Turns all urls and email addresses into clickable links. The +link+ parameter - # will limit what should be linked. You can add html attributes to the links using + # Turns all URLs and e-mail addresses into clickable links. The +link+ parameter + # will limit what should be linked. You can add HTML attributes to the links using # +href_options+. Options for +link+ are :all (default), - # :email_addresses, and :urls. + # :email_addresses, and :urls. If a block is given, each URL and + # e-mail address is yielded and the result is used as the link text. # - # auto_link("Go to http://www.rubyonrails.org and say hello to david@loudthinking.com") => - # Go to http://www.rubyonrails.org and - # say hello to david@loudthinking.com + # ==== Examples + # auto_link("Go to http://www.rubyonrails.org and say hello to david@loudthinking.com") + # # => "Go to http://www.rubyonrails.org and + # # say hello to david@loudthinking.com" # - # If a block is given, each url and email address is yielded and the - # result is used as the link text. + # auto_link("Visit http://www.loudthinking.com/ or e-mail david@loudthinking.com", :urls) + # # => "Visit http://www.loudthinking.com/ + # # or e-mail david@loudthinking.com" # - # auto_link(post.body, :all, :target => '_blank') do |text| + # auto_link("Visit http://www.loudthinking.com/ or e-mail david@loudthinking.com", :email_addresses) + # # => "Visit http://www.loudthinking.com/ or e-mail david@loudthinking.com" + # + # post_body = "Welcome to my new blog at http://www.myblog.com/. Please e-mail me at me@email.com." + # auto_link(post_body, :all, :target => '_blank') do |text| # truncate(text, 15) # end + # # => "Welcome to my new blog at http://www.m.... + # Please e-mail me at me@email.com." + # def auto_link(text, link = :all, href_options = {}, &block) return '' if text.blank? case link @@ -192,10 +311,17 @@ end end - # Strips link tags from +text+ leaving just the link label. + # Strips all link tags from +text+ leaving just the link text. # + # ==== Examples # strip_links('Ruby on Rails') - # => Ruby on Rails + # # => Ruby on Rails + # + # strip_links('Please e-mail me at me@email.com.') + # # => Please e-mail me at me@email.com. + # + # strip_links('Blog: Visit.') + # # => Blog: Visit def strip_links(text) text.gsub(/(.*?)<\/a>/mi, '\1') end @@ -204,15 +330,23 @@ VERBOTEN_ATTRS = /^on/i unless defined?(VERBOTEN_ATTRS) # Sanitizes the +html+ by converting
and ') - # => <script> do_nasty_stuff() </script> + # # => <script> do_nasty_stuff() </script> + # # sanitize('Click here for $100') - # => Click here for $100 + # # => Click here for $100 + # + # sanitize('Click here!!!') + # # => Click here!!! + # + # sanitize('') + # # => def sanitize(html) # only do this if absolutely necessary if html.index("<") @@ -248,6 +382,16 @@ # Strips all HTML tags from the +html+, including comments. This uses the # html-scanner tokenizer and so its HTML parsing ability is limited by # that of html-scanner. + # + # ==== Examples + # strip_tags("Strip these tags!") + # # => Strip these tags! + # + # strip_tags("Bold no more! See more here...") + # # => Bold no more! See more here... + # + # strip_tags("
Welcome to my website!
") + # # => Welcome to my website! def strip_tags(html) return html if html.blank? if html.index("<") @@ -269,25 +413,34 @@ # Creates a Cycle object whose _to_s_ method cycles through elements of an # array every time it is called. This can be used for example, to alternate - # classes for table rows: + # classes for table rows. You can use named cycles to allow nesting in loops. + # Passing a Hash as the last parameter with a :name key will create a + # named cycle. You can manually reset a cycle by calling reset_cycle and passing the + # name of the cycle. # + # ==== Examples + # # Alternate CSS classes for even and odd numbers... + # @items = [1,2,3,4] + # # <% @items.each do |item| %> # "> # # # <% end %> + #
item
# - # You can use named cycles to allow nesting in loops. Passing a Hash as - # the last parameter with a :name key will create a named cycle. - # You can manually reset a cycle by calling reset_cycle and passing the - # name of the cycle. # + # # Cycle CSS classes for rows, and text colors for values within each row + # @items = x = [{:first => 'Robert', :middle => 'Daniel', :last => 'James'}, + # {:first => 'Emily', :middle => 'Shannon', :maiden => 'Pike', :last => 'Hicks'}, + # {:first => 'June', :middle => 'Dae', :last => 'Jones'}] # <% @items.each do |item| %> # "row_class") # # <% item.values.each do |value| %> + # # "colors") -%>"> - # value + # <%= value %> # # <% end %> # <% reset_cycle("colors") %> @@ -312,6 +465,23 @@ # Resets a cycle so that it starts from the first element the next time # it is called. Pass in +name+ to reset a named cycle. + # + # ==== Example + # # Alternate CSS classes for even and odd numbers... + # @items = [[1,2,3,4], [5,6,3], [3,4,5,6,7,4]] + # + # <% @items.each do |item| %> + # "> + # <% item.each do |value| %> + # "colors") -%>"> + # <%= value %> + # + # <% end %> + # + # <% reset_cycle("colors") %> + # + # <% end %> + #
def reset_cycle(name = "default") cycle = get_cycle(name) cycle.reset unless cycle.nil? Index: actionpack/lib/action_view/helpers/number_helper.rb =================================================================== --- actionpack/lib/action_view/helpers/number_helper.rb (revision 6813) +++ actionpack/lib/action_view/helpers/number_helper.rb (working copy) @@ -4,19 +4,25 @@ # Methods are provided for phone numbers, currency, percentage, # precision, positional notation, and file size. module NumberHelper - # Formats a +number+ into a US phone number. You can customize the format + # Formats a +number+ into a US phone number (e.g., (555) 123-9876). You can customize the format # in the +options+ hash. + # + # ==== Options # * :area_code - Adds parentheses around the area code. - # * :delimiter - Specifies the delimiter to use, defaults to "-". + # * :delimiter - Specifies the delimiter to use (defaults to "-"). # * :extension - Specifies an extension to add to the end of the - # generated number + # generated number. # * :country_code - Sets the country code for the phone number. # - # number_to_phone(1235551234) => 123-555-1234 - # number_to_phone(1235551234, :area_code => true) => (123) 555-1234 - # number_to_phone(1235551234, :delimiter => " ") => 123 555 1234 - # number_to_phone(1235551234, :area_code => true, :extension => 555) => (123) 555-1234 x 555 - # number_to_phone(1235551234, :country_code => 1) + # ==== Examples + # number_to_phone(1235551234) # => 123-555-1234 + # number_to_phone(1235551234, :area_code => true) # => (123) 555-1234 + # number_to_phone(1235551234, :delimiter => " ") # => 123 555 1234 + # number_to_phone(1235551234, :area_code => true, :extension => 555) # => (123) 555-1234 x 555 + # number_to_phone(1235551234, :country_code => 1) # => +1-123-555-1234 + # + # number_to_phone(1235551234, :country_code => 1, :extension => 1343, :delimeter => ".") + # => +1.123.555.1234 x 1343 def number_to_phone(number, options = {}) number = number.to_s.strip unless number.nil? options = options.stringify_keys @@ -40,18 +46,22 @@ end end - # Formats a +number+ into a currency string. You can customize the format + # Formats a +number+ into a currency string (e.g., $13.65). You can customize the format # in the +options+ hash. - # * :precision - Sets the level of precision, defaults to 2 - # * :unit - Sets the denomination of the currency, defaults to "$" - # * :separator - Sets the separator between the units, defaults to "." - # * :delimiter - Sets the thousands delimiter, defaults to "," # - # number_to_currency(1234567890.50) => $1,234,567,890.50 - # number_to_currency(1234567890.506) => $1,234,567,890.51 - # number_to_currency(1234567890.506, :precision => 3) => $1,234,567,890.506 + # ==== Options + # * :precision - Sets the level of precision (defaults to 2). + # * :unit - Sets the denomination of the currency (defaults to "$"). + # * :separator - Sets the separator between the units (defaults to "."). + # * :delimiter - Sets the thousands delimiter (defaults to ","). + # + # ==== Examples + # number_to_currency(1234567890.50) # => $1,234,567,890.50 + # number_to_currency(1234567890.506) # => $1,234,567,890.51 + # number_to_currency(1234567890.506, :precision => 3) # => $1,234,567,890.506 + # # number_to_currency(1234567890.50, :unit => "£", :separator => ",", :delimiter => "") - # => £1234567890,50 + # # => £1234567890,50 def number_to_currency(number, options = {}) options = options.stringify_keys precision = options["precision"] || 2 @@ -67,14 +77,19 @@ end end - # Formats a +number+ as a percentage string. You can customize the + # Formats a +number+ as a percentage string (e.g., 65%). You can customize the # format in the +options+ hash. - # * :precision - Sets the level of precision, defaults to 3 - # * :separator - Sets the separator between the units, defaults to "." # - # number_to_percentage(100) => 100.000% - # number_to_percentage(100, {:precision => 0}) => 100% - # number_to_percentage(302.0574, {:precision => 2}) => 302.06% + # ==== Options + # * :precision - Sets the level of precision (defaults to 3). + # * :separator - Sets the separator between the units (defaults to "."). + # + # ==== Examples + # number_to_percentage(100) # => 100.000% + # number_to_percentage(100, :precision => 0) # => 100% + # + # number_to_percentage(302.24398923423, :precision => 5) + # # => 302.24399% def number_to_percentage(number, options = {}) options = options.stringify_keys precision = options["precision"] || 3 @@ -93,14 +108,20 @@ end end - # Formats a +number+ with grouped thousands using +delimiter+. You + # Formats a +number+ with grouped thousands using +delimiter+ (e.g., 12,324). You # can customize the format using optional delimiter and separator parameters. - # * delimiter - Sets the thousands delimiter, defaults to "," - # * separator - Sets the separator between the units, defaults to "." # - # number_with_delimiter(12345678) => 12,345,678 - # number_with_delimiter(12345678.05) => 12,345,678.05 - # number_with_delimiter(12345678, ".") => 12.345.678 + # ==== Options + # * delimiter - Sets the thousands delimiter (defaults to ","). + # * separator - Sets the separator between the units (defaults to "."). + # + # ==== Examples + # number_with_delimiter(12345678) # => 12,345,678 + # number_with_delimiter(12345678.05) # => 12,345,678.05 + # number_with_delimiter(12345678, ".") # => 12.345.678 + # + # number_with_delimiter(98765432.98, " ", ",") + # # => 98 765 432,98 def number_with_delimiter(number, delimiter=",", separator=".") begin parts = number.to_s.split('.') @@ -111,29 +132,35 @@ end end - # Formats a +number+ with the specified level of +precision+. The default + # Formats a +number+ with the specified level of +precision+ (e.g., 112.32 has a precision of 2). The default # level of precision is 3. # - # number_with_precision(111.2345) => 111.235 - # number_with_precision(111.2345, 2) => 111.24 + # ==== Examples + # number_with_precision(111.2345) # => 111.235 + # number_with_precision(111.2345, 2) # => 111.24 + # number_with_precision(13, 5) # => 13.00000 + # number_with_precision(389.32314, 0) # => 389 def number_with_precision(number, precision=3) "%01.#{precision}f" % number rescue number end - # Formats the bytes in +size+ into a more understandable representation. - # Useful for reporting file sizes to users. This method returns nil if + # Formats the bytes in +size+ into a more understandable representation + # (e.g., giving it 1500 yields 1.5 KB). This method is useful for + # reporting file sizes to users. This method returns nil if # +size+ cannot be converted into a number. You can change the default - # precision of 1 in +precision+. + # precision of 1 using the precision parameter +precision+. # - # number_to_human_size(123) => 123 Bytes - # number_to_human_size(1234) => 1.2 KB - # number_to_human_size(12345) => 12.1 KB - # number_to_human_size(1234567) => 1.2 MB - # number_to_human_size(1234567890) => 1.1 GB - # number_to_human_size(1234567890123) => 1.1 TB - # number_to_human_size(1234567, 2) => 1.18 MB + # ==== Examples + # number_to_human_size(123) # => 123 Bytes + # number_to_human_size(1234) # => 1.2 KB + # number_to_human_size(12345) # => 12.1 KB + # number_to_human_size(1234567) # => 1.2 MB + # number_to_human_size(1234567890) # => 1.1 GB + # number_to_human_size(1234567890123) # => 1.1 TB + # number_to_human_size(1234567, 2) # => 1.18 MB + # number_to_human_size(483989, 0) # => 4 MB def number_to_human_size(size, precision=1) size = Kernel.Float(size) case Index: actionpack/lib/action_view/helpers/pagination_helper.rb =================================================================== --- actionpack/lib/action_view/helpers/pagination_helper.rb (revision 6813) +++ actionpack/lib/action_view/helpers/pagination_helper.rb (working copy) @@ -1,11 +1,9 @@ module ActionView module Helpers - # Provides methods for linking to ActionController::Pagination objects. + # Provides methods for linking to ActionController::Pagination objects using a simple generator API. You can optionally + # also build your links manually using ActionView::Helpers::AssetHelper#link_to like so: # - # You can also build your links manually, like in this example: - # # <%= link_to "Previous page", { :page => paginator.current.previous } if paginator.current.previous %> - # # <%= link_to "Next page", { :page => paginator.current.next } if paginator.current.next %> module PaginationHelper unless const_defined?(:DEFAULT_OPTIONS) @@ -18,10 +16,11 @@ } end - # Creates a basic HTML link bar for the given +paginator+. - # +html_options+ are passed to +link_to+. + # Creates a basic HTML link bar for the given +paginator+. Links will be created + # for the next and/or previous page and for a number of other pages around the current + # pages position. The +html_options+ hash is passed to +link_to+ when the links are created. # - # +options+ are: + # ==== Options # :name:: the routing name for this paginator # (defaults to +page+) # :window_size:: the number of pages to show around @@ -34,6 +33,25 @@ # +false+) # :params:: any additional routing parameters # for page URLs + # + # ==== Examples + # # We'll assume we have a paginator setup in @person_pages... + # + # pagination_links(@person_pages) + # # => 1 2 3 ... 10 + # + # pagination_links(@person_pages, :link_to_current_page => true) + # # => 1 2 3 ... 10 + # + # pagination_links(@person_pages, :always_show_anchors => false) + # # => 1 2 3 + # + # pagination_links(@person_pages, :window_size => 1) + # # => 1 2 ... 10 + # + # pagination_links(@person_pages, :params => { :viewer => "flash" }) + # # => 1 2 3 ... + # # 10 def pagination_links(paginator, options={}, html_options={}) name = options[:name] || DEFAULT_OPTIONS[:name] params = (options[:params] || DEFAULT_OPTIONS[:params]).clone @@ -46,6 +64,26 @@ # Iterate through the pages of a given +paginator+, invoking a # block for each page number that needs to be rendered as a link. + # + # ==== Options + # :window_size:: the number of pages to show around + # the current page (defaults to +2+) + # :always_show_anchors:: whether or not the first and last + # pages should always be shown + # (defaults to +true+) + # :link_to_current_page:: whether or not the current page + # should be linked to (defaults to + # +false+) + # + # ==== Example + # # Turn paginated links into an Ajax call + # pagination_links_each(paginator, page_options) do |link| + # options = { :url => {:action => 'list'}, :update => 'results' } + # html_options = { :href => url_for(:action => 'list') } + # + # link_to_remote(link.to_s, options, html_options) + # end + end def pagination_links_each(paginator, options) options = DEFAULT_OPTIONS.merge(options) link_to_current_page = options[:link_to_current_page] Index: actionpack/lib/action_view/helpers/benchmark_helper.rb =================================================================== --- actionpack/lib/action_view/helpers/benchmark_helper.rb (revision 6813) +++ actionpack/lib/action_view/helpers/benchmark_helper.rb (working copy) @@ -2,17 +2,24 @@ module ActionView module Helpers + # This helper offers a method to measure the execution time of a block + # in a template. module BenchmarkHelper - # Measures the execution time of a block in a template and reports the result to the log. Example: + # 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. For example, let's say you thought your file + # processing method was taking too long; you could wrap it in a benchmark block. # - # <% benchmark "Notes section" do %> - # <%= expensive_notes_operation %> + # <% benchmark "Process data files" do %> + # <%= expensive_files_operation %> # <% end %> # - # Will add something like "Notes section (0.34523)" to the log. + # That would add something like "Process data files (0.34523)" to the log, + # which you can then use to compare timings when optimizing your code. # # You may give an optional logger level as the second argument - # (:debug, :info, :warn, :error). The default is :info. + # (:debug, :info, :warn, :error); the default value is :info. def benchmark(message = "Benchmarking", level = :info) if @logger real = Benchmark.realtime { yield } Index: actionpack/lib/action_view/helpers/form_tag_helper.rb =================================================================== --- actionpack/lib/action_view/helpers/form_tag_helper.rb (revision 6813) +++ actionpack/lib/action_view/helpers/form_tag_helper.rb (working copy) @@ -3,33 +3,37 @@ module ActionView module Helpers - # Provides a number of methods for creating form tags that doesn't rely on conventions with an object assigned to the template like - # FormHelper does. With the FormTagHelper, you provide the names and values yourself. + # Provides a number of methods for creating form tags that doesn't rely on an ActiveRecord object assigned to the template like + # FormHelper does. Instead, you provide the names and values manually. # - # NOTE: The html options disabled, readonly, and multiple can all be treated as booleans. So specifying :disabled => true - # will give disabled="disabled". + # NOTE: The HTML options disabled, readonly, and multiple can all be treated as booleans. So specifying + # :disabled => true will give disabled="disabled". module FormTagHelper # Starts a form tag that points the action to an url configured with url_for_options just like # ActionController::Base#url_for. The method for the form defaults to POST. # - # Examples: - # * form_tag('/posts') => - # * form_tag('/posts/1', :method => :put) => - # * form_tag('/upload', :multipart => true) => + # ==== Options + # * :multipart - If set to true, the enctype is set to "multipart/form-data". + # * :method - The method to use when submitting the form, usually either "get" or "post". + # If "put", "delete", or another verb is used, a hidden input with name _method + # is added to simulate the verb over post. + # * A list of parameters to feed to the URL the form will be posted to. + # + # ==== Examples + # form_tag('/posts') + # # => + # + # form_tag('/posts/1', :method => :put) + # # => + # + # form_tag('/upload', :multipart => true) + # # => # - # ERb example: # <% form_tag '/posts' do -%> #
<%= submit_tag 'Save' %>
# <% end -%> + # # =>
# - # Will output: - #
- # - # Options: - # * :multipart - If set to true, the enctype is set to "multipart/form-data". - # * :method - The method to use when submitting the form, usually either "get" or "post". - # If "put", "delete", or another verb is used, a hidden input with name _method - # is added to simulate the verb over post. def form_tag(url_for_options = {}, options = {}, *parameters_for_url, &block) html_options = html_options_for_form(url_for_options, options, *parameters_for_url) if block_given? @@ -39,45 +43,104 @@ end end - # Creates a dropdown selection box, or if the :multiple option is set to true, a multiple # choice selection box. # # Helpers::FormOptions can be used to create common select boxes such as countries, time zones, or - # associated records. + # associated records. option_tags is a string containing the option tags for the select box. # - # option_tags is a string containing the option tags for the select box: - # # Outputs + # ==== Options + # * :multiple - If set to true the selection will allow multiple choices. + # * :disabled - If set to true, the user will not be able to use this input. + # * Any other key creates standard HTML attributes for the tag. + # + # ==== Examples # select_tag "people", "" + # # => # - # Options: - # * :multiple - If set to true the selection will allow multiple choices. + # select_tag "count", "" + # # => + # + # select_tag "colors", "", :multiple => true + # # => + # + # select_tag "locations", "" + # # => + # + # select_tag "access", "", :multiple => true, :class => 'form_input' + # # => + # + # select_tag "destination", "", :disabled => true + # # => + # def select_tag(name, option_tags = nil, options = {}) content_tag :select, option_tags, { "name" => name, "id" => name }.update(options.stringify_keys) end - # Creates a standard text field. + # Creates a standard text field; use these text fields to input smaller chunks of text like a username + # or a search query. # - # Options: + # ==== Options # * :disabled - If set to true, the user will not be able to use this input. # * :size - The number of visible characters that will fit in the input. # * :maxlength - The maximum number of characters that the browser will allow the user to enter. + # * Any other key creates standard HTML attributes for the tag. # - # A hash of standard HTML options for the tag. + # ==== Examples + # text_field_tag 'name' + # # => + # + # text_field_tag 'query', 'Enter your search query here' + # # => + # + # text_field_tag 'request', nil, :class => 'special_input' + # # => + # + # text_field_tag 'address', '', :size => 75 + # # => + # + # text_field_tag 'zip', nil, :maxlength => 5 + # # => + # + # text_field_tag 'payment_amount', '$0.00', :disabled => true + # # => + # + # text_field_tag 'ip', '0.0.0.0', :maxlength => 15, :size => 20, :class => "ip-input" + # # => + # def text_field_tag(name, value = nil, options = {}) tag :input, { "type" => "text", "name" => name, "id" => name, "value" => value }.update(options.stringify_keys) end - # Creates a hidden field. + # Creates a hidden form input field used to transmit data that would be lost due to HTTP's statelessness or + # data that should be hidden from the user. # - # Takes the same options as text_field_tag + # ==== Options + # * Creates standard HTML attributes for the tag. + # + # ==== Examples + # hidden_field_tag 'tags_list' + # # => + # + # hidden_field_tag 'token', 'VUBJKB23UIVI1UU1VOBVI@' + # # => + # + # hidden_field_tag 'collected_input', '', :onchange => "alert('Input collected!')" + # # => + # def hidden_field_tag(name, value = nil, options = {}) text_field_tag(name, value, options.stringify_keys.update("type" => "hidden")) end - # 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: # - # If you are using file uploads then you will also need to set the multipart option for the form: # <%= form_tag { :action => "post" }, { :multipart => true } %> # <%= file_field_tag "file" %> # <%= submit_tag %> @@ -85,23 +148,96 @@ # # The specified URL will then be passed a File object containing the selected file, or if the field # was left blank, a StringIO object. + # + # ==== Options + # * Creates standard HTML attributes for the tag. + # * :disabled - If set to true, the user will not be able to use this input. + # + # ==== Examples + # file_field_tag 'attachment' + # # => + # + # file_field_tag 'avatar', :class => 'profile-input' + # # => + # + # file_field_tag 'picture', :disabled => true + # # => + # + # file_field_tag 'resume', :value => '~/resume.doc' + # # => + # + # file_field_tag 'user_pic', :accept => 'image/png,image/gif,image/jpeg' + # # => + # + # file_field_tag 'file', :accept => 'text/html', :class => 'upload', :value => 'index.html' + # # => + # def file_field_tag(name, options = {}) text_field_tag(name, nil, options.update("type" => "file")) end - # Creates a password field. + # Creates a password field, a masked text field that will hide the users input behind a mask character. # - # Takes the same options as text_field_tag + # ==== Options + # * :disabled - If set to true, the user will not be able to use this input. + # * :size - The number of visible characters that will fit in the input. + # * :maxlength - The maximum number of characters that the browser will allow the user to enter. + # * Any other key creates standard HTML attributes for the tag. + # + # ==== Examples + # password_field_tag 'pass' + # # => + # + # password_field_tag 'secret', 'Your secret here' + # # => + # + # password_field_tag 'masked', nil, :class => 'masked_input_field' + # # => + # + # password_field_tag 'token', '', :size => 15 + # # => + # + # password_field_tag 'key', nil, :maxlength => 16 + # # => + # + # password_field_tag 'confirm_pass', nil, :disabled => true + # # => + # + # password_field_tag 'pin', '1234', :maxlength => 4, :size => 6, :class => "pin-input" + # # => + # def password_field_tag(name = "password", value = nil, options = {}) text_field_tag(name, value, options.update("type" => "password")) end - # Creates a text input area. + # Creates a text input area; use a textarea for longer text inputs such as blog posts or descriptions. # - # Options: - # * :size - A string specifying the dimensions of the textarea. - # # Outputs - # <%= text_area_tag "body", nil, :size => "25x10" %> + # ==== Options + # * :size - A string specifying the dimensions of the textarea using dimensions (e.g., "25x10"). + # * :rows - Specify the number of rows in the textarea + # * :cols - Specify the number of columns in the textarea + # * :disabled - If set to true, the user will not be able to use this input. + # * Any other key creates standard HTML attributes for the tag. + # + # ==== Examples + # text_area_tag 'post' + # # => + # + # text_area_tag 'bio', @user.bio + # # => + # + # text_area_tag 'body', nil, :rows => 10, :cols => 25 + # # => + # + # text_area_tag 'body', nil, :size => "25x10" + # # => + # + # text_area_tag 'description', "Description goes here.", :disabled => true + # # => + # + # text_area_tag 'comment', nil, :class => 'comment_input' + # # => + # def text_area_tag(name, content = nil, options = {}) options.stringify_keys! @@ -112,14 +248,54 @@ content_tag :textarea, content, { "name" => name, "id" => name }.update(options.stringify_keys) end - # Creates a check box. + # Creates a check box form input tag. + # + # ==== Options + # * :disabled - If set to true, the user will not be able to use this input. + # * Any other key creates standard HTML options for the tag. + # + # ==== Examples + # check_box_tag 'accept' + # # => + # + # check_box_tag 'rock', 'rock music' + # # => + # + # check_box_tag 'receive_email', 'yes', true + # # => + # + # check_box_tag 'tos', 'yes', false, :class => 'accept_tos' + # # => + # + # check_box_tag 'eula', 'accepted', false, :disabled => true + # # => + # def check_box_tag(name, value = "1", checked = false, options = {}) html_options = { "type" => "checkbox", "name" => name, "id" => name, "value" => value }.update(options.stringify_keys) html_options["checked"] = "checked" if checked tag :input, html_options end - # Creates a radio button. + # Creates a radio button; use groups of radio buttons named the same to allow users to + # select from a group of options. + # + # ==== Options + # * :disabled - If set to true, the user will not be able to use this input. + # * Any other key creates standard HTML options for the tag. + # + # ==== Examples + # radio_button_tag 'gender', 'male' + # # => + # + # radio_button_tag 'receive_updates', 'no', true + # # => + # + # radio_button_tag 'time_slot', "3:00 p.m.", false, :disabled => true + # # => + # + # radio_button_tag 'color', "green", true, :class => "color_input" + # # => + # def radio_button_tag(name, value, checked = false, options = {}) pretty_tag_value = value.to_s.gsub(/\s/, "_").gsub(/(?!-)\W/, "").downcase html_options = { "type" => "radio", "name" => name, "id" => "#{name}_#{pretty_tag_value}", "value" => value }.update(options.stringify_keys) @@ -127,8 +303,34 @@ tag :input, html_options end - # Creates a submit button with the text value as the caption. If options contains a pair with the key of "disable_with", - # then the value will be used to rename a disabled version of the submit button. + # Creates a submit button with the text value as the caption. + # + # ==== Options + # * :disabled - If set to true, the user will not be able to use this input. + # * :disable_with - Value of this parameter will be used as the value for a disabled version + # of the submit button when the form is submitted. + # * Any other key creates standard HTML options for the tag. + # + # ==== Examples + # submit_tag + # # => + # + # submit_tag "Edit this article" + # # => + # + # submit_tag "Save edits", :disabled => true + # # => + # + # submit_tag "Complete sale", :disable_with => "Please wait..." + # # => + # + # submit_tag nil, :class => "form_submit" + # # => + # + # submit_tag "Edit", :disable_width => "Editing...", :class => 'edit-button' + # # => + # def submit_tag(value = "Save changes", options = {}) options.stringify_keys! @@ -150,6 +352,24 @@ # Displays an image which when clicked will submit the form. # # source is passed to AssetTagHelper#image_path + # + # ==== Options + # * :disabled - If set to true, the user will not be able to use this input. + # * Any other key creates standard HTML options for the tag. + # + # ==== Examples + # image_submit_tag("login.png") + # # => + # + # image_submit_tag("purchase.png"), :disabled => true + # # => + # + # image_submit_tag("search.png"), :class => 'search-button' + # # => + # + # image_submit_tag("agree.png"), :disabled => true, :class => "agree-disagree-button" + # # => + # def image_submit_tag(source, options = {}) tag :input, { "type" => "image", "src" => image_path(source) }.update(options.stringify_keys) end Index: actionpack/lib/action_view/helpers/scriptaculous_helper.rb =================================================================== --- actionpack/lib/action_view/helpers/scriptaculous_helper.rb (revision 6813) +++ actionpack/lib/action_view/helpers/scriptaculous_helper.rb (working copy) @@ -2,31 +2,63 @@ module ActionView module Helpers - # Provides a set of helpers for calling Scriptaculous JavaScript - # functions, including those which create Ajax controls and visual effects. - # - # To be able to use these helpers, you must include the Prototype + # Scriptaculous[http://script.aculo.us] is a JavaScript library that provides a set of functions + # for creating Ajax controls and visual effects. This helper provides a + # set of methods for calling these Scriptaculous functions using Ruby code + # to generate the JavaScript. + # + # === Usage + # To be able to use these helpers, you must first include the Prototype # JavaScript framework and the Scriptaculous JavaScript library in your - # pages. See the documentation for ActionView::Helpers::JavaScriptHelper - # for more information on including the necessary JavaScript. + # pages. # - # The Scriptaculous helpers' behavior can be tweaked with various options. - # See the documentation at http://script.aculo.us for more information on - # using these helpers in your application. + # <%= + # javascript_include_tag 'prototype' + # javascript_include_tag 'scriptaculous' + # %> + # + # (See the documentation for ActionView::Helpers::JavaScriptHelper + # for more information on including this and other JavaScript files) + # + # Once those are included, you are able to use Ruby to generate Scriptaculous + # calls. For example, let's say you wanted to highlight a shopping cart's total + # after an item had been added to it over Ajax. You could do something like this: + # + # <%= + # # Generates: Add to cart + # link_to_remote "Add to cart", :update => "total", + # :url => { :action => "add_to_cart" }, + # :complete => visual_effect(:highlight, "total", :duration => 0.75) + # %> + # + # The visual_effect method allows you to use various visual effects built-in to Scriptaculous + # (in this case, a faint, fading highlight); see the visual_effect method's documentation for more information. + # + # ScriptaculousHelper's behavior can be tweaked using the +js_options+ parameter. + # See the documentation at http://script.aculo.us for more information. module ScriptaculousHelper unless const_defined? :TOGGLE_EFFECTS TOGGLE_EFFECTS = [:toggle_appear, :toggle_slide, :toggle_blind] end - # Returns a JavaScript snippet to be used on the Ajax callbacks for - # starting visual effects. + # The Scriptaculous visual effects library has a number of effects built-in, such as changing opacity, highlighting, + # pulsating, fading out, and so on (see the documentation[http://wiki.script.aculo.us/scriptaculous/show/VisualEffects] for + # the visual effects for more information). The visual_effect method allow you to use these visual effects in Ajax callbacks + # by returning a JavaScript snippet to be used as the callback. # # Example: - # <%= link_to_remote "Reload", :update => "posts", + # <%= + # # Generates: Reload + # link_to_remote "Reload", :update => "posts", # :url => { :action => "reload" }, - # :complete => visual_effect(:highlight, "posts", :duration => 0.5) + # :complete => visual_effect(:highlight, "posts", :duration => 0.5) + # %> # - # If no element_id is given, it assumes "element" which should be a local + # If no +element_id+ is given, it assumes +element+ which should be a local # variable in the generated JavaScript execution context. This can be # used for example with drop_receiving_element: # @@ -35,11 +67,11 @@ # This would fade the element that was dropped on the drop receiving # element. # - # For toggling visual effects, you can use :toggle_appear, :toggle_slide, and - # :toggle_blind which will alternate between appear/fade, slidedown/slideup, and - # blinddown/blindup respectively. + # For toggling visual effects, you can use :toggle_appear, :toggle_slide, and + # :toggle_blind in the +js_options+ parameter which will alternate between appear/fade, slidedown/slideup, and + # blinddown/blindup, respectively. # - # You can change the behaviour with various options, see + # You can change the behaviour with various options; see # http://script.aculo.us for more documentation. def visual_effect(name, element_id = false, js_options = {}) element = element_id ? element_id.to_json : "element" @@ -57,24 +89,28 @@ end end - # Makes the element with the DOM ID specified by +element_id+ sortable - # by drag-and-drop and make an Ajax call whenever the sort order has - # changed. By default, the action called gets the serialized sortable + # Scriptaculous allows you to make container elements (for example,