From 55c18cfb28a69b73e4f720a61498ffe73fd6c22b Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Sun, 11 Jan 2009 19:22:19 +0000 Subject: - Add 'Performance test environment' to Performance guide - Add rake middleware and Josh's chat log to Rack guide - Remove long changelog from Active Record Finders guides --- .../html/activerecord_validations_callbacks.html | 2 +- railties/doc/guides/html/finders.html | 261 +++----- railties/doc/guides/html/performance_testing.html | 27 +- railties/doc/guides/html/rails_on_rack.html | 679 +++++++++++---------- .../guides/html/testing_rails_applications.html | 19 +- railties/doc/guides/source/finders.txt | 61 +- railties/doc/guides/source/performance_testing.txt | 13 + railties/doc/guides/source/rails_on_rack.txt | 34 ++ 8 files changed, 536 insertions(+), 560 deletions(-) (limited to 'railties/doc/guides') diff --git a/railties/doc/guides/html/activerecord_validations_callbacks.html b/railties/doc/guides/html/activerecord_validations_callbacks.html index 0862776f53..5251869119 100644 --- a/railties/doc/guides/html/activerecord_validations_callbacks.html +++ b/railties/doc/guides/html/activerecord_validations_callbacks.html @@ -645,7 +645,7 @@ http://www.gnu.org/software/src-highlite --> Note -If you want to validate the presence of a boolean field (where the real values are true and false), you will want to use validates_inclusion_of :field_name, :in ⇒ [true, false] This is due to the way Object#blank? handles boolean values. false.blank? # ⇒ true +If you want to validate the presence of a boolean field (where the real values are true and false), you will want to use validates_inclusion_of :field_name, :in => [true, false] This is due to the way Object#blank? handles boolean values. false.blank? # => true

The default error message for validates_presence_of is "can’t be empty".

diff --git a/railties/doc/guides/html/finders.html b/railties/doc/guides/html/finders.html index ba766b71b9..ea5b06ec92 100644 --- a/railties/doc/guides/html/finders.html +++ b/railties/doc/guides/html/finders.html @@ -198,12 +198,6 @@ ul#navMain { +

1. IDs, First, Last and All

ActiveRecord::Base has methods defined on it to make interacting with your database and the tables within it much, much easier. For finding records, the key method is find. This method allows you to pass arguments into it to perform certain queries on your database without the need of SQL. If you wanted to find the record with the id of 1, you could type Client.find(1) which would execute this query on your database:

@@ -482,10 +485,10 @@ http://www.gnu.org/software/src-highlite -->

You may see in Rails code that there are calls to methods such as Client.find(:all), Client.find(:first) and Client.find(:last). These methods are just alternatives to Client.all, Client.first and Client.last respectively.

Be aware that Client.first/Client.find(:first) and Client.last/Client.find(:last) will both return a single object, where as Client.all/Client.find(:all) will return an array of Client objects, just as passing in an array of ids to find will do also.

-

4. Conditions

+

2. Conditions

The find method allows you to specify conditions to limit the records returned. You can specify conditions as a string, array, or hash.

-

4.1. Pure String Conditions

+

2.1. Pure String Conditions

If you’d like to add conditions to your find, you could just specify them in there, just like Client.first(:conditions => "orders_count = 2"). This will find all clients where the orders_count field’s value is 2.

@@ -495,7 +498,7 @@ http://www.gnu.org/software/src-highlite -->
Building your own conditions as pure strings can leave you vulnerable to SQL injection exploits. For example, Client.first(:conditions => "name LIKE %#{params[:name]}%") is not safe. See the next section for the preferred way to handle conditions using an array.
-

4.2. Array Conditions

+

2.2. Array Conditions

