From 1f62c6d09f44d080a508e18ec2c44c0adb61b76e Mon Sep 17 00:00:00 2001 From: RAHUL CHAUDHARI Date: Tue, 11 Oct 2011 17:17:20 +0530 Subject: Fixed typos in active_support_core_extensions.textile --- railties/guides/source/active_support_core_extensions.textile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/active_support_core_extensions.textile b/railties/guides/source/active_support_core_extensions.textile index addf5f78be..ecc25c4f1c 100644 --- a/railties/guides/source/active_support_core_extensions.textile +++ b/railties/guides/source/active_support_core_extensions.textile @@ -1760,7 +1760,7 @@ h4(#string-conversions). Conversions h5. +ord+ -Ruby 1.9 defines +ord+ to be the codepoint of the first character of the receiver. Active Support backports +ord+ for single-byte encondings like ASCII or ISO-8859-1 in Ruby 1.8: +Ruby 1.9 defines +ord+ to be the codepoint of the first character of the receiver. Active Support backports +ord+ for single-byte encodings like ASCII or ISO-8859-1 in Ruby 1.8: "a".ord # => 97 @@ -1774,7 +1774,7 @@ In Ruby 1.8 +ord+ doesn't work in general in UTF8 strings, use the multibyte sup "à".mb_chars.ord # => 224, in UTF8 -Note that the 224 is different in both examples. In ISO-8859-1 "à" is represented as a single byte, 224. Its single-character representattion in UTF8 has two bytes, namely 195 and 160, but its Unicode codepoint is 224. If we call +ord+ on the UTF8 string "à" the return value will be 195 in Ruby 1.8. That is not an error, because UTF8 is unsupported, the call itself would be bogus. +Note that the 224 is different in both examples. In ISO-8859-1 "à" is represented as a single byte, 224. Its single-character representation in UTF8 has two bytes, namely 195 and 160, but its Unicode codepoint is 224. If we call +ord+ on the UTF8 string "à" the return value will be 195 in Ruby 1.8. That is not an error, because UTF8 is unsupported, the call itself would be bogus. INFO: +ord+ is equivalent to +getbyte(0)+. -- cgit v1.2.3 From 3ca269674f66558f6ced4d956ecae4959dacd596 Mon Sep 17 00:00:00 2001 From: mhutchin Date: Tue, 11 Oct 2011 06:27:01 -0700 Subject: Heavy copy editing of the find_each and find_in_batches section --- .../guides/source/active_record_querying.textile | 60 ++++++++++++---------- 1 file changed, 34 insertions(+), 26 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/active_record_querying.textile b/railties/guides/source/active_record_querying.textile index 81d73c4ccc..6ac9197f44 100644 --- a/railties/guides/source/active_record_querying.textile +++ b/railties/guides/source/active_record_querying.textile @@ -82,7 +82,7 @@ Active Record provides five different ways of retrieving a single object. h5. Using a Primary Key -Using Model.find(primary_key), you can retrieve the object corresponding to the supplied _primary key_ and matching the supplied options (if any). For example: +Using Model.find(primary_key), you can retrieve the object corresponding to the specified _primary key_ that matches any supplied options. For example: # Find the client with primary key (id) 10. @@ -170,7 +170,7 @@ h4. Retrieving Multiple Objects h5. Using Multiple Primary Keys -Model.find(array_of_primary_key) also accepts an array of _primary keys_. An array of all the matching records for the supplied _primary keys_ is returned. For example: +Model.find(array_of_primary_key) accepts an array of _primary keys_, returning an array containing all of the matching records for the supplied _primary keys_. For example: # Find the clients with primary keys 1 and 10. @@ -188,24 +188,26 @@ WARNING: Model.find(array_of_primary_key) will raise an +ActiveRecord:: h4. Retrieving Multiple Objects in Batches -Sometimes you need to iterate over a large set of records. For example to send a newsletter to all users, to export some data, etc. +We often need to iterate over a large set of records, as when we send a newsletter to a large set of users, or when we export data. -The following may seem very straightforward, at first: +This may appear straightforward: -# Very inefficient when users table has thousands of rows. +# This is very inefficient when the users table has thousands of rows. User.all.each do |user| NewsLetter.weekly_deliver(user) end -But if the total number of rows in the table is very large, the above approach may vary from being underperforming to being plain impossible. +But this approach becomes increasingly impractical as the table size increases, since +User.all.each+ instructs Active Record to fetch _the entire table_ in a single pass, build a model object per row, and then keep the entire array of model objects in memory. Indeed, if we have a large number of records, the entire collection may exceed the amount of memory available. -This is because +User.all.each+ makes Active Record fetch _the entire table_, build a model object per row, and keep the entire array of model objects in memory. Sometimes that is just too many objects and requires too much memory. +Rails provides two methods that address this problem by dividing records into memory-friendly batches for processing. The first method, +find_each+, retrieves a batch of records and then yields _each_ record to the block individually as a model. The second method, +find_in_batches+, retrieves a batch of records and then yields _the entire batch_ to the block as an array of models. + +TIP: The +find_each+ and +find_in_batches+ methods are intended for use in the batch processing of a large number of records that wouldn't fit in memory all at once. If you just need to loop over a thousand records the regular find methods are the preferred option. h5. +find_each+ -To efficiently iterate over a large table, Active Record provides a batch finder method called +find_each+: +The +find_each+ method retrieves a batch of records and then yields _each_ record to the block individually as a model. In the following example, +find_each+ will retrieve 1000 records (the current default for both +find_each+ and +find_in_batches+) and then yield each record individually to the block as a model. This process is repeated until all of the records have been processed: User.find_each do |user| @@ -213,11 +215,15 @@ User.find_each do |user| end -*Configuring the batch size* +h6. Options for +find_each+ + +The +find_each+ method accepts most of the options allowed by the regular +find+ method, except for +:order+ and +:limit+, which are reserved for internal use by +find_each+. -Behind the scenes, +find_each+ fetches rows in batches of 1000 and yields them one by one. The size of the underlying batches is configurable via the +:batch_size+ option. +Two additional options, +:batch_size+ and +:start+, are available as well. -To fetch +User+ records in batches of 5000, we can use: +*+:batch_size+* + +The +:batch_size+ option allows you to specify the number of records to be retrieved in each batch, before being passed individually to the block. For example, to retrieve records in batches of 5000: User.find_each(:batch_size => 5000) do |user| @@ -225,37 +231,39 @@ User.find_each(:batch_size => 5000) do |user| end -*Starting batch find from a specific primary key* +*+:start+* -Records are fetched in ascending order of the primary key, which must be an integer. The +:start+ option allows you to configure the first ID of the sequence whenever the lowest ID is not the one you need. This may be useful, for example, to be able to resume an interrupted batch process, provided it saves the last processed ID as a checkpoint. +By default, records are fetched in ascending order of the primary key, which must be an integer. The +:start+ option allows you to configure the first ID of the sequence whenever the lowest ID is not the one you need. This would be useful, for example, if you wanted to resume an interrupted batch process, provided you saved the last processed ID as a checkpoint. -To send newsletters only to users with the primary key starting from 2000, we can use: +For example, to send newsletters only to users with the primary key starting from 2000, and to retrieve them in batches of 5000: -User.find_each(:batch_size => 5000, :start => 2000) do |user| +User.find_each(:start => 2000, :batch_size => 5000) do |user| NewsLetter.weekly_deliver(user) end -*Additional options* +Another example would be if you wanted multiple workers handling the same processing queue. You could have each worker handle 10000 records by setting the appropriate :start option on each worker. -+find_each+ accepts the same options as the regular +find+ method. However, +:order+ and +:limit+ are needed internally and hence not allowed to be passed explicitly. +NOTE: The +:include+ option allows you to name associations that should be loaded alongside with the models. h5. +find_in_batches+ -You can also work by chunks instead of row by row using +find_in_batches+. This method is analogous to +find_each+, but it yields arrays of models instead: +The +find_in_batches+ method is similar to +find_each+, since both retrieve batches of records. The difference is that +find_in_batches+ yields _batches_ to the block as an array of models, instead of individually. The following example will yield to the supplied block an array of up to 1000 invoices at a time, with the final block containing any remaining invoices: -# Works in chunks of 1000 invoices at a time. +# Give add_invoices an array of 1000 invoices at a time Invoice.find_in_batches(:include => :invoice_lines) do |invoices| export.add_invoices(invoices) end -The above will each time yield to the supplied block an array of 1000 invoices (or the remaining invoices, if less than 1000). - NOTE: The +:include+ option allows you to name associations that should be loaded alongside with the models. +h6. Options for +find_in_batches+ + +The +find_in_batches+ method accepts the same +:batch_size+ and +:start+ options as +find_each+, as well as most of the options allowed by the regular +find+ method, except for +:order+ and +:limit+, which are reserved for internal use by +find_in_batches+. + h3. Conditions The +where+ method allows you to specify conditions to limit the records returned, representing the +WHERE+-part of the SQL statement. Conditions can either be specified as a string, array, or hash. @@ -268,7 +276,7 @@ WARNING: Building your own conditions as pure strings can leave you vulnerable t h4. Array Conditions -Now what if that number could vary, say as an argument from somewhere? The find then becomes something like: +Now what if that number could vary, say as an argument from somewhere? The find would then take the form: Client.where("orders_count = ?", params[:orders]) @@ -276,7 +284,7 @@ Client.where("orders_count = ?", params[:orders]) Active Record will go through the first element in the conditions value and any additional elements will replace the question marks +(?)+ in the first element. -Or if you want to specify two conditions, you can do it like: +If you want to specify multiple conditions: Client.where("orders_count = ? AND locked = ?", params[:orders], false) @@ -284,19 +292,19 @@ Client.where("orders_count = ? AND locked = ?", params[:orders], false) In this example, the first question mark will be replaced with the value in +params[:orders]+ and the second will be replaced with the SQL representation of +false+, which depends on the adapter. -The reason for doing code like: +This code is highly preferable: Client.where("orders_count = ?", params[:orders]) -instead of: +to this code: Client.where("orders_count = #{params[:orders]}") -is because of argument safety. Putting the variable directly into the conditions string will pass the variable to the database *as-is*. This means that it will be an unescaped variable directly from a user who may have malicious intent. If you do this, you put your entire database at risk because once a user finds out he or she can exploit your database they can do just about anything to it. Never ever put your arguments directly inside the conditions string. +because of argument safety. Putting the variable directly into the conditions string will pass the variable to the database *as-is*. This means that it will be an unescaped variable directly from a user who may have malicious intent. If you do this, you put your entire database at risk because once a user finds out he or she can exploit your database they can do just about anything to it. Never ever put your arguments directly inside the conditions string. TIP: For more information on the dangers of SQL injection, see the "Ruby on Rails Security Guide":security.html#sql-injection. -- cgit v1.2.3 From c4e29541724433fd1c96715bde829209066ca205 Mon Sep 17 00:00:00 2001 From: Stephen Pike Date: Tue, 11 Oct 2011 09:32:23 -0400 Subject: Runtime conditions for associations should use procs The association guide previously recommended using a trick with single quote delaying of string interpolation in order to handle setting association conditions that would be evaluated at runtime. Using a proc is the new way as this no longer works. --- railties/guides/source/association_basics.textile | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/association_basics.textile b/railties/guides/source/association_basics.textile index 479a3c1e30..6829eb8ef4 100644 --- a/railties/guides/source/association_basics.textile +++ b/railties/guides/source/association_basics.textile @@ -1229,17 +1229,15 @@ end If you use a hash-style +:conditions+ option, then record creation via this association will be automatically scoped using the hash. In this case, using +@customer.confirmed_orders.create+ or +@customer.confirmed_orders.build+ will create orders where the confirmed column has the value +true+. -If you need to evaluate conditions dynamically at runtime, you could use string interpolation in single quotes: +If you need to evaluate conditions dynamically at runtime, use a proc: class Customer < ActiveRecord::Base has_many :latest_orders, :class_name => "Order", - :conditions => 'orders.created_at > #{10.hours.ago.to_s(:db).inspect}' + :conditions => proc { "orders.created_at > #{10.hours.ago.to_s(:db).inspect}" } end -Be sure to use single quotes. - h6(#has_many-counter_sql). +:counter_sql+ Normally Rails automatically generates the proper SQL to count the association members. With the +:counter_sql+ option, you can specify a complete SQL statement to count them yourself. -- cgit v1.2.3 From 532e6d59b50b241d51d2a423bab5962d9cf7b0d4 Mon Sep 17 00:00:00 2001 From: Craig Monson Date: Wed, 12 Oct 2011 10:34:27 -0400 Subject: quoting 'and' to make it more distinct. --- railties/guides/source/active_record_querying.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/active_record_querying.textile b/railties/guides/source/active_record_querying.textile index 6ac9197f44..2e1f89cb78 100644 --- a/railties/guides/source/active_record_querying.textile +++ b/railties/guides/source/active_record_querying.textile @@ -1024,7 +1024,7 @@ You can also use +find_last_by_*+ methods which will find the last record matchi You can specify an exclamation point (!) on the end of the dynamic finders to get them to raise an +ActiveRecord::RecordNotFound+ error if they do not return any records, like +Client.find_by_name!("Ryan")+ -If you want to find both by name and locked, you can chain these finders together by simply typing +and+ between the fields. For example, +Client.find_by_first_name_and_locked("Ryan", true)+. +If you want to find both by name and locked, you can chain these finders together by simply typing "+and+" between the fields. For example, +Client.find_by_first_name_and_locked("Ryan", true)+. WARNING: Up to and including Rails 3.1, when the number of arguments passed to a dynamic finder method is lesser than the number of fields, say Client.find_by_name_and_locked("Ryan"), the behavior is to pass +nil+ as the missing argument. This is *unintentional* and this behavior will be changed in Rails 3.2 to throw an +ArgumentError+. -- cgit v1.2.3 From e6b2e7fbeab495a9ce0533d3f778cca9cb268597 Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Thu, 13 Oct 2011 02:17:01 +0530 Subject: refactor guide example --- railties/guides/source/security.textile | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/security.textile b/railties/guides/source/security.textile index 0f100e0adf..8837e06de5 100644 --- a/railties/guides/source/security.textile +++ b/railties/guides/source/security.textile @@ -157,9 +157,9 @@ One possibility is to set the expiry time-stamp of the cookie with the session i class Session < ActiveRecord::Base def self.sweep(time = 1.hour) - time = time.split.inject { |count, unit| - count.to_i.send(unit) - } if time.is_a?(String) + if time.is_a?(String) + time = time.split.inject { |count, unit| count.to_i.send(unit) } + end delete_all "updated_at < '#{time.ago.to_s(:db)}'" end -- cgit v1.2.3 From e537a3fcb1fd16d169889dfbca13eece9cc3bdf1 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Thu, 13 Oct 2011 18:04:55 +1100 Subject: [engines guide] change comments resource generation Totally didn't like where this section was going, so scrapped it. Scaffold is great for some things (lol) but nested resources is definitely not one of them. Best to walk people through how to do it right, as they would in the real world --- railties/guides/source/engines.textile | 87 +++++++++++++--------------------- 1 file changed, 33 insertions(+), 54 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/engines.textile b/railties/guides/source/engines.textile index db2db05e57..e22f3a7ae6 100644 --- a/railties/guides/source/engines.textile +++ b/railties/guides/source/engines.textile @@ -201,83 +201,62 @@ If you'd rather play around in the console, +rails console+ will also work just h4. Generating a comments resource -Now that the engine has the ability to create new blog posts, it only makes sense to add commenting functionality as well. +Now that the engine has the ability to create new blog posts, it only makes sense to add commenting functionality as well. To do get this, you'll need to generate a comment model, a comment controller and then modify the posts scaffold to display comments and allow people to create new ones. -To do this, you can run the scaffold generator this time and tell it to generate a +Comment+ resource instead, with the table having two columns: a +post_id+ integer and +text+ text column. +Run the model generator and tell it to generate a +Comment+ model, with the related table having two columns: a +post_id+ integer and +text+ text column. -$ rails generate scaffold Comment post_id:integer text:text +$ rails generate model Comment post_id:integer text:text +invoke active_record +create db/migrate/[timestamp]_create_blorgh_comments.rb +create app/models/blorgh/comment.rb +invoke test_unit +create test/unit/blorgh/comment_test.rb +create test/fixtures/blorgh/comments.yml -This generator call will generate almost the same files as it did the first time we called it for generating the +Post+ resource, but this time the files will be called things such as +app/controllers/blorgh/comments_controller.rb+ and +app/models/blorgh/comment.rb+. - -There's a few things wrong with how this generator has worked. It would be better if the comments resource was nested inside the posts resource in the routes, and if the controller created new comment entries inside a post. These are two very easy things to fix up. - -The +resources+ line from this generator is placed into the +config/routes.rb+ by the generator, but you're going to want to have comments nested underneath a post, and so it's a good idea to change these lines in the +config/routes.rb+ file: - - -Blorgh::Engine.routes.draw do - resources :comments - - resources :posts - -end - - -Into these: - - - Blorgh::Engine.routes.draw do - resources :posts do - resources :comments - end - end - +This generator call will generate just the necessary model files it needs, namespacing the files under a +blorgh+ directory and creating a model class called +Blorgh::Comment+. -That fixes the routes. For the controller, it's just as easy. When a request is made to this controller, it will be in the form of +post/:post_id/comments+. In order to find the comments that are being requested, the post is going to need to be fetched using something such as: +To show the comments on a post, edit +app/views/posts/show.html.erb+ and add this line before the "Edit" link: - -post = Post.find(params[:id]) - + +<%= render @post.comments %> + -Then to get the comments for this post it would be as simple as: +This line will require there to be a +has_many+ association for comments defined on the +Blorgh::Post+ model, which there isn't right now. To define one, open +app/models/blorgh/post.rb+ and add this line into the model: -post.comments +has_many :comments -Alternatively, the query to fetch the comments in actions such as the +index+ action would need to be changed from +Comment.all+ into +Comment.find_all_by_post_id(params[:post_id])+. However, the first way is cleaner and so it should be done that way. - -To fetch the post in the controller, add a +before_filter+ into the controller's class definition like this: +Turning the model into this: module Blorgh - class CommentsController < ApplicationController - before_filter :load_post - ... + class Post < ActiveRecord::Base + has_many :comments end end -This +before_filter+ will call the +load_post+ method before every request that comes into this controller. This method should be defined as a +private+ method after all the actions in the controller: - - -module Blorgh - class CommentsController < ApplicationController - before_filter :load_post +Because the +has_many+ is defined inside a class that is inside the +Blorgh+ module, Rails will know that you want to use the +Blorgh::Comment+ model for these objects. - # actions go here +Next, there needs to be a form so that comments can be created on a post. To add this, put this line underneath the call to +render @post.comments+ in +app/views/blorgh/posts/show.html.erb+: - private + +<%= render "comments/form" %> + - def load_post - @post = Post.find(params[:post_id]) - end - end -end - +Next, the partial that this line will render needs to exist. Create a new directory at +app/views/blorgh/comments+ and in it a new file called +_form.html.erb+ with this content to create the required partial: -With the post being loaded, the queries in the controller need to be altered in order to query within the scope of the relative post. All occurrences of +Comment+ in this controller should now be replaced with +@post.comments+ so that the queries are correctly scoped. + +<%= form_for [@post, @post.comments.build] do |f| %> +

+ <%= f.label :text %>
+ <%= f.text_area :text %> +

+<% end %> +
h3. Hooking into application -- cgit v1.2.3 From 66b2dc059f6c6649731e762b28b5136bf053daac Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Thu, 13 Oct 2011 18:05:33 +1100 Subject: [engines guide] don't show actual timestamp in migration generation --- railties/guides/source/engines.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/engines.textile b/railties/guides/source/engines.textile index e22f3a7ae6..2366de33d7 100644 --- a/railties/guides/source/engines.textile +++ b/railties/guides/source/engines.textile @@ -107,7 +107,7 @@ The first thing to generate for a blog engine is the +Post+ model and related co $ rails generate scaffold post title:string text:text invoke active_record -create db/migrate/20111006201642_create_blorgh_posts.rb +create db/migrate/[timestamp]_create_blorgh_posts.rb create app/models/blorgh/post.rb invoke test_unit create test/unit/blorgh/post_test.rb -- cgit v1.2.3 From dadfa1e34f3ffbc2de98eae88b9715c41f4a1b66 Mon Sep 17 00:00:00 2001 From: PoTe Date: Thu, 13 Oct 2011 22:31:32 -0200 Subject: security reasonS should be plural --- railties/guides/source/action_controller_overview.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/action_controller_overview.textile b/railties/guides/source/action_controller_overview.textile index d8d66302fe..5019d49686 100644 --- a/railties/guides/source/action_controller_overview.textile +++ b/railties/guides/source/action_controller_overview.textile @@ -796,7 +796,7 @@ NOTE: Certain exceptions are only rescuable from the +ApplicationController+ cla h3. Force HTTPS protocol -Sometime you might want to force a particular controller to only be accessible via an HTTPS protocol for security reason. Since Rails 3.1 you can now use +force_ssl+ method in your controller to enforce that: +Sometime you might want to force a particular controller to only be accessible via an HTTPS protocol for security reasons. Since Rails 3.1 you can now use +force_ssl+ method in your controller to enforce that: class DinnerController -- cgit v1.2.3 From 411613ab207d6ff61520ad78a10b046469db9a80 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Fri, 14 Oct 2011 07:42:06 +1100 Subject: [engines guide] improve wording for sentence describing comments/form partial --- railties/guides/source/engines.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/engines.textile b/railties/guides/source/engines.textile index 2366de33d7..48c5cbf797 100644 --- a/railties/guides/source/engines.textile +++ b/railties/guides/source/engines.textile @@ -247,7 +247,7 @@ Next, there needs to be a form so that comments can be created on a post. To add <%= render "comments/form" %> -Next, the partial that this line will render needs to exist. Create a new directory at +app/views/blorgh/comments+ and in it a new file called +_form.html.erb+ with this content to create the required partial: +Next, the partial that this line will render needs to exist. Create a new directory at +app/views/blorgh/comments+ and in it a new file called +_form.html.erb+ which has this content to create the required partial: <%= form_for [@post, @post.comments.build] do |f| %> -- cgit v1.2.3 From 690dd2f64c01985ece8690b9ac1c1ff2dfb6d968 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Fri, 14 Oct 2011 07:45:00 +1100 Subject: [engines guide] correct render line is blorgh/comments/form --- railties/guides/source/engines.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/engines.textile b/railties/guides/source/engines.textile index 48c5cbf797..faa9dff8b8 100644 --- a/railties/guides/source/engines.textile +++ b/railties/guides/source/engines.textile @@ -244,7 +244,7 @@ Because the +has_many+ is defined inside a class that is inside the +Blorgh+ mod Next, there needs to be a form so that comments can be created on a post. To add this, put this line underneath the call to +render @post.comments+ in +app/views/blorgh/posts/show.html.erb+: -<%= render "comments/form" %> +<%= render "blorgh/comments/form" %> Next, the partial that this line will render needs to exist. Create a new directory at +app/views/blorgh/comments+ and in it a new file called +_form.html.erb+ which has this content to create the required partial: -- cgit v1.2.3 From 2101bc9fd00f284ee5f86e72f35df9937289871b Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Fri, 14 Oct 2011 07:51:07 +1100 Subject: [engines guide] make it clear that the scaffold generator output isn't part of the actual command --- railties/guides/source/engines.textile | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/engines.textile b/railties/guides/source/engines.textile index faa9dff8b8..0df3889193 100644 --- a/railties/guides/source/engines.textile +++ b/railties/guides/source/engines.textile @@ -106,6 +106,11 @@ The first thing to generate for a blog engine is the +Post+ model and related co $ rails generate scaffold post title:string text:text + + +This command will output this information: + + invoke active_record create db/migrate/[timestamp]_create_blorgh_posts.rb create app/models/blorgh/post.rb @@ -207,12 +212,12 @@ Run the model generator and tell it to generate a +Comment+ model, with the rela $ rails generate model Comment post_id:integer text:text -invoke active_record -create db/migrate/[timestamp]_create_blorgh_comments.rb -create app/models/blorgh/comment.rb -invoke test_unit -create test/unit/blorgh/comment_test.rb -create test/fixtures/blorgh/comments.yml + invoke active_record + create db/migrate/[timestamp]_create_blorgh_comments.rb + create app/models/blorgh/comment.rb + invoke test_unit + create test/unit/blorgh/comment_test.rb + create test/fixtures/blorgh/comments.yml This generator call will generate just the necessary model files it needs, namespacing the files under a +blorgh+ directory and creating a model class called +Blorgh::Comment+. -- cgit v1.2.3 From 2c8b8ce9eebce7f128d1811dde71f854fa8806c3 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Fri, 14 Oct 2011 07:51:45 +1100 Subject: [engines guide] make clear that the comment generator command is just one line --- railties/guides/source/engines.textile | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/engines.textile b/railties/guides/source/engines.textile index 0df3889193..f642781c04 100644 --- a/railties/guides/source/engines.textile +++ b/railties/guides/source/engines.textile @@ -212,12 +212,17 @@ Run the model generator and tell it to generate a +Comment+ model, with the rela $ rails generate model Comment post_id:integer text:text - invoke active_record - create db/migrate/[timestamp]_create_blorgh_comments.rb - create app/models/blorgh/comment.rb - invoke test_unit - create test/unit/blorgh/comment_test.rb - create test/fixtures/blorgh/comments.yml + + +This will output the following: + + +invoke active_record +create db/migrate/[timestamp]_create_blorgh_comments.rb +create app/models/blorgh/comment.rb +invoke test_unit +create test/unit/blorgh/comment_test.rb +create test/fixtures/blorgh/comments.yml This generator call will generate just the necessary model files it needs, namespacing the files under a +blorgh+ directory and creating a model class called +Blorgh::Comment+. -- cgit v1.2.3 From 3d192c73854b82fba313f641250f2e36031c87b7 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Fri, 14 Oct 2011 18:05:45 +1100 Subject: [engines guide] Add heading for comments --- railties/guides/source/engines.textile | 1 + 1 file changed, 1 insertion(+) (limited to 'railties/guides') diff --git a/railties/guides/source/engines.textile b/railties/guides/source/engines.textile index f642781c04..616ea16b7a 100644 --- a/railties/guides/source/engines.textile +++ b/railties/guides/source/engines.textile @@ -230,6 +230,7 @@ This generator call will generate just the necessary model files it needs, names To show the comments on a post, edit +app/views/posts/show.html.erb+ and add this line before the "Edit" link: +

Comments

<%= render @post.comments %>
-- cgit v1.2.3 From aae77d2839349eb5034d6a72bfc351a532f1e6d7 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Fri, 14 Oct 2011 18:06:23 +1100 Subject: [engines guide] complete comments resource generation --- railties/guides/source/engines.textile | 65 ++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) (limited to 'railties/guides') diff --git a/railties/guides/source/engines.textile b/railties/guides/source/engines.textile index 616ea16b7a..12c454abd1 100644 --- a/railties/guides/source/engines.textile +++ b/railties/guides/source/engines.textile @@ -261,14 +261,79 @@ Next, there needs to be a form so that comments can be created on a post. To add Next, the partial that this line will render needs to exist. Create a new directory at +app/views/blorgh/comments+ and in it a new file called +_form.html.erb+ which has this content to create the required partial: +

