diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/obsolete.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/obsolete.rb index 22b0a126ca..def663b233 100644 --- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/obsolete.rb +++ b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/obsolete.rb @@ -1,6 +1,6 @@ =begin rdoc -= Obsolete methods that are depriciated += Obsolete methods that are deprecated If you really want to see them, go to lib/tmail/obsolete.rb and view to your heart's content. diff --git a/actionpack/lib/action_controller/base/http_authentication.rb b/actionpack/lib/action_controller/base/http_authentication.rb index 2519f55269..525787bf92 100644 --- a/actionpack/lib/action_controller/base/http_authentication.rb +++ b/actionpack/lib/action_controller/base/http_authentication.rb @@ -276,7 +276,7 @@ module ActionController # # The nonce is opaque to the client. Composed of Time, and hash of Time with secret # key from the Rails session secret generated upon creation of project. Ensures - # the time cannot be modifed by client. + # the time cannot be modified by client. def nonce(time = Time.now) t = time.to_i hashed = [t, secret_key] diff --git a/actionpack/lib/action_controller/base/request_forgery_protection.rb b/actionpack/lib/action_controller/base/request_forgery_protection.rb index 6ba86cd0be..ad06657f86 100644 --- a/actionpack/lib/action_controller/base/request_forgery_protection.rb +++ b/actionpack/lib/action_controller/base/request_forgery_protection.rb @@ -106,8 +106,7 @@ module ActionController #:nodoc: !request.content_type.nil? && request.content_type.verify_request? end - # Sets the token value for the current session. Pass a :secret option - # in +protect_from_forgery+ to add a custom salt to the hash. + # Sets the token value for the current session. def form_authenticity_token session[:_csrf_token] ||= ActiveSupport::SecureRandom.base64(32) end diff --git a/actionpack/lib/action_controller/routing.rb b/actionpack/lib/action_controller/routing.rb index ce59866531..5b9ded83dd 100644 --- a/actionpack/lib/action_controller/routing.rb +++ b/actionpack/lib/action_controller/routing.rb @@ -139,7 +139,7 @@ module ActionController # # In routes.rb # map.with_options :controller => 'blog' do |blog| # blog.show '', :action => 'list' - # blog.delete 'delete/:id', :action => 'delete', + # blog.delete 'delete/:id', :action => 'delete' # blog.edit 'edit/:id', :action => 'edit' # end # diff --git a/actionpack/lib/action_controller/routing/generation/url_rewriter.rb b/actionpack/lib/action_controller/routing/generation/url_rewriter.rb index 16720b915b..9717582b5e 100644 --- a/actionpack/lib/action_controller/routing/generation/url_rewriter.rb +++ b/actionpack/lib/action_controller/routing/generation/url_rewriter.rb @@ -93,7 +93,7 @@ module ActionController # # * :only_path - If true, the relative url is returned. Defaults to +false+. # * :protocol - The protocol to connect to. Defaults to 'http'. - # * :host - Specifies the host the link should be targetted at. + # * :host - Specifies the host the link should be targeted at. # If :only_path is false, this option must be # provided either explicitly, or via +default_url_options+. # * :port - Optionally specify the port to connect to. diff --git a/actionpack/lib/action_controller/routing/route_set.rb b/actionpack/lib/action_controller/routing/route_set.rb index f5a4b1e1db..040a7e2cb6 100644 --- a/actionpack/lib/action_controller/routing/route_set.rb +++ b/actionpack/lib/action_controller/routing/route_set.rb @@ -155,7 +155,7 @@ module ActionController def define_url_helper(route, name, kind, options) selector = url_helper_name(name, kind) - # The segment keys used for positional paramters + # The segment keys used for positional parameters hash_access_method = hash_access_name(name, kind) diff --git a/actionpack/lib/action_controller/testing/test_case.rb b/actionpack/lib/action_controller/testing/test_case.rb index 7b4eda58e5..a11755b517 100644 --- a/actionpack/lib/action_controller/testing/test_case.rb +++ b/actionpack/lib/action_controller/testing/test_case.rb @@ -56,7 +56,7 @@ module ActionController # # ActionController::TestCase will automatically infer the controller under test # from the test class name. If the controller cannot be inferred from the test - # class name, you can explicity set it with +tests+. + # class name, you can explicitly set it with +tests+. # # class SpecialEdgeCaseWidgetsControllerTest < ActionController::TestCase # tests WidgetController @@ -182,7 +182,7 @@ module ActionController @controller.send(:initialize_current_url) end end - + # Cause the action to be rescued according to the regular rules for rescue_action when the visitor is not local def rescue_action_in_public! @request.remote_addr = '208.77.188.166' # example.com diff --git a/actionpack/lib/action_view/helpers/date_helper.rb b/actionpack/lib/action_view/helpers/date_helper.rb index 72fe9a3232..332743d55b 100644 --- a/actionpack/lib/action_view/helpers/date_helper.rb +++ b/actionpack/lib/action_view/helpers/date_helper.rb @@ -112,12 +112,12 @@ module ActionView # ==== Options # * :use_month_numbers - Set to true if you want to use month numbers rather than month names (e.g. # "2" instead of "February"). - # * :use_short_month - Set to true if you want to use the abbreviated month name instead of the full - # name (e.g. "Feb" instead of "February"). - # * :add_month_number - Set to true if you want to show both, the month's number and name (e.g. + # * :use_short_month - Set to true if you want to use abbreviated month names instead of full + # month names (e.g. "Feb" instead of "February"). + # * :add_month_numbers - Set to true if you want to use both month numbers and month names (e.g. # "2 - February" instead of "February"). # * :use_month_names - Set to an array with 12 month names if you want to customize month names. - # Note: You can also use Rails' new i18n functionality for this. + # Note: You can also use Rails' i18n functionality for this. # * :date_separator - Specifies a string to separate the date fields. Default is "" (i.e. nothing). # * :start_year - Set the start year for the year select. Default is Time.now.year - 5. # * :end_year - Set the end year for the year select. Default is Time.now.year + 5. @@ -128,7 +128,7 @@ module ActionView # as a hidden field instead of showing a select field. Also note that this implicitly sets :discard_day to true. # * :discard_year - Set to true if you don't want to show a year select. This includes the year # as a hidden field instead of showing a select field. - # * :order - Set to an array containing :day, :month and :year do + # * :order - Set to an array containing :day, :month and :year to # customize the order in which the select fields are shown. If you leave out any of the symbols, the respective # select will not be shown (like when you set :discard_xxx => true. Defaults to the order defined in # the respective locale (e.g. [:year, :month, :day] in the en locale that ships with Rails). diff --git a/actionpack/lib/action_view/helpers/form_options_helper.rb b/actionpack/lib/action_view/helpers/form_options_helper.rb index 6adbab175f..8cb5882aab 100644 --- a/actionpack/lib/action_view/helpers/form_options_helper.rb +++ b/actionpack/lib/action_view/helpers/form_options_helper.rb @@ -167,31 +167,31 @@ module ActionView # # In addition to the :include_blank option documented above, # this method also supports a :model option, which defaults - # to TimeZone. This may be used by users to specify a different time - # zone model object. (See +time_zone_options_for_select+ for more - # information.) + # to ActiveSupport::TimeZone. This may be used by users to specify a + # different time zone model object. (See +time_zone_options_for_select+ + # for more information.) # - # You can also supply an array of TimeZone objects + # You can also supply an array of ActiveSupport::TimeZone objects # as +priority_zones+, so that they will be listed above the rest of the - # (long) list. (You can use TimeZone.us_zones as a convenience for - # obtaining a list of the US time zones, or a Regexp to select the zones + # (long) list. (You can use ActiveSupport::TimeZone.us_zones as a convenience + # for obtaining a list of the US time zones, or a Regexp to select the zones # of your choice) # # Finally, this method supports a :default option, which selects - # a default TimeZone if the object's time zone is +nil+. + # a default ActiveSupport::TimeZone if the object's time zone is +nil+. # # Examples: # time_zone_select( "user", "time_zone", nil, :include_blank => true) # # time_zone_select( "user", "time_zone", nil, :default => "Pacific Time (US & Canada)" ) # - # time_zone_select( "user", 'time_zone', TimeZone.us_zones, :default => "Pacific Time (US & Canada)") + # time_zone_select( "user", 'time_zone', ActiveSupport::TimeZone.us_zones, :default => "Pacific Time (US & Canada)") # - # time_zone_select( "user", 'time_zone', [ TimeZone['Alaska'], TimeZone['Hawaii'] ]) + # time_zone_select( "user", 'time_zone', [ ActiveSupport::TimeZone['Alaska'], ActiveSupport::TimeZone['Hawaii'] ]) # # time_zone_select( "user", 'time_zone', /Australia/) # - # time_zone_select( "user", "time_zone", TZInfo::Timezone.all.sort, :model => TZInfo::Timezone) + # time_zone_select( "user", "time_zone", ActiveSupport::Timezone.all.sort, :model => ActiveSupport::Timezone) def time_zone_select(object, method, priority_zones = nil, options = {}, html_options = {}) InstanceTag.new(object, method, self, options.delete(:object)).to_time_zone_select_tag(priority_zones, options, html_options) end @@ -393,20 +393,20 @@ module ActionView end # Returns a string of option tags for pretty much any time zone in the - # world. Supply a TimeZone name as +selected+ to have it marked as the - # selected option tag. You can also supply an array of TimeZone objects - # as +priority_zones+, so that they will be listed above the rest of the - # (long) list. (You can use TimeZone.us_zones as a convenience for - # obtaining a list of the US time zones, or a Regexp to select the zones - # of your choice) + # world. Supply a ActiveSupport::TimeZone name as +selected+ to have it + # marked as the selected option tag. You can also supply an array of + # ActiveSupport::TimeZone objects as +priority_zones+, so that they will + # be listed above the rest of the (long) list. (You can use + # ActiveSupport::TimeZone.us_zones as a convenience for obtaining a list + # of the US time zones, or a Regexp to select the zones of your choice) # # The +selected+ parameter must be either +nil+, or a string that names - # a TimeZone. + # a ActiveSupport::TimeZone. # - # By default, +model+ is the TimeZone constant (which can be obtained - # in Active Record as a value object). The only requirement is that the - # +model+ parameter be an object that responds to +all+, and returns - # an array of objects that represent time zones. + # By default, +model+ is the ActiveSupport::TimeZone constant (which can + # be obtained in Active Record as a value object). The only requirement + # is that the +model+ parameter be an object that responds to +all+, and + # returns an array of objects that represent time zones. # # NOTE: Only the option tags are returned, you have to wrap this call in # a regular HTML select tag. diff --git a/actionpack/lib/action_view/helpers/text_helper.rb b/actionpack/lib/action_view/helpers/text_helper.rb index ad0733a7e1..c3ce4c671e 100644 --- a/actionpack/lib/action_view/helpers/text_helper.rb +++ b/actionpack/lib/action_view/helpers/text_helper.rb @@ -436,7 +436,7 @@ module ActionView end # Returns the current cycle string after a cycle has been started. Useful - # for complex table highlighing or any other design need which requires + # for complex table highlighting or any other design need which requires # the current cycle string in more than one place. # # ==== Example @@ -544,7 +544,7 @@ module ActionView left, right = $`, $' # detect already linked URLs and URLs in the middle of a tag if left =~ /<[^>]+$/ && right =~ /^[^>]*>/ - # do not change string; URL is alreay linked + # do not change string; URL is already linked href else # don't include trailing punctuation character as part of the URL diff --git a/actionpack/lib/action_view/helpers/url_helper.rb b/actionpack/lib/action_view/helpers/url_helper.rb index de864f453c..c5a6d1f084 100644 --- a/actionpack/lib/action_view/helpers/url_helper.rb +++ b/actionpack/lib/action_view/helpers/url_helper.rb @@ -12,11 +12,11 @@ module ActionView # Returns the URL for the set of +options+ provided. This takes the # same options as +url_for+ in Action Controller (see the - # documentation for ActionController::Base#url_for). Note that by default - # :only_path is true so you'll get the relative /controller/action - # instead of the fully qualified URL like http://example.com/controller/action. + # documentation for ActionController::Base#url_for). Note that by default + # :only_path is true so you'll get the relative "/controller/action" + # instead of the fully qualified URL like "http://example.com/controller/action". # - # When called from a view, url_for returns an HTML escaped url. If you + # When called from a view, +url_for+ returns an HTML escaped url. If you # need an unescaped url, pass :escape => false in the +options+. # # ==== Options @@ -34,8 +34,8 @@ module ActionView # # If you instead of a hash pass a record (like an Active Record or Active Resource) as the options parameter, # you'll trigger the named route for that record. The lookup will happen on the name of the class. So passing - # a Workshop object will attempt to use the workshop_path route. If you have a nested route, such as - # admin_workshop_path you'll have to call that explicitly (it's impossible for url_for to guess that route). + # a Workshop object will attempt to use the +workshop_path+ route. If you have a nested route, such as + # +admin_workshop_path+ you'll have to call that explicitly (it's impossible for +url_for+ to guess that route). # # ==== Examples # <%= url_for(:action => 'index') %> @@ -97,10 +97,10 @@ module ActionView # Creates a link tag of the given +name+ using a URL created by the set # of +options+. See the valid options in the documentation for - # url_for. It's also possible to pass a string instead + # +url_for+. It's also possible to pass a string instead # of an options hash to get a link tag that uses the value of the string as the # href for the link, or use :back to link to the referrer - a JavaScript back - # link will be used in place of a referrer if none exists. If nil is passed as + # link will be used in place of a referrer if none exists. If +nil+ is passed as # a name, the link itself will become the name. # # ==== Signatures @@ -117,27 +117,22 @@ module ActionView # * :popup => true || array of window options - This will force the # link to open in a popup window. By passing true, a default browser window # will be opened with the URL. You can also specify an array of options - # that are passed-thru to JavaScripts window.open method. + # that are passed to the window.open JavaScript call. # * :method => symbol of HTTP verb - This modifier will dynamically # create an HTML form and immediately submit the form for processing using # the HTTP verb specified. Useful for having links perform a POST operation # in dangerous actions like deleting a record (which search bots can follow # while spidering your site). Supported verbs are :post, :delete and :put. # Note that if the user has JavaScript disabled, the request will fall back - # to using GET. If you are relying on the POST behavior, you should check - # for it in your controller's action by using the request object's methods - # for post?, delete? or put?. + # to using GET. If :href => '#' is used and the user has JavaScript + # disabled clicking the link will have no effect. If you are relying on the + # POST behavior, you should check for it in your controller's action by using + # the request object's methods for post?, delete? or put?. # * The +html_options+ will accept a hash of html attributes for the link tag. # - # Note that if the user has JavaScript disabled, the request will fall back - # to using GET. If :href => '#' is used and the user has JavaScript disabled - # clicking the link will have no effect. If you are relying on the POST - # behavior, your should check for it in your controller's action by using the - # request object's methods for post?, delete? or put?. - # # You can mix and match the +html_options+ with the exception of - # :popup and :method which will raise an ActionView::ActionViewError - # exception. + # :popup and :method which will raise an + # ActionView::ActionViewError exception. # # ==== Examples # Because it relies on +url_for+, +link_to+ supports both older-style controller/action/id arguments @@ -170,9 +165,11 @@ module ActionView # You can use a block as well if your link target is hard to fit into the name parameter. ERb example: # # <% link_to(@profile) do %> - # <%= @profile.name %> -- Check it out!! + # <%= @profile.name %> -- Check it out! # <% end %> - # # => David -- Check it out!! + # # => + # David -- Check it out! + # # # Classes and ids for CSS are easy to produce: # @@ -215,7 +212,9 @@ module ActionView # # => Delete Image + # m.setAttribute('value', 'delete');var s = document.createElement('input'); s.setAttribute('type', 'hidden'); + # s.setAttribute('name', 'authenticity_token'); s.setAttribute('value', 'Q/ttlxPYZ6R77B+vZ1sBkhj21G2isO9dpE6UtOHBApg='); + # f.appendChild(s)f.appendChild(m);f.submit(); };return false;">Delete Image def link_to(*args, &block) if block_given? options = args.first || {} @@ -246,21 +245,21 @@ module ActionView # by the set of +options+. This is the safest method to ensure links that # cause changes to your data are not triggered by search bots or accelerators. # If the HTML button does not work with your layout, you can also consider - # using the link_to method with the :method modifier as described in - # the link_to documentation. + # using the +link_to+ method with the :method modifier as described in + # the +link_to+ documentation. # - # The generated FORM element has a class name of button-to + # The generated form element has a class name of button-to # to allow styling of the form itself and its children. You can control # the form submission and input element behavior using +html_options+. # This method accepts the :method and :confirm modifiers - # described in the link_to documentation. If no :method modifier + # described in the +link_to+ documentation. If no :method modifier # is given, it will default to performing a POST operation. You can also # disable the button by passing :disabled => true in +html_options+. # If you are using RESTful routes, you can pass the :method # to change the HTTP verb used to submit the form. # # ==== Options - # The +options+ hash accepts the same options at url_for. + # The +options+ hash accepts the same options as url_for. # # There are a few special +html_options+: # * :method - Specifies the anchor name to be appended to the path. @@ -317,7 +316,7 @@ module ActionView # Creates a link tag of the given +name+ using a URL created by the set of # +options+ unless the current request URI is the same as the links, in # which case only the name is returned (or the given block is yielded, if - # one exists). You can give link_to_unless_current a block which will + # one exists). You can give +link_to_unless_current+ a block which will # specialize the default behavior (e.g., show a "Start Here" link rather # than the link's text). # @@ -343,7 +342,7 @@ module ActionView #
Hello, Rails!
@@ -400,7 +402,7 @@ Now you're ready to start working with posts. To do that, navigate to +http://lo
This is the result of Rails rendering the +index+ view of your posts. There aren't currently any posts in the database, but if you click the +New Post+ link you can create one. After that, you'll find that you can edit posts, look at their details, or destroy them. All of the logic and HTML to handle this was built by the single +script/generate scaffold+ command.
-TIP. In development mode (which is what you're working in by default), Rails reloads your application with every browser request, so there's no need to stop and restart the web server.
+TIP: In development mode (which is what you're working in by default), Rails reloads your application with every browser request, so there's no need to stop and restart the web server.
Congratulations, you're riding the rails! Now it's time to see how it all works.
@@ -461,7 +463,7 @@ The easiest place to start looking at functionality is with the code that lists
def index
- @posts = Post.find(:all)
+ @posts = Post.all
respond_to do |format|
format.html # index.html.erb
@@ -486,7 +488,7 @@ The +respond_to+ block handles both HTML and XML calls to this action. If you br
Content
-<% for post in @posts %>
+<% @posts.each do |post| %>
<%=h post.name %>
<%=h post.title %>
@@ -508,9 +510,9 @@ This view iterates over the contents of the +@posts+ array to display content an
* +h+ is a Rails helper method to sanitize displayed data, preventing cross-site scripting attacks
* +link_to+ builds a hyperlink to a particular destination
-* +edit_post_path+ is a helper that Rails provides as part of RESTful routing. You’ll see a variety of these helpers for the different actions that the controller includes.
+* +edit_post_path+ is a helper that Rails provides as part of RESTful routing. You'll see a variety of these helpers for the different actions that the controller includes.
-TIP. For more details on the rendering process, see "Layouts and Rendering in Rails":layouts_and_rendering.html.
+TIP: For more details on the rendering process, see "Layouts and Rendering in Rails":layouts_and_rendering.html.
h4. Customizing the Layout
@@ -582,7 +584,7 @@ The +new.html.erb+ view displays this empty Post to the user:
<%= link_to 'Back', posts_path %>
-The +form_for+ block is used to create an HTML form. Within this block, you have access to methods to build various controls on the form. For example, +f.text_field :name+ tells Rails to create a text input on the form, and to hook it up to the +name+ attribute of the instance being displayed. You can only use these methods with attributes of the model that the form is based on (in this case +name+, +title+, and +content+). Rails uses +form_for+ in preference to having your write raw HTML because the code is more succinct, and because it explicitly ties the form to a particular model instance.
+The +form_for+ block is used to create an HTML form. Within this block, you have access to methods to build various controls on the form. For example, +f.text_field :name+ tells Rails to create a text input on the form, and to hook it up to the +name+ attribute of the instance being displayed. You can only use these methods with attributes of the model that the form is based on (in this case +name+, +title+, and +content+). Rails uses +form_for+ in preference to having you write raw HTML because the code is more succinct, and because it explicitly ties the form to a particular model instance.
TIP: If you need to create an HTML form that displays arbitrary fields, not tied to a model, you should use the +form_tag+ method, which provides shortcuts for building forms that are not necessarily tied to a model instance.
@@ -609,7 +611,7 @@ end
The +create+ action instantiates a new Post object from the data supplied by the user on the form, which Rails makes available in the +params+ hash. After saving the new post, it uses +flash[:notice]+ to create an informational message for the user, and redirects to the show action for the post. If there's any problem, the +create+ action just shows the +new+ view a second time, with any error messages.
-Rails provides the +flash+ hash (usually just called the Flash) so that messages can be carried over to another action, providing the user with useful information on the status of their request. In the case of +create+, the user never actually sees any page rendered during the Post creation process, because it immediately redirects to the new Post as soon Rails saves the record. The Flash carries over a message to the next action, so that when the user is redirected back to the +show+ action, they are presented with a message saying "Post was successfully created."
+Rails provides the +flash+ hash (usually just called the Flash) so that messages can be carried over to another action, providing the user with useful information on the status of their request. In the case of +create+, the user never actually sees any page rendered during the Post creation process, because it immediately redirects to the new Post as soon Rails saves the record. The Flash carries over a message to the next action, so that when the user is redirected back to the +show+ action, they are presented with a message saying "Post was successfully created."
h4. Showing an Individual Post
@@ -710,7 +712,7 @@ end
In the +update+ action, Rails first uses the +:id+ parameter passed back from the edit view to locate the database record that's being edited. The +update_attributes+ call then takes the rest of the parameters from the request and applies them to this record. If all goes well, the user is redirected to the post's +show+ view. If there are any problems, it's back to +edit+ to correct them.
-NOTE. Sharp-eyed readers will have noticed that the +form_for+ declaration is identical for the +new+ and +edit+ views. Rails generates different code for the two forms because it's smart enough to notice that in the one case it's being passed a new record that has never been saved, and in the other case an existing record that has already been saved to the database. In a production Rails application, you would ordinarily eliminate this duplication by moving identical code to a _partial template_, which you could then include in both parent templates. But the scaffold generator tries not to make too many assumptions, and generates code that’s easy to modify if you want different forms for +create+ and +edit+.
+NOTE. Sharp-eyed readers will have noticed that the +form_for+ declaration is identical for the +new+ and +edit+ views. Rails generates different code for the two forms because it's smart enough to notice that in the one case it's being passed a new record that has never been saved, and in the other case an existing record that has already been saved to the database. In a production Rails application, you would ordinarily eliminate this duplication by moving identical code to a _partial template_, which you could then include in both parent templates. But the scaffold generator tries not to make too many assumptions, and generates code that's easy to modify if you want different forms for +create+ and +edit+.
h4. Destroying a Post
@@ -732,7 +734,7 @@ The +destroy+ method of an Active Record model instance removes the correspondin
h3. DRYing up the Code
-At this point, it’s worth looking at some of the tools that Rails provides to eliminate duplication in your code. In particular, you can use _partials_ to clean up duplication in views and _filters_ to help with duplication in controllers.
+At this point, it's worth looking at some of the tools that Rails provides to eliminate duplication in your code. In particular, you can use _partials_ to clean up duplication in views and _filters_ to help with duplication in controllers.
h4. Using Partials to Eliminate View Duplication
@@ -740,13 +742,13 @@ As you saw earlier, the scaffold-generated views for the +new+ and +edit+ action
new.html.erb:
-
+
New post
<%= render :partial => "form" %>
<%= link_to 'Back', posts_path %>
-
+
edit.html.erb:
@@ -785,11 +787,11 @@ As you saw earlier, the scaffold-generated views for the +new+ and +edit+ action
Now, when Rails renders the +new+ or +edit+ view, it will insert the +_form+ partial at the indicated point. Note the naming convention for partials: if you refer to a partial named +form+ inside of a view, the corresponding file is +_form.html.erb+, with a leading underscore.
-For more information on partials, refer to the "Layouts and Rending in Rails":layouts_and_rendering.html guide.
+For more information on partials, refer to the "Layouts and Rendering in Rails":layouts_and_rendering.html#using-partials guide.
h4. Using Filters to Eliminate Controller Duplication
-At this point, if you look at the controller for posts, you’ll see some duplication:
+At this point, if you look at the controller for posts, you'll see some duplication:
class PostsController < ApplicationController
@@ -815,7 +817,7 @@ class PostsController < ApplicationController
end
-Four instances of the exact same line of code doesn’t seem very DRY. Rails provides _filters_ as a way to address this sort of repeated code. In this case, you can DRY things up by using a +before_filter+:
+Four instances of the exact same line of code doesn't seem very DRY. Rails provides _filters_ as a way to address this sort of repeated code. In this case, you can DRY things up by using a +before_filter+:
class PostsController < ApplicationController
@@ -837,10 +839,10 @@ class PostsController < ApplicationController
# ...
end
- private
- def find_post
- @post = Post.find(params[:id])
- end
+private
+ def find_post
+ @post = Post.find(params[:id])
+ end
end
@@ -944,7 +946,7 @@ map.resources :posts, :has_many => :comments
This creates +comments+ as a _nested resource_ within +posts+. This is another part of capturing the hierarchical relationship that exists between posts and comments.
-TIP: For more information on routing, see the "Rails Routing from the Outside In":routing_outside_in.html guide.
+TIP: For more information on routing, see the "Rails Routing from the Outside In":routing.html guide.
h4. Generating a Controller
@@ -954,7 +956,7 @@ With the model in hand, you can turn your attention to creating a matching contr
$ script/generate controller Comments index show new edit
-This creates seven files:
+This creates eight files:
* +app/controllers/comments_controller.rb+ - The controller
* +app/helpers/comments_helper.rb+ - A view helper file
@@ -963,6 +965,7 @@ This creates seven files:
* +app/views/comments/new.html.erb+ - The view for the new action
* +app/views/comments/edit.html.erb+ - The view for the edit action
* +test/functional/comments_controller_test.rb+ - The functional tests for the controller
+* +test/unit/helpers/comments_helper_test.rb+ - The unit tests for the helper
The controller will be generated with empty methods and views for each action that you specified in the call to +script/generate controller+:
@@ -987,23 +990,21 @@ You'll need to flesh this out with code to actually process requests appropriate
class CommentsController < ApplicationController
+ before_filter :find_post
+
def index
- @post = Post.find(params[:post_id])
@comments = @post.comments
end
def show
- @post = Post.find(params[:post_id])
@comment = @post.comments.find(params[:id])
end
def new
- @post = Post.find(params[:post_id])
@comment = @post.comments.build
end
def create
- @post = Post.find(params[:post_id])
@comment = @post.comments.build(params[:comment])
if @comment.save
redirect_to post_comment_url(@post, @comment)
@@ -1013,12 +1014,10 @@ class CommentsController < ApplicationController
end
def edit
- @post = Post.find(params[:post_id])
@comment = @post.comments.find(params[:id])
end
def update
- @post = Post.find(params[:post_id])
@comment = Comment.find(params[:id])
if @comment.update_attributes(params[:comment])
redirect_to post_comment_url(@post, @comment)
@@ -1028,14 +1027,14 @@ class CommentsController < ApplicationController
end
def destroy
- @post = Post.find(params[:post_id])
@comment = Comment.find(params[:id])
@comment.destroy
+ redirect_to post_comments_path(@post)
+ end
- respond_to do |format|
- format.html { redirect_to post_comments_path(@post) }
- format.xml { head :ok }
- end
+private
+ def find_post
+ @post = Post.find(params[:post_id])
end
end
@@ -1198,6 +1197,18 @@ As a next step, I'll modify the +views/posts/show.html.erb+ view to show the com
Note that each post has its own individual comments collection, accessible as +@post.comments+. That's a consequence of the declarative associations in the models. Path helpers such as +post_comments_path+ come from the nested route declaration in +config/routes.rb+.
+h4. Deleting Associated Objects
+
+If you decide at some point to delete a post, you likely want to delete the comments associated with that post as well. You can do so by taking advantage of the association option +dependent+. All you need to do is modify the +post.rb+ as follows:
+
+
+class Post < ActiveRecord::Base
+ validates_presence_of :name, :title
+ validates_length_of :title, :minimum => 5
+ has_many :comments, :dependent => :destroy
+end
+
+
h3. Building a Multi-Model Form
Comments and posts are edited on two separate forms - which makes sense, given the flow of this mini-application. But what if you want to edit more than one thing on a single form? Rails 2.3 offers new support for nested forms. Let's add support for giving each post multiple tags, right in the form where you create the post. First, create a new model to hold the tags:
@@ -1212,7 +1223,7 @@ Run the migration to create the database table:
$ rake db:migrate
-Next, edit the +post.rb+ file to create the other side of the association, and to tell Rails that you intend to edit tags via posts:
+Next, edit the +post.rb+ file to create the other side of the association, and to tell Rails (via the +accepts_nested_attributes+ macro) that you intend to edit tags via posts:
class Post < ActiveRecord::Base
@@ -1221,7 +1232,7 @@ class Post < ActiveRecord::Base
has_many :comments
has_many :tags
- accepts_nested_attributes_for :tags, :allow_destroy => :true ,
+ accepts_nested_attributes_for :tags, :allow_destroy => :true,
:reject_if => proc { |attrs| attrs.all? { |k, v| v.blank? } }
end
@@ -1240,7 +1251,7 @@ You'll also need to modify +views/posts/_form.html.erb+ to include the tags:
<%= post_form.text_field :name %>
- <%= post_form.label :title, "title" %>
+ <%= post_form.label :title, "Title" %>
<%= post_form.text_field :title %>
@@ -1277,17 +1288,19 @@ Now that you've seen your first Rails application, you should feel free to updat
* The "Ruby On Rails guides":http://guides.rubyonrails.org
* The "Ruby on Rails mailing list":http://groups.google.com/group/rubyonrails-talk
-* The #rubyonrails channel on irc.freenode.net
+* The "#rubyonrails":irc://irc.freenode.net/#rubyonrails channel on irc.freenode.net
+* The "Rails Wiki":http://wiki.rubyonrails.org/
Rails also comes with built-in help that you can generate using the rake command-line utility:
-* Running +rake doc:guides+ will put a full copy of the Rails Guides in the +/doc/guides+ folder of your application. Open +/doc/guides/index.html+ in your web browser to explore the Guides.
-* Running +rake doc:rails+ will put a full copy of the API documentation for Rails in the +/doc/api+ folder of your application. Open +/doc/api/index.html+ in your web browser to explore the API documentation.
+* Running +rake doc:guides+ will put a full copy of the Rails Guides in the +doc/guides+ folder of your application. Open +doc/guides/index.html+ in your web browser to explore the Guides.
+* Running +rake doc:rails+ will put a full copy of the API documentation for Rails in the +doc/api+ folder of your application. Open +doc/api/index.html+ in your web browser to explore the API documentation.
h3. Changelog
"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/2
+* July 18, 2009: Minor cleanup in anticipation of Rails 2.3.3 by "Mike Gunderloy":credits.html#mgunderloy
* February 1, 2009: Updated for Rails 2.3 by "Mike Gunderloy":credits.html#mgunderloy
* November 3, 2008: Formatting patch from Dave Rothlisberger
* November 1, 2008: First approved version by "Mike Gunderloy":credits.html#mgunderloy
diff --git a/railties/guides/source/i18n.textile b/railties/guides/source/i18n.textile
index 103ccb1c7a..b588656821 100644
--- a/railties/guides/source/i18n.textile
+++ b/railties/guides/source/i18n.textile
@@ -97,7 +97,7 @@ The *translations load path* (+I18n.load_path+) is just a Ruby Array of paths to
NOTE: The backend will lazy-load these translations when a translation is looked up for the first time. This makes it possible to just swap the backend with something else even after translations have already been announced.
-The default +environment.rb+ files has instruction how to add locales from another directory and how to set a different default locale. Just uncomment and edit the specific lines.
+The default +environment.rb+ files has instructions on how to add locales from another directory and how to set a different default locale. Just uncomment and edit the specific lines.
# The internationalization framework can be changed
@@ -114,7 +114,7 @@ For the sake of completeness, let's mention that if you do not want to use the +
To tell the I18n library where it can find your custom translation files you can specify the load path anywhere in your application - just make sure it gets run before any translations are actually looked up. You might also want to change the default locale. The simplest thing possible is to put the following into an initializer:
-# in config/initializer/locale.rb
+# in config/initializers/locale.rb
# tell the I18n library where to find your translations
I18n.load_path << Dir[ File.join(RAILS_ROOT, 'lib', 'locale',
@@ -142,61 +142,28 @@ def set_locale
end
-This requires you to pass the locale as a URL query parameter as in +http://example.com/books?locale=pt+. (This is, for example, Google's approach.) So +http://localhost:3000?locale=pt+ will load the Portugese localization, whereas +http://localhost:3000?locale=de+ would load the German localization, and so on. You may skip the next section and head over to the *Internationalize your application* section, if you want to try things out by manually placing the locale in the URL and reloading the page.
+This requires you to pass the locale as a URL query parameter as in +http://example.com/books?locale=pt+. (This is, for example, Google's approach.) So +http://localhost:3000?locale=pt+ will load the Portuguese localization, whereas +http://localhost:3000?locale=de+ would load the German localization, and so on. You may skip the next section and head over to the *Internationalize your application* section, if you want to try things out by manually placing the locale in the URL and reloading the page.
Of course, you probably don't want to manually include the locale in every URL all over your application, or want the URLs look differently, e.g. the usual +http://example.com/pt/books+ versus +http://example.com/en/books+. Let's discuss the different options you have.
-IMPORTANT: The following examples rely on having available locales loaded into your application as an array of strings like +["en", "es", "gr"]+. This is not included in the current version of Rails 2.2 -- the forthcoming Rails version 2.3 will contain the easy accessor +available_locales+. (See "this commit":http://github.com/svenfuchs/i18n/commit/411f8fe7c8f3f89e9b6b921fa62ed66cb92f3af4 and background at "Rails I18n Wiki":http://rails-i18n.org/wiki/pages/i18n-available_locales.)
-
-So, for having available locales easily accessible in Rails 2.2, we have to include this support manually in an initializer, like this:
-
-
-# config/initializers/available_locales.rb
-#
-# Get loaded locales conveniently
-# See http://rails-i18n.org/wiki/pages/i18n-available_locales
-module I18n
- class << self
- def available_locales; backend.available_locales; end
- end
- module Backend
- class Simple
- def available_locales; translations.keys.collect { |l| l.to_s }.sort; end
- end
- end
-end
-
-# You need to "force-initialize" loaded locales
-I18n.backend.send(:init_translations)
-
-AVAILABLE_LOCALES = I18n.backend.available_locales
-RAILS_DEFAULT_LOGGER.debug "* Loaded locales: #{AVAILABLE_LOCALES.inspect}"
-
-
-You can then wrap the constant for easy access in ApplicationController:
-
-
-class ApplicationController < ActionController::Base
- def available_locales; AVAILABLE_LOCALES; end
-end
-
-
h4. Setting the Locale from the Domain Name
One option you have is to set the locale from the domain name where your application runs. For example, we want +www.example.com+ to load the English (or default) locale, and +www.example.es+ to load the Spanish locale. Thus the _top-level domain name_ is used for locale setting. This has several advantages:
-* The locale is an _obvious_ part of the URL
-* People intuitively grasp in which language the content will be displayed
-* It is very trivial to implement in Rails
-* Search engines seem to like that content in different languages lives at different, inter-linked domains
+* The locale is an _obvious_ part of the URL.
+* People intuitively grasp in which language the content will be displayed.
+* It is very trivial to implement in Rails.
+* Search engines seem to like that content in different languages lives at different, inter-linked domains.
-You can implement it like this in your ApplicationController:
+You can implement it like this in your +ApplicationController+:
before_filter :set_locale
+
def set_locale
I18n.locale = extract_locale_from_uri
end
+
# Get locale from top-level domain or return nil if such locale is not available
# You have to put something like:
# 127.0.0.1 application.com
@@ -205,7 +172,7 @@ end
# in your /etc/hosts file to try this out locally
def extract_locale_from_tld
parsed_locale = request.host.split('.').last
- (available_locales.include? parsed_locale) ? parsed_locale : nil
+ I18n.available_locales.include?(parsed_locale.to_sym) ? parsed_locale : nil
end
@@ -218,7 +185,7 @@ We can also set the locale from the _subdomain_ in a very similar way:
# in your /etc/hosts file to try this out locally
def extract_locale_from_subdomain
parsed_locale = request.subdomains.first
- (available_locales.include? parsed_locale) ? parsed_locale : nil
+ I18n.available_locales.include?(parsed_locale.to_sym) ? parsed_locale : nil
end
@@ -276,11 +243,11 @@ map.dashboard '/:locale', :controller => "dashboard"
Do take special care about the *order of your routes*, so this route declaration does not "eat" other ones. (You may want to add it directly before the +map.root+ declaration.)
-IMPORTANT: This solution has currently one rather big *downside*. Due to the _default_url_options_ implementation, you have to pass the +:id+ option explicitely, like this: +link_to 'Show', book_url(:id => book)+ and not depend on Rails' magic in code like +link_to 'Show', book+. If this should be a problem, have a look at two plugins which simplify work with routes in this way: Sven Fuchs's "routing_filter":http://github.com/svenfuchs/routing-filter/tree/master and Raul Murciano's "translate_routes":http://github.com/raul/translate_routes/tree/master. See also the page "How to encode the current locale in the URL":http://rails-i18n.org/wiki/pages/how-to-encode-the-current-locale-in-the-url in the Rails i18n Wiki.
+IMPORTANT: This solution has currently one rather big *downside*. Due to the _default_url_options_ implementation, you have to pass the +:id+ option explicitly, like this: +link_to 'Show', book_url(:id => book)+ and not depend on Rails' magic in code like +link_to 'Show', book+. If this should be a problem, have a look at two plugins which simplify work with routes in this way: Sven Fuchs's "routing_filter":http://github.com/svenfuchs/routing-filter/tree/master and Raul Murciano's "translate_routes":http://github.com/raul/translate_routes/tree/master. See also the page "How to encode the current locale in the URL":http://rails-i18n.org/wiki/pages/how-to-encode-the-current-locale-in-the-url in the Rails i18n Wiki.
h4. Setting the Locale from the Client Supplied Information
-In specific cases, it would make sense to set the locale from client-supplied information, i.e. not from the URL. This information may come for example from the users' prefered language (set in their browser), can be based on the users' geographical location inferred from their IP, or users can provide it simply by choosing the locale in your application interface and saving it to their profile. This approach is more suitable for web-based applications or services, not for websites -- see the box about _sessions_, _cookies_ and RESTful architecture above.
+In specific cases, it would make sense to set the locale from client-supplied information, i.e. not from the URL. This information may come for example from the users' preferred language (set in their browser), can be based on the users' geographical location inferred from their IP, or users can provide it simply by choosing the locale in your application interface and saving it to their profile. This approach is more suitable for web-based applications or services, not for websites -- see the box about _sessions_, _cookies_ and RESTful architecture above.
h5. Using +Accept-Language+
@@ -305,7 +272,7 @@ Of course, in a production environment you would need much more robust code, and
h5. Using GeoIP (or Similar) Database
-Another way of choosing the locale from client information would be to use a database for mapping the client IP to the region, such as "GeoIP Lite Country":http://www.maxmind.com/app/geolitecountry. The mechanics of the code would be very similar to the code above -- you would need to query the database for the user's IP, and look up your prefered locale for the country/region/city returned.
+Another way of choosing the locale from client information would be to use a database for mapping the client IP to the region, such as "GeoIP Lite Country":http://www.maxmind.com/app/geolitecountry. The mechanics of the code would be very similar to the code above -- you would need to query the database for the user's IP, and look up your preferred locale for the country/region/city returned.
h5. User Profile
@@ -315,7 +282,7 @@ h3. Internationalizing your Application
OK! Now you've initialized I18n support for your Ruby on Rails application and told it which locale to use and how to preserve it between requests. With that in place, you're now ready for the really interesting stuff.
-Let's _internationalize_ our application, i.e. abstract every locale-specific parts, and then _localize_ it, i.e. provide neccessary translations for these abstracts.
+Let's _internationalize_ our application, i.e. abstract every locale-specific parts, and then _localize_ it, i.e. provide necessary translations for these abstracts.
You most probably have something like this in one of your applications:
@@ -365,12 +332,12 @@ NOTE: Rails adds a +t+ (+translate+) helper method to your views so that you do
So let's add the missing translations into the dictionary files (i.e. do the "localization" part):
-# config/locale/en.yml
+# config/locales/en.yml
en:
hello_world: Hello World
hello_flash: Hello Flash
-# config/locale/pirate.yml
+# config/locales/pirate.yml
pirate:
hello_world: Ahoy World
hello_flash: Ahoy Flash
@@ -378,7 +345,7 @@ pirate:
There you go. Because you haven't changed the default_locale, I18n will use English. Your application now shows:
-!images/i18n/demo_translated_en.png(rails i18n demo translated to english)!
+!images/i18n/demo_translated_en.png(rails i18n demo translated to English)!
And when you change the URL to pass the pirate locale (+http://localhost:3000?locale=pirate+), you'll get:
@@ -386,7 +353,7 @@ And when you change the URL to pass the pirate locale (+http://localhost:3000?lo
NOTE: You need to restart the server when you add new locale files.
-You may use YAML (+.yml+) or plain Ruby (+.rb+) files for storing your translations in SimpleStore. YAML is the prefered option among Rails developers. However, it has one big disadvantage. YAML is very sensitive to whitespace and special characters, so the application may not load your dictionary properly. Ruby files will crash your application on first request, so you may easily find what's wrong. (If you encounter any "weird issues" with YAML dictionaries, try putting the relevant portion of your dictionary into a Ruby file.)
+You may use YAML (+.yml+) or plain Ruby (+.rb+) files for storing your translations in SimpleStore. YAML is the preferred option among Rails developers. However, it has one big disadvantage. YAML is very sensitive to whitespace and special characters, so the application may not load your dictionary properly. Ruby files will crash your application on first request, so you may easily find what's wrong. (If you encounter any "weird issues" with YAML dictionaries, try putting the relevant portion of your dictionary into a Ruby file.)
h4. Adding Date/Time Formats
@@ -402,7 +369,7 @@ OK! Now let's add a timestamp to the view, so we can demo the *date/time localiz
And in our pirate translations file let's add a time format (it's already there in Rails' defaults for English):
-# config/locale/pirate.yml
+# config/locales/pirate.yml
pirate:
time:
formats:
@@ -413,7 +380,7 @@ So that would give you:
!images/i18n/demo_localized_pirate.png(rails i18n demo localized time to pirate)!
-TIP: Right now you might need to add some more date/time formats in order to make the I18n backend work as expected (at least for the 'pirate' locale). Of course, there's a great chance that somebody already did all the work by *translating Rails's defaults for your locale*. See the "rails-i18n repository at Github":http://github.com/svenfuchs/rails-i18n/tree/master/rails/locale for an archive of various locale files. When you put such file(s) in +config/locale/+ directory, they will automatically be ready for use.
+TIP: Right now you might need to add some more date/time formats in order to make the I18n backend work as expected (at least for the 'pirate' locale). Of course, there's a great chance that somebody already did all the work by *translating Rails' defaults for your locale*. See the "rails-i18n repository at Github":http://github.com/svenfuchs/rails-i18n/tree/master/rails/locale for an archive of various locale files. When you put such file(s) in +config/locales/+ directory, they will automatically be ready for use.
h4. Localized Views
@@ -425,7 +392,7 @@ h4. Organization of Locale Files
When you are using the default SimpleStore shipped with the i18n library, dictionaries are stored in plain-text files on the disc. Putting translations for all parts of your application in one file per locale could be hard to manage. You can store these files in a hierarchy which makes sense to you.
-For example, your +config/locale+ directory could look like this:
+For example, your +config/locales+ directory could look like this:
|-defaults
@@ -463,7 +430,7 @@ Do check the "Rails i18n Wiki":http://rails-i18n.org/wiki for list of tools avai
h3. Overview of the I18n API Features
-You should have good understanding of using the i18n library now, knowing all neccessary aspects of internationalizing a basic Rails application. In the following chapters, we'll cover it's features in more depth.
+You should have good understanding of using the i18n library now, knowing all necessary aspects of internationalizing a basic Rails application. In the following chapters, we'll cover it's features in more depth.
Covered are features like these:
@@ -686,7 +653,7 @@ en:
# will translate User attribute "login" as "Handle"
-Then +User.human_name+ will return "Dude" and +User.human_attribute_name(:login)+ will return "Handle".
+Then +User.human_name+ will return "Dude" and +User.human_attribute_name("login")+ will return "Handle".
h5. Error Message Scopes
diff --git a/railties/guides/source/index.erb.textile b/railties/guides/source/index.erb.textile
index 4c8dd65a04..851d91da2f 100644
--- a/railties/guides/source/index.erb.textile
+++ b/railties/guides/source/index.erb.textile
@@ -1,5 +1,5 @@
<% content_for :header_section do %>
-h2. Ruby on Rails guides
+h2. Ruby on Rails Guides
These guides are designed to make you immediately productive with Rails, and to help you understand how all of the pieces fit together. There are two different versions of the Guides site, and you should be sure to use the one that applies to your situation:
diff --git a/railties/guides/source/layouts_and_rendering.textile b/railties/guides/source/layouts_and_rendering.textile
index 809d2b2172..0cee413ac3 100644
--- a/railties/guides/source/layouts_and_rendering.textile
+++ b/railties/guides/source/layouts_and_rendering.textile
@@ -204,7 +204,7 @@ TIP: You don't need to call +to_xml+ on the object that you want to render. If y
h5. Rendering Vanilla JavaScript
-Rails can render vanilla JavaScript (as an alternative to using +update+ with n +.rjs+ file):
+Rails can render vanilla JavaScript (as an alternative to using +update+ with an +.rjs+ file):
render :js => "alert('Hello Rails');"
@@ -266,7 +266,7 @@ render :xml => photo, :location => photo_url(photo)
h5. Finding Layouts
-To find the current layout, Rails first looks for a file in +app/views/layouts+ with the same base name as the controller. For example, rendering actions from the +PhotosController+ class will use +/app/views/layouts/photos.html.erb+ (or +app/views/layouts/photos.builder+). If there is no such controller-specific layout, Rails will use +/app/views/layouts/application.html.erb+ ot +/app/views/layouts/application.builder+. If there is no +.erb+ layout, Rails will use a +.builder+ layout if one exists. Rails also provides several ways to more precisely assign specific layouts to individual controllers and actions.
+To find the current layout, Rails first looks for a file in +app/views/layouts+ with the same base name as the controller. For example, rendering actions from the +PhotosController+ class will use +app/views/layouts/photos.html.erb+ (or +app/views/layouts/photos.builder+). If there is no such controller-specific layout, Rails will use +app/views/layouts/application.html.erb+ or +app/views/layouts/application.builder+. If there is no +.erb+ layout, Rails will use a +.builder+ layout if one exists. Rails also provides several ways to more precisely assign specific layouts to individual controllers and actions.
h6. Specifying Layouts on a per-Controller Basis
@@ -418,15 +418,15 @@ def show
end
-Note that the implicit render done by ActionController detects if +render+ has been called, and thus avoids this error. So this code will work with problems:
+Note that the implicit render done by ActionController detects if +render+ has been called, and thus avoids this error. Therefore, the following will work without errors:
- def show
- @book = Book.find(params[:id])
- if @book.special?
- render :action => "special_show"
- end
+def show
+ @book = Book.find(params[:id])
+ if @book.special?
+ render :action => "special_show"
end
+end
This will render a book with +special?+ set with the +special_show+ template, while other books will render with the default +show+ template.
@@ -447,7 +447,7 @@ redirect_to :back
h5. Getting a Different Redirect Status Code
-Rails uses HTTP status code 302 (permanent redirect) when you call +redirect_to+. If you'd like to use a different status code (perhaps 301, temporary redirect), you can do so by using the +:status+ option:
+Rails uses HTTP status code 302 (temporary redirect) when you call +redirect_to+. If you'd like to use a different status code (perhaps 301, permanent redirect), you can do so by using the +:status+ option:
redirect_to photos_path, :status => 301
@@ -519,10 +519,10 @@ h4. Asset Tags
Asset tags provide methods for generating HTML that links views to assets like images, javascript, stylesheets, and feeds. There are four types of include tag:
-* auto_discovery_link_tag
-* javascript_include_tag
-* stylesheet_link_tag
-* image_tag
+* +auto_discovery_link_tag+
+* +javascript_include_tag+
+* +stylesheet_link_tag+
+* +image_tag+
You can use these tags in layouts or other views, although the tags other than +image_tag+ are most commonly used in the +<head>+ section of a layout.
@@ -622,16 +622,16 @@ To include +public/stylesheets/main.css+ and +public/photos/columns.css+:
<%= stylesheet_link_tag "main", "/photos/columns" %>
-To include +http://example.com/main.cs+:
+To include +http://example.com/main.css+:
-<%= stylesheet_link_tag "http://example.com/main.cs" %>
+<%= stylesheet_link_tag "http://example.com/main.css" %>
-By default, +stylesheet_link_tag+ creates links with +media="screen" rel="stylesheet" type="text/css"+. You can override any of these defaults by specifying an appropriate option (:media, :rel, or :type):
+By default, +stylesheet_link_tag+ creates links with +media="screen" rel="stylesheet" type="text/css"+. You can override any of these defaults by specifying an appropriate option (+:media+, +:rel+, or +:type+):
-<%= stylesheet_link_tag "main_print", media => "print" %>
+<%= stylesheet_link_tag "main_print", :media => "print" %>
The +all+ option links every CSS file in +public/stylesheets+:
@@ -958,13 +958,13 @@ On pages generated by +NewsController+, you want to hide the top menu and add a
<% content_for :content do %>
<%= yield(:news_content) or yield %>
- <% end -%>
+<% end -%>
<%= render :file => 'layouts/application' %>
That's it. The News views will use the new layout, hiding the top menu and adding a new right menu inside the "content" div.
-There are several ways of getting similar results with different sub-templating schemes using this technique. Note that there is no limit in nesting levels. One can use the +ActionView::render+ method via +render :file => 'layouts/news'+ to base a new layout on the News layout. If one is sure she will not subtemplate the +News+ layout, she can ommit the +yield(:news_content) or + part.
+There are several ways of getting similar results with different sub-templating schemes using this technique. Note that there is no limit in nesting levels. One can use the +ActionView::render+ method via +render :file => 'layouts/news'+ to base a new layout on the News layout. If one is sure she will not subtemplate the +News+ layout, she can omit the +yield(:news_content) or + part.
h3. Changelog
diff --git a/railties/guides/source/migrations.textile b/railties/guides/source/migrations.textile
index 5ed94c30b7..5f49ac41f5 100644
--- a/railties/guides/source/migrations.textile
+++ b/railties/guides/source/migrations.textile
@@ -1,10 +1,10 @@
h2. Migrations
-Migrations are a convenient way for you to alter your database in a structured and organised manner. You could edit fragments of SQL by hand but you would then be responsible for telling other developers that they need to go and run it. You'd also have to keep track of which changes need to be run against the production machines next time you deploy.
+Migrations are a convenient way for you to alter your database in a structured and organized manner. You could edit fragments of SQL by hand but you would then be responsible for telling other developers that they need to go and run it. You'd also have to keep track of which changes need to be run against the production machines next time you deploy.
Active Record tracks which migrations have already been run so all you have to do is update your source and run +rake db:migrate+. Active Record will work out which migrations should be run. It will also update your +db/schema.rb+ file to match the structure of your database.
-Migrations also allow you to describe these transformations using Ruby. The great thing about this is that (like most of Active Record's functionality) it is database independent: you don't need to worry about the precise syntax of +CREATE TABLE+ any more that you worry about variations on +SELECT *+ (you can drop down to raw SQL for database specific features). For example you could use SQLite3 in development, but MySQL in production.
+Migrations also allow you to describe these transformations using Ruby. The great thing about this is that (like most of Active Record's functionality) it is database independent: you don't need to worry about the precise syntax of +CREATE TABLE+ any more than you worry about variations on +SELECT *+ (you can drop down to raw SQL for database specific features). For example you could use SQLite3 in development, but MySQL in production.
You'll learn all about migrations including:
@@ -78,7 +78,7 @@ Active Record provides methods that perform common data definition tasks in a da
If you need to perform tasks specific to your database (for example create a "foreign key":#active-record-and-referential-integrity constraint) then the +execute+ function allows you to execute arbitrary SQL. A migration is just a regular Ruby class so you're not limited to these functions. For example after adding a column you could write code to set the value of that column for existing records (if necessary using your models).
-On databases that support transactions with statements that change the schema (such as PostgreSQL), migrations are wrapped in a transaction. If the database does not support this (for example MySQL and SQLite) then when a migration fails the parts of it that succeeded will not be rolled back. You will have to unpick the changes that were made by hand.
+On databases that support transactions with statements that change the schema (such as PostgreSQL or SQLite3), migrations are wrapped in a transaction. If the database does not support this (for example MySQL) then when a migration fails the parts of it that succeeded will not be rolled back. You will have to unpick the changes that were made by hand.
h4. What's in a Name
@@ -508,7 +508,7 @@ The migration has its own minimal copy of the +Product+ model and no longer care
h4. Dealing with Changing Models
-For performance reasons information about the columns a model has is cached. For example if you add a column to a table and then try and use the corresponding model to insert a new row it may try and use the old column information. You can force Active Record to re-read the column information with the +reset_column_information+ method, for example
+For performance reasons information about the columns a model has is cached. For example if you add a column to a table and then try and use the corresponding model to insert a new row it may try to use the old column information. You can force Active Record to re-read the column information with the +reset_column_information+ method, for example
class AddPartNumberToProducts < ActiveRecord::Migration
@@ -538,7 +538,7 @@ There is no need (and it is error prone) to deploy a new instance of an app by r
For example, this is how the test database is created: the current development database is dumped (either to +db/schema.rb+ or +db/development.sql+) and then loaded into the test database.
-Schema files are also useful if you want a quick look at what attributes an Active Record object has. This information is not in the model's code and is frequently spread across several migrations but is all summed up in the schema file. The "annotate_models":http://agilewebdevelopment.com/plugins/annotate_models plugin, which automatically adds (and updates) comments at the top of each model summarising the schema, may also be of interest.
+Schema files are also useful if you want a quick look at what attributes an Active Record object has. This information is not in the model's code and is frequently spread across several migrations but is all summed up in the schema file. The "annotate_models":http://agilewebdevelopment.com/plugins/annotate_models plugin, which automatically adds (and updates) comments at the top of each model summarizing the schema, may also be of interest.
h4. Types of Schema Dumps
@@ -582,7 +582,7 @@ The Active Record way claims that intelligence belongs in your models, not in th
Validations such as +validates_uniqueness_of+ are one way in which models can enforce data integrity. The +:dependent+ option on associations allows models to automatically destroy child objects when the parent is destroyed. Like anything which operates at the application level these cannot guarantee referential integrity and so some people augment them with foreign key constraints.
-Although Active Record does not provide any tools for working directly with such features, the +execute+ method can be used to execute arbitrary SQL. There are also a number of plugins such as "redhillonrails":http://agilewebdevelopment.com/plugins/search?search=redhillonrails which add foreign key support to Active Record (including support for dumping foreign keys in +db/schema.rb+).
+Although Active Record does not provide any tools for working directly with such features, the +execute+ method can be used to execute arbitrary SQL. There are also a number of plugins such as "foreign_key_migrations":http://github.com/harukizaemon/foreign_key_migrations/tree/master which add foreign key support to Active Record (including support for dumping foreign keys in +db/schema.rb+).
h3. Changelog
diff --git a/railties/guides/source/performance_testing.textile b/railties/guides/source/performance_testing.textile
index 320a5b8472..f0dc9acbb8 100644
--- a/railties/guides/source/performance_testing.textile
+++ b/railties/guides/source/performance_testing.textile
@@ -293,7 +293,7 @@ WARNING: Performance test configurability is not yet enabled in Rails. But it wi
h4. Performance Test Environment
-Performance tests are run in the +development+ environment. But running performance tests will set the following configuration parameters:
+Performance tests are run in the +test+ environment. But running performance tests will set the following configuration parameters:
ActionController::Base.perform_caching = true
diff --git a/railties/guides/source/plugins.textile b/railties/guides/source/plugins.textile
index 55ecdcd3d1..a5d39c3d09 100644
--- a/railties/guides/source/plugins.textile
+++ b/railties/guides/source/plugins.textile
@@ -601,7 +601,7 @@ This is just a simple test to make sure the class is being loaded correctly. Af
end
-Adding directories to the load path makes them appear just like files in the the main app directory - except that they are only loaded once, so you have to restart the web server to see the changes in the browser. Removing directories from the 'load_once_paths' allow those changes to picked up as soon as you save the file - without having to restart the web server. This is particularly useful as you develop the plugin.
+Adding directories to the load path makes them appear just like files in the main app directory - except that they are only loaded once, so you have to restart the web server to see the changes in the browser. Removing directories from the 'load_once_paths' allow those changes to picked up as soon as you save the file - without having to restart the web server. This is particularly useful as you develop the plugin.
* *vendor/plugins/yaffle/lib/app/models/woodpecker.rb:*
diff --git a/railties/guides/source/rails_application_templates.textile b/railties/guides/source/rails_application_templates.textile
index 49cd5bf5f5..fc178fa44b 100644
--- a/railties/guides/source/rails_application_templates.textile
+++ b/railties/guides/source/rails_application_templates.textile
@@ -1,18 +1,238 @@
h2. Rails Application Templates
-This guide covers the Rails application templates, By referring to this guide, you will be able to:
+Application templates are simple ruby files containing DSL for adding plugins/gems/initializers etc. to your freshly created Rails project or an existing Rails project.
-* Use existing templates to generate a customized Rails application
-* Write your own reusable Rails application templates
+By referring to this guide, you will be able to:
+
+* Use templates to generate/customize Rails applications
+* Write your own reusable application templates using the Rails template API
endprologue.
-h3. Introduction
+h3. Usage
-Application templates are simple ruby files containing DSL for adding plugins/gems/initializers etc. to your freshly created Rails project or an existing Rails project.
+To apply a template, you need to provide the Rails generator with the location of the template you wish to apply, using -m option :
+
+
+$ rails blog -m ~/template.rb
+
+
+It's also possible to apply a template using a URL :
+
+
+$ rails blog -m http://gist.github.com/31208.txt
+
+
+Alternatively, you can use the rake task +rails:template+ to apply a template to an existing Rails application :
+
+
+$ rake rails:template LOCATION=~/template.rb
+
+
+h3. Template API
+
+Rails templates API is very self explanatory and easy to understand. Here's an example of a typical Rails template :
+
+
+# template.rb
+run "rm public/index.html"
+generate(:scaffold, "person name:string")
+route "map.root :controller => 'people'"
+rake("db:migrate")
+
+git :init
+git :add => "."
+git :commit => "-a -m 'Initial commit'"
+
+
+The following sections outlines the primary methods provided by the API :
+
+h4. gem(name, options = {})
+
+Adds a +config.gem+ entry for the supplied gem to the generated application’s +config/environment.rb+.
+
+For example, if your application depends on the gems +bj+ and +hpricot+ :
+
+
+gem "bj"
+gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net"
+
+
+Please note that this will NOT install the gems for you. So you may want to run the +rake gems:install+ task too :
+
+
+rake "gems:install"
+
+
+And let Rails take care of installing the required gems if they’re not already installed.
+
+h4. plugin(name, options = {})
+
+Installs a plugin to the generated application.
+
+Plugin can be installed from Git :
+
+
+plugin 'authentication', :git => 'git://github.com/foor/bar.git'
+
+
+You can even install plugins as git submodules :
+
+
+plugin 'authentication', :git => 'git://github.com/foor/bar.git',
+ :submodule => true
+
+
+Please note that you need to +git :init+ before you can install a plugin as a submodule.
+
+Or use plain old SVN :
+
+
+plugin 'wtfsvn', :svn => 'svn://crap.com/wtf/trunk'
+
+
+h4. vendor/lib/file/initializer(filename, data = nil, &block)
+
+Adds an initializer to the generated application’s +config/initializers+ directory.
+
+Lets say you like using +Object#not_nil?+ and +Object#not_blank?+ :
+
+
+initializer 'bloatlol.rb', <<-CODE
+class Object
+ def not_nil?
+ !nil?
+ end
+
+ def not_blank?
+ !blank?
+ end
+end
+CODE
+
+
+Similarly +lib()+ creates a file in the +lib/+ directory and +vendor()+ creates a file in the +vendor/+ directory.
+
+There is even +file()+, which accepts a relative path from +RAILS_ROOT+ and creates all the directories/file needed :
+
+
+file 'app/components/foo.rb', <<-CODE
+class Foo
+end
+CODE
+
+
+That’ll create +app/components+ directory and put +foo.rb+ in there.
+
+h4. rakefile(filename, data = nil, &block)
+
+Creates a new rake file under +lib/tasks+ with the supplied tasks :
+
+
+rakefile("bootstrap.rake") do
+ <<-TASK
+ namespace :boot do
+ task :strap do
+ puts "i like boots!"
+ end
+ end
+ TASK
+end
+
+
+The above creates +lib/tasks/bootstrap.rake+ with a +boot:strap+ rake task.
+
+h4. generate(what, args)
+
+Runs the supplied rails generator with given arguments. For example, I love to scaffold some whenever I’m playing with Rails :
+
+
+generate(:scaffold, "person", "name:string", "address:text", "age:number")
+
+
+h4. run(command)
+
+Executes an arbitrary command. Just like the backticks. Let's say you want to remove the +public/index.html+ file :
+
+
+run "rm public/index.html"
+
+
+h4. rake(command, options = {})
+
+Runs the supplied rake tasks in the Rails application. Let's say you want to migrate the database :
+
+
+rake "db:migrate"
+
+
+You can also run rake tasks with a different Rails environment :
+
+
+rake "db:migrate", :env => 'production'
+
+
+Or even use sudo :
+
+
+rake "gems:install", :sudo => true
+
+
+h4. route(routing_code)
+
+This adds a routing entry to the +config/routes.rb+ file. In above steps, we generated a person scaffold and also removed +public/index.html+. Now to make +PeopleController#index+ as the default page for the application :
+
+
+route "map.root :controller => :person"
+
+
+h4. inside(dir)
+
+I have my edge rails lying at +~/commit-rails/rails+. So every time i have to manually symlink edge from my new app. But now :
+
+
+inside('vendor') do
+ run "ln -s ~/commit-rails/rails rails"
+end
+
+
+So +inside()+ runs the command from the given directory.
+
+h4. ask(question)
+
++ask()+ gives you a chance to get some feedback from the user and use it in your templates. Lets say you want your user to name the new shiny library you’re adding :
+
+
+lib_name = ask("What do you want to call the shiny library ?")
+lib_name << ".rb" unless lib_name.index(".rb")
+
+lib lib_name, <<-CODE
+class Shiny
+end
+CODE
+
+
+h4. yes?(question) or no?(question)
+
+These methods let you ask questions from templates and decide the flow based on the user’s answer. Lets say you want to freeze rails only if the user want to :
+
+
+rake("rails:freeze:gems") if yes?("Freeze rails gems ?")
+no?(question) acts just the opposite.
+
+
+h4. git(:must => "-a love")
+
+Rails templates let you run any git command :
+
+
+git :init
+git :add => "."
+git :commit => "-a -m 'Initial commit'"
+
h3. Changelog
"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/78
-* April 17, 2009: Initial version by "Pratik":credits.html#lifo
+* April 29, 2009: Initial version by "Pratik":credits.html#lifo
diff --git a/railties/guides/source/rails_on_rack.textile b/railties/guides/source/rails_on_rack.textile
index 1164ed821d..545aaa18e0 100644
--- a/railties/guides/source/rails_on_rack.textile
+++ b/railties/guides/source/rails_on_rack.textile
@@ -48,7 +48,7 @@ app = Rack::Builder.new {
}.to_app
-Middlewares used in the code above are primarily useful only in the development envrionment. The following table explains their usage:
+Middlewares used in the code above are primarily useful only in the development environment. The following table explains their usage:
|_.Middleware|_.Purpose|
|+Rails::Rack::LogTailer+|Appends log file output to console|
@@ -229,7 +229,7 @@ h3. Rails Metal Applications
Rails Metal applications are minimal Rack applications specially designed for integrating with a typical Rails application. As Rails Metal Applications skip all of the Action Controller stack, serving a request has no overhead from the Rails framework itself. This is especially useful for infrequent cases where the performance of the full stack Rails framework is an issue.
-Ryan Bates' "railscast on Rails Metal":http://railscasts.com/episodes/150-rails-metal provides a nice walkthrough generating and using Rails Metal.
+Ryan Bates' "Railscast on Rails Metal":http://railscasts.com/episodes/150-rails-metal provides a nice walkthrough generating and using Rails Metal.
h4. Generating a Metal Application
diff --git a/railties/guides/source/routing.textile b/railties/guides/source/routing.textile
index e9adb4b308..355f385d49 100644
--- a/railties/guides/source/routing.textile
+++ b/railties/guides/source/routing.textile
@@ -236,7 +236,7 @@ will recognize incoming URLs containing +photo+ but route the requests to the Im
|GET |/photos/new |Images |new |return an HTML form for creating a new image|
|POST |/photos |Images |create |create a new image|
|GET |/photos/1 |Images |show |display a specific image|
-|GET |/photos/1/edit |Images |edit |return an HTML form for editing a image|
+|GET |/photos/1/edit |Images |edit |return an HTML form for editing an image|
|PUT |/photos/1 |Images |update |update a specific image|
|DELETE |/photos/1 |Images |destroy |delete a specific image|
@@ -416,7 +416,7 @@ map.resources :magazines do |magazine|
end
-TIP: Further below you'll learn about a convenient shortcut for this construct:
+map.resources :magazines, :has_many => :ads+.
+TIP: Further below you'll learn about a convenient shortcut for this construct:
+map.resources :magazines, :has_many => :ads+
In addition to the routes for magazines, this declaration will also create routes for ads, each of which requires the specification of a magazine in the URL:
@@ -614,7 +614,7 @@ To add a new route (one that creates a new resource), use the +:new+ option:
map.resources :photos, :new => { :upload => :post }
-This will enable Rails to recognize URLs such as +/photos/upload+ using the POST HTTP verb, and route them to the upload action of the Photos controller. It will also create the +upload_photos_path+ and +upload_photos_url+ route helpers.
+This will enable Rails to recognize URLs such as +/photos/new/upload+ using the POST HTTP verb, and route them to the upload action of the Photos controller. It will also create the +upload_new_photos_path+ and +upload_new_photos_url+ route helpers.
TIP: If you want to redefine the verbs accepted by one of the standard actions, you can do so by explicitly mapping that action. For example:
+map.resources :photos, :new => { :new => :any }+
This will allow the new action to be invoked by any request to +photos/new+, no matter what HTTP verb you use.
@@ -695,7 +695,7 @@ Regular routes need not use the +connect+ method. You can use any other name her
map.logout '/logout', :controller => 'sessions', :action => 'destroy'
-This will do two things. First, requests to +/logout+ will be sent to the +destroy+ method of the +Sessions+ controller. Second, Rails will maintain the +logout_path+ and +logout_url+ helpers for use within your code.
+This will do two things. First, requests to +/logout+ will be sent to the +destroy+ action of the +Sessions+ controller. Second, Rails will maintain the +logout_path+ and +logout_url+ helpers for use within your code.
h4. Route Requirements
diff --git a/railties/guides/source/security.textile b/railties/guides/source/security.textile
index 1b64cc1be7..c26bea5519 100644
--- a/railties/guides/source/security.textile
+++ b/railties/guides/source/security.textile
@@ -392,7 +392,7 @@ params[:user] #=> {:name => “ow3ned”, :admin => true}
So if you create a new user using mass-assignment, it may be too easy to become an administrator.
-Note that this vulnerability is not restricted to database columns. Any setter method, unless explicitly protected, is accessible via the attributes= method. In fact, this vulnerability is extended even further with the introduction of nested mass assignment (and nested object forms) in rails 2.3. The +accepts_nested_attributes_for+ declaration provides us the ability to extend mass assignment to model associations (+has_many+, +has_one+, +has_and_belongs_to_many+). For example:
+Note that this vulnerability is not restricted to database columns. Any setter method, unless explicitly protected, is accessible via the attributes= method. In fact, this vulnerability is extended even further with the introduction of nested mass assignment (and nested object forms) in Rails 2.3. The +accepts_nested_attributes_for+ declaration provides us the ability to extend mass assignment to model associations (+has_many+, +has_one+, +has_and_belongs_to_many+). For example:
class Person < ActiveRecord::Base
@@ -497,7 +497,7 @@ Depending on your web application, there may be more ways to hijack the user's a
h4. CAPTCHAs
--- _A CAPTCHA is a challenge-response test to determine that the response is not generated by a computer. It is often used to protect comment forms from automatic spam bots by asking the user to type the letters of a distorted image. The idea of a negative CAPTCHA is not to ask a user to proof that he is human, but reveal that a robot is a robot._
+-- _A CAPTCHA is a challenge-response test to determine that the response is not generated by a computer. It is often used to protect comment forms from automatic spam bots by asking the user to type the letters of a distorted image. The idea of a negative CAPTCHA is not for a user to prove that he is human, but reveal that a robot is a robot._
But not only spam robots (bots) are a problem, but also automatic login bots. A popular CAPTCHA API is "reCAPTCHA":http://recaptcha.net/ which displays two distorted images of words from old books. It also adds an angled line, rather than a distorted background and high levels of warping on the text as earlier CAPTCHAs did, because the latter were broken. As a bonus, using reCAPTCHA helps to digitize old books. "ReCAPTCHA":http://ambethia.com/recaptcha/ is also a Rails plug-in with the same name as the API.
@@ -967,7 +967,7 @@ Transfer-Encoding: chunked
Content-Type: text/html
-Under certain circumstances this would present the malicious HTML to the victim. However, this seems to work with Keep-Alive connections, only (and many browsers are using one-time connections). But you can't rely on this. _(highlight)In any case this is a serious bug, and you should update your Rails to version 2.0.5 or 2.1.2 to eliminate Header Injection (and thus response splitting) risks._
+Under certain circumstances this would present the malicious HTML to the victim. However, this only seems to work with Keep-Alive connections (and many browsers are using one-time connections). But you can't rely on this. _(highlight)In any case this is a serious bug, and you should update your Rails to version 2.0.5 or 2.1.2 to eliminate Header Injection (and thus response splitting) risks._
h3. Additional Resources
diff --git a/railties/guides/source/testing.textile b/railties/guides/source/testing.textile
index 12fc836edf..8318146ed3 100644
--- a/railties/guides/source/testing.textile
+++ b/railties/guides/source/testing.textile
@@ -211,7 +211,7 @@ $ rake db:migrate
$ rake db:test:load
-Above +rake db:migrate+ runs any pending migrations on the _developemnt_ environment and updates +db/schema.rb+. +rake db:test:load+ recreates the test database from the current db/schema.rb. On subsequent attempts it is a good to first run +db:test:prepare+ as it first checks for pending migrations and warns you appropriately.
+Above +rake db:migrate+ runs any pending migrations on the _development_ environment and updates +db/schema.rb+. +rake db:test:load+ recreates the test database from the current db/schema.rb. On subsequent attempts it is a good to first run +db:test:prepare+ as it first checks for pending migrations and warns you appropriately.
NOTE: +db:test:prepare+ will fail with an error if db/schema.rb doesn't exists.
@@ -372,7 +372,7 @@ NameError: undefined local variable or method `some_undefined_variable' for #
def test_should_route_to_post
@@ -860,7 +862,7 @@ The goals of testing your +ActionMailer+ classes are to ensure that:
h5. From All Sides
-There are two aspects of testing your mailer, the unit tests and the functional tests. In the unit tests, you run the mailer in isolation with tightly controlled inputs and compare the output to a knownvalue (a fixture -- yay! more fixtures!). In the functional tests you don't so much test the minute details produced by the mailer Instead we test that our controllers and models are using the mailer in the right way. You test to prove that the right email was sent at the right time.
+There are two aspects of testing your mailer, the unit tests and the functional tests. In the unit tests, you run the mailer in isolation with tightly controlled inputs and compare the output to a known value (a fixture -- yay! more fixtures!). In the functional tests you don't so much test the minute details produced by the mailer Instead we test that our controllers and models are using the mailer in the right way. You test to prove that the right email was sent at the right time.
h4. Unit Testing