diff options
Diffstat (limited to 'railties/guides/source')
19 files changed, 96 insertions, 266 deletions
diff --git a/railties/guides/source/2_3_release_notes.textile b/railties/guides/source/2_3_release_notes.textile index 67743a4797..15abba66ab 100644 --- a/railties/guides/source/2_3_release_notes.textile +++ b/railties/guides/source/2_3_release_notes.textile @@ -410,7 +410,7 @@ You're likely familiar with Rails' practice of adding timestamps to static asset h4. Asset Hosts as Objects -Asset hosts get more flexible in edge Rails with the ability to declare an asset host as a specific object that responds to a call. This allows you to to implement any complex logic you need in your asset hosting. +Asset hosts get more flexible in edge Rails with the ability to declare an asset host as a specific object that responds to a call. This allows you to implement any complex logic you need in your asset hosting. * More Information: "asset-hosting-with-minimum-ssl":http://github.com/dhh/asset-hosting-with-minimum-ssl/tree/master diff --git a/railties/guides/source/action_controller_overview.textile b/railties/guides/source/action_controller_overview.textile index 178d98c2d6..496dc7224b 100644 --- a/railties/guides/source/action_controller_overview.textile +++ b/railties/guides/source/action_controller_overview.textile @@ -615,26 +615,15 @@ Rails comes with two built-in HTTP authentication mechanisms: h4. HTTP Basic Authentication -HTTP basic authentication is an authentication scheme that is supported by the majority of browsers and other HTTP clients. As an example, consider an administration section which will only be available by entering a username and a password into the browser's HTTP basic dialog window. Using the built-in authentication is quite easy and only requires you to use one method, +authenticate_or_request_with_http_basic+. +HTTP basic authentication is an authentication scheme that is supported by the majority of browsers and other HTTP clients. As an example, consider an administration section which will only be available by entering a username and a password into the browser's HTTP basic dialog window. Using the built-in authentication is quite easy and only requires you to use one method, +http_basic_authenticate_with+. <ruby> class AdminController < ApplicationController - USERNAME, PASSWORD = "humbaba", "5baa61e4" - - before_filter :authenticate - - private - - def authenticate - authenticate_or_request_with_http_basic do |username, password| - username == USERNAME && - Digest::SHA1.hexdigest(password) == PASSWORD - end - end + http_basic_authenticate_with :name => "humbaba", :password => "5baa61e4" end </ruby> -With this in place, you can create namespaced controllers that inherit from +AdminController+. The before filter will thus be run for all actions in those controllers, protecting them with HTTP basic authentication. +With this in place, you can create namespaced controllers that inherit from +AdminController+. The filter will thus be run for all actions in those controllers, protecting them with HTTP basic authentication. h4. HTTP Digest Authentication diff --git a/railties/guides/source/action_view_overview.textile b/railties/guides/source/action_view_overview.textile index cfd71ad287..d0b3ee6bfc 100644 --- a/railties/guides/source/action_view_overview.textile +++ b/railties/guides/source/action_view_overview.textile @@ -1295,7 +1295,7 @@ end h5. update_page_tag -Works like update_page but wraps the generated JavaScript in a +script+ tag. Use this to include generated JavaScript in an ERb template. +Works like update_page but wraps the generated JavaScript in a +script+ tag. Use this to include generated JavaScript in an ERB template. h4. PrototypeHelper::JavaScriptGenerator::GeneratorMethods diff --git a/railties/guides/source/active_record_querying.textile b/railties/guides/source/active_record_querying.textile index f3a10b8b92..df8e35ed33 100644 --- a/railties/guides/source/active_record_querying.textile +++ b/railties/guides/source/active_record_querying.textile @@ -790,7 +790,7 @@ Post.includes(:comments).where("comments.visible", true) This would generate a query which contains a +LEFT OUTER JOIN+ whereas the +joins+ method would generate one using the +INNER JOIN+ function instead. <ruby> - SELECT "posts"."id" AS t0_r0, ... "comments"."updated_at" AS t1_r5 FROM "posts" LEFT OUTER JOIN "comments" ON "comments"."post_id" = "posts"."id" WHERE (comments.visible) + SELECT "posts"."id" AS t0_r0, ... "comments"."updated_at" AS t1_r5 FROM "posts" LEFT OUTER JOIN "comments" ON "comments"."post_id" = "posts"."id" WHERE (comments.visible = 1) </ruby> If there was no +where+ condition, this would generate the normal set of two queries. diff --git a/railties/guides/source/active_record_validations_callbacks.textile b/railties/guides/source/active_record_validations_callbacks.textile index 514d0322b9..c65dd52e48 100644 --- a/railties/guides/source/active_record_validations_callbacks.textile +++ b/railties/guides/source/active_record_validations_callbacks.textile @@ -822,7 +822,7 @@ The selectors to customize the style of error messages are: * +#errorExplanation p+ - Style for the paragraph that holds the message that appears right below the header of the +div+ element. * +#errorExplanation ul li+ - Style for the list items with individual error messages. -Scaffolding for example generates +public/stylesheets/scaffold.css+, which defines the red-based style you saw above. +Scaffolding for example generates +app/assets/stylesheets/scaffold.css.scss+, which later compiles to +app/assets/stylesheets/scaffold.css+ and defines the red-based style you saw above. The name of the class and the id can be changed with the +:class+ and +:id+ options, accepted by both helpers. diff --git a/railties/guides/source/active_support_core_extensions.textile b/railties/guides/source/active_support_core_extensions.textile index 788f528654..3ba840c044 100644 --- a/railties/guides/source/active_support_core_extensions.textile +++ b/railties/guides/source/active_support_core_extensions.textile @@ -442,6 +442,28 @@ require_library_or_gem('mysql') NOTE: Defined in +active_support/core_ext/kernel/requires.rb+. +h4. +in?+ and +either?+ + +The predicate +in?+ tests if an object is included in another object, and the predicate +either?+ tests if an object is included in a list of objects which will be passed as arguments. + +Examples of +in?+: + +<ruby> + 1.in?([1,2]) # => true + "lo".in?("hello") # => true + 25.in?(30..50) # => false +</ruby> + +Examples of +either?+: + +<ruby> + 1.either?(1,2,3) # => true + 5.either?(1,2,3) # => false + [1,2,3].either?([1,2,3], 2, [3,4,5]) # => true +</ruby> + +NOTE: Defined in +active_support/core_ext/object/inclusion.rb+. + h3. Extensions to +Module+ h4. +alias_method_chain+ diff --git a/railties/guides/source/ajax_on_rails.textile b/railties/guides/source/ajax_on_rails.textile index b80df4aa58..38a63ea483 100644 --- a/railties/guides/source/ajax_on_rails.textile +++ b/railties/guides/source/ajax_on_rails.textile @@ -3,14 +3,14 @@ h2. AJAX on Rails This guide covers the built-in Ajax/JavaScript functionality of Rails (and more); it will enable you to create rich and dynamic AJAX applications with ease! We will cover the following topics: * Quick introduction to AJAX and related technologies -* Handling JavaScript the Rails way: Rails helpers, RJS, Prototype and script.aculo.us +* Handling JavaScript the Rails way: Rails helpers, Prototype and script.aculo.us * Testing JavaScript functionality endprologue. h3. Hello AJAX - a Quick Intro -If you are a 'show me the code' type of person, you might want to skip this part and jump to the RJS section right away. However, I would really recommend to read it - you'll need the basics of DOM, http requests and other topics discussed here to really understand Ajax on Rails. +You'll need the basics of DOM, HTTP requests and other topics discussed here to really understand Ajax on Rails. h4. Asynchronous JavaScript + XML @@ -62,7 +62,7 @@ link_to_remote "Add to cart", * The second parameter, the +options+ hash is the most interesting part as it has the AJAX specific stuff: ** *:url* This is the only parameter that is always required to generate the simplest remote link (technically speaking, it is not required, you can pass an empty +options+ hash to +link_to_remote+ - but in this case the URL used for the POST request will be equal to your current URL which is probably not your intention). This URL points to your AJAX action handler. The URL is typically specified by Rails REST view helpers, but you can use the +url_for+ format too. -** *:update* There are basically two ways of injecting the server response into the page: One is involving RJS and we will discuss it in the next chapter, and the other is specifying a DOM id of the element we would like to update. The above example demonstrates the simplest way of accomplishing this - however, we are in trouble if the server responds with an error message because that will be injected into the page too! However, Rails has a solution for this situation: +** *:update* Specifying a DOM id of the element we would like to update. The above example demonstrates the simplest way of accomplishing this - however, we are in trouble if the server responds with an error message because that will be injected into the page too! However, Rails has a solution for this situation: <ruby> link_to_remote "Add to cart", @@ -178,12 +178,7 @@ h5. +remote_function+ h5. +update_page+ - -h3. JavaScript the Rails way: RJS - -In the last section we sent some AJAX requests to the server, and inserted the HTML response into the page (with the +:update+ option). However, sometimes a more complicated interaction with the page is needed, which you can either achieve with JavaScript... or with RJS! You are sending JavaScript instructions to the server in both cases, but while in the former case you have to write vanilla JavaScript, in the second you can code Rails, and sit back while Rails generates the JavaScript for you - so basically RJS is a Ruby DSL to write JavaScript in your Rails code. - -h4. JavaScript without RJS +h4. Serving JavaScript First we'll check out how to send JavaScript to the server manually. You are practically never going to need this, but it's interesting to understand what's going on under the hood. @@ -198,136 +193,6 @@ end What happens here is that by specifying the Content-Type header variable, we instruct the browser to evaluate the text we are sending over (rather than displaying it as plain text, which is the default behavior). -h4. Inline RJS - -As we said, the purpose of RJS is to write Ruby which is then auto-magically turned into JavaScript by Rails. The above example didn't look too Ruby-esque so let's see how to do it the Rails way: - -<ruby> -def javascript_test - render :update do |page| - page.alert "Hello from inline RJS" - end -end -</ruby> - -The above code snippet does exactly the same as the one in the previous section - going about it much more elegantly though. You don't need to worry about headers,write ugly JavaScript code into a string etc. When the first parameter to +render+ is +:update+, Rails expects a block with a single parameter (+page+ in our case, which is the traditional naming convention) which is an instance of the JavaScriptGenerator:"http://api.rubyonrails.org/classes/ActionView/Helpers/PrototypeHelper/JavaScriptGenerator/GeneratorMethods.html" object. As it's name suggests, JavaScriptGenerator is responsible for generating JavaScript from your Ruby code. You can execute multiple method calls on the +page+ instance - it's all turned into JavaScript code and sent to the server with the appropriate Content Type, "text/javascript". - -h4. RJS Templates - -If you don't want to clutter your controllers with view code (especially when your inline RJS is more than a few lines), you can move your RJS code to a template file. RJS templates should go to the +/app/views/+ directory, just as +.html.erb+ or any other view files of the appropriate controller, conventionally named +js.rjs+. - -To rewrite the above example, you can leave the body of the action empty, and create a RJS template named +javascript_test.js.rjs+, containing the following line: - -<ruby> -page.alert "Hello from inline RJS" -</ruby> - -h4. RJS Reference - -In this section we'll go through the methods RJS offers. - -h5. JavaScriptGenerator Methods - -h6. DOM Element Manipulation - -It is possible to manipulate multiple elements at once through the +page+ JavaScriptGenerator instance. Let's see this in action: - -<ruby> -page.show :div_one, :div_two -page.hide :div_one -page.remove :div_one, :div_two, :div_three -page.toggle :other_div -</ruby> - -The above methods (+show+, +hide+, +remove+, +toggle+) have the same semantics as the Prototype methods of the same name. You can pass an arbitrary number (but at least one) of DOM ids to these calls. - - -h6. Inserting and Replacing Content - -You can insert content into an element on the page with the +insert_html+ method: - -<ruby> -page.insert_html :top, :result, '42' -</ruby> - -The first parameter is the position of the new content relative to the element specified by the second parameter, a DOM id. - -Position can be one of these four values: - -*** +:before+ Inserts the response text just before the target element. -*** +:after+ The response is inserted after the target element. -*** +:top+ Inserts the text into the target element, before it's original content. -*** +:bottom+ The counterpart of +:top+: the response is inserted after the target element's original content. - -The third parameter can either be a string, or a hash of options to be passed to ActionView::Base#render - for example: - -<ruby> -page.insert_html :top, :result, :partial => "the_answer" -</ruby> - -You can replace the contents (innerHTML) of an element with the +replace_html+ method. The only difference is that since it's clear where should the new content go, there is no need for a position parameter - so +replace_html+ takes only two arguments, -the DOM id of the element you wish to modify and a string or a hash of options to be passed to ActionView::Base#render. - -h6. Delay - -You can delay the execution of a block of code with +delay+: - -<ruby> -page.delay(10) { page.alert('Hey! Just waited 10 seconds') } -</ruby> - -+delay+ takes one parameter (time to wait in seconds) and a block which will be executed after the specified time has passed - whatever else follows a +page.delay+ line is executed immediately, the delay affects only the code in the block. - -h6. Reloading and Redirecting - -You can reload the page with the +reload+ method: - -<ruby> -page.reload -</ruby> - -When using AJAX, you can't rely on the standard +redirect_to+ controller method - you have to use the +page+'s instance method, also called +redirect_to+: - -<ruby> -page.redirect_to some_url -</ruby> - -h6. Generating Arbitrary JavaScript - -Sometimes even the full power of RJS is not enough to accomplish everything, but you still don't want to drop to pure JavaScript. A nice golden mean is offered by the combination of +<<+, +assign+ and +call+ methods: - -<ruby> - page << "alert('1+1 equals 3')" -</ruby> - -So +<<+ is used to execute an arbitrary JavaScript statement, passed as string to the method. The above code is equivalent to: - -<ruby> - page.assign :result, 3 - page.call :alert, '1+1 equals ' + result -</ruby> - -+assign+ simply assigns a value to a variable. +call+ is similar to +<<+ with a slightly different syntax: the first parameter is the name of the function to call, followed by the list of parameters passed to the function. - -h6. Class Proxies - -h5. Element Proxies - -h5. Collection Proxies - -h5. RJS Helpers - - - -h3. I Want my Yellow Thingy: Quick overview of Script.aculo.us - -h4. Introduction - -h4. Visual Effects - -h4. Drag and Drop - - h3. Testing JavaScript diff --git a/railties/guides/source/api_documentation_guidelines.textile b/railties/guides/source/api_documentation_guidelines.textile index 7433507866..e22ffa4c04 100644 --- a/railties/guides/source/api_documentation_guidelines.textile +++ b/railties/guides/source/api_documentation_guidelines.textile @@ -29,7 +29,7 @@ Documentation has to be concise but comprehensive. Explore and document edge cas The proper names of Rails components have a space in between the words, like "Active Support". +ActiveRecord+ is a Ruby module, whereas Active Record is an ORM. All Rails documentation should consistently refer to Rails components by their proper name, and if in your next blog post or presentation you remember this tidbit and take it into account that'd be phenomenal. -Spell names correctly: Arel, Test::Unit, RSpec, HTML, MySQL, JavaScript, ERb. When in doubt, please have a look at some authoritative source like their official documentation. +Spell names correctly: Arel, Test::Unit, RSpec, HTML, MySQL, JavaScript, ERB. When in doubt, please have a look at some authoritative source like their official documentation. Use the article "an" for "SQL", as in "an SQL statement". Also "an SQLite database". diff --git a/railties/guides/source/command_line.textile b/railties/guides/source/command_line.textile index 581fece1ab..9d8a9caf08 100644 --- a/railties/guides/source/command_line.textile +++ b/railties/guides/source/command_line.textile @@ -215,13 +215,13 @@ $ rails generate scaffold HighScore game:string score:integer create app/views/layouts/ exists test/functional/ create test/unit/ - create public/stylesheets/ + create app/assets/stylesheets/ create app/views/high_scores/index.html.erb create app/views/high_scores/show.html.erb create app/views/high_scores/new.html.erb create app/views/high_scores/edit.html.erb create app/views/layouts/high_scores.html.erb - create public/stylesheets/scaffold.css + create app/assets/stylesheets/scaffold.css.scss create app/controllers/high_scores_controller.rb create test/functional/high_scores_controller_test.rb create app/helpers/high_scores_helper.rb @@ -484,7 +484,7 @@ end We take whatever args are supplied, save them to an instance variable, and literally copying from the Rails source, implement a +manifest+ method, which calls +record+ with a block, and we: * Check there's a *public* directory. You bet there is. -* Run the ERb template called "tutorial.erb". +* Run the ERB template called "tutorial.erb". * Save it into "Rails.root/public/tutorial.txt". * Pass in the arguments we saved through the +:assigns+ parameter. diff --git a/railties/guides/source/configuring.textile b/railties/guides/source/configuring.textile index 298335d484..53460b8c36 100644 --- a/railties/guides/source/configuring.textile +++ b/railties/guides/source/configuring.textile @@ -149,7 +149,7 @@ h4. Configuring Middleware Every Rails application comes with a standard set of middleware which it uses in this order in the development environment: -* +Rack::SSL+ Will force every requests to be under HTTPS protocol. Will be available if +config.force_ssl+ is set to _true_. +* +Rack::SSL+ Will force every request to be under HTTPS protocol. Will be available if +config.force_ssl+ is set to _true_. * +ActionDispatch::Static+ is used to serve static assets. Disabled if +config.serve_static_assets+ is _true_. * +Rack::Lock+ Will wrap the app in mutex so it can only be called by a single thread at a time. Only enabled if +config.action_controller.allow_concurrency+ is set to _false_, which it is by default. * +ActiveSupport::Cache::Strategy::LocalCache+ Serves as a basic memory backed cache. This cache is not thread safe and is intended only for serving as a temporary memory cache for a single thread. @@ -291,8 +291,6 @@ h4. Configuring Action View There are only a few configuration options for Action View, starting with four on +ActionView::Base+: -* +config.action_view.debug_rjs+ specifies whether RJS responses should be wrapped in a try/catch block that alerts the caught exception (and then re-raises it). The default is +false+. - * +config.action_view.field_error_proc+ provides an HTML generator for displaying errors that come from Active Record. The default is <tt>Proc.new{ |html_tag, instance| %Q(%<div class="field_with_errors">#{html_tag}</div>).html_safe }</tt> * +config.action_view.default_form_builder+ tells Rails which form builder to use by default. The default is +ActionView::Helpers::FormBuilder+. diff --git a/railties/guides/source/debugging_rails_applications.textile b/railties/guides/source/debugging_rails_applications.textile index 045b8823ca..fb17dccfb8 100644 --- a/railties/guides/source/debugging_rails_applications.textile +++ b/railties/guides/source/debugging_rails_applications.textile @@ -96,26 +96,6 @@ Will be rendered as follows: Title: Rails debugging guide </pre> -h4. Debugging RJS - -Rails has optional built-in support to debug RJS. When enabled, responses are wrapped in a try/catch block that displays the caught exception using +alert()+, and then re-raises it. - -The flag to enable RJS debugging in your configuration files is +config.action_view.debug_rjs+: - -<ruby> -config.action_view.debug_rjs = true -</ruby> - -or at any time setting +ActionView::Base.debug_rjs+: - -<ruby> -ActionView::Base.debug_rjs = true -</ruby> - -It is enabled by default in development mode, and disabled in the rest. - -TIP: For more information on debugging JavaScript, refer to "Firebug":http://getfirebug.com/, the popular debugger for Firefox. - h3. The Logger It can also be useful to save information to log files at runtime. Rails maintains a separate log file for each runtime environment. diff --git a/railties/guides/source/generators.textile b/railties/guides/source/generators.textile index d32ba48003..cd8ac3d6fd 100644 --- a/railties/guides/source/generators.textile +++ b/railties/guides/source/generators.textile @@ -190,7 +190,7 @@ $ rails generate scaffold User name:string invoke test_unit create test/unit/helpers/users_helper_test.rb invoke stylesheets - create public/stylesheets/scaffold.css + create app/assets/stylesheets/scaffold.css.scss </shell> Looking at this output, it's easy to understand how generators work in Rails 3.0 and above. The scaffold generator doesn't actually generate anything, it just invokes others to do the work. This allows us to add/replace/remove any of those invocations. For instance, the scaffold generator invokes the scaffold_controller generator, which invokes erb, test_unit and helper generators. Since each generator has a single responsibility, they are easy to reuse, avoiding code duplication. diff --git a/railties/guides/source/getting_started.textile b/railties/guides/source/getting_started.textile index 0661549644..3f9bd2b6da 100644 --- a/railties/guides/source/getting_started.textile +++ b/railties/guides/source/getting_started.textile @@ -368,7 +368,7 @@ The scaffold generator will build 15 files in your application, along with some |test/functional/posts_controller_test.rb |Functional testing harness for the posts controller| |test/unit/helpers/posts_helper_test.rb |Unit testing harness for the posts helper| |config/routes.rb |Edited to include routing information for posts| -|public/stylesheets/scaffold.css |Cascading style sheet to make the scaffolded views look better| +|app/assets/stylesheets/scaffold.css.scss |Cascading style sheet to make the scaffolded views look better| h4. Running a Migration @@ -501,8 +501,8 @@ def index @posts = Post.all respond_to do |format| - format.html # index.html.erb - format.xml { render :xml => @posts } + format.html # index.html.erb + format.json { render :json => @posts } end end </ruby> @@ -511,7 +511,7 @@ end TIP: For more information on finding records with Active Record, see "Active Record Query Interface":active_record_querying.html. -The +respond_to+ block handles both HTML and XML calls to this action. If you browse to "http://localhost:3000/posts.xml":http://localhost:3000/posts.xml, you'll see all of the posts in XML format. The HTML format looks for a view in +app/views/posts/+ with a name that corresponds to the action name. Rails makes all of the instance variables from the action available to the view. Here's +app/views/posts/index.html.erb+: +The +respond_to+ block handles both HTML and JSON calls to this action. If you browse to "http://localhost:3000/posts.json":http://localhost:3000/posts.json, you'll see a JSON containing all of the posts. The HTML format looks for a view in +app/views/posts/+ with a name that corresponds to the action name. Rails makes all of the instance variables from the action available to the view. Here's +app/views/posts/index.html.erb+: <erb> <h1>Listing posts</h1> @@ -584,8 +584,8 @@ def new @post = Post.new respond_to do |format| - format.html # new.html.erb - format.xml { render :xml => @post } + format.html # new.html.erb + format.json { render :json => @post } end end </ruby> @@ -653,13 +653,13 @@ def create respond_to do |format| if @post.save - format.html { redirect_to(@post, + format.html { redirect_to(@post, :notice => 'Post was successfully created.') } - format.xml { render :xml => @post, + format.json { render :json => @post, :status => :created, :location => @post } else - format.html { render :action => "new" } - format.xml { render :xml => @post.errors, + format.html { render :action => "new" } + format.json { render :json => @post.errors, :status => :unprocessable_entity } end end @@ -681,8 +681,8 @@ def show @post = Post.find(params[:id]) respond_to do |format| - format.html # show.html.erb - format.xml { render :xml => @post } + format.html # show.html.erb + format.json { render :json => @post } end end </ruby> @@ -743,12 +743,12 @@ def update respond_to do |format| if @post.update_attributes(params[:post]) - format.html { redirect_to(@post, + format.html { redirect_to(@post, :notice => 'Post was successfully updated.') } - format.xml { head :ok } + format.json { render :json => {}, :status => :ok } else - format.html { render :action => "edit" } - format.xml { render :xml => @post.errors, + format.html { render :action => "edit" } + format.json { render :json => @post.errors, :status => :unprocessable_entity } end end @@ -767,8 +767,8 @@ def destroy @post.destroy respond_to do |format| - format.html { redirect_to(posts_url) } - format.xml { head :ok } + format.html { redirect_to(posts_url) } + format.json { render :json => {}, :status => :ok } end end </ruby> @@ -1201,36 +1201,19 @@ h3. Security If you were to publish your blog online, anybody would be able to add, edit and delete posts or delete comments. -Rails provides a very simple HTTP authentication system that will work nicely in this situation. First, we enable simple HTTP based authentication in our <tt>app/controllers/application_controller.rb</tt>: +Rails provides a very simple HTTP authentication system that will work nicely in this situation. -<ruby> -class ApplicationController < ActionController::Base - protect_from_forgery - - private - - def authenticate - authenticate_or_request_with_http_basic do |user_name, password| - user_name == 'admin' && password == 'password' - end - end - -end -</ruby> - -You can obviously change the username and password to whatever you want. We put this method inside of +ApplicationController+ so that it is available to all of our controllers. - -Then in the +PostsController+ we need to have a way to block access to the various actions if the person is not authenticated, here we can use the Rails <tt>before_filter</tt> method, which allows us to specify that Rails must run a method and only then allow access to the requested action if that method allows it. +In the +PostsController+ we need to have a way to block access to the various actions if the person is not authenticated, here we can use the Rails <tt>http_basic_authenticate_with</tt> method, allowing access to the requested action if that method allows it. -To use the before filter, we specify it at the top of our +PostsController+, in this case, we want the user to be authenticated on every action, except for +index+ and +show+, so we write that: +To use the authentication system, we specify it at the top of our +PostsController+, in this case, we want the user to be authenticated on every action, except for +index+ and +show+, so we write that: <ruby> class PostsController < ApplicationController - before_filter :authenticate, :except => [:index, :show] + http_basic_authenticate_with :name => "dhh", :password => "secret", :except => :index # GET /posts - # GET /posts.xml + # GET /posts.json def index @posts = Post.all respond_to do |format| @@ -1242,7 +1225,7 @@ We also only want to allow authenticated users to delete comments, so in the +Co <ruby> class CommentsController < ApplicationController - before_filter :authenticate, :only => :destroy + http_basic_authenticate_with :name => "dhh", :password => "secret", :only => :destroy def create @post = Post.find(params[:post_id]) @@ -1475,6 +1458,7 @@ Two very common sources of data that are not UTF-8: h3. Changelog +* April 11, 2011: Changed scaffold_controller generator to create format block for JSON instead of XML "Sebastian Martinez":http://www.wyeworks.com * August 30, 2010: Minor editing after Rails 3 release by "Joost Baaij":http://www.spacebabies.nl * July 12, 2010: Fixes, editing and updating of code samples by "Jaime Iniesta":http://jaimeiniesta.com * May 16, 2010: Added a section on configuration gotchas to address common encoding problems that people might have by "Yehuda Katz":http://www.yehudakatz.com diff --git a/railties/guides/source/initialization.textile b/railties/guides/source/initialization.textile index 0cbbe1f389..7c01f01b24 100644 --- a/railties/guides/source/initialization.textile +++ b/railties/guides/source/initialization.textile @@ -478,8 +478,7 @@ The next line in +config/application.rb+ is: require 'rails/all' </ruby> -h4 +railties/lib/rails/all.rb+ - +h4. +railties/lib/rails/all.rb+ This file is responsible for requiring all the individual parts of Rails like so: @@ -591,7 +590,7 @@ h4. +activesupport/lib/active_support/deprecation/behaviors.rb+ This file defines the behavior of the +ActiveSupport::Deprecation+ module, setting up the +DEFAULT_BEHAVIORS+ hash constant which contains the three defaults to outputting deprecation warnings: +:stderr+, +:log+ and +:notify+. This file begins by requiring +activesupport/notifications+ and +activesupport/core_ext/array/wrap+. -h4 +activesupport/lib/active_support/notifications.rb+ +h4. +activesupport/lib/active_support/notifications.rb+ TODO: document +ActiveSupport::Notifications+. diff --git a/railties/guides/source/layout.html.erb b/railties/guides/source/layout.html.erb index f2681c6461..911655e0f4 100644 --- a/railties/guides/source/layout.html.erb +++ b/railties/guides/source/layout.html.erb @@ -111,7 +111,7 @@ <h3>Feedback</h3> <p> - You're encouraged to help in keeping the quality of this guide. + You're encouraged to help improve the quality of this guide. </p> <p> If you see any typos or factual errors you are confident to diff --git a/railties/guides/source/layouts_and_rendering.textile b/railties/guides/source/layouts_and_rendering.textile index 1548da0eb5..8dab578e6b 100644 --- a/railties/guides/source/layouts_and_rendering.textile +++ b/railties/guides/source/layouts_and_rendering.textile @@ -90,7 +90,7 @@ If we want to display the properties of all the books in our view, we can do so <%= link_to 'New book', new_book_path %> </ruby> -NOTE: The actual rendering is done by subclasses of +ActionView::TemplateHandlers+. This guide does not dig into that process, but it's important to know that the file extension on your view controls the choice of template handler. In Rails 2, the standard extensions are +.erb+ for ERB (HTML with embedded Ruby), +.rjs+ for RJS (JavaScript with embedded ruby) and +.builder+ for Builder (XML generator). +NOTE: The actual rendering is done by subclasses of +ActionView::TemplateHandlers+. This guide does not dig into that process, but it's important to know that the file extension on your view controls the choice of template handler. In Rails 2, the standard extensions are +.erb+ for ERB (HTML with embedded Ruby), and +.builder+ for Builder (XML generator). h4. Using +render+ @@ -250,18 +250,6 @@ render :inline => "xml.p {'Horrid coding practice!'}", :type => :builder </ruby> -h5. Using +render+ with +:update+ - -You can also render JavaScript-based page updates inline using the +:update+ option to +render+: - -<ruby> -render :update do |page| - page.replace_html 'warning', "Invalid options supplied" -end -</ruby> - -WARNING: Placing JavaScript updates in your controller may seem to streamline small updates, but it defeats the MVC orientation of Rails and will make it harder for other developers to follow the logic of your project. We recommend using a separate RJS template instead, no matter how small the update. - h5. Rendering Text You can send plain text - with no markup at all - back to the browser by using the +:text+ option to +render+: @@ -296,7 +284,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 an +.rjs+ file): +Rails can render vanilla JavaScript: <ruby> render :js => "alert('Hello Rails');" @@ -707,18 +695,28 @@ To include +http://example.com/main.js+: <%= javascript_include_tag "http://example.com/main.js" %> </erb> -The +defaults+ option loads the Prototype and Scriptaculous libraries: +The +:defaults+ option loads jQuery by default: <erb> <%= javascript_include_tag :defaults %> </erb> -The +all+ option loads every JavaScript file in +public/javascripts+, starting with the Prototype and Scriptaculous libraries: +If the application was generated with "-j prototype" <tt>:defaults</tt> loads Prototype and Scriptaculous. And you can in any case override the expansion in <tt>config/application.rb</tt>: + +<ruby> +config.action_view.javascript_expansions[:defaults] = %w(foo.js bar.js) +</ruby> + +When using <tt>:defaults</tt>, if an <tt>application.js</tt> file exists in <tt>public/javascripts</tt> it will be included as well at then end. + +The +:all+ option loads every JavaScript file in +public/javascripts+: <erb> <%= javascript_include_tag :all %> </erb> +Note that your defaults of choice will be included first, so they will be available to all subsequently included files. + You can supply the +:recursive+ option to load files in subfolders of +public/javascripts+ as well: <erb> diff --git a/railties/guides/source/ruby_on_rails_guides_guidelines.textile b/railties/guides/source/ruby_on_rails_guides_guidelines.textile index 6576758856..8e55780dca 100644 --- a/railties/guides/source/ruby_on_rails_guides_guidelines.textile +++ b/railties/guides/source/ruby_on_rails_guides_guidelines.textile @@ -10,10 +10,10 @@ Guides are written in "Textile":http://www.textism.com/tools/textile/. There's c h3. Prologue -Each guide should start with motivational text at the top. That's the little introduction in the blue area. The prologue should tell the readers what's the guide about, and what will they learn. See for example the "Routing Guide":routing.html. +Each guide should start with motivational text at the top (that's the little introduction in the blue area.) The prologue should tell the reader what the guide is about, and what they will learn. See for example the "Routing Guide":routing.html. h3. Titles - + The title of every guide uses +h2+, guide sections use +h3+, subsections +h4+, etc. Capitalize all words except for internal articles, prepositions, conjunctions, and forms of the verb to be: @@ -23,7 +23,7 @@ h5. Middleware Stack is an Array h5. When are Objects Saved? </plain> -Use same typography as in regular text: +Use the same typography as in regular text: <plain> h6. The +:content_type+ Option @@ -42,13 +42,13 @@ Those guidelines apply also to guides. h3. HTML Generation -To generate all the guides just cd into the +railties+ directory and execute +To generate all the guides, just +cd+ into the +railties+ directory and execute: <plain> bundle exec rake generate_guides </plain> -You'll need the gems erubis, i18n, and RedCloth. +(You may need to run +bundle install+ first to install the required gems.) To process +my_guide.textile+ and nothing else use the +ONLY+ environment variable: @@ -56,13 +56,13 @@ To process +my_guide.textile+ and nothing else use the +ONLY+ environment variab bundle exec rake generate_guides ONLY=my_guide </plain> -Although by default guides that have not been modified are not processed, so +ONLY+ is rarely needed in practice. +By default, guides that have not been modified are not processed, so +ONLY+ is rarely needed in practice. To force process of all the guides, pass +ALL=1+. -It is also recommended that you work with +WARNINGS=1+, this detects duplicate IDs and warns about broken internal links. +It is also recommended that you work with +WARNINGS=1+. This detects duplicate IDs and warns about broken internal links. -If you want to generate guides in languages other than English, you can keep them in a separate directory under +source+ (eg. <tt>source/es</tt>) and use the +LANGUAGE+ environment variable. +If you want to generate guides in languages other than English, you can keep them in a separate directory under +source+ (eg. <tt>source/es</tt>) and use the +LANGUAGE+ environment variable: <plain> rake generate_guides LANGUAGE=es @@ -70,7 +70,7 @@ rake generate_guides LANGUAGE=es h3. HTML Validation -Please do validate the generated HTML with +Please validate the generated HTML with: <plain> rake validate_guides @@ -80,4 +80,5 @@ Particularly, titles get an ID generated from their content and this often leads h3. Changelog +* March 31, 2011: grammar tweaks by "Josiah Ivey":http://twitter.com/josiahivey * October 5, 2010: ported from the docrails wiki and revised by "Xavier Noria":credits.html#fxn diff --git a/railties/guides/source/security.textile b/railties/guides/source/security.textile index 893f65856c..c9dc1c2d7c 100644 --- a/railties/guides/source/security.textile +++ b/railties/guides/source/security.textile @@ -893,12 +893,6 @@ h4. Ajax Injection If you use the "in_place_editor plugin":http://dev.rubyonrails.org/browser/plugins/in_place_editing, or actions that return a string, rather than rendering a view, _(highlight)you have to escape the return value in the action_. Otherwise, if the return value contains a XSS string, the malicious code will be executed upon return to the browser. Escape any input value using the h() method. -h4. RJS Injection - --- _Don't forget to escape in JavaScript (RJS) templates, too._ - -The RJS API generates blocks of JavaScript code based on Ruby code, thus allowing you to manipulate a view or parts of a view from the server side. <em class="highlight">If you allow user input in RJS templates, do escape it using +escape_javascript()+ within JavaScript functions, and in HTML parts using +h()+</em>. Otherwise an attacker could execute arbitrary JavaScript. - h4. Command Line Injection -- _Use user-supplied command line parameters with caution._ diff --git a/railties/guides/source/testing.textile b/railties/guides/source/testing.textile index d3f72509c6..e2317661ea 100644 --- a/railties/guides/source/testing.textile +++ b/railties/guides/source/testing.textile @@ -79,9 +79,9 @@ steve: Each fixture is given a name followed by an indented list of colon-separated key/value pairs. Records are separated by a blank space. You can place comments in a fixture file by using the # character in the first column. -h5. ERb'in It Up +h5. ERB'in It Up -ERb allows you to embed ruby code within templates. Both the YAML and CSV fixture formats are pre-processed with ERb when you load fixtures. This allows you to use Ruby to help you generate some sample data. +ERB allows you to embed ruby code within templates. Both the YAML and CSV fixture formats are pre-processed with ERB when you load fixtures. This allows you to use Ruby to help you generate some sample data. <erb> <% earth_size = 20 %> @@ -391,7 +391,7 @@ There are a bunch of different types of assertions you can use. Here's the compl |+assert_nil( obj, [msg] )+ |Ensures that +obj.nil?+ is true.| |+assert_not_nil( obj, [msg] )+ |Ensures that +obj.nil?+ is false.| |+assert_match( regexp, string, [msg] )+ |Ensures that a string matches the regular expression.| -|+assert_no_match( regexp, string, [msg] )+ |Ensures that a string doesn't matches the regular expression.| +|+assert_no_match( regexp, string, [msg] )+ |Ensures that a string doesn't match the regular expression.| |+assert_in_delta( expecting, actual, delta, [msg] )+ |Ensures that the numbers +expecting+ and +actual+ are within +delta+ of each other.| |+assert_throws( symbol, [msg] ) { block }+ |Ensures that the given block throws the symbol.| |+assert_raise( exception1, exception2, ... ) { block }+ |Ensures that the given block raises one of the given exceptions.| @@ -592,7 +592,6 @@ There are more assertions that are primarily used in testing views: |_.Assertion |_.Purpose| |+assert_select_email+ |Allows you to make assertions on the body of an e-mail. | -|+assert_select_rjs+ |Allows you to make assertions on an RJS response. +assert_select_rjs+ has variants which allow you to narrow down on the updated element or even a particular operation on an element.| |+assert_select_encoded+ |Allows you to make assertions on encoded HTML. It does this by un-encoding the contents of each element and then calling the block with all the un-encoded elements.| |+css_select(selector)+ or +css_select(element, selector)+ |Returns an array of all the elements selected by the _selector_. In the second variant it first matches the base _element_ and tries to match the _selector_ expression on any of its children. If there are no matches both variants return an empty array.| @@ -748,7 +747,8 @@ You don't need to set up and run your tests by hand on a test-by-test basis. Rai h3. Brief Note About +Test::Unit+ -Ruby ships with a boat load of libraries. One little gem of a library is +Test::Unit+, a framework for unit testing in Ruby. All the basic assertions discussed above are actually defined in +Test::Unit::Assertions+. The class +ActiveSupport::TestCase+ which we have been using in our unit and functional tests extends +Test::Unit::TestCase+ that it is how we can use all the basic assertions in our tests. +Ruby ships with a boat load of libraries. One little gem of a library is +Test::Unit+, a framework for unit testing in Ruby. All the basic assertions discussed above are actually defined in +Test::Unit::Assertions+. The class +ActiveSupport::TestCase+ which we have been using in our unit and functional tests extends +Test::Unit::TestCase+, allowing +us to use all of the basic assertions in our tests. NOTE: For more information on +Test::Unit+, refer to "test/unit Documentation":http://ruby-doc.org/stdlib/libdoc/test/unit/rdoc/ |