New comment

<%= form_for [@post, @post.comments.build] do |f| %>

<%= f.label :text %>
<%= f.text_area :text %>

+ <%= f.submit %> <% end %>
+This form, when submitted, is going to attempt to post to a route of +posts/:post_id/comments+ within the engine. This route doesn't exist at the moment, but can be created by changing the +resources :posts+ line inside +config/routes.rb+ into these lines: + + +resources :posts do + resources :comments +end + + +The route now will exist, but the controller that this route goes to does not. To create it, run this command: + + +$ rails g controller comments + + +This will generate the following things: + + +create app/controllers/blorgh/comments_controller.rb +invoke erb + exist app/views/blorgh/comments +invoke test_unit +create test/functional/blorgh/comments_controller_test.rb +invoke helper +create app/helpers/blorgh/comments_helper.rb +invoke test_unit +create test/unit/helpers/blorgh/comments_helper_test.rb +invoke assets +invoke js +create app/assets/javascripts/blorgh/comments.js +invoke css +create app/assets/stylesheets/blorgh/comments.css + + +The form will be making a +POST+ request to +/posts/:post_id/comments+, which will correspond with the +create+ action in +Blorgh::CommentsController+. This action needs to be created and can be done by putting the following lines inside the class definition in +app/controllers/blorgh/comments_controller.rb+: + + +def create + @post = Post.find(params[:post_id]) + @comment = @post.comments.build(params[:comment]) + flash[:notice] = "Comment has been created!" + redirect_to post_path +end + + +This is the final part required to get the new comment form working. Displaying the comments however, is not quite right yet. If you were to create a comment right now you would see this error: + + + Missing partial blorgh/comments/comment with {:handlers=>[:erb, :builder], :formats=>[:html], :locale=>[:en, :en]}. Searched in: + * "/Users/ryan/Sites/side_projects/blorgh/test/dummy/app/views" + * "/Users/ryan/Sites/side_projects/blorgh/app/views" + + +The engine is unable to find the partial required for rendering the comments. Rails has looked firstly in the application's (+test/dummy+) +app/views+ directory and then in the engine's +app/views+ directory. When it can't find it, it will throw this error. The engine knows to look for +blorgh/comments/comment+ because the model object it is receiving is from the +Blorgh::Comment+ class. + +This partial will be responsible for rendering just the comment text, for now. Create a new file at +app/views/blorgh/comments/_comment.html.erb+ and put this line inside it: + + +<%= comment_counter + 1 %>. <%= comment.text %> + + +The +comment_counter+ local variable is given to us by the +<%= render @post.comments %>+ call, as it will define this automatically and increment the counter as it iterates through each comment. It's used in this example to display a small number next to each comment when it's created. + +That completes the comment function of the blogging engine. Now it's time to use it within an application. h3. Hooking into application -- cgit v1.2.3 From 6df79bf580cf9a0464fce948c212bd117c378cc9 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Fri, 14 Oct 2011 18:43:49 +1100 Subject: [engines guide] WIP for explaining how to hook engine into application --- railties/guides/source/engines.textile | 46 ++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) (limited to 'railties/guides') diff --git a/railties/guides/source/engines.textile b/railties/guides/source/engines.textile index 12c454abd1..1eb0dcb77b 100644 --- a/railties/guides/source/engines.textile +++ b/railties/guides/source/engines.textile @@ -204,6 +204,14 @@ If you'd rather play around in the console, +rails console+ will also work just => #
+One final thing is that the +posts+ resource for this engine should be the root of the engine. Whenever someone goes to the root path where the engine is mounted, they should be shown a list of posts. This can be made to happen if this line is inserted into the +config/routes.rb+ file inside the engine: + + +root :to => "posts#index" + + +Now people will only need to go to the root of the engine to see all the posts, rather than visiting +/posts+. + h4. Generating a comments resource Now that the engine has the ability to create new blog posts, it only makes sense to add commenting functionality as well. To do get this, you'll need to generate a comment model, a comment controller and then modify the posts scaffold to display comments and allow people to create new ones. @@ -337,11 +345,49 @@ That completes the comment function of the blogging engine. Now it's time to use h3. Hooking into application +Using an engine within an application is very easy. First, the engine needs to be specified inside the application's +Gemfile+. If there isn't an application handy to test this out in, generate one using the +rails new+ command outside of the engine directory like this: + + +$ rails new unicorn + + +Usually, specifying the engine inside the Gemfile would be done by specifying it as a normal, everyday gem. + + +gem 'devise' + + +Because the +blorgh+ engine is still under development, it will need to have a +:path+ option for its +Gemfile+ specification: + + +gem 'blorgh', :path => "/path/to/blorgh" + + +If the whole +blorgh+ engine directory is copied to +vendor/engines/blorgh+ then it could be specified in the +Gemfile+ like this: + + +gem 'blorgh', :path => "vendor/engines/blorgh" + + +As described earlier, by placing the gem in the +Gemfile+ it will be loaded when Rails is loaded, as it will first require +lib/blorgh.rb+ in the engine and then +lib/blorgh/engine.rb+, which is the file that defines the major pieces of functionality for the engine. + +To make the engine's functionality accessible from within an application, it needs to be mounted in that application's +config/routes.rb+ file: + + + mount Blorgh::Engine, :at => "blog" + + +NOTE: Other engines, such as Devise, handle this a little differently by making you specify custom helpers such as +devise_for+ in the routes. These helpers do exactly the same thing, mounting pieces of the engines's functionality at a pre-defined path which may be customizable. + + + +This line will mount the engine TODO: Application will provide a User foundation class which the engine hooks into through a configuration setting, configurable in the application's initializers. The engine will be mounted at the +/blog+ path in the application. h3. Overriding engine functionality TODO: Cover how to override engine functionality in the engine, such as controllers and views. + IDEA: I like Devise's +devise :controllers => { "sessions" => "sessions" }+ idea. Perhaps we could incorporate that into the guide? TODO: Mention how to use assets within an engine? TODO: Mention how to depend on external gems, like RedCarpet. -- cgit v1.2.3