diff options
author | David Heinemeier Hansson <david@loudthinking.com> | 2011-10-25 17:22:55 -0500 |
---|---|---|
committer | David Heinemeier Hansson <david@loudthinking.com> | 2011-10-25 17:22:55 -0500 |
commit | 1d9ab88ee6360f54197ce21624d844425ec627b3 (patch) | |
tree | 252b3daf0d84e2a050c0da97b758f9ba06a3545e /railties | |
parent | 5daf07704ad21d885661216281ffc48b6ea6adfb (diff) | |
parent | 8aabdc69b7c498770e4c2864dad3e2790a40d10f (diff) | |
download | rails-1d9ab88ee6360f54197ce21624d844425ec627b3.tar.gz rails-1d9ab88ee6360f54197ce21624d844425ec627b3.tar.bz2 rails-1d9ab88ee6360f54197ce21624d844425ec627b3.zip |
Merge branch 'master' of github.com:rails/rails
Diffstat (limited to 'railties')
32 files changed, 561 insertions, 243 deletions
diff --git a/railties/CHANGELOG b/railties/CHANGELOG index 187dd2428f..7f7b24804d 100644 --- a/railties/CHANGELOG +++ b/railties/CHANGELOG @@ -1,5 +1,7 @@ *Rails 3.2.0 (unreleased)* +* Updated Rails::Rack::Logger middleware to apply any tags set in config.log_tags to the newly ActiveSupport::TaggedLogging Rails.logger. This makes it easy to tag log lines with debug information like subdomain and request id -- both very helpful in debugging multi-user production applications [DHH] + * Default options to `rails new` can be set in ~/.railsrc [Guillermo Iguaran] * Added destroy alias to Rails engines. [Guillermo Iguaran] diff --git a/railties/README.rdoc b/railties/README.rdoc index 95c43045b0..ae40600401 100644 --- a/railties/README.rdoc +++ b/railties/README.rdoc @@ -15,12 +15,21 @@ The latest version of Railties can be installed with RubyGems: * gem install railties -Documentation can be found at - -* http://api.rubyonrails.org +Source code can be downloaded as part of the Rails project on GitHub +* https://github.com/rails/rails/tree/master/railties == License Railties is released under the MIT license. +== Support + +API documentation is at + +* http://api.rubyonrails.org + +Bug reports and feature requests can be filed with the rest for the Ruby on Rails project here: + +* https://github.com/rails/rails/issues + diff --git a/railties/guides/code/getting_started/Gemfile b/railties/guides/code/getting_started/Gemfile index 51774934cd..898510dcaa 100644 --- a/railties/guides/code/getting_started/Gemfile +++ b/railties/guides/code/getting_started/Gemfile @@ -25,8 +25,3 @@ gem 'jquery-rails' # To use debugger # gem 'ruby-debug19', :require => 'ruby-debug' - -group :test do - # Pretty printed test output - gem 'turn', :require => false -end diff --git a/railties/guides/code/getting_started/config/environments/production.rb b/railties/guides/code/getting_started/config/environments/production.rb index 6ab63d30a6..dee8acfdfe 100644 --- a/railties/guides/code/getting_started/config/environments/production.rb +++ b/railties/guides/code/getting_started/config/environments/production.rb @@ -33,8 +33,11 @@ Blog::Application.configure do # See everything in the log (default is :info) # config.log_level = :debug + # Prepend all log lines with the following tags + # config.log_tags = [ :subdomain, :uuid ] + # Use a different logger for distributed setups - # config.logger = SyslogLogger.new + # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new) # Use a different cache store in production # config.cache_store = :mem_cache_store diff --git a/railties/guides/source/action_controller_overview.textile b/railties/guides/source/action_controller_overview.textile index d8d66302fe..b34c223b31 100644 --- a/railties/guides/source/action_controller_overview.textile +++ b/railties/guides/source/action_controller_overview.textile @@ -166,10 +166,10 @@ h3. Session Your application has a session for each user in which you can store small amounts of data that will be persisted between requests. The session is only available in the controller and the view and can use one of a number of different storage mechanisms: -* CookieStore - Stores everything on the client. -* DRbStore - Stores the data on a DRb server. -* MemCacheStore - Stores the data in a memcache. -* ActiveRecordStore - Stores the data in a database using Active Record. +* ActionDispatch::Session::CookieStore - Stores everything on the client. +* ActiveRecord::SessionStore - Stores the data in a database using Active Record. +* ActionDispatch::Session::CacheStore - Stores the data in the Rails cache. +* ActionDispatch::Session::MemCacheStore - Stores the data in a memcached cluster (this is a legacy implementation; consider using CacheStore instead). All session stores use a cookie to store a unique ID for each session (you must use a cookie, Rails will not allow you to pass the session ID in the URL as this is less secure). @@ -177,6 +177,8 @@ For most stores this ID is used to look up the session data on the server, e.g. The CookieStore can store around 4kB of data -- much less than the others -- but this is usually enough. Storing large amounts of data in the session is discouraged no matter which session store your application uses. You should especially avoid storing complex objects (anything other than basic Ruby objects, the most common example being model instances) in the session, as the server might not be able to reassemble them between requests, which will result in an error. +If your user sessions don't store critical data or don't need to be around for long periods (for instance if you just use the flash for messaging), you can consider using ActionDispatch::Session::CacheStore. This will store sessions using the cache implementation you have configured for your application. The advantage of this is that you can use your existing cache infrastructure for storing sessions without requiring any additional setup or administration. The downside, of course, is that the sessions will be ephemeral and could disappear at any time. + Read more about session storage in the "Security Guide":security.html. If you need a different session storage mechanism, you can change it in the +config/initializers/session_store.rb+ file: @@ -796,7 +798,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: <ruby> class DinnerController diff --git a/railties/guides/source/active_record_querying.textile b/railties/guides/source/active_record_querying.textile index 81d73c4ccc..2e1f89cb78 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 <tt>Model.find(primary_key)</tt>, you can retrieve the object corresponding to the supplied _primary key_ and matching the supplied options (if any). For example: +Using <tt>Model.find(primary_key)</tt>, you can retrieve the object corresponding to the specified _primary key_ that matches any supplied options. For example: <ruby> # Find the client with primary key (id) 10. @@ -170,7 +170,7 @@ h4. Retrieving Multiple Objects h5. Using Multiple Primary Keys -<tt>Model.find(array_of_primary_key)</tt> also accepts an array of _primary keys_. An array of all the matching records for the supplied _primary keys_ is returned. For example: +<tt>Model.find(array_of_primary_key)</tt> accepts an array of _primary keys_, returning an array containing all of the matching records for the supplied _primary keys_. For example: <ruby> # Find the clients with primary keys 1 and 10. @@ -188,24 +188,26 @@ WARNING: <tt>Model.find(array_of_primary_key)</tt> 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: <ruby> -# 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 </ruby> -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: <ruby> User.find_each do |user| @@ -213,11 +215,15 @@ User.find_each do |user| end </ruby> -*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: <ruby> User.find_each(:batch_size => 5000) do |user| @@ -225,37 +231,39 @@ User.find_each(:batch_size => 5000) do |user| end </ruby> -*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: <ruby> -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 </ruby> -*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 <tt>:start</tt> 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: <ruby> -# 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 </ruby> -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: <ruby> 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: <ruby> 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: <ruby> Client.where("orders_count = ?", params[:orders]) </ruby> -instead of: +to this code: <ruby> Client.where("orders_count = #{params[:orders]}") </ruby> -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. @@ -1016,7 +1024,7 @@ You can also use +find_last_by_*+ methods which will find the last record matchi You can specify an exclamation point (<tt>!</tt>) 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 <tt>Client.find_by_name_and_locked("Ryan")</tt>, 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+. diff --git a/railties/guides/source/active_support_core_extensions.textile b/railties/guides/source/active_support_core_extensions.textile index addf5f78be..c04e49281e 100644 --- a/railties/guides/source/active_support_core_extensions.textile +++ b/railties/guides/source/active_support_core_extensions.textile @@ -1426,6 +1426,14 @@ The method +pluralize+ returns the plural of its receiver: As the previous example shows, Active Support knows some irregular plurals and uncountable nouns. Built-in rules can be extended in +config/initializers/inflections.rb+. That file is generated by the +rails+ command and has instructions in comments. ++pluralize+ can also take an optional +count+ parameter. If <tt>count == 1</tt> the singular form will be returned. For any other value of +count+ the plural form will be returned: + +<ruby> +"dude".pluralize(0) # => "dudes" +"dude".pluralize(1) # => "dude" +"dude".pluralize(2) # => "dudes" +</ruby> + Active Record uses this method to compute the default table name that corresponds to a model: <ruby> @@ -1760,7 +1768,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: <ruby> "a".ord # => 97 @@ -1774,7 +1782,7 @@ In Ruby 1.8 +ord+ doesn't work in general in UTF8 strings, use the multibyte sup "à".mb_chars.ord # => 224, in UTF8 </ruby> -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)+. diff --git a/railties/guides/source/asset_pipeline.textile b/railties/guides/source/asset_pipeline.textile index afaf0f6fe3..6eb4ae49e3 100644 --- a/railties/guides/source/asset_pipeline.textile +++ b/railties/guides/source/asset_pipeline.textile @@ -349,7 +349,7 @@ bundle exec rake assets:precompile </plain> For faster asset precompiles, you can partially load your application by setting -+config.assets.initialize_on_precompile+ to false, though in that case templates ++config.assets.initialize_on_precompile+ to false in +config/application.rb+, though in that case templates cannot see application objects or methods. *Heroku requires this to be false.* WARNING: If you set +config.assets.initialize_on_precompile+ to false, be sure to 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: <ruby> 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 </ruby> -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. diff --git a/railties/guides/source/command_line.textile b/railties/guides/source/command_line.textile index f6b33d283c..3f8643eca3 100644 --- a/railties/guides/source/command_line.textile +++ b/railties/guides/source/command_line.textile @@ -381,15 +381,15 @@ $ rake about About your application's environment Ruby version 1.8.7 (x86_64-linux) RubyGems version 1.3.6 -Rack version 1.1 -Rails version 3.1.0 +Rack version 1.3 +Rails version 3.2.0.beta JavaScript Runtime Node.js (V8) -Active Record version 3.1.0 -Action Pack version 3.1.0 -Active Resource version 3.1.0 -Action Mailer version 3.1.0 -Active Support version 3.1.0 -Middleware ActionDispatch::Static, Rack::Lock, Rack::Runtime, Rails::Rack::Logger, ActionDispatch::ShowExceptions, ActionDispatch::RemoteIp, ActionDispatch::Callbacks, ActionDispatch::Cookies, ActionDispatch::Session::CookieStore, ActionDispatch::Flash, ActionDispatch::ParamsParser, Rack::MethodOverride, ActionDispatch::Head +Active Record version 3.2.0.beta +Action Pack version 3.2.0.beta +Active Resource version 3.2.0.beta +Action Mailer version 3.2.0.beta +Active Support version 3.2.0.beta +Middleware ActionDispatch::Static, Rack::Lock, Rack::Runtime, Rack::MethodOverride, ActionDispatch::RequestId, Rails::Rack::Logger, ActionDispatch::ShowExceptions, ActionDispatch::RemoteIp, ActionDispatch::Reloader, ActionDispatch::Callbacks, ActiveRecord::ConnectionAdapters::ConnectionManagement, ActiveRecord::QueryCache, ActionDispatch::Cookies, ActionDispatch::Session::CookieStore, ActionDispatch::Flash, ActionDispatch::ParamsParser, ActionDispatch::Head, Rack::ConditionalGet, Rack::ETag, ActionDispatch::BestStandardsSupport Application root /home/foobar/commandsapp Environment development Database adapter sqlite3 diff --git a/railties/guides/source/configuring.textile b/railties/guides/source/configuring.textile index baf944cf8d..58b92e7f9e 100644 --- a/railties/guides/source/configuring.textile +++ b/railties/guides/source/configuring.textile @@ -64,7 +64,7 @@ NOTE. The +config.asset_path+ configuration is ignored if the asset pipeline is * +config.autoload_paths+ accepts an array of paths from which Rails will autoload constants. Default is all directories under +app+. -* +config.cache_classes+ controls whether or not application classes and modules should be reloaded on each request. Defaults to true in development mode, and false in test and production modes. Can also be enabled with +threadsafe!+. +* +config.cache_classes+ controls whether or not application classes and modules should be reloaded on each request. Defaults to false in development mode, and true in test and production modes. Can also be enabled with +threadsafe!+. * +config.action_view.cache_template_loading+ controls whether or not templates should be reloaded on each request. Defaults to whatever is set for +config.cache_classes+. diff --git a/railties/guides/source/engines.textile b/railties/guides/source/engines.textile index 6be347e1a5..da56f3d0ed 100644 --- a/railties/guides/source/engines.textile +++ b/railties/guides/source/engines.textile @@ -98,7 +98,7 @@ Also in the test directory is the +test/integration+ directory, where integratio h3. Providing engine functionality -The engine that this guide covers will provide posting and commenting functionality. +The engine that this guide covers will provide posting and commenting functionality and follows a similar thread to the "Getting Started Guide":getting-started.html, with some new twists. h4. Generating a post resource @@ -106,8 +106,13 @@ The first thing to generate for a blog engine is the +Post+ model and related co <shell> $ rails generate scaffold post title:string text:text +</shell> + +This command will output this information: + +<shell> 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 @@ -199,94 +204,403 @@ If you'd rather play around in the console, +rails console+ will also work just => #<Blorgh::Post id: 1 ...> </ruby> +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: + +<ruby> +root :to => "posts#index" +</ruby> + +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. +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. <shell> -$ rails generate scaffold Comment post_id:integer text:text +$ rails generate model Comment post_id:integer text:text </shell> -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+. +This will output the following: -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. +<shell> +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 +</shell> + +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+. + +To show the comments on a post, edit +app/views/posts/show.html.erb+ and add this line before the "Edit" link: + +<erb> +<h3>Comments</h3> +<%= render @post.comments %> +</erb> -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: +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: <ruby> -Blorgh::Engine.routes.draw do +has_many :comments +</ruby> + +Turning the model into this: + +<ruby> +module Blorgh + class Post < ActiveRecord::Base + has_many :comments + end +end +</ruby> + +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. + +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+: + +<erb> +<%= render "blorgh/comments/form" %> +</erb> + +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: + +<erb> +<h3>New comment</h3> +<%= form_for [@post, @post.comments.build] do |f| %> + <p> + <%= f.label :text %><br /> + <%= f.text_area :text %> + </p> + <%= f.submit %> +<% end %> +</erb> + +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: + +<ruby> +resources :posts do resources :comments +end +</ruby> - resources :posts +The route now will exist, but the controller that this route goes to does not. To create it, run this command: + +<shell> +$ rails g controller comments +</shell> + +This will generate the following things: +<shell> +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 +</shell> + +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+: + +<ruby> +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 </ruby> -Into these: +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: + +<text> + 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" +</text> + +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: + +<erb> +<%= comment_counter + 1 %>. <%= comment.text %> +</erb> + +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 an application + +Using an engine within an application is very easy. This section covers how to mount the engine into an application and the initial setup required for it, as well as linking the engine to a +User+ class provided by the application to provide ownership for posts and comments within the engine. + +h4. Mounting the engine + +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: + +<shell> +$ rails new unicorn +</shell> + +Usually, specifying the engine inside the Gemfile would be done by specifying it as a normal, everyday gem. <ruby> - Blorgh::Engine.routes.draw do - resources :posts do - resources :comments - end - end +gem 'devise' </ruby> -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: +Because the +blorgh+ engine is still under development, it will need to have a +:path+ option for its +Gemfile+ specification: <ruby> -post = Post.find(params[:id]) +gem 'blorgh', :path => "/path/to/blorgh" </ruby> -Then to get the comments for this post it would be as simple as: +If the whole +blorgh+ engine directory is copied to +vendor/engines/blorgh+ then it could be specified in the +Gemfile+ like this: <ruby> -post.comments +gem 'blorgh', :path => "vendor/engines/blorgh" </ruby> -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. +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 fetch the post in the controller, add a +before_filter+ into the controller's class definition like this: +To make the engine's functionality accessible from within an application, it needs to be mounted in that application's +config/routes.rb+ file: <ruby> -module Blorgh - class CommentsController < ApplicationController - before_filter :load_post - ... +mount Blorgh::Engine, :at => "blog" +</ruby> + +This line will mount the engine at +blog+ in the application. Making it accessible at +http://localhost:3000/blog+ when the application runs with +rails s+. + +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. + +h4. Engine setup + +The engine contains migrations for the +blorgh_posts+ and +blorgh_comments+ table which need to be created in the application's database so that the engine's models can query them correctly. To copy these migrations into the application use this command: + +<shell> +$ rake blorgh:install:migrations +</shell> + +This command, when run for the first time will copy over all the migrations from the engine. When run the next time, it will only copy over migrations that haven't been copied over already. The first run for this command will output something such as this: + +<shell> +Copied migration [timestamp_1]_create_blorgh_posts.rb from blorgh +Copied migration [timestamp_2]_create_blorgh_comments.rb from blorgh +</shell> + +The first timestamp (+\[timestamp_1\]+) will be the current time and the second timestamp (+\[timestamp_2\]+) will be the current time plus a second. The reason for this is so that the migrations for the engine are run after any existing migrations in the application. + +To run these migrations within the context of the application, simply run +rake db:migrate+. When accessing the engine through +http://localhost:3000/blog+, the posts will be empty. This is because the table created inside the application is different from the one created within the engine. Go ahead, play around with the newly mounted engine. You'll find that it's the same as when it was only an engine. + +h4. Using a class provided by the application + +When an engine is created, it may want to use specific classes from an application to provide links between the pieces of the engine and the pieces of the application. In the case of the +blorgh+ engine, making posts and comments have authors would make a lot of sense. + +Usually, an application would have a +User+ class that would provide the objects that would represent the posts' and comments' authors, but there could be a case where the application calls this class something different, such as +Person+. It's because of this reason that the engine should not hardcode the associations to be exactly for a +User+ class, but should allow for some flexibility around what the class is called. + +To keep it simple in this case, the application will have a class called +User+ which will represent the users of the application. It can be generated using this command: + +<shell> +rails g model user name:string +</shell> + +The +rake db:migrate+ command needs to be run here to ensure that our application has the +users+ table for future use. + +Also to keep it simple, the posts form will have a new text field called +author_name_+ where users can elect to put their name. The engine will then take this name and create a new +User+ object from it or find one that already has that name, and then associate the post with it. + +First, the +author_name+ text field needs to be added to the +app/views/blorgh/posts/_form.html.erb+ partial inside the engine. This can be added above the +title+ field with this code: + +<erb> +<div class="field"> + <%= f.label :author_name %><br /> + <%= f.text_field :author_name %> +</div> +</erb> + +The +Blorgh::Post+ model should then have some code to convert the +author_name+ field into an actual +User+ object and associate it as that post's +author+ before the post is saved. It will also need to have an +attr_accessor+ setup for this field so that the setter and getter methods are defined for it. + +To do all this, you'll need to add the +attr_accessor+ for +author_name+, the association for the author and the +before_save+ call into +app/models/blorgh/post.rb+. The +author+ association will be hard-coded to the +User+ class for the time being. + +<ruby> +attr_accessor :author_name +belongs_to :author, :class_name => "User" + +before_save :set_author + +private + def set_author + self.author = User.find_or_create_by_name(author_name) end +</ruby> + +By defining that the +author+ association's object is represented by the +User+ class a link is established between the engine and the application. There needs to be a way of associating the records in the +blorgh_posts+ table with the records in the +users+ table. Because the association is called +author+, there should be an +author_id+ column added to the +blorgh_posts+ table. + +To generate this new column, run this command within the engine: + +<shell> +$ rails g migration add_author_id_to_blorgh_posts author_id:integer +</shell> + +NOTE: Due to the migration's name and the column specification after it, Rails will automatically know that you want to add a column to a specific table and write that into the migration for you. You don't need to tell it any more than this. + +This migration will need to be run on the application. To do that, it must first be copied using this command: + +<shell> +$ rake blorgh:install:migrations +</shell> + +Notice here that only _one_ migration was copied over here. This is because the first two migrations were copied over the first time this command was run. + +<shell> + NOTE: Migration [timestamp]_create_blorgh_posts.rb from blorgh has been skipped. Migration with the same name already exists. + NOTE: Migration [timestamp]_create_blorgh_comments.rb from blorgh has been skipped. Migration with the same name already exists. + Copied migration [timestamp]_add_author_id_to_blorgh_posts.rb from blorgh +</shell> + +Run this migration using this command: + +<shell> +$ rake db:migrate +</shell> + +Now with all the pieces in place, an action will take place that will associate an author -- represented by a record in the +users+ table -- with a post, represented by the +blorgh_posts+ table from the engine. + +Finally, the author's name should be displayed on the post's page. Add this code above the "Title" output inside +app/views/blorgh/posts/show.html.erb+: + +<erb> +<p> + <b>Author:</b> + <%= @post.author %> +</p> +</erb> + +WARNING: For posts created previously, this will break the +show+ page for them. We recommend deleting these posts and starting again, or manually assigning an author using +rails c+. + +By outputting +@post.author+ using the +<%=+ tag the +to_s+ method will be called on the object. By default, this will look quite ugly: + +<text> +#<User:0x00000100ccb3b0> +</text> + +This is undesirable and it would be much better to have the user's name there. To do this, add a +to_s+ method to the +User+ class within the application: + +<ruby> +def to_s + name end </ruby> -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: +Now instead of the ugly Ruby object output the author's name will be displayed. + +h4. Configuring an engine + +The next step is to make the class that represents a +User+ in the application customizable for the engine. This is because, as explained before, that class may not always be +User+. To make this customizable, the engine will have a configuration setting called +user_class+ that will be used to specify what the class representing users is inside the application. + +To define this configuration setting, you should use a +mattr_accessor+ inside the +Blorgh+ module for the engine, located at +lib/blorgh.rb+ inside the engine. Inside this module, put this line: <ruby> -module Blorgh - class CommentsController < ApplicationController - before_filter :load_post +mattr_accessor :user_class +</ruby> - # actions go here +This method works like its brothers +attr_accessor+ and +cattr_accessor+, but provides a setter and getter method on the module with the specified name. To use it, it must be referenced using +Blorgh.user_class+. - private +The next step is switching the +Blorgh::Post+ model over to this new setting. For the +belongs_to+ association inside this model (+app/models/blorgh/post.rb+), it will now become this: - def load_post - @post = Post.find(params[:post_id]) - end - end -end +<ruby> +belongs_to :author, :class_name => Blorgh.user_class </ruby> -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. +The +set_author+ method also located in this class should also use this class: +<ruby> +self.author = Blorgh.user_class.constantize.find_or_create_by_name(author_name) +</ruby> -h3. Hooking into application +To set this configuration setting within the application, an initializer should be used. By using an initializer, the configuration will be set up before the application starts and makes references to the classes of the engine which may depend on this configuration setting existing. -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. +Create a new initializer at +config/initializers/blorgh.rb+ inside the application where the +blorgh+ engine is installed and put this content in it: -h3. Overriding engine functionality +<ruby> +Blorgh.user_class = "User" +</ruby> -TODO: Cover how to override engine functionality in the engine, such as controllers and views. +WARNING: It's very important here to use the +String+ version of the class, rather than the class itself. If you were to use the class, Rails would attempt to load that class and then reference the related table, which could lead to problems if the table wasn't already existing. Therefore, a +String+ should be used and then converted to a class using +constantize+ in the engine later on. + +Go ahead and try to create a new post. You will see that it works exactly in the same way as before, except this time the engine is using the configuration setting in +config/initializers/blorgh.rb+ to learn what the class is. + +There are now no strict dependencies on what the class is, only what the class's API must be. The engine simply requires this class to define a +find_or_create_by_name+ method which returns an object of that class to be associated with a post when it's created. + +h3. Extending engine functionality + +This section looks at overriding or adding functionality to the views, controllers and models provided by an engine. + +h4. Overriding views + +When Rails looks for a view to render, it will first look in the +app/views+ directory of the application. If it cannot find the view there, then it will check in the +app/views+ directories of all engines which have this directory. + +In the +blorgh+ engine, there is a currently a file at +app/views/blorgh/posts/index.html.erb+. When the engine is asked to render the view for +Blorgh::PostsController+'s +index+ action, it will first see if it can find it at +app/views/blorgh/posts/index.html.erb+ within the application and then if it cannot it will look inside the engine. + +By overriding this view in the application, by simply creating a new file at +app/views/blorgh/posts/index.html.erb+, you can completely change what this view would normally output. + +Try this now by creating a new file at +app/views/blorgh/posts/index.html.erb+ and put this content in it: + +<erb> +<h1>Posts</h1> +<%= link_to "New Post", new_post_path %> +<% @posts.each do |post| %> + <h2><%= post.title %></h2> + <small>By <%= post.author %></small> + <%= simple_format(post.text) %> + <hr> +<% end %> +</erb> + +Rather than looking like the default scaffold, the page will now look like this: + +!images/engines_post_override.png(Engine scaffold overriden)! + +h4. Controllers + +TODO: Explain how to extend a controller. IDEA: I like Devise's +devise :controllers => { "sessions" => "sessions" }+ idea. Perhaps we could incorporate that into the guide? + +h4. Models + +TODO: Explain how to extend models provided by an engine. + +h4. Routes + +Within the application, you may wish to link to some area within the engine. Due to the fact that the engine's routes are isolated (by the +isolate_namespace+ call within the +lib/blorgh/engine.rb+ file), you will need to prefix these routes with the engine name. This means rather than having something such as: + +<erb> +<%= link_to "Blog posts", posts_path %> +</erb> + +It needs to be written as: + +<erb> +<%= link_to "Blog posts", blorgh.posts_path %> +</erb> + +This allows for the engine _and_ the application to both have a +posts_path+ routing helper and to not interfere with each other. You may also reference another engine's routes from inside an engine using this same syntax. + +If you wish to reference the application inside the engine in a similar way, use the +main_app+ helper: + +<erb> +<%= link_to "Home", main_app.root_path %> +</erb> + TODO: Mention how to use assets within an engine? TODO: Mention how to depend on external gems, like RedCarpet. diff --git a/railties/guides/source/initialization.textile b/railties/guides/source/initialization.textile index 32b41fdd2c..f88405a2fd 100644 --- a/railties/guides/source/initialization.textile +++ b/railties/guides/source/initialization.textile @@ -7,7 +7,7 @@ This guide explains the internals of the initialization process in Rails as of R endprologue. -This guide goes through every single file, class and method call that is required to boot up the Ruby on Rails stack for a default Rails 3.1 application, explaining each part in detail a long the way. For this guide, we will be focusing on how the two most common methods (+rails server+ and Passenger) boot a Rails application. +This guide goes through every single file, class and method call that is required to boot up the Ruby on Rails stack for a default Rails 3.1 application, explaining each part in detail along the way. For this guide, we will be focusing on how the two most common methods (+rails server+ and Passenger) boot a Rails application. NOTE: Paths in this guide are relative to Rails or a Rails application unless otherwise specified. @@ -243,7 +243,7 @@ In this file there are a lot of lines such as this inside the +ActiveSupport+ mo autoload :Inflector </ruby> -Due to the overriding of the +autoload+ method, Ruby will know to look for this file at +activesupport/lib/active_support/inflector.rb+ when the +Inflector+ class is first referenced. +Due to the overriding of the +autoload+ method, Ruby will know how to look for this file at +activesupport/lib/active_support/inflector.rb+ when the +Inflector+ class is first referenced. The +active_support/lib/active_support/version.rb+ that is also required here simply defines an +ActiveSupport::VERSION+ constant which defines a couple of constants inside this module, the main constant of this is +ActiveSupport::VERSION::STRING+ which returns the current version of ActiveSupport. diff --git a/railties/guides/source/layouts_and_rendering.textile b/railties/guides/source/layouts_and_rendering.textile index 69ef05104c..df7b9b364c 100644 --- a/railties/guides/source/layouts_and_rendering.textile +++ b/railties/guides/source/layouts_and_rendering.textile @@ -334,7 +334,7 @@ render :status => 500 render :status => :forbidden </ruby> -Rails understands both numeric status codes and symbols for status codes. +Rails understands both numeric and symbolic status codes. h6. The +:location+ Option @@ -348,9 +348,9 @@ 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+ 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 +h6. Specifying Layouts for Controllers -You can override the automatic layout conventions in your controllers by using the +layout+ declaration in the controller. For example: +You can override the default layout conventions in your controllers by using the +layout+ declaration. For example: <ruby> class ProductsController < ApplicationController @@ -359,9 +359,9 @@ class ProductsController < ApplicationController end </ruby> -With this declaration, all methods within +ProductsController+ will use +app/views/layouts/inventory.html.erb+ for their layout. +With this declaration, all of the methods within +ProductsController+ will use +app/views/layouts/inventory.html.erb+ for their layout. -To assign a specific layout for the entire application, use a declaration in your +ApplicationController+ class: +To assign a specific layout for the entire application, use a +layout+ declaration in your +ApplicationController+ class: <ruby> class ApplicationController < ActionController::Base @@ -370,7 +370,7 @@ class ApplicationController < ActionController::Base end </ruby> -With this declaration, all views in the entire application will use +app/views/layouts/main.html.erb+ for their layout. +With this declaration, all of the views in the entire application will use +app/views/layouts/main.html.erb+ for their layout. h6. Choosing Layouts at Runtime @@ -392,9 +392,9 @@ class ProductsController < ApplicationController end </ruby> -Now, if the current user is a special user, they'll get a special layout when viewing a product. You can even use an inline method to determine the layout: +Now, if the current user is a special user, they'll get a special layout when viewing a product. -You can also decide the layout by passing a Proc object, the block you give the Proc will be given the +controller+ instance, so you can make decisions based on the current request. For example: +You can even use an inline method, such as a Proc, to determine the layout. For example, if you pass a Proc object, the block you give the Proc will be given the +controller+ instance, so the layout can be determined based on the current request: <ruby> class ProductsController < ApplicationController @@ -404,7 +404,7 @@ end h6. Conditional Layouts -Layouts specified at the controller level support +:only+ and +:except+ options that take either a method name or an array of method names which correspond to method names within the controller: +Layouts specified at the controller level support the +:only+ and +:except+ options. These options take either a method name, or an array of method names, corresponding to method names within the controller: <ruby> class ProductsController < ApplicationController @@ -416,7 +416,7 @@ With this declaration, the +product+ layout would be used for everything but the h6. Layout Inheritance -Layouts are shared downwards in the hierarchy, and more specific layouts always override more general ones. For example: +Layout declarations cascade downward in the hierarchy, and more specific layout declarations always override more general ones. For example: * +application_controller.rb+ @@ -495,9 +495,9 @@ def show end </ruby> -Make sure you use +and return+ and not +&& return+ because while the former will work, the latter will not due to operator precedence in the Ruby Language. +Make sure to use +and return+ and not +&& return+, since +&& return+ will not work due to the operator precedence in the Ruby Language. -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: +Note that the implicit render done by ActionController detects if +render+ has been called, so the following will work without errors: <ruby> def show @@ -518,7 +518,7 @@ Another way to handle returning responses to an HTTP request is with +redirect_t redirect_to photos_url </ruby> -You can use +redirect_to+ with any arguments that you could use with +link_to+ or +url_for+. In addition, there's a special redirect that sends the user back to the page they just came from: +You can use +redirect_to+ with any arguments that you could use with +link_to+ or +url_for+. There's also a special redirect that sends the user back to the page they just came from: <ruby> redirect_to :back @@ -526,7 +526,7 @@ redirect_to :back h5. Getting a Different Redirect Status Code -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: +Rails uses HTTP status code 302, a temporary redirect, when you call +redirect_to+. If you'd like to use a different status code, perhaps 301, a permanent redirect, you can use the +:status+ option: <ruby> redirect_to photos_path, :status => 301 @@ -536,7 +536,7 @@ Just like the +:status+ option for +render+, +:status+ for +redirect_to+ accepts h5. The Difference Between +render+ and +redirect_to+ -Sometimes inexperienced developers conceive of +redirect_to+ as a sort of +goto+ command, moving execution from one place to another in your Rails code. This is _not_ correct. Your code stops running and waits for a new request for the browser. It just happens that you've told the browser what request it should make next, by sending back an HTTP 302 status code. +Sometimes inexperienced developers think of +redirect_to+ as a sort of +goto+ command, moving execution from one place to another in your Rails code. This is _not_ correct. Your code stops running and waits for a new request for the browser. It just happens that you've told the browser what request it should make next, by sending back an HTTP 302 status code. Consider these actions to see the difference: @@ -553,7 +553,7 @@ def show end </ruby> -With the code in this form, there will likely be a problem if the +@book+ variable is +nil+. Remember, a +render :action+ doesn't run any code in the target action, so nothing will set up the +@books+ variable that the +index+ view is presumably depending on. One way to fix this is to redirect instead of rendering: +With the code in this form, there will likely be a problem if the +@book+ variable is +nil+. Remember, a +render :action+ doesn't run any code in the target action, so nothing will set up the +@books+ variable that the +index+ view will probably require. One way to fix this is to redirect instead of rendering: <ruby> def index @@ -570,9 +570,9 @@ end With this code, the browser will make a fresh request for the index page, the code in the +index+ method will run, and all will be well. -The only downside to this code, is that it requires a round trip to the browser, the browser requested the show action with +/books/1+ and the controller finds that there are no books, so the controller sends out a 302 redirect response to the browser telling it to go to +/books/+, the browser complies and sends a new request back to the controller asking now for the +index+ action, the controller then gets all the books in the database and renders the index template, sending it back down to the browser which then shows it on your screen. +The only downside to this code is that it requires a round trip to the browser: the browser requested the show action with +/books/1+ and the controller finds that there are no books, so the controller sends out a 302 redirect response to the browser telling it to go to +/books/+, the browser complies and sends a new request back to the controller asking now for the +index+ action, the controller then gets all the books in the database and renders the index template, sending it back down to the browser which then shows it on your screen. -While in a small app, this added latency might not be a problem, it is something to think about when speed of response is of the essence. One way to handle this double request (though a contrived example) could be: +While in a small application, this added latency might not be a problem, it is something to think about if response time is a concern. We can demonstrate one way to handle this with a contrived example: <ruby> def index @@ -588,7 +588,7 @@ def show end </ruby> -Which would detect that there are no books, populate the +@books+ instance variable with all the books in the database and then directly render the +index.html.erb+ template returning it to the browser with a flash alert message telling the user what happened. +This would detect that there are no books with the specified ID, populate the +@books+ instance variable with all the books in the model, and then directly render the +index.html.erb+ template, returning it to the browser with a flash alert message to tell the user what happened. h4. Using +head+ To Build Header-Only Responses @@ -598,7 +598,7 @@ The +head+ method can be used to send responses with only headers to the browser head :bad_request </ruby> -Which would produce the following header: +This would produce the following header: <shell> HTTP/1.1 400 Bad Request @@ -611,7 +611,7 @@ Set-Cookie: _blog_session=...snip...; path=/; HttpOnly Cache-Control: no-cache </shell> -Or you can use other HTTP headers to convey additional information: +Or you can use other HTTP headers to convey other information: <ruby> head :created, :location => photo_path(@photo) @@ -633,15 +633,15 @@ Cache-Control: no-cache h3. Structuring Layouts -When Rails renders a view as a response, it does so by combining the view with the current layout (using the rules for finding the current layout that were covered earlier in this guide). Within a layout, you have access to three tools for combining different bits of output to form the overall response: +When Rails renders a view as a response, it does so by combining the view with the current layout, using the rules for finding the current layout that were covered earlier in this guide. Within a layout, you have access to three tools for combining different bits of output to form the overall response: * Asset tags * +yield+ and +content_for+ * Partials -h4. Asset Tags +h4. Asset Tag Helpers -Asset tags provide methods for generating HTML that links views to feeds, JavaScript, stylesheets, images, videos and audios. These are the six asset tags available in Rails: +Asset tag helpers provide methods for generating HTML that link views to feeds, JavaScript, stylesheets, images, videos and audios. There are six asset tag helpers available in Rails: * +auto_discovery_link_tag+ * +javascript_include_tag+ @@ -650,11 +650,11 @@ Asset tags provide methods for generating HTML that links views to feeds, JavaSc * +video_tag+ * +audio_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. +You can use these tags in layouts or other views, although the +auto_discovery_link_tag+, +javascript_include_tag+, and +stylesheet_link_tag+, are most commonly used in the +<head>+ section of a layout. -WARNING: The asset tags do _not_ verify the existence of the assets at the specified locations; they simply assume that you know what you're doing and generate the link. +WARNING: The asset tag helpers do _not_ verify the existence of the assets at the specified locations; they simply assume that you know what you're doing and generate the link. -h5. Linking to Feeds with +auto_discovery_link_tag+ +h5. Linking to Feeds with the +auto_discovery_link_tag+ The +auto_discovery_link_tag+ helper builds HTML that most browsers and newsreaders can use to detect the presences of RSS or ATOM feeds. It takes the type of the link (+:rss+ or +:atom+), a hash of options that are passed through to url_for, and a hash of options for the tag: @@ -663,13 +663,13 @@ The +auto_discovery_link_tag+ helper builds HTML that most browsers and newsread {:title => "RSS Feed"}) %> </erb> -There are three tag options available for +auto_discovery_link_tag+: +There are three tag options available for the +auto_discovery_link_tag+: -* +:rel+ specifies the +rel+ value in the link (defaults to "alternate") +* +:rel+ specifies the +rel+ value in the link. The default value is "alternate". * +:type+ specifies an explicit MIME type. Rails will generate an appropriate MIME type automatically. -* +:title+ specifies the title of the link +* +:title+ specifies the title of the link. The default value is the upshifted +:type+ value, for example, "ATOM" or "RSS". -h5. Linking to JavaScript Files with +javascript_include_tag+ +h5. Linking to JavaScript Files with the +javascript_include_tag+ The +javascript_include_tag+ helper returns an HTML +script+ tag for each source provided. Rails looks in +public/javascripts+ for these files by default, but you can specify a full path relative to the document root, or a URL, if you prefer. For example, to include +public/javascripts/main.js+: @@ -738,7 +738,7 @@ By default, the combined file will be delivered as +javascripts/all.js+. You can You can even use dynamic paths such as +cache/#{current_site}/main/display+. -h5. Linking to CSS Files with +stylesheet_link_tag+ +h5. Linking to CSS Files with the +stylesheet_link_tag+ The +stylesheet_link_tag+ helper returns an HTML +<link>+ tag for each source provided. Rails looks in +public/stylesheets+ for these files by default, but you can specify a full path relative to the document root, or a URL, if you prefer. For example, to include +public/stylesheets/main.css+: @@ -764,7 +764,7 @@ To include +http://example.com/main.css+: <%= stylesheet_link_tag "http://example.com/main.css" %> </erb> -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, the +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+): <erb> <%= stylesheet_link_tag "main_print", :media => "print" %> @@ -797,7 +797,7 @@ By default, the combined file will be delivered as +stylesheets/all.css+. You ca You can even use dynamic paths such as +cache/#{current_site}/main/display+. -h5. Linking to Images with +image_tag+ +h5. Linking to Images with the +image_tag+ The +image_tag+ helper builds an HTML +<img />+ tag to the specified file. By default, files are loaded from +public/images+. @@ -846,7 +846,7 @@ In addition to the above special tags, you can supply a final hash of standard H :class => 'nav_bar' %> </erb> -h5. Linking to Videos with +video_tag+ +h5. Linking to Videos with the +video_tag+ The +video_tag+ helper builds an HTML 5 +<video>+ tag to the specified file. By default, files are loaded from +public/videos+. @@ -882,7 +882,7 @@ This will produce: <video><source src="trailer.ogg" /><source src="movie.ogg" /></video> </erb> -h5. Linking to Audio files with +audio_tag+ +h5. Linking to Audio Files with the +audio_tag+ The +audio_tag+ helper builds an HTML 5 +<audio>+ tag to the specified file. By default, files are loaded from +public/audios+. @@ -933,7 +933,7 @@ You can also create a layout with multiple yielding regions: The main body of the view will always render into the unnamed +yield+. To render content into a named +yield+, you use the +content_for+ method. -h4. Using +content_for+ +h4. Using the +content_for+ Method The +content_for+ method allows you to insert content into a named +yield+ block in your layout. For example, this view would work with the layout that you just saw: diff --git a/railties/guides/source/rails_on_rack.textile b/railties/guides/source/rails_on_rack.textile index 57c03b54dc..d6cbd84b1f 100644 --- a/railties/guides/source/rails_on_rack.textile +++ b/railties/guides/source/rails_on_rack.textile @@ -166,8 +166,9 @@ Much of Action Controller's functionality is implemented as Middlewares. The fol |+Rack::Lock+|Sets <tt>env["rack.multithread"]</tt> flag to +true+ and wraps the application within a Mutex.| |+ActionController::Failsafe+|Returns HTTP Status +500+ to the client if an exception gets raised while dispatching.| |+ActiveRecord::QueryCache+|Enables the Active Record query cache.| -|+ActionController::Session::CookieStore+|Uses the cookie based session store.| -|+ActionController::Session::MemCacheStore+|Uses the memcached based session store.| +|+ActionDispatch::Session::CookieStore+|Uses the cookie based session store.| +|+ActionDispatch::Session::CacheStore+|Uses the Rails cache based session store.| +|+ActionDispatch::Session::MemCacheStore+|Uses the memcached based session store.| |+ActiveRecord::SessionStore+|Uses the database based session store.| |+Rack::MethodOverride+|Sets HTTP method based on +_method+ parameter or <tt>env["HTTP_X_HTTP_METHOD_OVERRIDE"]</tt>.| |+Rack::Head+|Discards the response body if the client sends a +HEAD+ request.| diff --git a/railties/guides/source/security.textile b/railties/guides/source/security.textile index 0f100e0adf..a499ef3d39 100644 --- a/railties/guides/source/security.textile +++ b/railties/guides/source/security.textile @@ -82,9 +82,9 @@ This will also be a good idea, if you modify the structure of an object and old h4. Session Storage --- _Rails provides several storage mechanisms for the session hashes. The most important are SessionStore and CookieStore._ +-- _Rails provides several storage mechanisms for the session hashes. The most important are ActiveRecord::SessionStore and ActionDispatch::Session::CookieStore._ -There are a number of session storages, i.e. where Rails saves the session hash and session id. Most real-live applications choose SessionStore (or one of its derivatives) over file storage due to performance and maintenance reasons. SessionStore keeps the session id and hash in a database table and saves and retrieves the hash on every request. +There are a number of session storages, i.e. where Rails saves the session hash and session id. Most real-live applications choose ActiveRecord::SessionStore (or one of its derivatives) over file storage due to performance and maintenance reasons. ActiveRecord::SessionStore keeps the session id and hash in a database table and saves and retrieves the hash on every request. Rails 2 introduced a new default session storage, CookieStore. CookieStore saves the session hash directly in a cookie on the client-side. The server retrieves the session hash from the cookie and eliminates the need for a session id. That will greatly increase the speed of the application, but it is a controversial storage option and you have to think about the security implications of it: @@ -157,9 +157,9 @@ One possibility is to set the expiry time-stamp of the cookie with the session i <ruby> 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 diff --git a/railties/lib/rails/application.rb b/railties/lib/rails/application.rb index cbb2d23238..82fffe86bb 100644 --- a/railties/lib/rails/application.rb +++ b/railties/lib/rails/application.rb @@ -164,7 +164,8 @@ module Rails middleware.use ::Rack::Lock unless config.allow_concurrency middleware.use ::Rack::Runtime middleware.use ::Rack::MethodOverride - middleware.use ::Rails::Rack::Logger # must come after Rack::MethodOverride to properly log overridden methods + middleware.use ::ActionDispatch::RequestId + middleware.use ::Rails::Rack::Logger, config.log_tags # must come after Rack::MethodOverride to properly log overridden methods middleware.use ::ActionDispatch::ShowExceptions, config.consider_all_requests_local middleware.use ::ActionDispatch::RemoteIp, config.action_dispatch.ip_spoofing_check, config.action_dispatch.trusted_proxies if config.action_dispatch.x_sendfile_header.present? diff --git a/railties/lib/rails/application/bootstrap.rb b/railties/lib/rails/application/bootstrap.rb index 0aff05b681..c2cb121e42 100644 --- a/railties/lib/rails/application/bootstrap.rb +++ b/railties/lib/rails/application/bootstrap.rb @@ -24,12 +24,12 @@ module Rails initializer :initialize_logger, :group => :all do Rails.logger ||= config.logger || begin path = config.paths["log"].first - logger = ActiveSupport::BufferedLogger.new(path) + logger = ActiveSupport::TaggedLogging.new(ActiveSupport::BufferedLogger.new(path)) logger.level = ActiveSupport::BufferedLogger.const_get(config.log_level.to_s.upcase) logger.auto_flushing = false if Rails.env.production? logger rescue StandardError - logger = ActiveSupport::BufferedLogger.new(STDERR) + logger = ActiveSupport::TaggedLogging.new(ActiveSupport::BufferedLogger.new(STDERR)) logger.level = ActiveSupport::BufferedLogger::WARN logger.warn( "Rails Error: Unable to access log file. Please ensure that #{path} exists and is chmod 0666. " + diff --git a/railties/lib/rails/application/configuration.rb b/railties/lib/rails/application/configuration.rb index 448521d2f0..8f5b28faf8 100644 --- a/railties/lib/rails/application/configuration.rb +++ b/railties/lib/rails/application/configuration.rb @@ -8,7 +8,7 @@ module Rails attr_accessor :allow_concurrency, :asset_host, :asset_path, :assets, :cache_classes, :cache_store, :consider_all_requests_local, :dependency_loading, :filter_parameters, - :force_ssl, :helpers_paths, :logger, :preload_frameworks, + :force_ssl, :helpers_paths, :logger, :log_tags, :preload_frameworks, :reload_plugins, :secret_token, :serve_static_assets, :ssl_options, :static_cache_control, :session_options, :time_zone, :whiny_nils diff --git a/railties/lib/rails/commands/server.rb b/railties/lib/rails/commands/server.rb index 23392276d5..20484a10c8 100644 --- a/railties/lib/rails/commands/server.rb +++ b/railties/lib/rails/commands/server.rb @@ -78,7 +78,7 @@ module Rails middlewares = [] middlewares << [Rails::Rack::LogTailer, log_path] unless options[:daemonize] middlewares << [Rails::Rack::Debugger] if options[:debugger] - middlewares << [Rails::Rack::ContentLength] + middlewares << [::Rack::ContentLength] Hash.new(middlewares) end diff --git a/railties/lib/rails/generators/app_base.rb b/railties/lib/rails/generators/app_base.rb index 294563ad06..10fdfdd8a9 100644 --- a/railties/lib/rails/generators/app_base.rb +++ b/railties/lib/rails/generators/app_base.rb @@ -138,7 +138,7 @@ module Rails if options.dev? <<-GEMFILE.strip_heredoc gem 'rails', :path => '#{Rails::Generators::RAILS_DEV_PATH}' - gem 'journey', :path => '#{Rails::Generators::JOURNEY_DEV_PATH}' + gem 'journey', :git => 'git://github.com/rails/journey.git' GEMFILE elsif options.edge? <<-GEMFILE.strip_heredoc @@ -150,7 +150,7 @@ module Rails gem 'rails', '#{Rails::VERSION::STRING}' # Bundle edge Rails instead: - # gem 'rails', :git => 'git://github.com/rails/rails.git' + # gem 'rails', :git => 'git://github.com/rails/rails.git' GEMFILE end end @@ -158,11 +158,11 @@ module Rails def gem_for_database # %w( mysql oracle postgresql sqlite3 frontbase ibm_db sqlserver jdbcmysql jdbcsqlite3 jdbcpostgresql ) case options[:database] - when "oracle" then "ruby-oci8" - when "postgresql" then "pg" - when "frontbase" then "ruby-frontbase" - when "mysql" then "mysql2" - when "sqlserver" then "activerecord-sqlserver-adapter" + when "oracle" then "ruby-oci8" + when "postgresql" then "pg" + when "frontbase" then "ruby-frontbase" + when "mysql" then "mysql2" + when "sqlserver" then "activerecord-sqlserver-adapter" when "jdbcmysql" then "activerecord-jdbcmysql-adapter" when "jdbcsqlite3" then "activerecord-jdbcsqlite3-adapter" when "jdbcpostgresql" then "activerecord-jdbcpostgresql-adapter" @@ -190,17 +190,6 @@ module Rails end end - def turn_gemfile_entry - unless RUBY_VERSION < "1.9.2" || options[:skip_test_unit] - <<-GEMFILE.strip_heredoc - group :test do - # Pretty printed test output - gem 'turn', :require => false - end - GEMFILE - end - end - def assets_gemfile_entry <<-GEMFILE.strip_heredoc # Gems used only for assets and not required diff --git a/railties/lib/rails/generators/rails/app/app_generator.rb b/railties/lib/rails/generators/rails/app/app_generator.rb index c8648d19f8..3e32f758a4 100644 --- a/railties/lib/rails/generators/rails/app/app_generator.rb +++ b/railties/lib/rails/generators/rails/app/app_generator.rb @@ -144,8 +144,6 @@ module Rails # We need to store the RAILS_DEV_PATH in a constant, otherwise the path # can change in Ruby 1.8.7 when we FileUtils.cd. RAILS_DEV_PATH = File.expand_path("../../../../../..", File.dirname(__FILE__)) - JOURNEY_DEV_PATH = File.expand_path("../../../../../../../journey", File.dirname(__FILE__)) - RESERVED_NAMES = %w[application destroy benchmarker profiler plugin runner test] class AppGenerator < AppBase diff --git a/railties/lib/rails/generators/rails/app/templates/Gemfile b/railties/lib/rails/generators/rails/app/templates/Gemfile index 910cd16950..d3b8f4d595 100644 --- a/railties/lib/rails/generators/rails/app/templates/Gemfile +++ b/railties/lib/rails/generators/rails/app/templates/Gemfile @@ -21,5 +21,3 @@ source 'http://rubygems.org' # To use debugger # <%= ruby_debugger_gemfile_entry %> - -<%= turn_gemfile_entry -%> diff --git a/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt index 64e2c09467..50f2df3d35 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt +++ b/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt @@ -33,8 +33,11 @@ # See everything in the log (default is :info) # config.log_level = :debug + # Prepend all log lines with the following tags + # config.log_tags = [ :subdomain, :uuid ] + # Use a different logger for distributed setups - # config.logger = SyslogLogger.new + # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new) # Use a different cache store in production # config.cache_store = :mem_cache_store diff --git a/railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb b/railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb index 01fe6dda7a..9ec2e34545 100644 --- a/railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb +++ b/railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb @@ -26,23 +26,23 @@ class <%= controller_class_name %>ControllerTest < ActionController::TestCase end test "should show <%= singular_table_name %>" do - get :show, <%= key_value :id, "@#{singular_table_name}.to_param" %> + get :show, <%= key_value :id, "@#{singular_table_name}" %> assert_response :success end test "should get edit" do - get :edit, <%= key_value :id, "@#{singular_table_name}.to_param" %> + get :edit, <%= key_value :id, "@#{singular_table_name}" %> assert_response :success end test "should update <%= singular_table_name %>" do - put :update, <%= key_value :id, "@#{singular_table_name}.to_param" %>, <%= key_value singular_table_name, "@#{singular_table_name}.attributes" %> + put :update, <%= key_value :id, "@#{singular_table_name}" %>, <%= key_value singular_table_name, "@#{singular_table_name}.attributes" %> assert_redirected_to <%= singular_table_name %>_path(assigns(:<%= singular_table_name %>)) end test "should destroy <%= singular_table_name %>" do assert_difference('<%= class_name %>.count', -1) do - delete :destroy, <%= key_value :id, "@#{singular_table_name}.to_param" %> + delete :destroy, <%= key_value :id, "@#{singular_table_name}" %> end assert_redirected_to <%= index_helper %>_path diff --git a/railties/lib/rails/rack.rb b/railties/lib/rails/rack.rb index d4a41b217e..d1ee96f7fd 100644 --- a/railties/lib/rails/rack.rb +++ b/railties/lib/rails/rack.rb @@ -1,6 +1,5 @@ module Rails module Rack - autoload :ContentLength, "rails/rack/content_length" autoload :Debugger, "rails/rack/debugger" autoload :Logger, "rails/rack/logger" autoload :LogTailer, "rails/rack/log_tailer" diff --git a/railties/lib/rails/rack/content_length.rb b/railties/lib/rails/rack/content_length.rb deleted file mode 100644 index 6839af4152..0000000000 --- a/railties/lib/rails/rack/content_length.rb +++ /dev/null @@ -1,38 +0,0 @@ -require 'action_dispatch' -require 'rack/utils' - -module Rails - module Rack - # Sets the Content-Length header on responses with fixed-length bodies. - class ContentLength - include ::Rack::Utils - - def initialize(app, sendfile=nil) - @app = app - @sendfile = sendfile - end - - def call(env) - status, headers, body = @app.call(env) - headers = HeaderHash.new(headers) - - if !STATUS_WITH_NO_ENTITY_BODY.include?(status.to_i) && - !headers['Content-Length'] && - !headers['Transfer-Encoding'] && - !(@sendfile && headers[@sendfile]) - - old_body = body - body, length = [], 0 - old_body.each do |part| - body << part - length += bytesize(part) - end - old_body.close if old_body.respond_to?(:close) - headers['Content-Length'] = length.to_s - end - - [status, headers, body] - end - end - end -end
\ No newline at end of file diff --git a/railties/lib/rails/rack/logger.rb b/railties/lib/rails/rack/logger.rb index 3be262de08..89de10c83d 100644 --- a/railties/lib/rails/rack/logger.rb +++ b/railties/lib/rails/rack/logger.rb @@ -1,32 +1,46 @@ require 'active_support/core_ext/time/conversions' +require 'active_support/core_ext/object/blank' module Rails module Rack # Log the request started and flush all loggers after it. class Logger < ActiveSupport::LogSubscriber - def initialize(app) - @app = app + def initialize(app, tags=nil) + @app, @tags = app, tags.presence end def call(env) - before_dispatch(env) - @app.call(env) - ensure - after_dispatch(env) + if @tags + Rails.logger.tagged(compute_tags(env)) { call_app(env) } + else + call_app(env) + end end protected - def before_dispatch(env) + def call_app(env) request = ActionDispatch::Request.new(env) path = request.filtered_path - - info "\n\nStarted #{request.request_method} \"#{path}\" " \ - "for #{request.ip} at #{Time.now.to_default_s}" + Rails.logger.info "\n\nStarted #{request.request_method} \"#{path}\" for #{request.ip} at #{Time.now.to_default_s}" + @app.call(env) + ensure + ActiveSupport::LogSubscriber.flush_all! end - def after_dispatch(env) - ActiveSupport::LogSubscriber.flush_all! + def compute_tags(env) + request = ActionDispatch::Request.new(env) + + @tags.collect do |tag| + case tag + when Proc + tag.call(request) + when Symbol + request.send(tag) + else + tag + end + end end end end diff --git a/railties/lib/rails/tasks/engine.rake b/railties/lib/rails/tasks/engine.rake index 2152e811f5..eea8abe7d2 100644 --- a/railties/lib/rails/tasks/engine.rake +++ b/railties/lib/rails/tasks/engine.rake @@ -2,6 +2,7 @@ task "load_app" do namespace :app do load APP_RAKEFILE end + task :environment => "app:environment" if !defined?(ENGINE_PATH) || !ENGINE_PATH ENGINE_PATH = find_engine_path(APP_RAKEFILE) diff --git a/railties/test/application/middleware_test.rb b/railties/test/application/middleware_test.rb index 093cb6ca2a..4703a59326 100644 --- a/railties/test/application/middleware_test.rb +++ b/railties/test/application/middleware_test.rb @@ -30,6 +30,7 @@ module ApplicationTests "ActiveSupport::Cache::Strategy::LocalCache", "Rack::Runtime", "Rack::MethodOverride", + "ActionDispatch::RequestId", "Rails::Rack::Logger", # must come after Rack::MethodOverride to properly log overridden methods "ActionDispatch::ShowExceptions", "ActionDispatch::RemoteIp", diff --git a/railties/test/generators/app_generator_test.rb b/railties/test/generators/app_generator_test.rb index 133efb872f..955ed09361 100644 --- a/railties/test/generators/app_generator_test.rb +++ b/railties/test/generators/app_generator_test.rb @@ -143,6 +143,16 @@ class AppGeneratorTest < Rails::Generators::TestCase end end + def test_config_postgresql_database + run_generator([destination_root, "-d", "postgresql"]) + assert_file "config/database.yml", /postgresql/ + unless defined?(JRUBY_VERSION) + assert_file "Gemfile", /^gem\s+["']pg["']$/ + else + assert_file "Gemfile", /^gem\s+["']activerecord-jdbcpostgresql-adapter["']$/ + end + end + def test_config_jdbcmysql_database run_generator([destination_root, "-d", "jdbcmysql"]) assert_file "config/database.yml", /mysql/ @@ -242,21 +252,6 @@ class AppGeneratorTest < Rails::Generators::TestCase end end - def test_inclusion_of_turn_gem_in_gemfile - run_generator - assert_file "Gemfile" do |contents| - assert_match(/gem 'turn'/, contents) unless RUBY_VERSION < '1.9.2' - assert_no_match(/gem 'turn'/, contents) if RUBY_VERSION < '1.9.2' - end - end - - def test_turn_gem_is_not_included_in_gemfile_if_skipping_test_unit - run_generator [destination_root, "--skip-test-unit"] - assert_file "Gemfile" do |contents| - assert_no_match(/gem 'turn'/, contents) unless RUBY_VERSION < '1.9.2' - end - end - def test_inclusion_of_ruby_debug run_generator assert_file "Gemfile" do |contents| diff --git a/railties/test/railties/shared_tests.rb b/railties/test/railties/shared_tests.rb index 21fde49ff7..7653e52d26 100644 --- a/railties/test/railties/shared_tests.rb +++ b/railties/test/railties/shared_tests.rb @@ -21,6 +21,23 @@ module RailtiesTest assert_match "alert()", last_response.body end + def test_rake_environment_can_be_called_in_the_engine_or_plugin + boot_rails + + @plugin.write "Rakefile", <<-RUBY + APP_RAKEFILE = '#{app_path}/Rakefile' + load 'rails/tasks/engine.rake' + task :foo => :environment do + puts "Task ran" + end + RUBY + + Dir.chdir(@plugin.path) do + output = `bundle exec rake foo` + assert_match "Task ran", output + end + end + def test_copying_migrations @plugin.write "db/migrate/1_create_users.rb", <<-RUBY class CreateUsers < ActiveRecord::Migration |