Now what if that number could vary, say as a argument from somewhere, or perhaps from the user’s level status somewhere? The find then becomes something like Client.first(:conditions => ["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. If you want to specify two conditions, you can do it like Client.first(:conditions => ["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:

@@ -581,7 +584,7 @@ http://www.gnu.org/software/src-highlite -->
Client.all(:conditions =>
   ["created_at >= ? AND created_at <= ?", params[:start_date], params[:end_date]])

Just like in Ruby. If you want a shorter syntax be sure to check out the Hash Conditions section later on in the guide.

-

4.3. Placeholder Conditions

+

2.3. Placeholder Conditions

Similar to the array style of params you can also specify keys in your conditions:

Client.all(:conditions =>
   ["created_at >= :start_date AND created_at <= :end_date", { :start_date => params[:start_date], :end_date => params[:end_date] }])

This makes for clearer readability if you have a large number of variable conditions.

-

4.4. Hash Conditions

+

2.4. Hash Conditions

Rails also allows you to pass in a hash conditions which can increase the readability of your conditions syntax. With hash conditions, you pass in a hash with keys of the fields you want conditionalised and the values of how you want to conditionalise them:

SELECT * FROM `clients` WHERE (`clients`.`orders_count` IN (1,2,3))
-

5. Ordering

+

3. Ordering

If you’re getting a set of records and want to order them in ascending order by the created_at field in your table, you can use Client.all(:order => "created_at"). If you’d like to order it in descending order, just tell it to do that using Client.all(:order => "created_at desc"). The value for this option is passed in as sanitized SQL and allows you to sort via multiple fields: Client.all(:order => "created_at desc, orders_count asc").

-

6. Selecting Certain Fields

+

4. Selecting Certain Fields

To select certain fields, you can use the select option like this: Client.first(:select => "viewable_by, locked"). This select option does not use an array of fields, but rather requires you to type SQL-like code. The above code will execute SELECT viewable_by, locked FROM clients LIMIT 1 on your database.

Be careful because this also means you’re initializing a model object with only the fields that you’ve selected. If you attempt to access a field that is not in the initialized record you’ll receive:

@@ -666,7 +669,7 @@ http://www.gnu.org/software/src-highlite -->

Where <attribute> is the atrribute you asked for. The id method will not raise the ActiveRecord::MissingAttributeError, so just be careful when working with associations because they need the id method to function properly.

You can also call SQL functions within the select option. For example, if you would like to only grab a single record per unique value in a certain field by using the DISTINCT function you can do it like this: Client.all(:select => "DISTINCT(name)").

-

7. Limit & Offset

+

5. Limit & Offset

If you want to limit the amount of records to a certain subset of all the records retrieved you usually use limit for this, sometimes coupled with offset. Limit is the maximum number of records that will be retrieved from a query, and offset is the number of records it will start reading from from the first record of the set. Take this code for example:

@@ -696,7 +699,7 @@ http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
SELECT * FROM clients LIMIT 5, 5
-

8. Group

+

6. Group

The group option for find is useful, for example, if you want to find a collection of the dates orders were created on. You could use the option in this context:

@@ -714,7 +717,7 @@ http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
SELECT * FROM orders GROUP BY date(created_at)
-

9. Having

+

7. Having

The :having option allows you to specify SQL and acts as a kind of a filter on the group option. :having can only be specified when :group is specified.

An example of using it would be:

@@ -726,7 +729,7 @@ http://www.gnu.org/software/src-highlite -->
Order.all(:group => "date(created_at)", :having => ["created_at > ?", 1.month.ago])

This will return single order objects for each day, but only for the last month.

-

10. Read Only

+

8. Read Only

readonly is a find option that you can set in order to make that instance of the record read-only. Any attempt to alter or destroy the record will not succeed, raising an ActiveRecord::ReadOnlyRecord exception. To set this option, specify it like this:

@@ -745,7 +748,7 @@ http://www.gnu.org/software/src-highlite --> client.locked = false client.save
-

11. Lock

+

9. Lock

If you’re wanting to stop race conditions for a specific record (for example, you’re incrementing a single field for a record, potentially from multiple simultaneous connections) you can use the lock option to ensure that the record is updated correctly. For safety, you should use this inside a transaction.

@@ -768,11 +771,11 @@ http://www.gnu.org/software/src-highlite --> t.increment!(:views) end
-

12. Making It All Work Together

+

10. Making It All Work Together

You can chain these options together in no particular order as Active Record will write the correct SQL for you. If you specify two instances of the same options inside the find method Active Record will use the last one you specified. This is because the options passed to find are a hash and defining the same key twice in a hash will result in the last definition being used.

-

13. Eager Loading

+

11. Eager Loading

Eager loading is loading associated records along with any number of records in as few queries as possible. For example, if you wanted to load all the addresses associated with all the clients in a single query you could use Client.all(:include => :address). If you wanted to include both the address and mailing address for the client you would use Client.find(:all, :include => [:address, :mailing_address]). Include will first find the client records and then load the associated address records. Running script/server in one window, and executing the code through script/console in another window, the output should look similar to this:

@@ -814,7 +817,7 @@ http://www.gnu.org/software/src-highlite -->
Client.first(:include => "orders", :conditions =>
   ["orders.created_at >= ? AND orders.created_at <= ?", 2.weeks.ago, Time.now])
-

14. Dynamic finders

+

12. Dynamic finders

For every field (also known as an attribute) you define in your table, Active Record provides a finder method. If you have a field called name on your Client model for example, you get find_by_name and find_all_by_name for free from Active Record. If you have also have a locked field on the Client model, you also get find_by_locked and find_all_by_locked.

You can do find_last_by_* methods too which will find the last record matching your argument.

@@ -840,7 +843,7 @@ http://www.gnu.org/software/src-highlite -->
client = Client.find_or_initialize_by_name('Ryan')

will either assign an existing client object with the name Ryan to the client local variable, or initialize a new object similar to calling Client.new(:name => Ryan). From here, you can modify other fields in client by calling the attribute setters on it: client.locked = true and when you want to write it to the database just call save on it.

-

15. Finding By SQL

+

13. Finding By SQL

If you’d like to use your own SQL to find records in a table you can use find_by_sql. The find_by_sql method will return an array of objects even the underlying query returns just a single record. For example you could run this query:

@@ -851,7 +854,7 @@ http://www.gnu.org/software/src-highlite -->
Client.find_by_sql("SELECT * FROM clients INNER JOIN orders ON clients.id = orders.client_id ORDER clients.created_at desc")

find_by_sql provides you with a simple way of making custom calls to the database and retrieving instantiated objects.

-

16. select_all

+

14. select_all

find_by_sql has a close relative called connection#select_all. select_all will retrieve objects from the database using custom SQL just like find_by_sql but will not instantiate them. Instead, you will get an array of hashes where each hash indicates a record.

@@ -861,14 +864,14 @@ http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
Client.connection.select_all("SELECT * FROM `clients` WHERE `id` = '1'")
-

17. Working with Associations

+

15. Working with Associations

When you define a has_many association on a model you get the find method and dynamic finders also on that association. This is helpful for finding associated records within the scope of an existing record, for example finding all the orders for a client that have been sent and not received by doing something like Client.find(params[:id]).orders.find_by_sent_and_received(true, false). Having this find method available on associations is extremely helpful when using nested resources.

-

18. Named Scopes

+

16. Named Scopes

Named scopes are another way to add custom finding behavior to the models in the application. Named scopes provide an object-oriented way to narrow the results of a query.

-

18.1. Simple Named Scopes

+

16.1. Simple Named Scopes

Suppose we want to find all clients who are male. You could use this code:

named_scope :active, :conditions => { :active => true } end

You can call this new named_scope with Client.active.all and this will do the same query as if we just used Client.all(:conditions => ["active = ?", true]). If you want to find the first client within this named scope you could do Client.active.first.

-

18.2. Combining Named Scopes

+

16.2. Combining Named Scopes

If you wanted to find all the clients who are active and male you can stack the named scopes like this:

Client.males.active.all(:conditions => ["age > ?", params[:age]])
-

18.3. Runtime Evaluation of Named Scope Conditions

+

16.3. Runtime Evaluation of Named Scope Conditions

Consider the following code:

named_scope :recent, lambda { { :conditions => ["created_at > ?", 2.weeks.ago] } } end

And now every time the recent named scope is called, the code in the lambda block will be executed, so you’ll get actually 2 weeks ago from the code execution, not 2 weeks ago from the time the model was loaded.

-

18.4. Named Scopes with Multiple Models

+

16.4. Named Scopes with Multiple Models

In a named scope you can use :include and :joins options just like in find.

lambda { { :conditions => ["orders.created_at > ?", 2.weeks.ago] } } end

This method, called as Client.active_within_2_weeks.all, will return all clients who have placed orders in the past 2 weeks.

-

18.5. Arguments to Named Scopes

+

16.5. Arguments to Named Scopes

If you want to pass to a named scope a required arugment, just specify it as a block argument like this:

end

This will work with Client.recent(2.weeks.ago).all and Client.recent.all, with the latter always returning records with a created_at date between right now and 2 weeks ago.

Remember that named scopes are stackable, so you will be able to do Client.recent(2.weeks.ago).unlocked.all to find all clients created between right now and 2 weeks ago and have their locked field set to false.

-

18.6. Anonymous Scopes

+

16.6. Anonymous Scopes

All Active Record models come with a named scope named scoped, which allows you to create anonymous scopes. For example:

Client.scoped(:conditions => { :gender => "male" })

Just like named scopes, anonymous scopes can be stacked, either with other anonymous scopes or with regular named scopes.

-

19. Existence of Objects

+

17. Existence of Objects

If you simply want to check for the existence of the object there’s a method called exists?. This method will query the database using the same query as find, but instead of returning an object or collection of objects it will return either true or false+.

@@ -1004,7 +1007,7 @@ http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
Client.exists?(:conditions => "first_name = 'Ryan'")
-

20. Calculations

+

18. Calculations

This section uses count as an example method in this preamble, but the options described apply to all sub-sections.

count takes conditions much in the same way exists? does:

@@ -1038,10 +1041,10 @@ http://www.gnu.org/software/src-highlite --> LEFT OUTER JOIN orders ON orders.client_id = client.id WHERE (clients.first_name = 'Ryan' AND orders.status = 'received')

This code specifies clients.first_name just in case one of the join tables has a field also called first_name and it uses orders.status because that’s the name of our join table.

-

20.1. Count

+

18.1. Count

If you want to see how many records are in your model’s table you could call Client.count and that will return the number. If you want to be more specific and find all the clients with their age present in the database you can use Client.count(:age).

For options, please see the parent section, Calculations.

-

20.2. Average

+

18.2. Average

If you want to see the average of a certain number in one of your tables you can call the average method on the class that relates to the table. This method call will look something like this:

Client.average("orders_count")

This will return a number (possibly a floating point number such as 3.14159265) representing the average value in the field.

For options, please see the parent section, Calculations.

-

20.3. Minimum

+

18.3. Minimum

If you want to find the minimum value of a field in your table you can call the minimum method on the class that relates to the table. This method call will look something like this:

Client.minimum("age")

For options, please see the parent section, Calculations

-

20.4. Maximum

+

18.4. Maximum

If you want to find the maximum value of a field in your table you can call the maximum method on the class that relates to the table. This method call will look something like this:

Client.maximum("age")

For options, please see the parent section, Calculations

-

20.5. Sum

+

18.5. Sum

If you want to find the sum of a field for all records in your table you can call the sum method on the class that relates to the table. This method call will look something like this:

Client.sum("orders_count")

For options, please see the parent section, Calculations

-

21. Credits

-
-

Thanks to Ryan Bates for his awesome screencast on named scope #108. The information within the named scope section is intentionally similar to it, and without the cast may have not been possible.

-

Thanks to Mike Gunderloy for his tips on creating this guide.

-
-

22. Changelog

+

19. Changelog

  • -December 29 2008: Added James B. Byrne’s suggestions from this ticket -

    -
  • -
  • -

    -December 23 2008: Xavier Noria suggestions added! From this ticket and this ticket and this ticket -

    -
  • -
  • -

    -December 22 2008: Added section on having. -

    -
  • -
  • -

    -December 22 2008: Added description of how to make hash conditions use an IN expression mentioned here -

    -
  • -
  • -

    -December 22 2008: Mentioned using SQL as values for the lock option as mentioned in this ticket -

    -
  • -
  • -

    -December 21 2008: Fixed this ticket minus two points; the lock SQL syntax and the having option. -

    -
  • -
  • -

    -December 21 2008: Added more to the has conditions section. -

    -
  • -
  • -

    -December 17 2008: Fixed up syntax errors. -

    -
  • -
  • -

    -December 16 2008: Covered hash conditions that were introduced in Rails 2.2.2. -

    -
  • -
  • -

    -December 1 2008: Added using an SQL function example to Selecting Certain Fields section as per this ticket -

    -
  • -
  • -

    -November 23 2008: Added documentation for find_by_last and find_by_bang! -

    -
  • -
  • -

    -November 21 2008: Fixed all points specified in this comment and this comment -

    -
  • -
  • -

    -November 18 2008: Fixed all points specified in this comment -

    -
  • -
  • -

    -November 8, 2008: Editing pass by Mike Gunderloy . First release version. -

    -
  • -
  • -

    -October 27, 2008: Added scoped section, added named params for conditions and added sub-section headers for conditions section by Ryan Bigg -

    -
  • -
  • -

    -October 27, 2008: Fixed up all points specified in this comment with an exception of the final point by Ryan Bigg -

    -
  • -
  • -

    -October 26, 2008: Editing pass by Mike Gunderloy . First release version. -

    -
  • -
  • -

    -October 22, 2008: Calculations complete, first complete draft by Ryan Bigg -

    -
  • -
  • -

    -October 21, 2008: Extended named scope section by Ryan Bigg -

    -
  • -
  • -

    -October 9, 2008: Lock, count, cleanup by Ryan Bigg -

    -
  • -
  • -

    -October 6, 2008: Eager loading by Ryan Bigg -

    -
  • -
  • -

    -October 5, 2008: Covered conditions by Ryan Bigg -

    -
  • -
  • -

    -October 1, 2008: Covered limit/offset, formatting changes by Ryan Bigg -

    -
  • -
  • -

    -September 28, 2008: Covered first/last/all by Ryan Bigg +December 29 2008: Initial version by Ryan Bigg

diff --git a/railties/doc/guides/html/performance_testing.html b/railties/doc/guides/html/performance_testing.html index 2e6ba0a891..ddad6506a9 100644 --- a/railties/doc/guides/html/performance_testing.html +++ b/railties/doc/guides/html/performance_testing.html @@ -214,6 +214,8 @@ ul#navMain {
  • Tuning Test Runs
  • +
  • Performance Test Environment
  • +
  • Installing GC-Patched Ruby
  • @@ -560,12 +562,23 @@ http://www.gnu.org/software/src-highlite --> Performance test configurability is not yet enabled in Rails. But it will be soon.
    -

    1.7. Installing GC-Patched Ruby

    +

    1.7. Performance Test Environment

    +

    Performance tests are run in the development environment. But running performance tests will set the following configuration parameters:

    +
    +
    +
    ActionController::Base.perform_caching = true
    +ActiveSupport::Dependencies.mechanism = :require
    +Rails.logger.level = ActiveSupport::BufferedLogger::INFO
    +

    As ActionController::Base.perform_caching is set to true, performance tests will behave much as they do in the production environment.

    +

    1.8. Installing GC-Patched Ruby

    To get the best from Rails performance tests, you need to build a special Ruby binary with some super powers - GC patch for measuring GC Runs/Time and memory/object allocation.

    The process is fairly straight forward. If you’ve never compiled a Ruby binary before, follow these steps to build a ruby binary inside your home directory:

    -

    1.7.1. Installation

    +

    1.8.1. Installation

    Compile Ruby and apply this GC Patch:

    -

    1.7.2. Download and Extract

    +

    1.8.2. Download and Extract

    [lifo@null ~]$ wget <download the latest stable ruby from ftp://ftp.ruby-lang.org/pub/ruby> [lifo@null ~]$ tar -xzvf <ruby-version.tar.gz> [lifo@null ~]$ cd <ruby-version>
    -

    1.7.3. Apply the patch

    +

    1.8.3. Apply the patch

    [lifo@null ruby-version]$ curl http://rubyforge.org/tracker/download.php/1814/7062/17676/3291/ruby186gc.patch | patch -p0
    -

    1.7.4. Configure and Install

    +

    1.8.4. Configure and Install

    The following will install ruby in your home directory’s /rubygc directory. Make sure to replace <homedir> with a full patch to your actual home directory.

    [lifo@null ruby-version]$ ./configure --prefix=/<homedir>/rubygc
     [lifo@null ruby-version]$ make && make install
    -

    1.7.5. Prepare aliases

    +

    1.8.5. Prepare aliases

    For convenience, add the following lines in your ~/.profile:

    @@ -601,7 +614,7 @@ alias gcgem='~/rubygc/bin/gem' alias gcirb='~/rubygc/bin/irb' alias gcrails='~/rubygc/bin/rails'
    -

    1.7.6. Install rubygems and dependency gems

    +

    1.8.6. Install rubygems and dependency gems

    Download Rubygems and install it from source. Rubygem’s README file should have necessary installation instructions.

    Additionally, install the following gems :

    - + - +

    Rails on Rack

    -
    -
    -

    This guide covers Rails integration with Rack and interfacing with other Rack components. By referring to this guide, you will be able to:

    -
      -
    • -

      -Create Rails Metal applications -

      -
    • -
    • -

      -Use Rack Middlewares in your Rails applications -

      -
    • -
    • -

      -Understand Action Pack’s internal Middleware stack -

      -
    • -
    • -

      -Define custom internal Middleware stack -

      -
    • -
    • -

      -Understand the best practices for developing a middleware aimed at Rails applications -

      -
    • -
    -
    - - - -
    -Note -This guide assumes a working knowledge of Rack protocol and Rack concepts such as middlewares
    -
    -
    -
    -

    1. Introduction to Rack

    -
    -
    -
    -

    Explaining Rack is not really in the scope of this guide. In case you are not familiar with Rack’s basics, you should check out the following links:

    - -
    -

    2. Rails on Rack

    -
    -

    2.1. ActionController::Dispatcher.new

    -

    ActionController::Dispatcher.new is the primary Rack application object of a Rails application. It responds to call method with a single env argument and returns a Rack response. Any Rack compliant web server should be using ActionController::Dispatcher.new object to serve a Rails application.

    -

    2.2. script/server

    -

    script/server does the basic job of creating a Rack::Builder object and starting the webserver. This is Rails equivalent of Rack’s rackup script.

    -

    Here’s how script/server creates an instance of Rack::Builder

    -
    -
    -
    app = Rack::Builder.new {
    -  use Rails::Rack::LogTailer unless options[:detach]
    -  use Rails::Rack::Static
    -  use Rails::Rack::Debugger if options[:debugger]
    -  run ActionController::Dispatcher.new
    -}.to_app
    -

    Middlewares used in the code above are most useful in development envrionment. The following table explains their usage:

    -
    - --- - - - - - - - - - - - - - - - - - - - -
    Middleware Purpose

    Rails::Rack::LogTailer

    Appends log file output to console

    Rails::Rack::Static

    Serves static files inside RAILS_ROOT/public directory

    Rails::Rack::Debugger

    Starts Debugger

    -
    -

    2.3. rackup

    -

    To use rackup instead of Rails' script/server, you can put the following inside config.ru of your Rails application’s root directory:

    -
    -
    -
    # RAILS_ROOT/config.ru
    -require "config/environment"
    -
    -use Rails::Rack::LogTailer
    -use Rails::Rack::Static
    -run ActionController::Dispatcher.new
    -

    And start the server:

    -
    -
    -
    [lifo@null application]$ rackup
    -

    To find out more about different rackup options:

    -
    -
    -
    [lifo@null application]$ rackup --help
    -
    -

    3. Action Controller Middleware Stack

    -
    -

    Many of Action Controller’s internal components are implemented as Rack middlewares. ActionController::Dispatcher uses ActionController::MiddlewareStack to combine various internal and external middlewares to form a complete Rails Rack application.

    -
    - - - -
    -Note - -
    What is ActionController::MiddlewareStack ?
    ActionController::MiddlewareStack is Rails equivalent of Rack::Builder, but built for better flexibility and more features to meet Rails' requirements.
    -
    -

    3.1. Adding Middlewares

    -

    Rails provides a very simple configuration interface for adding generic Rack middlewares to a Rails applications.

    -

    Here’s how you can add middlewares via environment.rb

    -
    -
    -
    # environment.rb
    -
    -config.middleware.use Rack::BounceFavicon
    -

    3.2. Internal Middleware Stack

    -
    -
    -
    use "ActionController::Lock", :if => lambda {
    -  !ActionController::Base.allow_concurrency
    -}
    -
    -use "ActionController::Failsafe"
    -
    -use "ActiveRecord::QueryCache", :if => lambda { defined?(ActiveRecord) }
    -
    -["ActionController::Session::CookieStore",
    - "ActionController::Session::MemCacheStore",
    - "ActiveRecord::SessionStore"].each do |store|
    -   use(store, ActionController::Base.session_options,
    -      :if => lambda {
    -        if session_store = ActionController::Base.session_store
    -          session_store.name == store
    -        end
    -      }
    -    )
    -end
    -
    -use ActionController::VerbPiggybacking
    -
    - --- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    Middleware Purpose

    ActionController::Lock

    Mutex

    ActionController::Failsafe

    Never fail

    ActiveRecord::QueryCache

    Query caching

    ActionController::Session::CookieStore

    Query caching

    ActionController::Session::MemCacheStore

    Query caching

    ActiveRecord::SessionStore

    Query caching

    ActionController::VerbPiggybacking

    _method hax

    -
    -

    3.3. Custom Internal Middleware Stack

    -

    VERIFY THIS WORKS. Just a code dump at the moment.

    -

    Put the following in an initializer.

    -
    -
    -
    ActionController::Dispatcher.middleware = ActionController::MiddlewareStack.new do |m|
    -  m.use ActionController::Lock
    -  m.use ActionController::Failsafe
    -  m.use ActiveRecord::QueryCache
    -  m.use ActionController::Session::CookieStore
    -  m.use ActionController::VerbPiggybacking
    -end
    -
    -

    4. Rails Metal Applications

    -
    -

    Rails Metal applications are minimal Rack applications specially designed for integrating with a typical Rails applications. As Rails Metal Applications skip all of the Action Controller stack, serving a request has no overhead from the Rails framework itself. This is especially useful for infrequent cases where the performance of the full stack Rails framework is an issue.

    -

    4.1. Generating a Metal Application

    -

    Rails provides a generator called performance_test for creating new performance tests:

    -
    -
    -
    script/generate metal poller
    -

    This generates poller.rb in the app/metal directory:

    -
    -
    -
    # Allow the metal piece to run in isolation
    -require(File.dirname(__FILE__) + "/../../config/environment") unless defined?(Rails)
    -
    -class Poller
    -  def self.call(env)
    -    if env["PATH_INFO"] =~ /^\/poller/
    -      [200, {"Content-Type" => "text/html"}, ["Hello, World!"]]
    -    else
    -      [404, {"Content-Type" => "text/html"}, ["Not Found"]]
    -    end
    -  end
    -end
    -

    Metal applications are an optimization. You should make sure to understand the related performance implications before using it.

    -
    -

    5. Changelog

    -
    - -
      -
    • -

      -January 11, 2009: First version by Pratik -

      -
    • -
    -
    +
    +
    +

    This guide covers Rails integration with Rack and interfacing with other Rack components. By referring to this guide, you will be able to:

    +
      +
    • +

      +Create Rails Metal applications +

      +
    • +
    • +

      +Use Rack Middlewares in your Rails applications +

      +
    • +
    • +

      +Understand Action Pack’s internal Middleware stack +

      +
    • +
    • +

      +Define custom internal Middleware stack +

      +
    • +
    • +

      +Understand the best practices for developing a middleware aimed at Rails applications +

      +
    • +
    +
    + + + +
    +Note +This guide assumes a working knowledge of Rack protocol and Rack concepts such as middlewares, url maps and Rack::Builder.
    +
    +
    +
    +

    1. Introduction to Rack

    +
    +
    +
    +

    Explaining Rack is not really in the scope of this guide. In case you are not familiar with Rack’s basics, you should check out the following links:

    + +
    +

    2. Rails on Rack

    +
    +

    2.1. ActionController::Dispatcher.new

    +

    ActionController::Dispatcher.new is the primary Rack application object of a Rails application. It responds to call method with a single env argument and returns a Rack response. Any Rack compliant web server should be using ActionController::Dispatcher.new object to serve a Rails application.

    +

    2.2. script/server

    +

    script/server does the basic job of creating a Rack::Builder object and starting the webserver. This is Rails equivalent of Rack’s rackup script.

    +

    Here’s how script/server creates an instance of Rack::Builder

    +
    +
    +
    app = Rack::Builder.new {
    +  use Rails::Rack::LogTailer unless options[:detach]
    +  use Rails::Rack::Static
    +  use Rails::Rack::Debugger if options[:debugger]
    +  run ActionController::Dispatcher.new
    +}.to_app
    +

    Middlewares used in the code above are most useful in development envrionment. The following table explains their usage:

    +
    + +++ + + + + + + + + + + + + + + + + + + + +
    Middleware Purpose

    Rails::Rack::LogTailer

    Appends log file output to console

    Rails::Rack::Static

    Serves static files inside RAILS_ROOT/public directory

    Rails::Rack::Debugger

    Starts Debugger

    +
    +

    2.3. rackup

    +

    To use rackup instead of Rails' script/server, you can put the following inside config.ru of your Rails application’s root directory:

    +
    +
    +
    # RAILS_ROOT/config.ru
    +require "config/environment"
    +
    +use Rails::Rack::LogTailer
    +use Rails::Rack::Static
    +run ActionController::Dispatcher.new
    +

    And start the server:

    +
    +
    +
    [lifo@null application]$ rackup
    +

    To find out more about different rackup options:

    +
    +
    +
    [lifo@null application]$ rackup --help
    +
    +

    3. Action Controller Middleware Stack

    +
    +

    Many of Action Controller’s internal components are implemented as Rack middlewares. ActionController::Dispatcher uses ActionController::MiddlewareStack to combine various internal and external middlewares to form a complete Rails Rack application.

    +
    + + + +
    +Note + +
    What is ActionController::MiddlewareStack ?
    ActionController::MiddlewareStack is Rails equivalent of Rack::Builder, but built for better flexibility and more features to meet Rails' requirements.
    +
    +

    3.1. Adding Middlewares

    +

    Rails provides a very simple configuration interface for adding generic Rack middlewares to a Rails applications.

    +

    Here’s how you can add middlewares via environment.rb

    +
    +
    +
    # environment.rb
    +
    +config.middleware.use Rack::BounceFavicon
    +

    3.2. Internal Middleware Stack

    +
    +
    +
    use "ActionController::Lock", :if => lambda {
    +  !ActionController::Base.allow_concurrency
    +}
    +
    +use "ActionController::Failsafe"
    +
    +use "ActiveRecord::QueryCache", :if => lambda { defined?(ActiveRecord) }
    +
    +["ActionController::Session::CookieStore",
    + "ActionController::Session::MemCacheStore",
    + "ActiveRecord::SessionStore"].each do |store|
    +   use(store, ActionController::Base.session_options,
    +      :if => lambda {
    +        if session_store = ActionController::Base.session_store
    +          session_store.name == store
    +        end
    +      }
    +    )
    +end
    +
    +use ActionController::VerbPiggybacking
    +
    + +++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Middleware Purpose

    ActionController::Lock

    Mutex

    ActionController::Failsafe

    Never fail

    ActiveRecord::QueryCache

    Query caching

    ActionController::Session::CookieStore

    Query caching

    ActionController::Session::MemCacheStore

    Query caching

    ActiveRecord::SessionStore

    Query caching

    ActionController::VerbPiggybacking

    _method hax

    +
    +

    3.3. Customizing Internal Middleware Stack

    +

    VERIFY THIS WORKS. Just a code dump at the moment.

    +

    Put the following in an initializer.

    +
    +
    +
    ActionController::Dispatcher.middleware = ActionController::MiddlewareStack.new do |m|
    +  m.use ActionController::Lock
    +  m.use ActionController::Failsafe
    +  m.use ActiveRecord::QueryCache
    +  m.use ActionController::Session::CookieStore
    +  m.use ActionController::VerbPiggybacking
    +end
    +

    Josh says :

    +
    +
    +

    3.4. Inspecting Middleware Stack

    +

    Rails has a handy rake task for inspecting the middleware stack in use:

    +
    +
    +
    $ rake middleware
    +

    For a freshly generated Rails application, this will produce:

    +
    +
    +
    use ActionController::Lock
    +use ActionController::Failsafe
    +use ActiveRecord::QueryCache
    +use ActionController::Session::CookieStore, {:secret=>"aa5150a22c1a5f24112260c33ae2131a88d7539117bfdcd5696fb2be385b60c6da9f7d4ed0a67e3b8cc85cc4e653ba0111dd1f3f8999520f049e2262068c16a6", :session_key=>"_edge_session"}
    +use Rails::Rack::Metal
    +use ActionController::VerbPiggybacking
    +run ActionController::Dispatcher.new
    +

    This rake task is very useful if the application requires highly customized Rack middleware setup.

    +
    +

    4. Rails Metal Applications

    +
    +

    Rails Metal applications are minimal Rack applications specially designed for integrating with a typical Rails application. As Rails Metal Applications skip all of the Action Controller stack, serving a request has no overhead from the Rails framework itself. This is especially useful for infrequent cases where the performance of the full stack Rails framework is an issue.

    +

    4.1. Generating a Metal Application

    +

    Rails provides a generator called performance_test for creating new performance tests:

    +
    +
    +
    script/generate metal poller
    +

    This generates poller.rb in the app/metal directory:

    +
    +
    +
    # Allow the metal piece to run in isolation
    +require(File.dirname(__FILE__) + "/../../config/environment") unless defined?(Rails)
    +
    +class Poller
    +  def self.call(env)
    +    if env["PATH_INFO"] =~ /^\/poller/
    +      [200, {"Content-Type" => "text/html"}, ["Hello, World!"]]
    +    else
    +      [404, {"Content-Type" => "text/html"}, ["Not Found"]]
    +    end
    +  end
    +end
    +

    Metal applications are an optimization. You should make sure to understand the related performance implications before using it.

    +
    +

    5. Middlewares and Rails

    +
    +
    +

    6. Changelog

    +
    + +
      +
    • +

      +January 11, 2009: First version by Pratik +

      +
    • +
    +
    diff --git a/railties/doc/guides/html/testing_rails_applications.html b/railties/doc/guides/html/testing_rails_applications.html index ac6ecc73b9..457f93f622 100644 --- a/railties/doc/guides/html/testing_rails_applications.html +++ b/railties/doc/guides/html/testing_rails_applications.html @@ -1157,7 +1157,7 @@ by Lorenzo Bettini http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
    assert_select 'title', "Welcome to Rails Testing Guide"
    -

    You can also use nested assert_select blocks. In this case the inner assert_select will run the assertion on each element selected by the outer assert_select block:

    +

    You can also use nested assert_select blocks. In this case the inner assert_select runs the assertion on the complete collection of elements selected by the outer assert_select block:

    assert_select 'ul.navigation' do
       assert_select 'li.menu_item'
     end
    -

    The assert_select assertion is quite powerful. For more advanced usage, refer to its documentation.

    +

    Alternatively the collection of elements selected by the outer assert_select may be iterated through so that assert_select may be called separately for each element. Suppose for example that the response contains two ordered lists, each with four list elements then the following tests will both pass.

    +
    +
    +
    assert_select "ol" do |elements|
    +  elements.each do |element|
    +    assert_select element, "li", 4
    +  end
    +end
    +
    +assert_select "ol" do
    +  assert_select "li", 8
    +end
    +

    The assert_select assertion is quite powerful. For more advanced usage, refer to its documentation.

    4.6.1. Additional View-based Assertions

    There are more assertions that are primarily used in testing views:

    diff --git a/railties/doc/guides/source/finders.txt b/railties/doc/guides/source/finders.txt index a6a7f61c12..c334033437 100644 --- a/railties/doc/guides/source/finders.txt +++ b/railties/doc/guides/source/finders.txt @@ -1,23 +1,19 @@ Rails Finders ============= -This guide covers the +find+ method defined in ActiveRecord::Base, as well as other ways of finding particular instances of your models. By using this guide, you will be able to: +This guide covers different ways to retrieve data from the database using Active Record. By referring to this guide, you will be able to: * Find records using a variety of methods and conditions * Specify the order, retrieved attributes, grouping, and other properties of the found records -* Use eager loading to cut down on the number of database queries in your application -* Use dynamic finders +* Use eager loading to reduce the number of database queries needed for data retrieval +* Use dynamic finders methods * Create named scopes to add custom finding behavior to your models * Check for the existence of particular records -* Perform aggregate calculations on Active Record models +* Perform various calculations on Active Record models If you're used to using raw SQL to find database records then, generally, you will find that there are better ways to carry out the same operations in Rails. Active Record insulates you from the need to use SQL in most cases. -Generated SQL statements that appear in the log files may have their arguments quoted. Further, the form of quoting will be DBMS specific; SQLite3 will use "\ for example while MySQL will use `\ instead. Because of this, simply copying SQL from the examples contained within this guide may not work in your database system. Please consult the database systems manual before attempting to execute any SQL. - -== The Sample Models - -This guide demonstrates finding using the following models: +Code examples in this guide use one or more of the following models: [source,ruby] ------------------------------------------------------- @@ -27,26 +23,38 @@ class Client < ActiveRecord::Base has_many :orders has_and_belongs_to_many :roles end +------------------------------------------------------- +[source,ruby] +------------------------------------------------------- class Address < ActiveRecord::Base belongs_to :client end +------------------------------------------------------- +[source,ruby] +------------------------------------------------------- class MailingAddress < Address end +------------------------------------------------------- +[source,ruby] +------------------------------------------------------- class Order < ActiveRecord::Base belongs_to :client, :counter_cache => true end +------------------------------------------------------- +[source,ruby] +------------------------------------------------------- class Role < ActiveRecord::Base has_and_belongs_to_many :clients end ------------------------------------------------------- -== Database Agnostic - +**** Active Record will perform queries on the database for you and is compatible with most database systems (MySQL, PostgreSQL and SQLite to name a few). Regardless of which database system you're using, the Active Record method format will always be the same. +**** == IDs, First, Last and All @@ -759,37 +767,8 @@ Client.sum("orders_count") For options, please see the parent section, <<_calculations, Calculations>> -== Credits - -Thanks to Ryan Bates for his awesome screencast on named scope #108. The information within the named scope section is intentionally similar to it, and without the cast may have not been possible. - -Thanks to Mike Gunderloy for his tips on creating this guide. - == Changelog http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16[Lighthouse ticket] -* December 29 2008: Added http://rails.lighthouseapp.com/projects/16213/tickets/16-activerecord-finders#ticket-16-32[James B. Byrne's suggestions from this ticket] -* December 23 2008: Xavier Noria suggestions added! From http://rails.lighthouseapp.com/projects/16213/tickets/16-activerecord-finders#ticket-16-27[this ticket] and http://rails.lighthouseapp.com/projects/16213/tickets/16-activerecord-finders#ticket-16-28[this ticket] and http://rails.lighthouseapp.com/projects/16213/tickets/16-activerecord-finders#ticket-16-29[this ticket] -* December 22 2008: Added section on having. -* December 22 2008: Added description of how to make hash conditions use an IN expression http://rails.loglibrary.com/chats/15279234[mentioned here] -* December 22 2008: Mentioned using SQL as values for the lock option as mentioned in http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-24[this ticket] -* December 21 2008: Fixed http://rails.lighthouseapp.com/projects/16213/tickets/16-activerecord-finders#ticket-16-22[this ticket] minus two points; the lock SQL syntax and the having option. -* December 21 2008: Added more to the has conditions section. -* December 17 2008: Fixed up syntax errors. -* December 16 2008: Covered hash conditions that were introduced in Rails 2.2.2. -* December 1 2008: Added using an SQL function example to Selecting Certain Fields section as per http://rails.lighthouseapp.com/projects/16213/tickets/36-adding-an-example-for-using-distinct-to-ar-finders[this ticket] -* November 23 2008: Added documentation for +find_by_last+ and +find_by_bang!+ -* November 21 2008: Fixed all points specified in http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-13[this comment] and http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-14[this comment] -* November 18 2008: Fixed all points specified in http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-11[this comment] -* November 8, 2008: Editing pass by link:../authors.html#mgunderloy[Mike Gunderloy] . First release version. -* October 27, 2008: Added scoped section, added named params for conditions and added sub-section headers for conditions section by Ryan Bigg -* October 27, 2008: Fixed up all points specified in http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-6[this comment] with an exception of the final point by Ryan Bigg -* October 26, 2008: Editing pass by link:../authors.html#mgunderloy[Mike Gunderloy] . First release version. -* October 22, 2008: Calculations complete, first complete draft by Ryan Bigg -* October 21, 2008: Extended named scope section by Ryan Bigg -* October 9, 2008: Lock, count, cleanup by Ryan Bigg -* October 6, 2008: Eager loading by Ryan Bigg -* October 5, 2008: Covered conditions by Ryan Bigg -* October 1, 2008: Covered limit/offset, formatting changes by Ryan Bigg -* September 28, 2008: Covered first/last/all by Ryan Bigg +* December 29 2008: Initial version by Ryan Bigg \ No newline at end of file diff --git a/railties/doc/guides/source/performance_testing.txt b/railties/doc/guides/source/performance_testing.txt index 84a42cecde..03099dbc98 100644 --- a/railties/doc/guides/source/performance_testing.txt +++ b/railties/doc/guides/source/performance_testing.txt @@ -301,6 +301,19 @@ By default, each performance test is run +4 times+ in benchmarking mode and +1 t CAUTION: Performance test configurability is not yet enabled in Rails. But it will be soon. +=== Performance Test Environment === + +Performance tests are run in the +development+ environment. But running performance tests will set the following configuration parameters: + +[source, shell] +---------------------------------------------------------------------------- +ActionController::Base.perform_caching = true +ActiveSupport::Dependencies.mechanism = :require +Rails.logger.level = ActiveSupport::BufferedLogger::INFO +---------------------------------------------------------------------------- + +As +ActionController::Base.perform_caching+ is set to +true+, performance tests will behave much as they do in the production environment. + [[gc]] === Installing GC-Patched Ruby === diff --git a/railties/doc/guides/source/rails_on_rack.txt b/railties/doc/guides/source/rails_on_rack.txt index b5a798bdc7..ad316567cc 100644 --- a/railties/doc/guides/source/rails_on_rack.txt +++ b/railties/doc/guides/source/rails_on_rack.txt @@ -161,6 +161,40 @@ ActionController::Dispatcher.middleware = ActionController::MiddlewareStack.new end ---------------------------------------------------------------------------- +Josh says : + +**** +3.3: I wouldn't recommend this: custom internal stack +i'd recommend using config.middleware.use api +we still need a better api for swapping out existing middleware, etc +config.middleware.swap AC::Sessions, My::Sessoins +or something like that +**** + +=== Inspecting Middleware Stack === + +Rails has a handy rake task for inspecting the middleware stack in use: + +[source, shell] +---------------------------------------------------------------------------- +$ rake middleware +---------------------------------------------------------------------------- + +For a freshly generated Rails application, this will produce: + +[source, ruby] +---------------------------------------------------------------------------- +use ActionController::Lock +use ActionController::Failsafe +use ActiveRecord::QueryCache +use ActionController::Session::CookieStore, {:secret=>"aa5150a22c1a5f24112260c33ae2131a88d7539117bfdcd5696fb2be385b60c6da9f7d4ed0a67e3b8cc85cc4e653ba0111dd1f3f8999520f049e2262068c16a6", :session_key=>"_edge_session"} +use Rails::Rack::Metal +use ActionController::VerbPiggybacking +run ActionController::Dispatcher.new +---------------------------------------------------------------------------- + +This rake task is very useful if the application requires highly customized Rack middleware setup. + == Rails Metal Applications == Rails Metal applications are minimal Rack applications specially designed for integrating with a typical Rails application. As Rails Metal Applications skip all of the Action Controller stack, serving a request has no overhead from the Rails framework itself. This is especially useful for infrequent cases where the performance of the full stack Rails framework is an issue. -- cgit v1.2.3