aboutsummaryrefslogtreecommitdiffstats
path: root/railties
diff options
context:
space:
mode:
authorJeremy Kemper <jeremy@bitsweat.net>2009-01-10 12:14:44 -0800
committerJeremy Kemper <jeremy@bitsweat.net>2009-01-10 12:14:44 -0800
commit223a1d9451c88800e9fcc93a726fdebec99e2650 (patch)
tree207b0b671778ac7a0e00829f6f642256b261cb28 /railties
parent13c6c3cfc59ff0b400b294dce15f32752b0fb5f5 (diff)
parent9fe69b225cfbf12c02ee1433adf3a5aa17bcdf59 (diff)
downloadrails-223a1d9451c88800e9fcc93a726fdebec99e2650.tar.gz
rails-223a1d9451c88800e9fcc93a726fdebec99e2650.tar.bz2
rails-223a1d9451c88800e9fcc93a726fdebec99e2650.zip
Merge branch 'master' into savepoints
Diffstat (limited to 'railties')
-rw-r--r--railties/CHANGELOG390
-rw-r--r--railties/doc/guides/html/activerecord_validations_callbacks.html81
-rw-r--r--railties/doc/guides/html/finders.html6
-rw-r--r--railties/doc/guides/html/getting_started_with_rails.html2
-rw-r--r--railties/doc/guides/html/layouts_and_rendering.html2
-rw-r--r--railties/doc/guides/html/testing_rails_applications.html1470
-rw-r--r--railties/doc/guides/source/activerecord_validations_callbacks.txt75
-rw-r--r--railties/doc/guides/source/command_line.txt145
-rw-r--r--railties/doc/guides/source/finders.txt186
-rw-r--r--railties/doc/guides/source/form_helpers.txt121
-rw-r--r--railties/doc/guides/source/getting_started_with_rails.txt2
-rw-r--r--railties/doc/guides/source/i18n.txt260
-rw-r--r--railties/doc/guides/source/images/i18n/demo_localized_pirate.pngbin0 -> 36500 bytes
-rw-r--r--railties/doc/guides/source/images/i18n/demo_translated_en.pngbin0 -> 32877 bytes
-rw-r--r--railties/doc/guides/source/images/i18n/demo_translated_pirate.pngbin0 -> 34506 bytes
-rw-r--r--railties/doc/guides/source/images/i18n/demo_translation_missing.pngbin0 -> 34373 bytes
-rw-r--r--railties/doc/guides/source/images/i18n/demo_untranslated.pngbin0 -> 32793 bytes
-rw-r--r--railties/doc/guides/source/testing_rails_applications.txt20
-rw-r--r--railties/lib/commands/about.rb2
-rw-r--r--railties/lib/commands/dbconsole.rb2
-rw-r--r--railties/lib/commands/runner.rb4
-rw-r--r--railties/lib/commands/server.rb2
-rw-r--r--railties/lib/initializer.rb27
-rw-r--r--railties/lib/rails/backtrace_cleaner.rb8
-rw-r--r--railties/lib/rails/plugin/locator.rb2
-rw-r--r--railties/lib/rails/rack.rb3
-rw-r--r--railties/lib/rails/rack/log_tailer.rb35
-rw-r--r--railties/lib/rails/rack/logger.rb28
-rw-r--r--railties/lib/rails/rack/metal.rb36
-rw-r--r--railties/lib/rails_generator/commands.rb2
-rw-r--r--railties/lib/rails_generator/generators/applications/app/template_runner.rb131
-rw-r--r--railties/lib/rails_generator/generators/components/metal/USAGE8
-rw-r--r--railties/lib/rails_generator/generators/components/metal/metal_generator.rb8
-rw-r--r--railties/lib/rails_generator/generators/components/metal/templates/metal.rb12
-rw-r--r--railties/lib/tasks/databases.rake2
-rw-r--r--railties/lib/tasks/middleware.rake2
-rw-r--r--railties/lib/tasks/tmp.rake4
-rw-r--r--railties/lib/test_help.rb1
-rw-r--r--railties/test/console_app_test.rb10
-rw-r--r--railties/test/error_page_test.rb11
-rw-r--r--railties/test/fcgi_dispatcher_test.rb49
-rw-r--r--railties/test/gem_dependency_test.rb25
-rw-r--r--railties/test/generators/rails_template_runner_test.rb190
43 files changed, 1796 insertions, 1568 deletions
diff --git a/railties/CHANGELOG b/railties/CHANGELOG
index 9ce7b6349c..b313f082a3 100644
--- a/railties/CHANGELOG
+++ b/railties/CHANGELOG
@@ -1,6 +1,6 @@
*2.3.0 [Edge]*
-* Add a rake task to apply a template to an existing application : rake rails:template LOCATION=~/template.rb [Pratik]
+* Add a rake task to apply a template to an existing application : rake rails:template LOCATION=~/template.rb [Pratik Naik]
* Add "-m/--template" option to Rails generator to apply a template to the generated application. [Jeremy McAnally]
@@ -45,31 +45,31 @@
rails <application name> --template=http://gist.github.com/31208.txt
-* Extracted the process scripts (inspector, reaper, spawner) into the plugin irs_process_scripts [DHH]
+* Extracted the process scripts (inspector, reaper, spawner) into the plugin irs_process_scripts [David Heinemeier Hansson]
* Changed Rails.root to return a Pathname object (allows for Rails.root.join('app', 'controllers') => "#{RAILS_ROOT}/app/controllers") #1482 [Damian Janowski/?]
-* Added view path support for engines [DHH]
+* Added view path support for engines [David Heinemeier Hansson]
-* Added that config/routes.rb files in engine plugins are automatically loaded (and reloaded when they change in dev mode) [DHH]
+* Added that config/routes.rb files in engine plugins are automatically loaded (and reloaded when they change in dev mode) [David Heinemeier Hansson]
-* Added app/[models|controllers|helpers] to the load path for plugins that has an app directory (go engines ;)) [DHH]
+* Added app/[models|controllers|helpers] to the load path for plugins that has an app directory (go engines ;)) [David Heinemeier Hansson]
* Add config.preload_frameworks to load all frameworks at startup. Default to false so Rails autoloads itself as it's used. Turn this on for Passenger and JRuby. Also turned on by config.threadsafe! [Jeremy Kemper]
-* Add a rake task to generate dispatchers : rake rails:generate_dispatchers [Pratik]
+* Add a rake task to generate dispatchers : rake rails:generate_dispatchers [Pratik Naik]
* "rails <app>" will not generate public/dispatch.cgi/fcgi/rb files by default now. Please use "--with-dispatchers" option if you need them. [Yaroslav Markin, Pratik Naik]
* Added rake rails:update:application_controller to renamed application.rb to application_controller.rb -- included in rake rails:update so upgrading to 2.3 will automatically trigger it #1439 [kastner]
-* Added Rails.backtrace_cleaner as an accessor for the Rails::BacktraceCleaner instance used by the framework to cut down on backtrace noise and config/initializers/backtrace_silencers.rb to add your own (or turn them all off) [DHH]
+* Added Rails.backtrace_cleaner as an accessor for the Rails::BacktraceCleaner instance used by the framework to cut down on backtrace noise and config/initializers/backtrace_silencers.rb to add your own (or turn them all off) [David Heinemeier Hansson]
* Switch from Test::Unit::TestCase to ActiveSupport::TestCase. [Jeremy Kemper]
-* Added config.i18n settings gatherer to config/environment, auto-loading of all locales in config/locales/*.rb,yml, and config/locales/en.yml as a sample locale [DHH]
+* Added config.i18n settings gatherer to config/environment, auto-loading of all locales in config/locales/*.rb,yml, and config/locales/en.yml as a sample locale [David Heinemeier Hansson]
-* BACKWARDS INCOMPATIBLE: Renamed application.rb to application_controller.rb and removed all the special casing that was in place to support the former. You must do this rename in your own application when you upgrade to this version [DHH]
+* BACKWARDS INCOMPATIBLE: Renamed application.rb to application_controller.rb and removed all the special casing that was in place to support the former. You must do this rename in your own application when you upgrade to this version [David Heinemeier Hansson]
*2.2.1 [RC2] (November 14th, 2008)*
@@ -110,9 +110,9 @@
* Plugins check for the gem init path (rails/init.rb) before the standard plugin init path (init.rb) [Jacek Becela]
-* Changed all generated tests to use the test/do declaration style [DHH]
+* Changed all generated tests to use the test/do declaration style [David Heinemeier Hansson]
-* Wrapped Rails.env in StringInquirer so you can do Rails.env.development? [DHH]
+* Wrapped Rails.env in StringInquirer so you can do Rails.env.development? [David Heinemeier Hansson]
* Fixed that RailsInfoController wasn't considering all requests local in development mode (Edgard Castro) [#310 state:resolved]
@@ -127,13 +127,13 @@
* Rails Edge info returns the latest git commit hash [Francesc Esplugas]
-* Added Rails.public_path to control where HTML and assets are expected to be loaded from (defaults to Rails.root + "/public") #11581 [nicksieger]
+* Added Rails.public_path to control where HTML and assets are expected to be loaded from (defaults to Rails.root + "/public") #11581 [Nick Sieger]
* rake time:zones:local finds correct base utc offset for zones in the Southern Hemisphere [Geoff Buesing]
-* Don't require rails/gem_builder during rails initialization, it's only needed for the gems:build task. [rick]
+* Don't require rails/gem_builder during rails initialization, it's only needed for the gems:build task. [Rick Olson]
-* script/performance/profiler compatibility with the ruby-prof >= 0.5.0. Closes #9176. [Catfish]
+* script/performance/profiler compatibility with the ruby-prof >= 0.5.0. Closes #9176. [Jonathan del Strother]
* Flesh out rake gems:unpack to unpack all gems, and add rake gems:build for native extensions. #11513 [ddollar]
@@ -143,11 +143,11 @@
rake gems:build # builds all unpacked gems
rake gems:build GEM=mygem # builds only the gem 'mygem'
-* Add config.active_support for future configuration options. Also, add more new Rails 3 config settings to new_rails_defaults.rb [rick]
+* Add config.active_support for future configuration options. Also, add more new Rails 3 config settings to new_rails_defaults.rb [Rick Olson]
-* Add Rails.logger, Rails.root, Rails.env and Rails.cache shortcuts for RAILS_* constants [pratik]
+* Add Rails.logger, Rails.root, Rails.env and Rails.cache shortcuts for RAILS_* constants [Pratik Naik]
-* Allow files in plugins to be reloaded like the rest of the application. [rick]
+* Allow files in plugins to be reloaded like the rest of the application. [Rick Olson]
Enables or disables plugin reloading.
@@ -162,7 +162,7 @@
Dependencies.load_once_paths << lib_path
-* Small tweak to allow plugins to specify gem dependencies. [rick]
+* Small tweak to allow plugins to specify gem dependencies. [Rick Olson]
# OLD open_id_authentication plugin init.rb
require 'yadis'
@@ -177,7 +177,7 @@
ActionController::Base.send :include, OpenIdAuthentication
end
-* Added config.gem for specifying which gems are required by the application, as well as rake tasks for installing and freezing gems. [rick]
+* Added config.gem for specifying which gems are required by the application, as well as rake tasks for installing and freezing gems. [Rick Olson]
Rails::Initializer.run do |config|
config.gem "bj"
@@ -194,23 +194,23 @@
# Unpack specified gem to vendor/gems/gem_name-x.x.x
rake gems:unpack GEM=bj
-* Removed the default .htaccess configuration as there are so many good deployment options now (kept it as an example in README) [DHH]
+* Removed the default .htaccess configuration as there are so many good deployment options now (kept it as an example in README) [David Heinemeier Hansson]
* config.time_zone accepts TZInfo::Timezone identifiers as well as Rails TimeZone identifiers [Geoff Buesing]
* Rails::Initializer#initialize_time_zone raises an error if value assigned to config.time_zone is not recognized. Rake time zone tasks only require ActiveSupport instead of entire environment [Geoff Buesing]
-* Stop adding the antiquated test/mocks/* directories and only add them to the path if they're still there for legacy reasons [DHH]
+* Stop adding the antiquated test/mocks/* directories and only add them to the path if they're still there for legacy reasons [David Heinemeier Hansson]
-* Added that gems can now be plugins if they include rails/init.rb #11444 [jbarnette]
+* Added that gems can now be plugins if they include rails/init.rb #11444 [John Barnette]
-* Added Plugin#about method to programmatically access the about.yml in a plugin #10979 [lazyatom]
+* Added Plugin#about method to programmatically access the about.yml in a plugin #10979 [James Adam]
plugin = Rails::Plugin.new(path_to_my_plugin)
plugin.about["author"] # => "James Adam"
plugin.about["url"] # => "http://interblah.net"
-* Improve documentation. [Radar, Jan De Poorter, chuyeow, xaviershay, danger, miloops, Xavier Noria, Sunny Ripert]
+* Improve documentation. [Ryan Bigg, Jan De Poorter, Cheah Chu Yeow, Xavier Shay, Jack Danger Canty, Emilio Tagua, Xavier Noria, Sunny Ripert]
* Added config.time_zone = 'UTC' in the default environment.rb [Geoff Buesing]
@@ -218,7 +218,7 @@
* Add config.time_zone for configuring the default Time.zone value. #10982 [Geoff Buesing]
-* Added support for installing plugins hosted at git repositories #11294 [danger]
+* Added support for installing plugins hosted at git repositories #11294 [Jack Danger Canty]
* Fixed that script/generate would not look for plugin generators in plugin_paths #11000 [glv]
@@ -226,7 +226,7 @@
* Added a -e/--export to script/plugin install, uses svn export. #10847 [jon@blankpad.net)]
-* Reshuffle load order so that routes and observers are initialized after plugins and app initializers. Closes #10980 [rick]
+* Reshuffle load order so that routes and observers are initialized after plugins and app initializers. Closes #10980 [Rick Olson]
* Git support for script/generate. #10690 [ssoroka]
@@ -234,7 +234,7 @@
* Resurrect WordNet synonym lookups. #10710 [tom./, matt]
-* Added config.cache_store to environment options to control the default cache store (default is FileStore if tmp/cache is present, otherwise MemoryStore is used) [DHH]
+* Added config.cache_store to environment options to control the default cache store (default is FileStore if tmp/cache is present, otherwise MemoryStore is used) [David Heinemeier Hansson]
* Added that rails:update is run when you do rails:freeze:edge to ensure you also get the latest JS and config files #10565 [jeff]
@@ -247,9 +247,9 @@
*2.0.2* (December 16th, 2007)
-* Changed the default database from mysql to sqlite3, so now running "rails myapp" will have a config/database.yml that's setup for SQLite3 (which in OS X Leopard is installed by default, so is the gem, so everything Just Works with no database configuration at all). To get a Rails application preconfigured for MySQL, just run "rails -d mysql myapp" [DHH]
+* Changed the default database from mysql to sqlite3, so now running "rails myapp" will have a config/database.yml that's setup for SQLite3 (which in OS X Leopard is installed by default, so is the gem, so everything Just Works with no database configuration at all). To get a Rails application preconfigured for MySQL, just run "rails -d mysql myapp" [David Heinemeier Hansson]
-* Turned on ActionView::Base.cache_template_loading by default in config/environments/production.rb to prevent file system stat calls for every template loading to see if it changed (this means that you have to restart the application to see template changes in production mode) [DHH]
+* Turned on ActionView::Base.cache_template_loading by default in config/environments/production.rb to prevent file system stat calls for every template loading to see if it changed (this means that you have to restart the application to see template changes in production mode) [David Heinemeier Hansson]
* Introduce `rake secret` to output a crytographically secure secret key for use with cookie sessions #10363 [revans]
@@ -273,19 +273,19 @@
* The test task stops with a warning if you have pending migrations. #10377 [Josh Knowles]
-* Add warning to documentation about using transactional fixtures when the code under test uses transactions itself. Closes #7548 [thijsv]
+* Add warning to documentation about using transactional fixtures when the code under test uses transactions itself. Closes #7548 [Thijs van der Vossen]
* Update Prototype to 1.6.0.1. [sam]
* Update script.aculo.us to 1.8.0.1. [madrobby]
-* Added db:fixtures:identity as a way of locating what ID a foxy fixture was assigned #10332 [jbarnette]
+* Added db:fixtures:identity as a way of locating what ID a foxy fixture was assigned #10332 [John Barnette]
-* Generated fixtures should not specify ids since theyre expected to be foxy fixtures #10330 [jbarnette]
+* Generated fixtures should not specify ids since theyre expected to be foxy fixtures #10330 [John Barnette]
* Update to Prototype -r8232. [sam]
-* Introduce SecretKeyGenerator for more secure session secrets than CGI::Session's pseudo-random id generator. Consider extracting to Active Support later. #10286 [Hongli Lai]
+* Introduce SecretKeyGenerator for more secure session secrets than CGI::Session's pseudo-random id generator. Consider extracting to Active Support later. #10286 [Hongli Lai (Phusion)]
* RAILS_GEM_VERSION may be set to any valid gem version specifier. #10057 [Chad Woolley, Cheah Chu Yeow]
@@ -295,11 +295,11 @@
* Only load ActionMailer::TestCase if ActionMailer is loaded. Closes #10137 [defunkt]
-* Fixed that db:reset would use migrations instead of loading db/schema.rb [DHH]
+* Fixed that db:reset would use migrations instead of loading db/schema.rb [David Heinemeier Hansson]
* Ensure the plugin loader only loads plugins once. Closes #10102 [haruki_zaemon]
-* Refactor Plugin Loader. Add plugin lib paths early, and add lots of tests. Closes #9795 [lazyatom]
+* Refactor Plugin Loader. Add plugin lib paths early, and add lots of tests. Closes #9795 [James Adam]
* Added --skip-timestamps to generators that produce models #10036 [Tim Pope]
@@ -313,7 +313,7 @@
* config/boot.rb correctly detects RAILS_GEM_VERSION. #9834 [alexch, thewoolleyman]
-* Fixed incorrect migration number if script/generate executed outside of Rails root #7080 [jeremymcanally]
+* Fixed incorrect migration number if script/generate executed outside of Rails root #7080 [Jeremy McAnally]
* Update Prototype to 1.6.0_rc1 and script.aculo.us to 1.8.0 preview 0. [sam, madrobby]
@@ -326,7 +326,7 @@
* db:create works with remote databases whereas db:create:all only creates
databases on localhost. #9753 [Trevor Wennblom]
-* Removed calls to fixtures in generated tests as fixtures :all is now present by default in test_helper.rb [DHH]
+* Removed calls to fixtures in generated tests as fixtures :all is now present by default in test_helper.rb [David Heinemeier Hansson]
* Add --prefix option to script/server when using mongrel. [dacat]
@@ -335,13 +335,13 @@ databases on localhost. #9753 [Trevor Wennblom]
* Fixed that installing plugins from SVN repositories that use trunk/ will work #8188 [evan]
-* Moved the SourceAnnotationExtractor to a separate file in case libraries try to load the rails rake tasks twice. [Rick]
+* Moved the SourceAnnotationExtractor to a separate file in case libraries try to load the rails rake tasks twice. [Rick Olson]
* Moved Dispatcher to ActionController::Dispatcher. [Jeremy Kemper]
-* Changed the default logger from Ruby's own Logger with the clean_logger extensions to ActiveSupport::BufferedLogger for performance reasons [DHH]. (You can change it back with config.logger = Logger.new("/path/to/log", level).)
+* Changed the default logger from Ruby's own Logger with the clean_logger extensions to ActiveSupport::BufferedLogger for performance reasons [David Heinemeier Hansson]. (You can change it back with config.logger = Logger.new("/path/to/log", level).)
-* Added a default 422.html page to be rendered when ActiveRecord::RecordInvalid, ActiveRecord::RecordNotSaved, or ActionController::InvalidAuthenticityToken is raised [DHH]
+* Added a default 422.html page to be rendered when ActiveRecord::RecordInvalid, ActiveRecord::RecordNotSaved, or ActionController::InvalidAuthenticityToken is raised [David Heinemeier Hansson]
* Added --skip-fixture option to script/generate model #6862 [sandofsky]
@@ -349,15 +349,15 @@ databases on localhost. #9753 [Trevor Wennblom]
* Fixed the placement of fixture files for nested models when generating through script/generate model #7547 [jkit]
-* Added TEMPLATE option to rake doc:app to set a custom output template #7737 [Jakob S]
+* Added TEMPLATE option to rake doc:app to set a custom output template #7737 [Jakob Skjerning]
-* Added VERBOSE option to rake db:migrate to turn off output #8204 [jbarnette]
+* Added VERBOSE option to rake db:migrate to turn off output #8204 [John Barnette]
* Fixed that rake doc:app should use UTF-8 #8906 [farzy]
* Fixes rake annotations to search erb and builder files as well #9150 [m.langenberg]
-* Removed web_service generator [Koz]
+* Removed web_service generator [Michael Koziarski]
* Added the :all option to config.plugins that'll include the rest of the plugins not already explicitly named #9613 [Frederick Cheung]. Example:
@@ -366,11 +366,11 @@ databases on localhost. #9753 [Trevor Wennblom]
* Added symbols as a legal way of specifying plugins in config.plugins #9629 [tom]
-* Removed deprecated task names, like clear_logs, in favor of the new namespaced style [DHH]
+* Removed deprecated task names, like clear_logs, in favor of the new namespaced style [David Heinemeier Hansson]
-* Support multiple config.after_initialize blocks so plugins and apps can more easily cooperate. #9582 [zdennis]
+* Support multiple config.after_initialize blocks so plugins and apps can more easily cooperate. #9582 [Zach Dennis]
-* Added db:drop:all to drop all databases declared in config/database.yml [DHH]
+* Added db:drop:all to drop all databases declared in config/database.yml [David Heinemeier Hansson]
* Use attribute pairs instead of the migration name to create add and remove column migrations. Closes #9166 [Pratik Naik]
@@ -382,11 +382,11 @@ databases on localhost. #9753 [Trevor Wennblom]
ruby script/generation migration RemoveSomeStuffFromCustomers first_name:string last_name:string
-* Add ActiveResource to Rails::Info. Closes #8741 [kampers]
+* Add ActiveResource to Rails::Info. Closes #8741 [Chris Kampmeier]
* use Gem.find_name instead of search when freezing gems. Prevent false positives for other gems with rails in the name. Closes #8729 [wselman]
-* Automatically generate add/remove column commands in specially named migrations like AddLocationToEvent. Closes #9006 [zenspider]
+* Automatically generate add/remove column commands in specially named migrations like AddLocationToEvent. Closes #9006 [Ryan Davis]
* Default to plural table name in Rails Generator if ActiveRecord is not present. Closes #8963 [evan]
@@ -404,7 +404,7 @@ databases on localhost. #9753 [Trevor Wennblom]
* Fix that FCGIs would leave log files open when asked to shut down by USR2. #3028 [Sebastian Kanthak, Josh Peek]
-* Fixed that dispatcher preparation callbacks only run once in production mode. Mock Routes.reload so that dispatcher preparation callback tests run. [Rick]
+* Fixed that dispatcher preparation callbacks only run once in production mode. Mock Routes.reload so that dispatcher preparation callback tests run. [Rick Olson]
* Fix syntax error in dispatcher than wrecked failsafe responses. #8625 [mtitorenko]
@@ -432,11 +432,11 @@ databases on localhost. #9753 [Trevor Wennblom]
* Generators use *.html.erb view template naming. #8278 [Tim Pope]
-* Updated resource_scaffold and model generators to use short-hand style migrations [DHH]
+* Updated resource_scaffold and model generators to use short-hand style migrations [David Heinemeier Hansson]
* Updated initializer to only load #{RAILS_ENV}.rb once. Added deprecation warning for config.breakpoint_server. [Nicholas Seckar]
-* Removed breakpointer and Binding.of_caller in favor of relying on ruby-debug by Kent Sibilev since the breakpointer has been broken since Ruby 1.8.4 and will not be coming back [DHH]
+* Removed breakpointer and Binding.of_caller in favor of relying on ruby-debug by Kent Sibilev since the breakpointer has been broken since Ruby 1.8.4 and will not be coming back [David Heinemeier Hansson]
To use the new debugger, start your server with script/server --debugger and insert a call to 'debugger'
(instead of 'breakpoint') where you want to jump into the debugger.
@@ -454,13 +454,13 @@ databases on localhost. #9753 [Trevor Wennblom]
* Include Active Resource in rails:freeze:edge rake task. [Thomas Fuchs]
-* Include Active Resource instead of Action Web Service [DHH] You can add AWS back with this in config/environment.rb:
+* Include Active Resource instead of Action Web Service [David Heinemeier Hansson] You can add AWS back with this in config/environment.rb:
config.load_paths += %W( #{RAILS_ROOT}/vendor/rails/actionwebservice/lib )
...or just gem 'actionwebservice'
-* Give generate scaffold a more descriptive database message. Closes #7316 [jeremymcanally]
+* Give generate scaffold a more descriptive database message. Closes #7316 [Jeremy McAnally]
* Canonicalize RAILS_ROOT by using File.expand_path on Windows, which doesn't have to worry about symlinks, and Pathname#realpath elsewhere, which respects symlinks in relative paths but is incompatible with Windows. #6755 [Jeremy Kemper, trevor]
@@ -474,19 +474,19 @@ databases on localhost. #9753 [Trevor Wennblom]
* Split plugin location and loading out of the initializer and into a new Plugin namespace, which includes Plugin::Locater and Plugin::Loader. The loader class that is used can be customized using the config.plugin_loader option. Those monkey patching the plugin loading subsystem take note, the internals changing here will likely break your modifications. The good news is that it should be substantially easier to hook into the plugin locating and loading process now. [Marcel Molina Jr.]
-* Added assumption that all plugin creators desire to be sharing individuals and release their work under the MIT license [DHH]
+* Added assumption that all plugin creators desire to be sharing individuals and release their work under the MIT license [David Heinemeier Hansson]
* Added source-annotations extractor tasks to rake [Jamis Buck]. This allows you to add FIXME, OPTIMIZE, and TODO comments to your source code that can then be extracted in concert with rake notes (shows all), rake notes:fixme, rake notes:optimize and rake notes:todo.
-* Added fixtures :all to test_helper.rb to assume that most people just want all their fixtures loaded all the time [DHH]
+* Added fixtures :all to test_helper.rb to assume that most people just want all their fixtures loaded all the time [David Heinemeier Hansson]
-* Added config/initializers where all ruby files within it are automatically loaded after the Rails configuration is done, so you don't have to litter the environment.rb file with a ton of mixed stuff [DHH]
+* Added config/initializers where all ruby files within it are automatically loaded after the Rails configuration is done, so you don't have to litter the environment.rb file with a ton of mixed stuff [David Heinemeier Hansson]
* For new apps, generate a random secret for the cookie-based session store. [Jeremy Kemper]
-* Stop swallowing errors during rake test [Koz]
+* Stop swallowing errors during rake test [Michael Koziarski]
-* Update Rails Initializer to use ActionController::Base#view_paths [Rick]
+* Update Rails Initializer to use ActionController::Base#view_paths [Rick Olson]
* Fix gem deprecation warnings, which also means depending on RubyGems 0.9.0+ [Chad Fowler]
@@ -504,12 +504,12 @@ databases on localhost. #9753 [Trevor Wennblom]
* Fixed that webrick would strip leading newlines and hang connection #4156 [psross]
-* Ensure plugins are in the Dependencies.load_once_paths collection by default. [Rick]
+* Ensure plugins are in the Dependencies.load_once_paths collection by default. [Rick Olson]
If you really want your plugins to reload, add this to the very top of init.rb:
Dependencies.load_once_paths.delete(lib_path)
-* Allow config.to_prepare to work, make the dispatcher safe to 're require'. [Koz, Nicholas Seckar]
+* Allow config.to_prepare to work, make the dispatcher safe to 're require'. [Michael Koziarski, Nicholas Seckar]
* Fix scaffold_resource generator so it respects the --pretend argument when creating the routes file. Closes #6852 [fearoffish]
@@ -519,25 +519,25 @@ databases on localhost. #9753 [Trevor Wennblom]
* Don't generate a components directory in new Rails apps. [Jeremy Kemper]
-* Fixed script/process/spawner to work properly with Mongrel including in -r (daemonize mode) [DHH]
+* Fixed script/process/spawner to work properly with Mongrel including in -r (daemonize mode) [David Heinemeier Hansson]
-* Added one-letter aliases for the three default environments to script/console, so script/console p will load the production environment (t for test, d for development) [DHH]
+* Added one-letter aliases for the three default environments to script/console, so script/console p will load the production environment (t for test, d for development) [David Heinemeier Hansson]
-* Fixed that script/server running against Mongrel should tail the proper log regardless of the environment [DHH]
+* Fixed that script/server running against Mongrel should tail the proper log regardless of the environment [David Heinemeier Hansson]
* Update initializer to load Rails::VERSION as soon as possible. Closes #6698. [Nicholas Seckar]
-* Added ActiveRecord::Base.clear_active_connections! in development mode so the database connection is not carried over from request to request. Some databases won't reread the schema if that doesn't happen (I'm looking at you SQLite), so you have to restart the server after each migration (= no fun) [DHH]
+* Added ActiveRecord::Base.clear_active_connections! in development mode so the database connection is not carried over from request to request. Some databases won't reread the schema if that doesn't happen (I'm looking at you SQLite), so you have to restart the server after each migration (= no fun) [David Heinemeier Hansson]
-* Made RAILS_GEM_VERSION work for beta gems too, so specifying 1.1.6 will give you 1.1.6.4520 if available [DHH]
+* Made RAILS_GEM_VERSION work for beta gems too, so specifying 1.1.6 will give you 1.1.6.4520 if available [David Heinemeier Hansson]
* Update to Prototype and script.aculo.us [5579]. [Thomas Fuchs]
-* Made script/server work with -e and -d when using Mongrel [DHH]
+* Made script/server work with -e and -d when using Mongrel [David Heinemeier Hansson]
* Update to Prototype 1.5.0_rc2 [5550] which makes it work in Opera again [Thomas Fuchs]
-* Make sure that exceptions which are thrown outside of the user code try their best to be handeled in ApplicationController#rescue_action [Tobias Luetke]
+* Make sure that exceptions which are thrown outside of the user code try their best to be handeled in ApplicationController#rescue_action [Tobias Lütke]
* Rails::VERSION::STRING should always be available without having to require 'rails/version'. #6244 [fearoffish]
@@ -561,31 +561,31 @@ databases on localhost. #9753 [Trevor Wennblom]
* resource and scaffold_resource generators add a restful route to config/routes.rb [Jeremy Kemper]
-* Revert environment changes for autoload_paths. [Koz]
+* Revert environment changes for autoload_paths. [Michael Koziarski]
* Update to latest Prototype, which doesn't serialize disabled form elements, adds clone() to arrays, empty/non-string Element.update() and adds a fixes excessive error reporting in WebKit beta versions [Thomas Fuchs]
-* Clean up the output of rake stats, de-emphasise components and apis, and remove the indents for tests [Koz]
+* Clean up the output of rake stats, de-emphasise components and apis, and remove the indents for tests [Michael Koziarski]
-* Added option to script/process/spawner of specifying the binding address #5133 [zsombor]
+* Added option to script/process/spawner of specifying the binding address #5133 [Dee Zsombor]
* Update environment.rb comments to include config.autoload_paths. Closes #6478 [caio]
-* Update scaffold to use new form_tag block functionality. Closes #6480. [BobSilva]
+* Update scaffold to use new form_tag block functionality. Closes #6480. [Bob Silva]
* Plugin generator: check for class collisions. #4833 [vinbarnes@gmail.com]
* Mailer generator: handle mailers in modules, set mime_version in unit test. [Jeremy Kemper]
-* Set $KCODE to 'u' by default to enable the multibyte safe String#chars proxy. [Koz]
+* Set $KCODE to 'u' by default to enable the multibyte safe String#chars proxy. [Michael Koziarski]
-* Added config.plugins to control which plugins are loaded #6269 [skaes]. By default, everything in vendor/plugins will be loaded, but if you specify config.plugins, only those will be loaded. Example:
+* Added config.plugins to control which plugins are loaded #6269 [Stefan Kaes]. By default, everything in vendor/plugins will be loaded, but if you specify config.plugins, only those will be loaded. Example:
config.plugins = %w[ routing_navigator simply_helpful ]
* Clean up html on included error pages. [Tim Lucas]
-* Fixed default 404.html and 500.htmls to remove extreme ugliness and include human language [DHH]
+* Fixed default 404.html and 500.htmls to remove extreme ugliness and include human language [David Heinemeier Hansson]
* Update to latest Prototype and script.aculo.us trunk versions [Thomas Fuchs]
@@ -593,17 +593,17 @@ databases on localhost. #9753 [Trevor Wennblom]
* Fixed test:uncommitted on Windows (backslash issue) #4999 [paul@paulbutcher.com]
-* Fixed migration creation to work with namespaced models, so script/generate model Gallery::Image will use create_table :gallery_images #6327 [BobSilva]
+* Fixed migration creation to work with namespaced models, so script/generate model Gallery::Image will use create_table :gallery_images #6327 [Bob Silva]
* Fixed rename_table on SQLite tables with indexes defined #5942 [brandon@opensoul.org]
-* Added default timeout setting of 5 seconds to SQLite3 database.yml configurations [DHH]
+* Added default timeout setting of 5 seconds to SQLite3 database.yml configurations [David Heinemeier Hansson]
-* Added generated attribute options to script/generate model, like the one found in scaffold_resource and resource [DHH]. Examples:
+* Added generated attribute options to script/generate model, like the one found in scaffold_resource and resource [David Heinemeier Hansson]. Examples:
./script/generate model post title:string created_on:date body:text published:boolean
-* Added script/generate resource which works just like scaffold_resource, but creates empty placeholders instead of predefined [DHH]
+* Added script/generate resource which works just like scaffold_resource, but creates empty placeholders instead of predefined [David Heinemeier Hansson]
* script/runner can run files, pass on arguments, and be used as a shebang. #6286 [Tuxie, dlpond]
#!/usr/bin/env /path/to/my/app/script/runner
@@ -612,7 +612,7 @@ databases on localhost. #9753 [Trevor Wennblom]
* Look for rake tasks in plugin subdirs. #6259 [obrie]
-* Added map.connect ':controller/:action/:id.:format' as a default route to config/routes.rb [DHH]
+* Added map.connect ':controller/:action/:id.:format' as a default route to config/routes.rb [David Heinemeier Hansson]
* Updated prototype.js to 1.5.0_rc1 with latest fixes. [Rick Olson]
@@ -624,7 +624,7 @@ databases on localhost. #9753 [Trevor Wennblom]
* script/server creates the tmp/pids directory. #6204 [jonathan]
-* Fix script/console --sandbox for internal transactions changes. #5738 [chris@octopod.info, charles.gerungan@gmail.com]
+* Fix script/console --sandbox for internal transactions changes. #5738 [Chris McGrath, charles.gerungan@gmail.com]
* Remove the uncanny default of adding all app/models/*/ directories to the load path. This change will break application which expect the current behavior. As
documented in initializer.rb, the workaround is:
@@ -637,7 +637,7 @@ References #6031. [Nicholas Seckar]
* Update to Prototype 1.5.0_rc1 [sam]
-* Formally Deprecate the old rake tasks. [Koz]
+* Formally Deprecate the old rake tasks. [Michael Koziarski]
* Thoroughly test the FCGI dispatcher. #5970 [Kevin Clark]
@@ -670,7 +670,7 @@ References #6031. [Nicholas Seckar]
* Fix Dispatcher.reset_application! so that AR subclasses are removed and Observers re-initialized *after* Reloadable classes are removed. Closes #5743. [Rick Olson]
-* Clarify usage of script/plugin source. Closes #5344. [james.adam@gmail.com]
+* Clarify usage of script/plugin source. Closes #5344. [James Adam]
* Add Dispatcher.to_prepare and config.to_prepare to provide a pre-request hook. [Nicholas Seckar]
@@ -678,7 +678,7 @@ References #6031. [Nicholas Seckar]
* Added that you can change the web server port in config/lighttpd.conf from script/server --port/-p #5465 [mats@imediatec.co.uk]
-* script/performance/profiler compatibility with the new ruby-prof, including an option to choose the results printer. #5679 [shugo@ruby-lang.org]
+* script/performance/profiler compatibility with the new ruby-prof, including an option to choose the results printer. #5679 [Shugo Maeda]
* Fixed the failsafe response so it uses either the current recognized controller or ApplicationController. [Rick Olson]
@@ -692,7 +692,7 @@ References #6031. [Nicholas Seckar]
* Ensure the logger is initialized. #5629 [mike@clarkware.com]
-* Added Mongrel-spawning capabilities to script/process/spawner. Mongrel will be the default choice if installed, otherwise FCGI is tried [DHH]. Examples:
+* Added Mongrel-spawning capabilities to script/process/spawner. Mongrel will be the default choice if installed, otherwise FCGI is tried [David Heinemeier Hansson]. Examples:
spawner # starts instances on 8000, 8001, and 8002 using Mongrel if available
spawner fcgi # starts instances on 8000, 8001, and 8002 using FCGI
@@ -735,15 +735,15 @@ References #6031. [Nicholas Seckar]
* Mongrel: script/server works on Win32. #5499 [jeremydurham@gmail.com]
-* Remove opts.on { |options[:option_name] } style hash assignment. Closes #4440. [nicksieger@gmail.com]
+* Remove opts.on { |options[:option_name] } style hash assignment. Closes #4440. [Nick Sieger]
* Mongrel support for script/server. #5475 [jeremydurham@gmail.com]
-* Fix script/plugin so it doesn't barf on invalid URLs [Rick]
+* Fix script/plugin so it doesn't barf on invalid URLs [Rick Olson]
* Fix plugin install bug at dir with space. (closes #5359) [Yoshimasa NIWA]
-* Fix bug with 'script/plugin install' so it reports unknown plugin names correctly. [Rick]
+* Fix bug with 'script/plugin install' so it reports unknown plugin names correctly. [Rick Olson]
* Added uninstall.rb hook to plugin handling, such that plugins have a way of removing assets and other artifacts on removal #5003 [takiuchi@drecom.co.jp]
@@ -753,11 +753,11 @@ References #6031. [Nicholas Seckar]
* Make "script/plugin install" work with svn+ssh URLs. [Sam Stephenson]
-* Added lib/ to the directories that will get application docs generated [DHH]
+* Added lib/ to the directories that will get application docs generated [David Heinemeier Hansson]
-* Add observer generator. Closes #5167. [francois.beausoleil@gmail.com]
+* Add observer generator. Closes #5167. [François Beausoleil]
-* Session migration generator obeys pluralize_table_names. #5145 [james.adam@gmail.com]
+* Session migration generator obeys pluralize_table_names. #5145 [James Adam]
* rake test:recent understands subdirectories. #2925 [jerrett@bravenet.com]
@@ -765,17 +765,17 @@ References #6031. [Nicholas Seckar]
* The app generator sets a session key in application.rb so apps running on the same host may distinguish their cookies. #2967 [rcoder, rails-bug@owl.me.uk]
-* Distinguish the spawners for different processes [DHH]
+* Distinguish the spawners for different processes [David Heinemeier Hansson]
-* Added -n/--process to script/process/spawner name the process pid (default is dispatch) [DHH]
+* Added -n/--process to script/process/spawner name the process pid (default is dispatch) [David Heinemeier Hansson]
* Namespaced OrderedHash so the Rails implementation does not clash with any others. (fixes #4911) [Julian Tarkhanov]
* Replace Ruby's deprecated append_features in favor of included. [Marcel Molina Jr.]
-* Added script/process/inspector to do simple process status information on Rails dispatchers keeping pid files in tmp/pids [DHH]
+* Added script/process/inspector to do simple process status information on Rails dispatchers keeping pid files in tmp/pids [David Heinemeier Hansson]
-* Added pid file usage to script/process/spawner and script/process/reaper along with a directive in default config/lighttpd.conf file to record the pid. They will all save their pid file in tmp/pids [DHH]
+* Added pid file usage to script/process/spawner and script/process/reaper along with a directive in default config/lighttpd.conf file to record the pid. They will all save their pid file in tmp/pids [David Heinemeier Hansson]
*1.2.3* (March 12th, 2007)
@@ -784,14 +784,14 @@ References #6031. [Nicholas Seckar]
* Windows: include MinGW in RUBY_PLATFORM check. #2982 [okkez000@gmail.com, Kaspar Schiess]
-* Stop swallowing errors during rake test [Koz]
+* Stop swallowing errors during rake test [Michael Koziarski]
*1.2.2* (February 5th, 2007)
* Fix gem deprecation warnings, which also means depending on RubyGems 0.9.0+ [Chad Fowler]
-* Require the dispatcher for Rails::Configuration#to_prepare. [Rick]
+* Require the dispatcher for Rails::Configuration#to_prepare. [Rick Olson]
*1.2.1* (January 16th, 2007)
@@ -807,7 +807,7 @@ References #6031. [Nicholas Seckar]
* Fixed that webrick would strip leading newlines and hang connection #4156 [psross]
-* Ensure plugins are in the Dependencies.load_once_paths collection by default. [Rick]
+* Ensure plugins are in the Dependencies.load_once_paths collection by default. [Rick Olson]
If you really want your plugins to reload, add this to the very top of init.rb:
Dependencies.load_once_paths.delete(lib_path)
@@ -820,23 +820,23 @@ References #6031. [Nicholas Seckar]
* Don't generate a components directory in new Rails apps. [Jeremy Kemper]
-* Fixed script/process/spawner to work properly with Mongrel including in -r (daemonize mode) [DHH]
+* Fixed script/process/spawner to work properly with Mongrel including in -r (daemonize mode) [David Heinemeier Hansson]
-* Deprecated the name route "root" as it'll be used as a shortcut for map.connect '' in Rails 2.0 [DHH]
+* Deprecated the name route "root" as it'll be used as a shortcut for map.connect '' in Rails 2.0 [David Heinemeier Hansson]
-* Fixed that script/server running against Mongrel should tail the proper log regardless of the environment [DHH]
+* Fixed that script/server running against Mongrel should tail the proper log regardless of the environment [David Heinemeier Hansson]
* Update initializer to load Rails::VERSION as soon as possible. Closes #6698. [Nicholas Seckar]
-* Added ActiveRecord::Base.clear_active_connections! in development mode so the database connection is not carried over from request to request. Some databases won't reread the schema if that doesn't happen (I'm looking at you SQLite), so you have to restart the server after each migration (= no fun) [DHH]
+* Added ActiveRecord::Base.clear_active_connections! in development mode so the database connection is not carried over from request to request. Some databases won't reread the schema if that doesn't happen (I'm looking at you SQLite), so you have to restart the server after each migration (= no fun) [David Heinemeier Hansson]
-* Made RAILS_GEM_VERSION work for beta gems too, so specifying 1.1.6 will give you 1.1.6.4520 if available [DHH]
+* Made RAILS_GEM_VERSION work for beta gems too, so specifying 1.1.6 will give you 1.1.6.4520 if available [David Heinemeier Hansson]
* Update to Prototype and script.aculo.us [5579]. [Sam Stephenson, Thomas Fuchs]
-* Made script/server work with -e and -d when using Mongrel [DHH]
+* Made script/server work with -e and -d when using Mongrel [David Heinemeier Hansson]
-* Make sure that exceptions which are thrown outside of the user code try their best to be handeled in ApplicationController#rescue_action [Tobias Luetke]
+* Make sure that exceptions which are thrown outside of the user code try their best to be handeled in ApplicationController#rescue_action [Tobias Lütke]
* Rails::VERSION::STRING should always be available without having to require 'rails/version'. #6244 [fearoffish]
@@ -856,29 +856,29 @@ References #6031. [Nicholas Seckar]
* resource and scaffold_resource generators add a restful route to config/routes.rb [Jeremy Kemper]
-* Revert environment changes for autoload_paths. [Koz]
+* Revert environment changes for autoload_paths. [Michael Koziarski]
-* Clean up the output of rake stats, de-emphasise components and apis, and remove the indents for tests [Koz]
+* Clean up the output of rake stats, de-emphasise components and apis, and remove the indents for tests [Michael Koziarski]
-* Added option to script/process/spawner of specifying the binding address #5133 [zsombor]
+* Added option to script/process/spawner of specifying the binding address #5133 [Dee Zsombor]
* Update environment.rb comments to include config.autoload_paths. Closes #6478 [caio]
-* Update scaffold to use new form_tag block functionality. Closes #6480. [BobSilva]
+* Update scaffold to use new form_tag block functionality. Closes #6480. [Bob Silva]
* Plugin generator: check for class collisions. #4833 [vinbarnes@gmail.com]
* Mailer generator: handle mailers in modules, set mime_version in unit test. [Jeremy Kemper]
-* Set $KCODE to 'u' by default to enable the multibyte safe String#chars proxy. [Koz]
+* Set $KCODE to 'u' by default to enable the multibyte safe String#chars proxy. [Michael Koziarski]
-* Added config.plugins to control which plugins are loaded #6269 [skaes]. By default, everything in vendor/plugins will be loaded, but if you specify config.plugins, only those will be loaded. Example:
+* Added config.plugins to control which plugins are loaded #6269 [Stefan Kaes]. By default, everything in vendor/plugins will be loaded, but if you specify config.plugins, only those will be loaded. Example:
config.plugins = %w[ routing_navigator simply_helpful ]
* Clean up html on included error pages. [Tim Lucas]
-* Fixed default 404.html and 500.htmls to remove extreme ugliness and include human language [DHH]
+* Fixed default 404.html and 500.htmls to remove extreme ugliness and include human language [David Heinemeier Hansson]
* Update to latest Prototype and script.aculo.us trunk versions [Thomas Fuchs]
@@ -886,17 +886,17 @@ References #6031. [Nicholas Seckar]
* Fixed test:uncommitted on Windows (backslash issue) #4999 [paul@paulbutcher.com]
-* Fixed migration creation to work with namespaced models, so script/generate model Gallery::Image will use create_table :gallery_images #6327 [BobSilva]
+* Fixed migration creation to work with namespaced models, so script/generate model Gallery::Image will use create_table :gallery_images #6327 [Bob Silva]
* Fixed rename_table on SQLite tables with indexes defined #5942 [brandon@opensoul.org]
-* Added default timeout setting of 5 seconds to SQLite3 database.yml configurations [DHH]
+* Added default timeout setting of 5 seconds to SQLite3 database.yml configurations [David Heinemeier Hansson]
-* Added generated attribute options to script/generate model, like the one found in scaffold_resource and resource [DHH]. Examples:
+* Added generated attribute options to script/generate model, like the one found in scaffold_resource and resource [David Heinemeier Hansson]. Examples:
./script/generate model post title:string created_on:date body:text published:boolean
-* Added script/generate resource which works just like scaffold_resource, but creates empty placeholders instead of predefined [DHH]
+* Added script/generate resource which works just like scaffold_resource, but creates empty placeholders instead of predefined [David Heinemeier Hansson]
* script/runner can run files, pass on arguments, and be used as a shebang. #6286 [Tuxie, dlpond]
#!/usr/bin/env /path/to/my/app/script/runner
@@ -905,13 +905,13 @@ References #6031. [Nicholas Seckar]
* Look for rake tasks in plugin subdirs. #6259 [obrie]
-* Added map.connect ':controller/:action/:id.:format' as a default route to config/routes.rb [DHH]
+* Added map.connect ':controller/:action/:id.:format' as a default route to config/routes.rb [David Heinemeier Hansson]
* session_migration generator adds an index on updated_at. #6207 [grg]
* script/server creates the tmp/pids directory. #6204 [jonathan]
-* Fix script/console --sandbox for internal transactions changes. #5738 [chris@octopod.info, charles.gerungan@gmail.com]
+* Fix script/console --sandbox for internal transactions changes. #5738 [Chris McGrath, charles.gerungan@gmail.com]
* Remove the uncanny default of adding all app/models/*/ directories to the load path. This change will break application which expect the current behavior. As
documented in initializer.rb, the workaround is:
@@ -922,7 +922,7 @@ References #6031. [Nicholas Seckar]
* Update to script.aculo.us 1.6.3 [Thomas Fuchs]
-* Formally Deprecate the old rake tasks. [Koz]
+* Formally Deprecate the old rake tasks. [Michael Koziarski]
* Thoroughly test the FCGI dispatcher. #5970 [Kevin Clark]
@@ -953,7 +953,7 @@ References #6031. [Nicholas Seckar]
* Fix Dispatcher.reset_application! so that AR subclasses are removed and Observers re-initialized *after* Reloadable classes are removed. Closes #5743. [Rick Olson]
-* Clarify usage of script/plugin source. Closes #5344. [james.adam@gmail.com]
+* Clarify usage of script/plugin source. Closes #5344. [James Adam]
* Add Dispatcher.to_prepare and config.to_prepare to provide a pre-request hook. [Nicholas Seckar]
@@ -961,7 +961,7 @@ References #6031. [Nicholas Seckar]
* Added that you can change the web server port in config/lighttpd.conf from script/server --port/-p #5465 [mats@imediatec.co.uk]
-* script/performance/profiler compatibility with the new ruby-prof, including an option to choose the results printer. #5679 [shugo@ruby-lang.org]
+* script/performance/profiler compatibility with the new ruby-prof, including an option to choose the results printer. #5679 [Shugo Maeda]
* Fixed the failsafe response so it uses either the current recognized controller or ApplicationController. [Rick Olson]
@@ -975,7 +975,7 @@ References #6031. [Nicholas Seckar]
* Ensure the logger is initialized. #5629 [mike@clarkware.com]
-* Added Mongrel-spawning capabilities to script/process/spawner. Mongrel will be the default choice if installed, otherwise FCGI is tried [DHH]. Examples:
+* Added Mongrel-spawning capabilities to script/process/spawner. Mongrel will be the default choice if installed, otherwise FCGI is tried [David Heinemeier Hansson]. Examples:
spawner # starts instances on 8000, 8001, and 8002 using Mongrel if available
spawner fcgi # starts instances on 8000, 8001, and 8002 using FCGI
@@ -1018,15 +1018,15 @@ References #6031. [Nicholas Seckar]
* Mongrel: script/server works on Win32. #5499 [jeremydurham@gmail.com]
-* Remove opts.on { |options[:option_name] } style hash assignment. Closes #4440. [nicksieger@gmail.com]
+* Remove opts.on { |options[:option_name] } style hash assignment. Closes #4440. [Nick Sieger]
* Mongrel support for script/server. #5475 [jeremydurham@gmail.com]
-* Fix script/plugin so it doesn't barf on invalid URLs [Rick]
+* Fix script/plugin so it doesn't barf on invalid URLs [Rick Olson]
* Fix plugin install bug at dir with space. (closes #5359) [Yoshimasa NIWA]
-* Fix bug with 'script/plugin install' so it reports unknown plugin names correctly. [Rick]
+* Fix bug with 'script/plugin install' so it reports unknown plugin names correctly. [Rick Olson]
* Added uninstall.rb hook to plugin handling, such that plugins have a way of removing assets and other artifacts on removal #5003 [takiuchi@drecom.co.jp]
@@ -1036,11 +1036,11 @@ References #6031. [Nicholas Seckar]
* Make "script/plugin install" work with svn+ssh URLs. [Sam Stephenson]
-* Added lib/ to the directories that will get application docs generated [DHH]
+* Added lib/ to the directories that will get application docs generated [David Heinemeier Hansson]
-* Add observer generator. Closes #5167. [francois.beausoleil@gmail.com]
+* Add observer generator. Closes #5167. [François Beausoleil]
-* Session migration generator obeys pluralize_table_names. #5145 [james.adam@gmail.com]
+* Session migration generator obeys pluralize_table_names. #5145 [James Adam]
* rake test:recent understands subdirectories. #2925 [jerrett@bravenet.com]
@@ -1048,17 +1048,17 @@ References #6031. [Nicholas Seckar]
* The app generator sets a session key in application.rb so apps running on the same host may distinguish their cookies. #2967 [rcoder, rails-bug@owl.me.uk]
-* Distinguish the spawners for different processes [DHH]
+* Distinguish the spawners for different processes [David Heinemeier Hansson]
-* Added -n/--process to script/process/spawner name the process pid (default is dispatch) [DHH]
+* Added -n/--process to script/process/spawner name the process pid (default is dispatch) [David Heinemeier Hansson]
* Namespaced OrderedHash so the Rails implementation does not clash with any others. (fixes #4911) [Julian Tarkhanov]
* Replace Ruby's deprecated append_features in favor of included. [Marcel Molina Jr.]
-* Added script/process/inspector to do simple process status information on Rails dispatchers keeping pid files in tmp/pids [DHH]
+* Added script/process/inspector to do simple process status information on Rails dispatchers keeping pid files in tmp/pids [David Heinemeier Hansson]
-* Added pid file usage to script/process/spawner and script/process/reaper along with a directive in default config/lighttpd.conf file to record the pid. They will all save their pid file in tmp/pids [DHH]
+* Added pid file usage to script/process/spawner and script/process/reaper along with a directive in default config/lighttpd.conf file to record the pid. They will all save their pid file in tmp/pids [David Heinemeier Hansson]
*1.1.6* (August 10th, 2006)
@@ -1093,9 +1093,9 @@ References #6031. [Nicholas Seckar]
* Change the scaffolding layout to use yield rather than @content_for_layout. [Marcel Molina Jr.]
-* Added rake rails:update:configs to update config/boot.rb from the latest (also included in rake rails:update) [DHH]
+* Added rake rails:update:configs to update config/boot.rb from the latest (also included in rake rails:update) [David Heinemeier Hansson]
-* Fixed that boot.rb would set RAILS_GEM_VERSION twice, not respect an uncommented RAILS_GEM_VERSION line, and not use require_gem [DHH]
+* Fixed that boot.rb would set RAILS_GEM_VERSION twice, not respect an uncommented RAILS_GEM_VERSION line, and not use require_gem [David Heinemeier Hansson]
*1.1.1* (April 6th, 2006)
@@ -1106,7 +1106,7 @@ References #6031. [Nicholas Seckar]
* Fixed that the -r/--ruby path option of the rails command was not being respected #4549 [ryan.raaum@gmail.com]
-* Added that Dispatcher exceptions should not be shown to the user unless a default log has not been configured. Instead show public/500.html [DHH]
+* Added that Dispatcher exceptions should not be shown to the user unless a default log has not been configured. Instead show public/500.html [David Heinemeier Hansson]
* Fixed that rake clone_structure_to_test should quit on pgsql if the dump is unsuccesful #4585 [augustz@augustz.com]
@@ -1114,9 +1114,9 @@ References #6031. [Nicholas Seckar]
* Install alias so Rails::InfoController is accessible at /rails_info. Closes #4546. [Nicholas Seckar]
-* Fixed that spawner should daemonize if running in repeat mode [DHH]
+* Fixed that spawner should daemonize if running in repeat mode [David Heinemeier Hansson]
-* Added TAG option for rake rails:freeze:edge, so you can say rake rails:freeze:edge TAG=rel_1-1-0 to lock to the 1.1.0 release [DHH]
+* Added TAG option for rake rails:freeze:edge, so you can say rake rails:freeze:edge TAG=rel_1-1-0 to lock to the 1.1.0 release [David Heinemeier Hansson]
* Applied Prototype $() performance patches (#4465, #4477) and updated script.aculo.us [Sam Stephenson, Thomas Fuchs]
@@ -1126,13 +1126,13 @@ References #6031. [Nicholas Seckar]
* Fixed rake rails:freeze:gems #4518 [benji@silverinsanity.com]
-* Added -f/--freeze option to rails command for freezing the application to the Rails version it was generated with [DHH]
+* Added -f/--freeze option to rails command for freezing the application to the Rails version it was generated with [David Heinemeier Hansson]
* Added gem binding of apps generated through the rails command to the gems of they were generated with [Nicholas Seckar]
-* Added expiration settings for JavaScript, CSS, HTML, and images to default lighttpd.conf [DHH]
+* Added expiration settings for JavaScript, CSS, HTML, and images to default lighttpd.conf [David Heinemeier Hansson]
-* Added gzip compression for JavaScript, CSS, and HTML to default lighttpd.conf [DHH]
+* Added gzip compression for JavaScript, CSS, and HTML to default lighttpd.conf [David Heinemeier Hansson]
* Avoid passing escapeHTML non-string in Rails' info controller [Nicholas Seckar]
@@ -1191,19 +1191,19 @@ References #6031. [Nicholas Seckar]
* Added tracking of database and framework versions in script/about #4088 [charles.gerungan@gmail.com/Rick Olson]
-* Added public/javascripts/application.js as a sample since it'll automatically be included in javascript_include_tag :defaults [DHH]
+* Added public/javascripts/application.js as a sample since it'll automatically be included in javascript_include_tag :defaults [David Heinemeier Hansson]
-* Added socket cleanup for lighttpd, both before and after [DHH]
+* Added socket cleanup for lighttpd, both before and after [David Heinemeier Hansson]
-* Added automatic creation of tmp/ when running script/server [DHH]
+* Added automatic creation of tmp/ when running script/server [David Heinemeier Hansson]
-* Added silence_stream that'll work on both STDERR or STDOUT or any other stream and deprecated silence_stderr in the process [DHH]
+* Added silence_stream that'll work on both STDERR or STDOUT or any other stream and deprecated silence_stderr in the process [David Heinemeier Hansson]
* Added reload! method to script/console to reload all models and others that include Reloadable without quitting the console #4056 [esad@esse.at]
-* Added that rake rails:freeze:edge will now just export all the contents of the frameworks instead of just lib, so stuff like rails:update:scripts, rails:update:javascripts, and script/server on lighttpd still just works #4047 [DHH]
+* Added that rake rails:freeze:edge will now just export all the contents of the frameworks instead of just lib, so stuff like rails:update:scripts, rails:update:javascripts, and script/server on lighttpd still just works #4047 [David Heinemeier Hansson]
-* Added fix for upload problems with lighttpd from Safari/IE to config/lighttpd.conf #3999 [thijs@fngtps.com]
+* Added fix for upload problems with lighttpd from Safari/IE to config/lighttpd.conf #3999 [Thijs van der Vossen]
* Added test:uncommitted to test changes since last checkin to Subversion #4035 [technomancy@gmail.com]
@@ -1217,9 +1217,9 @@ References #6031. [Nicholas Seckar]
* Add integration test support to app generation and testing [Jamis Buck]
-* Added namespaces to all tasks, so for example load_fixtures is now db:fixtures:load. All the old task names are still valid, they just point to the new namespaced names. "rake -T" will only show the namespaced ones, though [DHH]
+* Added namespaces to all tasks, so for example load_fixtures is now db:fixtures:load. All the old task names are still valid, they just point to the new namespaced names. "rake -T" will only show the namespaced ones, though [David Heinemeier Hansson]
-* CHANGED DEFAULT: ActiveRecord::Base.schema_format is now :ruby by default instead of :sql. This means that we'll assume you want to live in the world of db/schema.rb where the grass is green and the girls are pretty. If your schema contains un-dumpable elements, such as constraints or database-specific column types, you just got an invitation to either 1) patch the dumper to include foreign key support, 2) stop being db specific, or 3) just change the default in config/environment.rb to config.active_record.schema_format = :sql -- we even include an example for that on new Rails skeletons now. Brought to you by the federation of opinionated framework builders! [DHH]
+* CHANGED DEFAULT: ActiveRecord::Base.schema_format is now :ruby by default instead of :sql. This means that we'll assume you want to live in the world of db/schema.rb where the grass is green and the girls are pretty. If your schema contains un-dumpable elements, such as constraints or database-specific column types, you just got an invitation to either 1) patch the dumper to include foreign key support, 2) stop being db specific, or 3) just change the default in config/environment.rb to config.active_record.schema_format = :sql -- we even include an example for that on new Rails skeletons now. Brought to you by the federation of opinionated framework builders! [David Heinemeier Hansson]
* Added -r/--repeat option to script/process/spawner that offers the same loop protection as the spinner did. This deprecates the script/process/spinner, so it's no longer included in the default Rails skeleton, but still available for backwards compatibility #3461 [ror@andreas-s.net]
@@ -1230,17 +1230,17 @@ References #6031. [Nicholas Seckar]
* Added more information to script/plugin's doings to ease debugging #3755 [Rick Olson]
-* Changed the default configuration for lighttpd to use tmp/sockets instead of log/ for the FastCGI sockets [DHH]
+* Changed the default configuration for lighttpd to use tmp/sockets instead of log/ for the FastCGI sockets [David Heinemeier Hansson]
-* Added a default configuration of the FileStore for fragment caching if tmp/cache is available, which makes action/fragment caching ready to use out of the box with no additional configuration [DHH]
+* Added a default configuration of the FileStore for fragment caching if tmp/cache is available, which makes action/fragment caching ready to use out of the box with no additional configuration [David Heinemeier Hansson]
-* Changed the default session configuration to place sessions in tmp/sessions, if that directory is available, instead of /tmp (this essentially means a goodbye to 9/10 White Screen of Death errors and should have web hosting firms around the world cheering) [DHH]
+* Changed the default session configuration to place sessions in tmp/sessions, if that directory is available, instead of /tmp (this essentially means a goodbye to 9/10 White Screen of Death errors and should have web hosting firms around the world cheering) [David Heinemeier Hansson]
-* Added tmp/sessions, tmp/cache, and tmp/sockets as default directories in the Rails skeleton [DHH]
+* Added tmp/sessions, tmp/cache, and tmp/sockets as default directories in the Rails skeleton [David Heinemeier Hansson]
-* Added that script/generate model will now automatically create a migration file for the model created. This can be turned off by calling the generator with --skip-migration [DHH]
+* Added that script/generate model will now automatically create a migration file for the model created. This can be turned off by calling the generator with --skip-migration [David Heinemeier Hansson]
-* Added -d/--database option to the rails command, so you can do "rails --database=sqlite2 myapp" to start a new application preconfigured to use SQLite2 as the database. Removed the configuration examples from SQLite and PostgreSQL from the default MySQL configuration [DHH]
+* Added -d/--database option to the rails command, so you can do "rails --database=sqlite2 myapp" to start a new application preconfigured to use SQLite2 as the database. Removed the configuration examples from SQLite and PostgreSQL from the default MySQL configuration [David Heinemeier Hansson]
* Allow script/server -c /path/to/lighttpd.conf [Jeremy Kemper]
@@ -1248,13 +1248,13 @@ References #6031. [Nicholas Seckar]
* Update script.aculo.us to V1.5.3 [Thomas Fuchs]
-* Added SIGTRAP signal handler to RailsFCGIHandler that'll force the process into a breakpoint after the next request. This breakpoint can then be caught with script/breakpointer and give you access to the Ruby image inside that process. Useful for debugging memory leaks among other things [DHH]
+* Added SIGTRAP signal handler to RailsFCGIHandler that'll force the process into a breakpoint after the next request. This breakpoint can then be caught with script/breakpointer and give you access to the Ruby image inside that process. Useful for debugging memory leaks among other things [David Heinemeier Hansson]
-* Changed default lighttpd.conf to use CWD from lighttpd 1.4.10 that allows the same configuration to be used for both detach and not. Also ensured that auto-repeaping of FCGIs only happens when lighttpd is not detached. [DHH]
+* Changed default lighttpd.conf to use CWD from lighttpd 1.4.10 that allows the same configuration to be used for both detach and not. Also ensured that auto-repeaping of FCGIs only happens when lighttpd is not detached. [David Heinemeier Hansson]
* Added Configuration#after_initialize for registering a block which gets called after the framework is fully initialized. Useful for things like per-environment configuration of plugins. [Michael Koziarski]
-* Added check for RAILS_FRAMEWORK_ROOT constant that allows the Rails framework to be found in a different place than vendor/rails. Should be set in boot.rb. [DHH]
+* Added check for RAILS_FRAMEWORK_ROOT constant that allows the Rails framework to be found in a different place than vendor/rails. Should be set in boot.rb. [David Heinemeier Hansson]
* Fixed that static requests could unlock the mutex guarding dynamic requests in the WEBrick servlet #3433 [tom@craz8.com]
@@ -1272,7 +1272,7 @@ References #6031. [Nicholas Seckar]
* Fix typo in mailer generator USAGE. #3458 [chriztian.steinmeier@gmail.com]
-* Ignore version mismatch between pg_dump and the database server. #3457 [simon.stapleton@gmail.com]
+* Ignore version mismatch between pg_dump and the database server. #3457 [Simon Stapleton]
* Reap FCGI processes after lighttpd exits. [Sam Stephenson]
@@ -1304,11 +1304,11 @@ References #6031. [Nicholas Seckar]
* Have the lighttpd server script report the actual ip to which the server is bound. #2903. [Adam]
-* Add plugin library directories to the load path after the lib directory so that libraries in the lib directory get precedence. #2910. [james.adam@gmail.com]
+* Add plugin library directories to the load path after the lib directory so that libraries in the lib directory get precedence. #2910. [James Adam]
* Make help for the console command more explicit about how to specify the desired environment in which to run the console. #2911. [anonymous]
-* PostgreSQL: the purge_test_database Rake task shouldn't explicitly specify the template0 template when creating a fresh test database. #2964 [dreamer3@gmail.com]
+* PostgreSQL: the purge_test_database Rake task shouldn't explicitly specify the template0 template when creating a fresh test database. #2964 [Dreamer3]
* Introducing the session_migration generator. Creates an add_session_table migration. Allows generator to specify migrations directory. #2958, #2960 [Rick Olson]
@@ -1326,19 +1326,19 @@ References #6031. [Nicholas Seckar]
* Make sure that legacy db tasks also reference :database for SQLite #2830 [kazuhiko@fdiary.net]
-* Pass __FILE__ when evaluating plugins' init.rb. #2817 [james.adam@gmail.com]
+* Pass __FILE__ when evaluating plugins' init.rb. #2817 [James Adam]
* Better svn status matching for generators. #2814 [François Beausoleil <francois.beausoleil@gmail.com>, Blair Zajac <blair@orcaware.com>]
-* Don't reload routes until plugins have been loaded so they have a chance to extend the routing capabilities [DHH]
+* Don't reload routes until plugins have been loaded so they have a chance to extend the routing capabilities [David Heinemeier Hansson]
* Don't detach or fork for script/server tailing [Nicholas Seckar]
-* Changed all script/* to use #!/usr/bin/env ruby instead of hard-coded Ruby path. public/dispatcher.* still uses the hard-coded path for compatibility with web servers that don't have Ruby in path [DHH]
+* Changed all script/* to use #!/usr/bin/env ruby instead of hard-coded Ruby path. public/dispatcher.* still uses the hard-coded path for compatibility with web servers that don't have Ruby in path [David Heinemeier Hansson]
-* Force RAILS_ENV to be "test" when running tests, so that ENV["RAILS_ENV"] = "production" in config/environment.rb doesn't wreck havok [DHH] #2660
+* Force RAILS_ENV to be "test" when running tests, so that ENV["RAILS_ENV"] = "production" in config/environment.rb doesn't wreck havok [David Heinemeier Hansson] #2660
-* Correct versioning in :freeze_gems Rake task. #2778 [jakob@mentalized.net, Jeremy Kemper]
+* Correct versioning in :freeze_gems Rake task. #2778 [Jakob Skjerning, Jeremy Kemper]
* Added an omnipresent RailsInfoController with a properties action that delivers an HTML rendering of Rails::Info (but only when local_request? is true). Added a new default index.html which fetches this with Ajax. [Sam Stephenson]
@@ -1353,7 +1353,7 @@ References #6031. [Nicholas Seckar]
* Use require_library_or_gem 'fcgi' in script/server [Sam Stephenson]
-* Added default lighttpd config in config/lighttpd.conf and added a default runner for lighttpd in script/server (works like script/server, but using lighttpd and FastCGI). It will use lighttpd if available, otherwise WEBrick. You can force either or using 'script/server lighttpd' or 'script/server webrick' [DHH]
+* Added default lighttpd config in config/lighttpd.conf and added a default runner for lighttpd in script/server (works like script/server, but using lighttpd and FastCGI). It will use lighttpd if available, otherwise WEBrick. You can force either or using 'script/server lighttpd' or 'script/server webrick' [David Heinemeier Hansson]
* New configuration option config.plugin_paths which may be a single path like the default 'vendor/plugins' or an array of paths: ['vendor/plugins', 'lib/plugins']. [Jeremy Kemper]
@@ -1379,7 +1379,7 @@ References #6031. [Nicholas Seckar]
* Make fcgi handler respond to TERM signals with an explicit exit [Jamis Buck]
-* Added demonstration of fixture use to the test case generated by the model generator [DHH]
+* Added demonstration of fixture use to the test case generated by the model generator [David Heinemeier Hansson]
* If specified, pass PostgreSQL client character encoding to createdb. #2703 [Kazuhiko <kazuhiko@fdiary.net>]
@@ -1399,7 +1399,7 @@ References #6031. [Nicholas Seckar]
* The PostgreSQL :db_structure_dump Rake task limits its dump to the schema search path in database.yml. [Anatol Pomozov <anatol.pomozov@gmail.com>]
-* Add task to generate rdoc for all installed plugins. [Marcel Molina]
+* Add task to generate rdoc for all installed plugins. [Marcel Molina Jr.]
* Update script.aculo.us to V1.5_rc4 [Thomas Fuchs]
@@ -1407,15 +1407,15 @@ References #6031. [Nicholas Seckar]
* Migrations may be destroyed: script/destroy migration foo. #2635 [Charles M. Gerungan <charles.gerungan@gmail.com>, Jamis Buck, Jeremy Kemper]
-* Added that plugins can carry generators and that generator stub files can be created along with new plugins using script/generate plugin <name> --with-generator [DHH]
+* Added that plugins can carry generators and that generator stub files can be created along with new plugins using script/generate plugin <name> --with-generator [David Heinemeier Hansson]
-* Removed app/apis as a default empty dir since its automatically created when using script/generate web_service [DHH]
+* Removed app/apis as a default empty dir since its automatically created when using script/generate web_service [David Heinemeier Hansson]
* Added script/plugin to manage plugins (install, remove, list, etc) [Ryan Tomayko]
-* Added test_plugins task: Run the plugin tests in vendor/plugins/**/test (or specify with PLUGIN=name) [DHH]
+* Added test_plugins task: Run the plugin tests in vendor/plugins/**/test (or specify with PLUGIN=name) [David Heinemeier Hansson]
-* Added plugin generator to create a stub structure for a new plugin in vendor/plugins (see "script/generate plugin" for help) [DHH]
+* Added plugin generator to create a stub structure for a new plugin in vendor/plugins (see "script/generate plugin" for help) [David Heinemeier Hansson]
* Fixed scaffold generator when started with only 1 parameter #2609 [self@mattmower.com]
@@ -1446,7 +1446,7 @@ References #6031. [Nicholas Seckar]
*0.14.0 (RC1)* (October 16th, 2005)
-* Moved generator folder from RAILS_ROOT/generators to RAILS_ROOT/lib/generators [Tobias Luetke]
+* Moved generator folder from RAILS_ROOT/generators to RAILS_ROOT/lib/generators [Tobias Lütke]
* Fix rake dev and related commands [Nicholas Seckar]
@@ -1457,7 +1457,7 @@ References #6031. [Nicholas Seckar]
* Added Rails framework freezing tasks: freeze_gems (freeze to current gems), freeze_edge (freeze to Rails SVN trunk), unfreeze_rails (float with newest gems on system)
-* Added update_javascripts task which will fetch all the latest js files from your current rails install. Use after updating rails. [Tobias Luetke]
+* Added update_javascripts task which will fetch all the latest js files from your current rails install. Use after updating rails. [Tobias Lütke]
* Added cleaning of RAILS_ROOT to useless elements such as '../non-dot-dot/'. Provides cleaner backtraces and error messages. [Nicholas Seckar]
@@ -1483,7 +1483,7 @@ References #6031. [Nicholas Seckar]
* Make the migration generator only check files ending in *.rb when calculating the next file name #2317 [Chad Fowler]
-* Added prevention of duplicate migrations from the generator #2240 [fbeausoleil@ftml.net]
+* Added prevention of duplicate migrations from the generator #2240 [François Beausoleil]
* Add db_schema_dump and db_schema_import rake tasks to work with the new ActiveRecord::SchemaDumper (for dumping a schema to and reading a schema from a ruby file).
@@ -1499,7 +1499,7 @@ References #6031. [Nicholas Seckar]
* Added -m/--mime-types option to the WEBrick server, so you can specify a Apache-style mime.types file to load #2059 [ask@develooper.com]
-* Added -c/--svn option to the generator that'll add new files and remove destroyed files using svn add/revert/remove as appropriate #2064 [kevin.clark@gmail.com]
+* Added -c/--svn option to the generator that'll add new files and remove destroyed files using svn add/revert/remove as appropriate #2064 [Kevin Clark]
* Added -c/--charset option to WEBrick server, so you can specify a default charset (which without changes is UTF-8) #2084 [wejn@box.cz]
@@ -1531,9 +1531,9 @@ References #6031. [Nicholas Seckar]
* Added convenience controls for FCGI processes (especially when managed remotely): spinner, spawner, and reaper. They reside in script/process. More details can be had by calling them with -h/--help.
-* Added load_fixtures task to the Rakefile, which will load all the fixtures into the database for the current environment #1791 [Marcel Molina]
+* Added load_fixtures task to the Rakefile, which will load all the fixtures into the database for the current environment #1791 [Marcel Molina Jr.]
-* Added an empty robots.txt to public/, so that web servers asking for it won't trigger a dynamic call, like favicon.ico #1738 [michael@schubert]
+* Added an empty robots.txt to public/, so that web servers asking for it won't trigger a dynamic call, like favicon.ico #1738 [Michael Schubert]
* Dropped the 'immediate close-down' of FCGI processes since it didn't work consistently and produced bad responses when it didn't. So now a TERM ensures exit after the next request (just as if the process is handling a request when it receives the signal). This means that you'll have to 'nudge' all FCGI processes with a request in order to ensure that they have all reloaded. This can be done by something like ./script/process/repear --nudge 'http://www.myapp.com' --instances 10, which will load the myapp site 10 times (and thus hit all of the 10 FCGI processes once, enough to shut down).
@@ -1544,13 +1544,13 @@ References #6031. [Nicholas Seckar]
* Fixed that each request with the WEBrick adapter would open a new database connection #1685 [Sam Stephenson]
-* Added support for SQL Server in the database rake tasks #1652 [ken.barker@gmail.com] Note: osql and scptxfr may need to be installed on your development environment. This involves getting the .exes and a .rll (scptxfr) from a production SQL Server (not developer level SQL Server). Add their location to your Environment PATH and you are all set.
+* Added support for SQL Server in the database rake tasks #1652 [Ken Barker] Note: osql and scptxfr may need to be installed on your development environment. This involves getting the .exes and a .rll (scptxfr) from a production SQL Server (not developer level SQL Server). Add their location to your Environment PATH and you are all set.
* Added a VERSION parameter to the migrate task that allows you to do "rake migrate VERSION=34" to migrate to the 34th version traveling up or down depending on the current version
-* Extend Ruby version check to include RUBY_RELEASE_DATE >= '2005-12-25', the final Ruby 1.8.2 release #1674 [court3nay@gmail.com]
+* Extend Ruby version check to include RUBY_RELEASE_DATE >= '2005-12-25', the final Ruby 1.8.2 release #1674 [court3nay]
-* Improved documentation for environment config files #1625 [court3nay@gmail.com]
+* Improved documentation for environment config files #1625 [court3nay]
*0.13.0* (6 July, 2005)
@@ -1561,19 +1561,19 @@ References #6031. [Nicholas Seckar]
* Added "migrate" as rake task to execute all the pending migrations from db/migrate
-* Fixed that model generator would make fixtures plural, even if ActiveRecord::Base.pluralize_table_names was false #1185 [Marcel Molina]
+* Fixed that model generator would make fixtures plural, even if ActiveRecord::Base.pluralize_table_names was false #1185 [Marcel Molina Jr.]
* Added a DOCTYPE of HTML transitional to the HTML files generated by Rails #1124 [Michael Koziarski]
* SIGTERM also gracefully exits dispatch.fcgi. Ignore SIGUSR1 on Windows.
-* Add the option to manually manage garbage collection in the FastCGI dispatcher. Set the number of requests between GC runs in your public/dispatch.fcgi [skaes@web.de]
+* Add the option to manually manage garbage collection in the FastCGI dispatcher. Set the number of requests between GC runs in your public/dispatch.fcgi [Stefan Kaes]
* Allow dynamic application reloading for dispatch.fcgi processes by sending a SIGHUP. If the process is currently handling a request, the request will be allowed to complete first. This allows production fcgi's to be reloaded without having to restart them.
* RailsFCGIHandler (dispatch.fcgi) no longer tries to explicitly flush $stdout (CgiProcess#out always calls flush)
-* Fixed rakefile actions against PostgreSQL when the password is all numeric #1462 [michael@schubert.cx]
+* Fixed rakefile actions against PostgreSQL when the password is all numeric #1462 [Michael Schubert]
* ActionMailer::Base subclasses are reloaded with the other rails components #1262
@@ -1587,7 +1587,7 @@ References #6031. [Nicholas Seckar]
* Fixed Webrick to escape + characters in URL's the same way that lighttpd and apache do #1397 [Nicholas Seckar]
-* Added -e/--environment option to script/runner #1408 [fbeausoleil@ftml.net]
+* Added -e/--environment option to script/runner #1408 [François Beausoleil]
* Modernize the scaffold generator to use the simplified render and test methods and to change style from @params["id"] to params[:id]. #1367
@@ -1628,7 +1628,7 @@ References #6031. [Nicholas Seckar]
* Added lazy typing for generate, such that ./script/generate cn == ./script/generate controller and the likes #1051 [k@v2studio.com]
-* Fixed that ownership is brought over in pg_dump during tests for PostgreSQL #1060 [pburleson@gmail.com]
+* Fixed that ownership is brought over in pg_dump during tests for PostgreSQL #1060 [pburleson]
* Upgraded to Active Record 1.10.0, Action Pack 1.8.0, Action Mailer 0.9.0, Action Web Service 0.7.0, Active Support 1.0.4
@@ -1648,11 +1648,11 @@ References #6031. [Nicholas Seckar]
* Added additional error handling to the FastCGI dispatcher to catch even errors taking down the entire process
-* Improved the generated scaffold code a lot to take advantage of recent Rails developments #882 [Tobias Luetke]
+* Improved the generated scaffold code a lot to take advantage of recent Rails developments #882 [Tobias Lütke]
* Combined the script/environment.rb used for gems and regular files version. If vendor/rails/* has all the frameworks, then files version is used, otherwise gems #878 [Nicholas Seckar]
-* Changed .htaccess to allow dispatch.* to be called from a sub-directory as part of the push with Action Pack to make Rails work on non-vhost setups #826 [Nicholas Seckar/Tobias Luetke]
+* Changed .htaccess to allow dispatch.* to be called from a sub-directory as part of the push with Action Pack to make Rails work on non-vhost setups #826 [Nicholas Seckar/Tobias Lütke]
* Added script/runner which can be used to run code inside the environment by eval'ing the first parameter. Examples:
@@ -1676,9 +1676,9 @@ References #6031. [Nicholas Seckar]
*0.10.1* (7th March, 2005)
-* Fixed rake stats to ignore editor backup files like model.rb~ #791 [skanthak]
+* Fixed rake stats to ignore editor backup files like model.rb~ #791 [Sebastian Kanthak]
-* Added exception shallowing if the DRb server can't be started (not worth making a fuss about to distract new users) #779 [Tobias Luetke]
+* Added exception shallowing if the DRb server can't be started (not worth making a fuss about to distract new users) #779 [Tobias Lütke]
* Added an empty favicon.ico file to the public directory of new applications (so the logs are not spammed by its absence)
@@ -1711,7 +1711,7 @@ References #6031. [Nicholas Seckar]
*0.10.0* (24th February, 2005)
-* Changed default IP binding for WEBrick from 127.0.0.1 to 0.0.0.0 so that the server is accessible both locally and remotely #696 [Marcel]
+* Changed default IP binding for WEBrick from 127.0.0.1 to 0.0.0.0 so that the server is accessible both locally and remotely #696 [Marcel Molina Jr.]
* Fixed that script/server -d was broken so daemon mode couldn't be used #687 [Nicholas Seckar]
@@ -1778,7 +1778,7 @@ References #6031. [Nicholas Seckar]
*0.9.4.1* (January 18th, 2005)
-* Added 5-second timeout to WordNet alternatives on creating reserved-word models #501 [Marcel Molina]
+* Added 5-second timeout to WordNet alternatives on creating reserved-word models #501 [Marcel Molina Jr.]
* Fixed binding of caller #496 [Alexey]
@@ -1787,22 +1787,22 @@ References #6031. [Nicholas Seckar]
*0.9.4* (January 17th, 2005)
-* Added that ApplicationController will catch a ControllerNotFound exception if someone attempts to access a url pointing to an unexisting controller [Tobias Luetke]
+* Added that ApplicationController will catch a ControllerNotFound exception if someone attempts to access a url pointing to an unexisting controller [Tobias Lütke]
* Flipped code-to-test ratio around to be more readable #468 [Scott Baron]
* Fixed log file permissions to be 666 instead of 777 (so they're not executable) #471 [Lucas Carlson]
-* Fixed that auto reloading would some times not work or would reload the models twice #475 [Tobias Luetke]
+* Fixed that auto reloading would some times not work or would reload the models twice #475 [Tobias Lütke]
* Added rewrite rules to deal with caching to public/.htaccess
* Added the option to specify a controller name to "generate scaffold" and made the default controller name the plural form of the model.
* Added that rake clone_structure_to_test, db_structure_dump, and purge_test_database tasks now pick up the source database to use from
- RAILS_ENV instead of just forcing development #424 [Tobias Luetke]
+ RAILS_ENV instead of just forcing development #424 [Tobias Lütke]
-* Fixed script/console to work with Windows (that requires the use of irb.bat) #418 [octopod]
+* Fixed script/console to work with Windows (that requires the use of irb.bat) #418 [Chris McGrath]
* Fixed WEBrick servlet slowdown over time by restricting the load path reloading to mod_ruby
diff --git a/railties/doc/guides/html/activerecord_validations_callbacks.html b/railties/doc/guides/html/activerecord_validations_callbacks.html
index cb381e7191..039e3d1891 100644
--- a/railties/doc/guides/html/activerecord_validations_callbacks.html
+++ b/railties/doc/guides/html/activerecord_validations_callbacks.html
@@ -231,7 +231,7 @@ ul#navMain {
<li><a href="#_the_tt_validates_length_of_tt_helper">The <tt>validates_length_of</tt> helper</a></li>
- <li><a href="#_the_tt_validates_numericallity_of_tt_helper">The <tt>validates_numericallity_of</tt> helper</a></li>
+ <li><a href="#_the_tt_validates_numericality_of_tt_helper">The <tt>validates_numericality_of</tt> helper</a></li>
<li><a href="#_the_tt_validates_presence_of_tt_helper">The <tt>validates_presence_of</tt> helper</a></li>
@@ -338,7 +338,7 @@ Create your own custom validation methods
</li>
<li>
<p>
-Work with the error messages generated by the validation proccess
+Work with the error messages generated by the validation process
</p>
</li>
<li>
@@ -405,7 +405,7 @@ http://www.gnu.org/software/src-highlite -->
&gt;&gt; p.new_record?
=&gt; false</tt></pre>
</div></div>
-<div class="para"><p>Saving new records means sending an SQL insert operation to the database, while saving existing records (by calling either <tt>save</tt> or <tt>update_attributes</tt>) will result in a SQL update operation. Active Record will use this facts to perform validations upon your objects, avoiding then to be recorded to the database if their inner state is invalid in some way. You can specify validations that will be beformed every time a object is saved, just when you're creating a new record or when you're updating an existing one.</p></div>
+<div class="para"><p>Saving new records means sending an SQL insert operation to the database, while saving existing records (by calling either <tt>save</tt> or <tt>update_attributes</tt>) will result in a SQL update operation. Active Record will use these facts to perform validations upon your objects, avoiding then to be recorded to the database if their inner state is invalid in some way. You can specify validations that will be beformed every time a object is saved, just when you're creating a new record or when you're updating an existing one.</p></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
@@ -524,7 +524,8 @@ by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> MovieFile <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
- validates_exclusion_of <span style="color: #990000">:</span>format<span style="color: #990000">,</span> <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">in</span></span> <span style="color: #990000">=&gt;</span> <span style="color: #990000">%</span>w<span style="color: #990000">(</span>mov avi<span style="color: #990000">),</span> <span style="color: #990000">:</span>message <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Extension %s is not allowed"</span>
+ validates_exclusion_of <span style="color: #990000">:</span>format<span style="color: #990000">,</span> <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">in</span></span> <span style="color: #990000">=&gt;</span> <span style="color: #990000">%</span>w<span style="color: #990000">(</span>mov avi<span style="color: #990000">),</span>
+ <span style="color: #990000">:</span>message <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Extension %s is not allowed"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>The <tt>validates_exclusion_of</tt> helper has an option <tt>:in</tt> that receives the set of values that will not be accepted for the validated attributes. The <tt>:in</tt> option has an alias called <tt>:within</tt> that you can use for the same purpose, if you'd like to. In the previous example we used the <tt>:message</tt> option to show how we can personalize it with the current attribute's value, through the <tt>%s</tt> format mask.</p></div>
@@ -537,7 +538,8 @@ by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Product <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
- validates_format_of <span style="color: #990000">:</span>description<span style="color: #990000">,</span> <span style="color: #990000">:</span>with <span style="color: #990000">=&gt;</span> <span style="color: #FF6600">/^[a-zA-Z]+$/</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>message <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Only letters allowed"</span>
+ validates_format_of <span style="color: #990000">:</span>description<span style="color: #990000">,</span> <span style="color: #990000">:</span>with <span style="color: #990000">=&gt;</span> <span style="color: #FF6600">/^[a-zA-Z]+$/</span><span style="color: #990000">,</span>
+ <span style="color: #990000">:</span>message <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Only letters allowed"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>The default error message for <tt>validates_format_of</tt> is "<em>is invalid</em>".</p></div>
@@ -549,7 +551,8 @@ by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Coffee <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
- validates_inclusion_of <span style="color: #990000">:</span>size<span style="color: #990000">,</span> <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">in</span></span> <span style="color: #990000">=&gt;</span> <span style="color: #990000">%</span>w<span style="color: #990000">(</span>small medium large<span style="color: #990000">),</span> <span style="color: #990000">:</span>message <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"%s is not a valid size"</span>
+ validates_inclusion_of <span style="color: #990000">:</span>size<span style="color: #990000">,</span> <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">in</span></span> <span style="color: #990000">=&gt;</span> <span style="color: #990000">%</span>w<span style="color: #990000">(</span>small medium large<span style="color: #990000">),</span>
+ <span style="color: #990000">:</span>message <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"%s is not a valid size"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>The <tt>validates_inclusion_of</tt> helper has an option <tt>:in</tt> that receives the set of values that will be accepted. The <tt>:in</tt> option has an alias called <tt>:within</tt> that you can use for the same purpose, if you'd like to. In the previous example we used the <tt>:message</tt> option to show how we can personalize it with the current attribute's value, through the <tt>%s</tt> format mask.</p></div>
@@ -602,7 +605,7 @@ http://www.gnu.org/software/src-highlite -->
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>This helper has an alias called <tt>validates_size_of</tt>, it's the same helper with a different name. You can use it if you'd like to.</p></div>
-<h3 id="_the_tt_validates_numericallity_of_tt_helper">3.9. The <tt>validates_numericallity_of</tt> helper</h3>
+<h3 id="_the_tt_validates_numericality_of_tt_helper">3.9. The <tt>validates_numericality_of</tt> helper</h3>
<div class="para"><p>This helper validates that your attributes have only numeric values. By default, it will match an optional sign followed by a integral or floating point number. Using the <tt>:integer_only</tt> option set to true, you can specify that only integral numbers are allowed.</p></div>
<div class="para"><p>If you use <tt>:integer_only</tt> set to <tt>true</tt>, then it will use the <tt><span>/\A[+\-]?\d+\Z/</span></tt> regular expression to validate the attribute's value. Otherwise, it will try to convert the value using <tt>Kernel.Float</tt>.</p></div>
<div class="listingblock">
@@ -611,11 +614,11 @@ by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Player <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
- validates_numericallity_of <span style="color: #990000">:</span>points
- validates_numericallity_of <span style="color: #990000">:</span>games_played<span style="color: #990000">,</span> <span style="color: #990000">:</span>integer_only <span style="color: #990000">=&gt;</span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span>
+ validates_numericality_of <span style="color: #990000">:</span>points
+ validates_numericality_of <span style="color: #990000">:</span>games_played<span style="color: #990000">,</span> <span style="color: #990000">:</span>integer_only <span style="color: #990000">=&gt;</span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<div class="para"><p>The default error message for <tt>validates_numericallity_of</tt> is "<em>is not a number</em>".</p></div>
+<div class="para"><p>The default error message for <tt>validates_numericality_of</tt> is "<em>is not a number</em>".</p></div>
<h3 id="_the_tt_validates_presence_of_tt_helper">3.10. The <tt>validates_presence_of</tt> helper</h3>
<div class="para"><p>This helper validates that the attributes are not empty. It uses the <tt>blank?</tt> method to check if the value is either <tt>nil</tt> or an empty string (if the string has only spaces, it will still be considered empty).</p></div>
<div class="listingblock">
@@ -673,7 +676,8 @@ by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Holiday <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
- validates_uniqueness_of <span style="color: #990000">:</span>name<span style="color: #990000">,</span> <span style="color: #990000">:</span>scope <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>year<span style="color: #990000">,</span> <span style="color: #990000">:</span>message <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Should happen once per year"</span>
+ validates_uniqueness_of <span style="color: #990000">:</span>name<span style="color: #990000">,</span> <span style="color: #990000">:</span>scope <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>year<span style="color: #990000">,</span>
+ <span style="color: #990000">:</span>message <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Should happen once per year"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>There is also a <tt>:case_sensitive</tt> option that you can use to define if the uniqueness contraint will be case sensitive or not. This option defaults to true.</p></div>
@@ -692,7 +696,7 @@ http://www.gnu.org/software/src-highlite -->
<div class="sectionbody">
<div class="para"><p>There are some common options that all the validation helpers can use. Here they are, except for the <tt>:if</tt> and <tt>:unless</tt> options, which we'll cover right at the next topic.</p></div>
<h3 id="_the_tt_allow_nil_tt_option">4.1. The <tt>:allow_nil</tt> option</h3>
-<div class="para"><p>You may use the <tt>:allow_nil</tt> option everytime you just want to trigger a validation if the value being validated is not <tt>nil</tt>. You may be asking yourself if it makes any sense to use <tt>:allow_nil</tt> and <tt>validates_presence_of</tt> together. Well, it does. Remember, validation will be skipped only for <tt>nil</tt> attributes, but empty strings are not considered <tt>nil</tt>.</p></div>
+<div class="para"><p>You may use the <tt>:allow_nil</tt> option everytime you want to trigger a validation only if the value being validated is not <tt>nil</tt>. You may be asking yourself if it makes any sense to use <tt>:allow_nil</tt> and <tt>validates_presence_of</tt> together. Well, it does. Remember, validation will be skipped only for <tt>nil</tt> attributes, but empty strings are not considered <tt>nil</tt>.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -713,9 +717,14 @@ by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
- validates_uniqueness_of <span style="color: #990000">:</span>email<span style="color: #990000">,</span> <span style="color: #990000">:</span>on <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>create <span style="font-style: italic"><span style="color: #9A1900"># =&gt; it will be possible to update email with a duplicated value</span></span>
- validates_numericallity_of <span style="color: #990000">:</span>age<span style="color: #990000">,</span> <span style="color: #990000">:</span>on <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>update <span style="font-style: italic"><span style="color: #9A1900"># =&gt; it will be possible to create the record with a 'non-numerical age'</span></span>
- validates_presence_of <span style="color: #990000">:</span>name<span style="color: #990000">,</span> <span style="color: #990000">:</span>on <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>save <span style="font-style: italic"><span style="color: #9A1900"># =&gt; that's the default</span></span>
+ <span style="font-style: italic"><span style="color: #9A1900"># =&gt; it will be possible to update email with a duplicated value</span></span>
+ validates_uniqueness_of <span style="color: #990000">:</span>email<span style="color: #990000">,</span> <span style="color: #990000">:</span>on <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>create
+
+ <span style="font-style: italic"><span style="color: #9A1900"># =&gt; it will be possible to create the record with a 'non-numerical age'</span></span>
+ validates_numericality_of <span style="color: #990000">:</span>age<span style="color: #990000">,</span> <span style="color: #990000">:</span>on <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>update
+
+ <span style="font-style: italic"><span style="color: #9A1900"># =&gt; the default</span></span>
+ validates_presence_of <span style="color: #990000">:</span>name<span style="color: #990000">,</span> <span style="color: #990000">:</span>on <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>save
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
</div>
@@ -756,7 +765,8 @@ by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Account <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
- validates_confirmation_of <span style="color: #990000">:</span>password<span style="color: #990000">,</span> <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">unless</span></span> <span style="color: #990000">=&gt;</span> Proc<span style="color: #990000">.</span>new <span style="color: #FF0000">{</span> <span style="color: #990000">|</span>a<span style="color: #990000">|</span> a<span style="color: #990000">.</span>password<span style="color: #990000">.</span>blank? <span style="color: #FF0000">}</span>
+ validates_confirmation_of <span style="color: #990000">:</span>password<span style="color: #990000">,</span>
+ <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">unless</span></span> <span style="color: #990000">=&gt;</span> Proc<span style="color: #990000">.</span>new <span style="color: #FF0000">{</span> <span style="color: #990000">|</span>a<span style="color: #990000">|</span> a<span style="color: #990000">.</span>password<span style="color: #990000">.</span>blank? <span style="color: #FF0000">}</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
</div>
@@ -770,7 +780,8 @@ http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Invoice <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> validate_on_create
- errors<span style="color: #990000">.</span>add<span style="color: #990000">(:</span>expiration_date<span style="color: #990000">,</span> <span style="color: #FF0000">"can't be in the past"</span><span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">if</span></span> <span style="color: #990000">!</span>expiration_date<span style="color: #990000">.</span>blank? <span style="font-weight: bold"><span style="color: #0000FF">and</span></span> expiration_date <span style="color: #990000">&lt;</span> Date<span style="color: #990000">.</span>today
+ errors<span style="color: #990000">.</span>add<span style="color: #990000">(:</span>expiration_date<span style="color: #990000">,</span> <span style="color: #FF0000">"can't be in the past"</span><span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">if</span></span>
+ <span style="color: #990000">!</span>expiration_date<span style="color: #990000">.</span>blank? <span style="font-weight: bold"><span style="color: #0000FF">and</span></span> expiration_date <span style="color: #990000">&lt;</span> Date<span style="color: #990000">.</span>today
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
@@ -781,14 +792,17 @@ by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Invoice <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
- validate <span style="color: #990000">:</span>expiration_date_cannot_be_in_the_past<span style="color: #990000">,</span> <span style="color: #990000">:</span>discount_cannot_be_more_than_total_value
+ validate <span style="color: #990000">:</span>expiration_date_cannot_be_in_the_past<span style="color: #990000">,</span>
+ <span style="color: #990000">:</span>discount_cannot_be_more_than_total_value
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> expiration_date_cannot_be_in_the_past
- errors<span style="color: #990000">.</span>add<span style="color: #990000">(:</span>expiration_date<span style="color: #990000">,</span> <span style="color: #FF0000">"can't be in the past"</span><span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">if</span></span> <span style="color: #990000">!</span>expiration_date<span style="color: #990000">.</span>blank? <span style="font-weight: bold"><span style="color: #0000FF">and</span></span> expiration_date <span style="color: #990000">&lt;</span> Date<span style="color: #990000">.</span>today
+ errors<span style="color: #990000">.</span>add<span style="color: #990000">(:</span>expiration_date<span style="color: #990000">,</span> <span style="color: #FF0000">"can't be in the past"</span><span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">if</span></span>
+ <span style="color: #990000">!</span>expiration_date<span style="color: #990000">.</span>blank? <span style="font-weight: bold"><span style="color: #0000FF">and</span></span> expiration_date <span style="color: #990000">&lt;</span> Date<span style="color: #990000">.</span>today
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> discount_cannot_be_greater_than_total_value
- errors<span style="color: #990000">.</span>add<span style="color: #990000">(:</span>discount<span style="color: #990000">,</span> <span style="color: #FF0000">"can't be greater than total value"</span><span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">unless</span></span> discount <span style="color: #990000">&lt;=</span> total_value
+ errors<span style="color: #990000">.</span>add<span style="color: #990000">(:</span>discount<span style="color: #990000">,</span> <span style="color: #FF0000">"can't be greater than total value"</span><span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">unless</span></span>
+ discount <span style="color: #990000">&lt;=</span> total_value
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
@@ -874,16 +888,18 @@ person<span style="color: #990000">.</span>errors<span style="color: #990000">.<
person <span style="color: #990000">=</span> Person<span style="color: #990000">.</span>new<span style="color: #990000">(:</span>name <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"JD"</span><span style="color: #990000">)</span>
person<span style="color: #990000">.</span>valid? <span style="font-style: italic"><span style="color: #9A1900"># =&gt; false</span></span>
-person<span style="color: #990000">.</span>errors<span style="color: #990000">.</span>on<span style="color: #990000">(:</span>name<span style="color: #990000">)</span> <span style="font-style: italic"><span style="color: #9A1900"># =&gt; "is too short (minimum is 3 characters)"</span></span>
+person<span style="color: #990000">.</span>errors<span style="color: #990000">.</span>on<span style="color: #990000">(:</span>name<span style="color: #990000">)</span>
+<span style="font-style: italic"><span style="color: #9A1900"># =&gt; "is too short (minimum is 3 characters)"</span></span>
person <span style="color: #990000">=</span> Person<span style="color: #990000">.</span>new
person<span style="color: #990000">.</span>valid? <span style="font-style: italic"><span style="color: #9A1900"># =&gt; false</span></span>
-person<span style="color: #990000">.</span>errors<span style="color: #990000">.</span>on<span style="color: #990000">(:</span>name<span style="color: #990000">)</span> <span style="font-style: italic"><span style="color: #9A1900"># =&gt; ["can't be blank", "is too short (minimum is 3 characters)"]</span></span>
+person<span style="color: #990000">.</span>errors<span style="color: #990000">.</span>on<span style="color: #990000">(:</span>name<span style="color: #990000">)</span>
+<span style="font-style: italic"><span style="color: #9A1900"># =&gt; ["can't be blank", "is too short (minimum is 3 characters)"]</span></span>
</tt></pre></div></div>
<div class="ilist"><ul>
<li>
<p>
-<tt>clear</tt> is used when you intentionally wants to clear all the messages in the <tt>errors</tt> collection.
+<tt>clear</tt> is used when you intentionally want to clear all the messages in the <tt>errors</tt> collection. However, calling <tt>errors.clear</tt> upon an invalid object won't make it valid: the <tt>errors</tt> collection will now be empty, but the next time you call <tt>valid?</tt> or any method that tries to save this object to the database, the validations will run. If any of them fails, the <tt>errors</tt> collection will get filled again.
</p>
</li>
</ul></div>
@@ -898,10 +914,15 @@ http://www.gnu.org/software/src-highlite -->
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
person <span style="color: #990000">=</span> Person<span style="color: #990000">.</span>new
-puts person<span style="color: #990000">.</span>valid? <span style="font-style: italic"><span style="color: #9A1900"># =&gt; false</span></span>
-person<span style="color: #990000">.</span>errors<span style="color: #990000">.</span>on<span style="color: #990000">(:</span>name<span style="color: #990000">)</span> <span style="font-style: italic"><span style="color: #9A1900"># =&gt; ["can't be blank", "is too short (minimum is 3 characters)"]</span></span>
+person<span style="color: #990000">.</span>valid? <span style="font-style: italic"><span style="color: #9A1900"># =&gt; false</span></span>
+person<span style="color: #990000">.</span>errors<span style="color: #990000">.</span>on<span style="color: #990000">(:</span>name<span style="color: #990000">)</span>
+<span style="font-style: italic"><span style="color: #9A1900"># =&gt; ["can't be blank", "is too short (minimum is 3 characters)"]</span></span>
+
person<span style="color: #990000">.</span>errors<span style="color: #990000">.</span>clear
-person<span style="color: #990000">.</span>errors <span style="font-style: italic"><span style="color: #9A1900"># =&gt; nil</span></span>
+person<span style="color: #990000">.</span>errors<span style="color: #990000">.</span>empty? <span style="font-style: italic"><span style="color: #9A1900"># =&gt; true</span></span>
+p<span style="color: #990000">.</span>save <span style="font-style: italic"><span style="color: #9A1900"># =&gt; false</span></span>
+p<span style="color: #990000">.</span>errors<span style="color: #990000">.</span>on<span style="color: #990000">(:</span>name<span style="color: #990000">)</span>
+<span style="font-style: italic"><span style="color: #9A1900"># =&gt; ["can't be blank", "is too short (minimum is 3 characters)"]</span></span>
</tt></pre></div></div>
</div>
<h2 id="_callbacks">8. Callbacks</h2>
@@ -910,7 +931,7 @@ person<span style="color: #990000">.</span>errors <span style="font-style: itali
<h3 id="_callbacks_registration">8.1. Callbacks registration</h3>
<div class="para"><p>In order to use the available callbacks, you need to registrate them. There are two ways of doing that.</p></div>
<h3 id="_registering_callbacks_by_overriding_the_callback_methods">8.2. Registering callbacks by overriding the callback methods</h3>
-<div class="para"><p>You can specify the callback method direcly, by overriding it. Let's see how it works using the <tt>before_validation</tt> callback, which will surprisingly run right before any validation is done.</p></div>
+<div class="para"><p>You can specify the callback method directly, by overriding it. Let's see how it works using the <tt>before_validation</tt> callback, which will surprisingly run right before any validation is done.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -1094,7 +1115,7 @@ Readability, since your callback declarations will live at the beggining of your
</div>
<h2 id="_halting_execution">10. Halting Execution</h2>
<div class="sectionbody">
-<div class="para"><p>As you start registering new callbacks for your models, they will be queued for execution. This queue will include all your model's validations, the registered callbacks and the database operation to be executed. However, if at any moment one of the callback methods returns a boolean <tt>false</tt> (not <tt>nil</tt>) value, this execution chain will be halted and the desired operation will not complete: your model will not get persisted in the database, or your records will not get deleted and so on.</p></div>
+<div class="para"><p>As you start registering new callbacks for your models, they will be queued for execution. This queue will include all your model's validations, the registered callbacks and the database operation to be executed. However, if at any moment one of the <tt>before_create</tt>, <tt>before_save</tt>, <tt>before_update</tt> or <tt>before_destroy</tt> callback methods returns a boolean <tt>false</tt> (not <tt>nil</tt>) value, this execution chain will be halted and the desired operation will not complete: your model will not get persisted in the database, or your records will not get deleted and so on.</p></div>
</div>
<h2 id="_callback_classes">11. Callback classes</h2>
<div class="sectionbody">
@@ -1174,7 +1195,7 @@ http://www.gnu.org/software/src-highlite -->
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<h3 id="_registering_observers">12.1. Registering observers</h3>
-<div class="para"><p>If you payed attention, you may be wondering where Active Record Observers are referenced in our applications, so they get instantiate and begin to interact with our models. For observers to work we need to register then in our application's <strong>config/environment.rb</strong> file. In this file there is a commented out line where we can define the observers that our application should load at start-up.</p></div>
+<div class="para"><p>If you payed attention, you may be wondering where Active Record Observers are referenced in our applications, so they get instantiate and begin to interact with our models. For observers to work we need to register them somewhere. The usual place to do that is in our application's <strong>config/environment.rb</strong> file. In this file there is a commented out line where we can define the observers that our application should load at start-up.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -1183,6 +1204,8 @@ http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-style: italic"><span style="color: #9A1900"># Activate observers that should always be running</span></span>
config<span style="color: #990000">.</span>active_record<span style="color: #990000">.</span>observers <span style="color: #990000">=</span> <span style="color: #990000">:</span>registration_observer<span style="color: #990000">,</span> <span style="color: #990000">:</span>auditor
</tt></pre></div></div>
+<div class="para"><p>You can uncomment the line with <tt>config.active_record.observers</tt> and change the symbols for the name of the observers that should be registered.</p></div>
+<div class="para"><p>It's also possible to register callbacks in any of the files living at <strong>config/environments/</strong>, if you want an observer to work only in a specific environment. There is not a <tt>config.active_record.observers</tt> line at any of those files, but you can simply add it.</p></div>
<h3 id="_where_to_put_the_observers_source_files">12.2. Where to put the observers' source files</h3>
<div class="para"><p>By convention, you should always save your observers' source files inside <strong>app/models</strong>.</p></div>
</div>
diff --git a/railties/doc/guides/html/finders.html b/railties/doc/guides/html/finders.html
index c2c1db99e3..603f488cc9 100644
--- a/railties/doc/guides/html/finders.html
+++ b/railties/doc/guides/html/finders.html
@@ -609,6 +609,7 @@ http://www.gnu.org/software/src-highlite -->
<h2 id="_selecting_certain_fields">6. Selecting Certain Fields</h2>
<div class="sectionbody">
<div class="para"><p>To select certain fields, you can use the select option like this: <tt>Client.first(:select &#8658; "viewable_by, locked")</tt>. This select option does not use an array of fields, but rather requires you to type SQL-like code. The above code will execute <tt>SELECT viewable_by, locked FROM clients LIMIT 0,1</tt> on your database.</p></div>
+<div class="para"><p>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 <tt>DISTINCT</tt> function you can do it like this: <tt>Client.all(:select &#8658; "DISTINCT(name)")</tt>.</p></div>
</div>
<h2 id="_limit_amp_offset">7. Limit &amp; Offset</h2>
<div class="sectionbody">
@@ -1051,6 +1052,11 @@ http://www.gnu.org/software/src-highlite -->
<div class="ilist"><ul>
<li>
<p>
+December 1 2008: Added using an SQL function example to Selecting Certain Fields section as per <a href="http://rails.lighthouseapp.com/projects/16213/tickets/36-adding-an-example-for-using-distinct-to-ar-finders">this ticket</a>
+</p>
+</li>
+<li>
+<p>
November 23 2008: Added documentation for <tt>find_by_last</tt> and <tt>find_by_bang!</tt>
</p>
</li>
diff --git a/railties/doc/guides/html/getting_started_with_rails.html b/railties/doc/guides/html/getting_started_with_rails.html
index 4fc92f8ad7..ac16a79ac1 100644
--- a/railties/doc/guides/html/getting_started_with_rails.html
+++ b/railties/doc/guides/html/getting_started_with_rails.html
@@ -1723,7 +1723,7 @@ http://www.gnu.org/software/src-highlite -->
<td class="icon">
<img src="./images/icons/tip.png" alt="Tip" />
</td>
-<td class="content">For more information on routing, see the <a href="../routing_outside_in">Rails Routing from the Outside In</a> guide.</td>
+<td class="content">For more information on routing, see the <a href="../routing_outside_in.html">Rails Routing from the Outside In</a> guide.</td>
</tr></table>
</div>
<h3 id="_generating_a_controller">8.4. Generating a Controller</h3>
diff --git a/railties/doc/guides/html/layouts_and_rendering.html b/railties/doc/guides/html/layouts_and_rendering.html
index 7138c45853..30c114ef82 100644
--- a/railties/doc/guides/html/layouts_and_rendering.html
+++ b/railties/doc/guides/html/layouts_and_rendering.html
@@ -642,7 +642,7 @@ end</tt></pre>
<div class="para"><p>With those declarations, the <tt>inventory</tt> layout would be used only for the <tt>index</tt> method, the <tt>product</tt> layout would be used for everything else except the <tt>rss</tt> method, and the <tt>rss</tt> method will have its layout determined by the automatic layout rules.</p></div>
<h5 id="_layout_inheritance">Layout Inheritance</h5>
<div class="para"><p>Layouts are shared downwards in the hierarchy, and more specific layouts always override more general ones. For example:</p></div>
-<div class="para"><p><tt>application.rb</tt>:</p></div>
+<div class="para"><p><tt>application_controller.rb</tt>:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
diff --git a/railties/doc/guides/html/testing_rails_applications.html b/railties/doc/guides/html/testing_rails_applications.html
index b8a99767ee..a94c81dc5f 100644
--- a/railties/doc/guides/html/testing_rails_applications.html
+++ b/railties/doc/guides/html/testing_rails_applications.html
@@ -219,48 +219,9 @@ ul#navMain {
<li><a href="#_preparing_you_application_for_testing">Preparing you Application for Testing</a></li>
- <li><a href="#_running_tests">Running Tests</a></li>
-
- <li><a href="#_what_to_include_in_your_unit_tests">What to Include in Your Unit Tests</a></li>
-
- <li><a href="#_assertions_available">Assertions Available</a></li>
-
- <li><a href="#_rails_specific_assertions">Rails Specific Assertions</a></li>
-
- </ul>
- </li>
- <li>
- <a href="#_functional_tests_for_your_controllers">Functional Tests for Your Controllers</a>
- <ul>
-
- <li><a href="#_what_to_include_in_your_functional_tests">What to include in your Functional Tests</a></li>
-
- <li><a href="#_available_request_types_for_functional_tests">Available Request Types for Functional Tests</a></li>
-
- <li><a href="#_the_4_hashes_of_the_apocalypse">The 4 Hashes of the Apocalypse</a></li>
-
- <li><a href="#_instance_variables_available">Instance Variables Available</a></li>
-
- <li><a href="#_a_fuller_functional_test_example">A Fuller Functional Test Example</a></li>
-
- <li><a href="#_testing_views">Testing Views</a></li>
-
- </ul>
- </li>
- <li>
- <a href="#_integration_testing">Integration Testing</a>
- <ul>
-
- <li><a href="#_helpers_available_for_integration_tests">Helpers Available for Integration tests</a></li>
-
- <li><a href="#_integration_testing_examples">Integration Testing Examples</a></li>
-
</ul>
</li>
<li>
- <a href="#_rake_tasks_for_running_your_tests">Rake Tasks for Running your Tests</a>
- </li>
- <li>
<a href="#_brief_note_about_test_unit">Brief Note About Test::Unit</a>
</li>
<li>
@@ -585,994 +546,595 @@ $ rake db<span style="color: #990000">:</span><span style="font-weight: bold"><s
<td class="content"><tt>db:test:prepare</tt> will fail with an error if db/schema.rb doesn't exists.</td>
</tr></table>
</div>
-<h4 id="_rake_tasks_for_preparing_you_application_for_testing">3.1.1. Rake Tasks for Preparing you Application for Testing ==</h4>
-<div class="para"><p>--------------------------------`----------------------------------------------------
-Tasks Description</p></div>
+<h4 id="_rake_tasks_for_preparing_your_application_for_testing">3.1.1. Rake Tasks for Preparing your Application for Testing</h4>
<div class="listingblock">
<div class="content">
-<pre><tt>+rake db:test:clone+ Recreate the test database from the current environment's database schema
-+rake db:test:clone_structure+ Recreate the test databases from the development structure
-+rake db:test:load+ Recreate the test database from the current +schema.rb+
-+rake db:test:prepare+ Check for pending migrations and load the test schema
-+rake db:test:purge+ Empty the test database.</tt></pre>
+<pre><tt>Tasks Description</tt></pre>
</div></div>
-<div class="admonitionblock">
-<table><tr>
-<td class="icon">
-<img src="./images/icons/tip.png" alt="Tip" />
-</td>
-<td class="content">You can see all these rake tasks and their descriptions by running <tt>rake &#8212;tasks &#8212;describe</tt></td>
-</tr></table>
-</div>
-<h3 id="_running_tests">3.2. Running Tests</h3>
-<div class="para"><p>Running a test is as simple as invoking the file containing the test cases through Ruby:</p></div>
+<div class="para"><p><tt>rake db:test:clone</tt> Recreate the test database from the current environment's database schema
+<tt>rake db:test:clone_structure</tt> Recreate the test databases from the development structure
+<tt>rake db:test:load</tt> Recreate the test database from the current <tt>schema.rb</tt>
+<tt>rake db:test:prepare</tt> Check for pending migrations and load the test schema
+<tt>rake db:test:purge</tt> Empty the test database.</p></div>
<div class="listingblock">
-<div class="content"><!-- Generator: GNU source-highlight 2.9
-by Lorenzo Bettini
-http://www.lorenzobettini.it
-http://www.gnu.org/software/src-highlite -->
-<pre><tt>$ cd <span style="font-weight: bold"><span style="color: #0000FF">test</span></span>
-$ ruby unit/post_test<span style="color: #990000">.</span>rb
+<div class="content">
+<pre><tt>
+TIP: You can see all these rake tasks and their descriptions by running +rake \-\-tasks \-\-describe+
-Loaded suite unit/post_test
-Started
-<span style="color: #990000">.</span>
-Finished <span style="font-weight: bold"><span style="color: #0000FF">in</span></span> <span style="color: #993399">0.023513</span> seconds<span style="color: #990000">.</span>
+=== Running Tests ===
-<span style="color: #993399">1</span> tests<span style="color: #990000">,</span> <span style="color: #993399">1</span> assertions<span style="color: #990000">,</span> <span style="color: #993399">0</span> failures<span style="color: #990000">,</span> <span style="color: #993399">0</span> errors
-</tt></pre></div></div>
-<div class="para"><p>This will run all the test methods from the test case.</p></div>
-<div class="para"><p>You can also run a particular test method from the test case by using the <tt>-n</tt> switch with the <tt>test method name</tt>.</p></div>
+Running a test is as simple as invoking the file containing the test cases through Ruby:
+
+[source, shell]</tt></pre>
+</div></div>
+<div class="para"><p>$ cd test
+$ ruby unit/post_test.rb</p></div>
+<div class="para"><p>Loaded suite unit/post_test
+Started
+.
+Finished in 0.023513 seconds.</p></div>
+<div class="para"><p>1 tests, 1 assertions, 0 failures, 0 errors</p></div>
<div class="listingblock">
<div class="content">
-<pre><tt>$ ruby unit/post_test.rb -n test_truth
+<pre><tt>
+This will run all the test methods from the test case.
-Loaded suite unit/post_test
+You can also run a particular test method from the test case by using the +-n+ switch with the +test method name+.</tt></pre>
+</div></div>
+<div class="para"><p>$ ruby unit/post_test.rb -n test_truth</p></div>
+<div class="para"><p>Loaded suite unit/post_test
Started
.
-Finished in 0.023513 seconds.
+Finished in 0.023513 seconds.</p></div>
+<div class="para"><p>1 tests, 1 assertions, 0 failures, 0 errors</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>
+The +.+ (dot) above indicates a passing test. When a test fails you see an +F+; when a test throws an error you see an +E+ in its place. The last line of the output is the summary.
-1 tests, 1 assertions, 0 failures, 0 errors</tt></pre>
+To see how a test failure is reported, you can add a failing test to the +post_test.rb+ test case.
+
+[source,ruby]</tt></pre>
</div></div>
-<div class="para"><p>The <tt>.</tt> (dot) above indicates a passing test. When a test fails you see an <tt>F</tt>; when a test throws an error you see an <tt>E</tt> in its place. The last line of the output is the summary.</p></div>
-<div class="para"><p>To see how a test failure is reported, you can add a failing test to the <tt>post_test.rb</tt> test case.</p></div>
-<div class="listingblock">
-<div class="content"><!-- Generator: GNU source-highlight 2.9
-by Lorenzo Bettini
-http://www.lorenzobettini.it
-http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_should_not_save_post_without_title
- post <span style="color: #990000">=</span> Post<span style="color: #990000">.</span>new
- assert <span style="color: #990000">!</span>post<span style="color: #990000">.</span>save
-<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-</tt></pre></div></div>
-<div class="para"><p>Let us run this newly added test.</p></div>
+<div class="para"><p>def test_should_not_save_post_without_title
+ post = Post.new
+ assert !post.save
+end</p></div>
<div class="listingblock">
<div class="content">
-<pre><tt>$ ruby unit/post_test.rb -n test_should_not_save_post_without_title
+<pre><tt>
+Let us run this newly added test.</tt></pre>
+</div></div>
+<div class="para"><p>$ ruby unit/post_test.rb -n test_should_not_save_post_without_title
Loaded suite unit/post_test
Started
F
-Finished in 0.197094 seconds.
-
- 1) Failure:
+Finished in 0.197094 seconds.</p></div>
+<div class="literalblock">
+<div class="content">
+<pre><tt> 1) Failure:
test_should_not_save_post_without_title(PostTest)
[unit/post_test.rb:11:in `test_should_not_save_post_without_title'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run']:
-&lt;false&gt; is not true.
-
-1 tests, 1 assertions, 1 failures, 0 errors</tt></pre>
+&lt;false&gt; is not true.</tt></pre>
</div></div>
-<div class="para"><p>In the output, <tt>F</tt> denotes a failure. You can see the corresponding trace shown under <tt>1)</tt> along with the name of the failing test. The next few lines contain the stack trace followed by a message which mentions the actual value and the expected value by the assertion. The default assertion messages provide just enough information to help pinpoint the error. To make the assertion failure message more readable every assertion provides an optional message parameter, as shown here:</p></div>
+<div class="para"><p>1 tests, 1 assertions, 1 failures, 0 errors</p></div>
<div class="listingblock">
-<div class="content"><!-- Generator: GNU source-highlight 2.9
-by Lorenzo Bettini
-http://www.lorenzobettini.it
-http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_should_not_save_post_without_title
- post <span style="color: #990000">=</span> Post<span style="color: #990000">.</span>new
- assert <span style="color: #990000">!</span>post<span style="color: #990000">.</span>save<span style="color: #990000">,</span> <span style="color: #FF0000">"Saved the post without a title"</span>
-<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-</tt></pre></div></div>
-<div class="para"><p>Running this test shows the friendlier assertion message:</p></div>
+<div class="content">
+<pre><tt>
+In the output, +F+ denotes a failure. You can see the corresponding trace shown under +1)+ along with the name of the failing test. The next few lines contain the stack trace followed by a message which mentions the actual value and the expected value by the assertion. The default assertion messages provide just enough information to help pinpoint the error. To make the assertion failure message more readable every assertion provides an optional message parameter, as shown here:
+
+[source,ruby]</tt></pre>
+</div></div>
+<div class="para"><p>def test_should_not_save_post_without_title
+ post = Post.new
+ assert !post.save, "Saved the post without a title"
+end</p></div>
<div class="listingblock">
<div class="content">
-<pre><tt>$ ruby unit/post_test.rb -n test_should_not_save_post_without_title
+<pre><tt>
+Running this test shows the friendlier assertion message:</tt></pre>
+</div></div>
+<div class="para"><p>$ ruby unit/post_test.rb -n test_should_not_save_post_without_title
Loaded suite unit/post_test
Started
F
-Finished in 0.198093 seconds.
-
- 1) Failure:
+Finished in 0.198093 seconds.</p></div>
+<div class="literalblock">
+<div class="content">
+<pre><tt> 1) Failure:
test_should_not_save_post_without_title(PostTest)
[unit/post_test.rb:11:in `test_should_not_save_post_without_title'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run']:
Saved the post without a title.
-&lt;false&gt; is not true.
-
-1 tests, 1 assertions, 1 failures, 0 errors</tt></pre>
+&lt;false&gt; is not true.</tt></pre>
</div></div>
-<div class="para"><p>Now to get this test to pass we can add a model level validation for the <em>title</em> field.</p></div>
+<div class="para"><p>1 tests, 1 assertions, 1 failures, 0 errors</p></div>
<div class="listingblock">
-<div class="content"><!-- Generator: GNU source-highlight 2.9
-by Lorenzo Bettini
-http://www.lorenzobettini.it
-http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Post <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
- validates_presence_of <span style="color: #990000">:</span>title
-<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-</tt></pre></div></div>
-<div class="para"><p>Now the test should pass. Let us verify by running the test again:</p></div>
+<div class="content">
+<pre><tt>
+Now to get this test to pass we can add a model level validation for the _title_ field.
+
+[source,ruby]</tt></pre>
+</div></div>
+<div class="para"><p>class Post &lt; ActiveRecord::Base
+ validates_presence_of :title
+end</p></div>
<div class="listingblock">
<div class="content">
-<pre><tt>$ ruby unit/post_test.rb -n test_should_not_save_post_without_title
+<pre><tt>
+Now the test should pass. Let us verify by running the test again:</tt></pre>
+</div></div>
+<div class="para"><p>$ ruby unit/post_test.rb -n test_should_not_save_post_without_title
Loaded suite unit/post_test
Started
.
-Finished in 0.193608 seconds.
+Finished in 0.193608 seconds.</p></div>
+<div class="para"><p>1 tests, 1 assertions, 0 failures, 0 errors</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>
+Now if you noticed we first wrote a test which fails for a desired functionality, then we wrote some code which adds the functionality and finally we ensured that our test passes. This approach to software development is referred to as _Test-Driven Development_ (TDD).
-1 tests, 1 assertions, 0 failures, 0 errors</tt></pre>
+TIP: Many Rails developers practice _Test-Driven Development_ (TDD). This is an excellent way to build up a test suite that exercises every part of your application. TDD is beyond the scope of this guide, but one place to start is with link:http://andrzejonsoftware.blogspot.com/2007/05/15-tdd-steps-to-create-rails.html[15 TDD steps to create a Rails application].
+
+To see how an error gets reported, here's a test containing an error:
+
+[source,ruby]</tt></pre>
</div></div>
-<div class="para"><p>Now if you noticed we first wrote a test which fails for a desired functionality, then we wrote some code which adds the functionality and finally we ensured that our test passes. This approach to software development is referred to as <em>Test-Driven Development</em> (TDD).</p></div>
-<div class="admonitionblock">
-<table><tr>
-<td class="icon">
-<img src="./images/icons/tip.png" alt="Tip" />
-</td>
-<td class="content">Many Rails developers practice <em>Test-Driven Development</em> (TDD). This is an excellent way to build up a test suite that exercises every part of your application. TDD is beyond the scope of this guide, but one place to start is with <a href="http://andrzejonsoftware.blogspot.com/2007/05/15-tdd-steps-to-create-rails.html">15 TDD steps to create a Rails application</a>.</td>
-</tr></table>
-</div>
-<div class="para"><p>To see how an error gets reported, here's a test containing an error:</p></div>
-<div class="listingblock">
-<div class="content"><!-- Generator: GNU source-highlight 2.9
-by Lorenzo Bettini
-http://www.lorenzobettini.it
-http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_should_report_error
- <span style="font-style: italic"><span style="color: #9A1900"># some_undefined_variable is not defined elsewhere in the test case</span></span>
+<div class="para"><p>def test_should_report_error
+ # some_undefined_variable is not defined elsewhere in the test case
some_undefined_variable
- assert <span style="font-weight: bold"><span style="color: #0000FF">true</span></span>
-<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-</tt></pre></div></div>
-<div class="para"><p>Now you can see even more output in the console from running the tests:</p></div>
+ assert true
+end</p></div>
<div class="listingblock">
<div class="content">
-<pre><tt>$ ruby unit/post_test.rb -n test_should_report_error
+<pre><tt>
+Now you can see even more output in the console from running the tests:</tt></pre>
+</div></div>
+<div class="para"><p>$ ruby unit/post_test.rb -n test_should_report_error
Loaded suite unit/post_test
Started
E
-Finished in 0.195757 seconds.
-
- 1) Error:
+Finished in 0.195757 seconds.</p></div>
+<div class="literalblock">
+<div class="content">
+<pre><tt> 1) Error:
test_should_report_error(PostTest):
NameError: undefined local variable or method `some_undefined_variable' for #&lt;PostTest:0x2cc9de8&gt;
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.1.1/lib/action_controller/test_process.rb:467:in `method_missing'
unit/post_test.rb:16:in `test_should_report_error'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
- /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run'
-
-1 tests, 0 assertions, 0 failures, 1 errors</tt></pre>
+ /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run'</tt></pre>
</div></div>
-<div class="para"><p>Notice the <em>E</em> in the output. It denotes a test with error.</p></div>
-<div class="admonitionblock">
-<table><tr>
-<td class="icon">
-<img src="./images/icons/note.png" alt="Note" />
-</td>
-<td class="content">The execution of each test method stops as soon as any error or a assertion failure is encountered, and the test suite continues with the next method. All test methods are executed in alphabetical order.</td>
-</tr></table>
-</div>
-<h3 id="_what_to_include_in_your_unit_tests">3.3. What to Include in Your Unit Tests</h3>
-<div class="para"><p>Ideally you would like to include a test for everything which could possibly break. It's a good practice to have at least one test for each of your validations and at least one test for every method in your model.</p></div>
-<h3 id="_assertions_available">3.4. Assertions Available</h3>
-<div class="para"><p>By now you've caught a glimpse of some of the assertions that are available. Assertions are the worker bees of testing. They are the ones that actually perform the checks to ensure that things are going as planned.</p></div>
-<div class="para"><p>There are a bunch of different types of assertions you can use. Here's the complete list of assertions that ship with <tt>test/unit</tt>, the testing library used by Rails. The <tt>[msg]</tt> parameter is an optional string message you can specify to make your test failure messages clearer. It's not required.</p></div>
-<div class="tableblock">
-<table rules="all"
-frame="hsides"
-cellspacing="0" cellpadding="4">
-<col width="754" />
-<col width="834" />
-<thead>
- <tr>
- <th align="left">
- Assertion
- </th>
- <th align="left">
- Purpose
- </th>
- </tr>
-</thead>
-<tbody valign="top">
- <tr>
- <td align="left">
- <tt>assert( boolean, [msg] )</tt>
- </td>
- <td align="left">
- Ensures that the object/expression is true.
- </td>
- </tr>
- <tr>
- <td align="left">
- <tt>assert_equal( obj1, obj2, [msg] )</tt>
- </td>
- <td align="left">
- Ensures that <tt>obj1 == obj2</tt> is true.
- </td>
- </tr>
- <tr>
- <td align="left">
- <tt>assert_not_equal( obj1, obj2, [msg] )</tt>
- </td>
- <td align="left">
- Ensures that <tt>obj1 == obj2</tt> is false.
- </td>
- </tr>
- <tr>
- <td align="left">
- <tt>assert_same( obj1, obj2, [msg] )</tt>
- </td>
- <td align="left">
- Ensures that <tt>obj1.equal?(obj2)</tt> is true.
- </td>
- </tr>
- <tr>
- <td align="left">
- <tt>assert_not_same( obj1, obj2, [msg] )</tt>
- </td>
- <td align="left">
- Ensures that <tt>obj1.equal?(obj2)</tt> is false.
- </td>
- </tr>
- <tr>
- <td align="left">
- <tt>assert_nil( obj, [msg] )</tt>
- </td>
- <td align="left">
- Ensures that <tt>obj.nil?</tt> is true.
- </td>
- </tr>
- <tr>
- <td align="left">
- <tt>assert_not_nil( obj, [msg] )</tt>
- </td>
- <td align="left">
- Ensures that <tt>obj.nil?</tt> is false.
- </td>
- </tr>
- <tr>
- <td align="left">
- <tt>assert_match( regexp, string, [msg] )</tt>
- </td>
- <td align="left">
- Ensures that a string matches the regular expression.
- </td>
- </tr>
- <tr>
- <td align="left">
- <tt>assert_no_match( regexp, string, [msg] )</tt>
- </td>
- <td align="left">
- Ensures that a string doesn't matches the regular expression.
- </td>
- </tr>
- <tr>
- <td align="left">
- <tt>assert_in_delta( expecting, actual, delta, [msg] )</tt>
- </td>
- <td align="left">
- Ensures that the numbers <tt>expecting</tt> and <tt>actual</tt> are within <tt>delta</tt> of each other.
- </td>
- </tr>
- <tr>
- <td align="left">
- <tt>assert_throws( symbol, [msg] ) { block }</tt>
- </td>
- <td align="left">
- Ensures that the given block throws the symbol.
- </td>
- </tr>
- <tr>
- <td align="left">
- <tt>assert_raises( exception1, exception2, &#8230; ) { block }</tt>
- </td>
- <td align="left">
- Ensures that the given block raises one of the given exceptions.
- </td>
- </tr>
- <tr>
- <td align="left">
- <tt>assert_nothing_raised( exception1, exception2, &#8230; ) { block }</tt>
- </td>
- <td align="left">
- Ensures that the given block doesn't raise one of the given exceptions.
- </td>
- </tr>
- <tr>
- <td align="left">
- <tt>assert_instance_of( class, obj, [msg] )</tt>
- </td>
- <td align="left">
- Ensures that <tt>obj</tt> is of the <tt>class</tt> type.
- </td>
- </tr>
- <tr>
- <td align="left">
- <tt>assert_kind_of( class, obj, [msg] )</tt>
- </td>
- <td align="left">
- Ensures that <tt>obj</tt> is or descends from <tt>class</tt>.
- </td>
- </tr>
- <tr>
- <td align="left">
- <tt>assert_respond_to( obj, symbol, [msg] )</tt>
- </td>
- <td align="left">
- Ensures that <tt>obj</tt> has a method called <tt>symbol</tt>.
- </td>
- </tr>
- <tr>
- <td align="left">
- <tt>assert_operator( obj1, operator, obj2, [msg] )</tt>
- </td>
- <td align="left">
- Ensures that <tt>obj1.operator(obj2)</tt> is true.
- </td>
- </tr>
- <tr>
- <td align="left">
- <tt>assert_send( array, [msg] )</tt>
- </td>
- <td align="left">
- Ensures that executing the method listed in <tt>array[1]</tt> on the object in <tt>array[0]</tt> with the parameters of <tt>array[2 and up]</tt> is true. This one is weird eh?
- </td>
- </tr>
- <tr>
- <td align="left">
- <tt>flunk( [msg] )</tt>
- </td>
- <td align="left">
- Ensures failure. This is useful to explicitly mark a test that isn't finished yet.
- </td>
- </tr>
-</tbody>
-</table>
-</div>
-<div class="para"><p>Because of the modular nature of the testing framework, it is possible to create your own assertions. In fact, that's exactly what Rails does. It includes some specialized assertions to make your life easier.</p></div>
-<div class="admonitionblock">
-<table><tr>
-<td class="icon">
-<img src="./images/icons/note.png" alt="Note" />
-</td>
-<td class="content">Creating your own assertions is an advanced topic that we won't cover in this tutorial.</td>
-</tr></table>
-</div>
-<h3 id="_rails_specific_assertions">3.5. Rails Specific Assertions</h3>
-<div class="para"><p>Rails adds some custom assertions of its own to the <tt>test/unit</tt> framework:</p></div>
-<div class="tableblock">
-<table rules="all"
-frame="hsides"
-cellspacing="0" cellpadding="4">
-<col width="948" />
-<col width="640" />
-<thead>
- <tr>
- <th align="left">
- Assertion
- </th>
- <th align="left">
- Purpose
- </th>
- </tr>
-</thead>
-<tbody valign="top">
- <tr>
- <td align="left">
- <tt>assert_valid(record)</tt>
- </td>
- <td align="left">
- Ensures that the passed record is valid by Active Record standards and returns any error messages if it is not.
- </td>
- </tr>
- <tr>
- <td align="left">
- <tt>assert_difference(expressions, difference = 1, message = nil) {|| &#8230;}</tt>
- </td>
- <td align="left">
- Test numeric difference between the return value of an expression as a result of what is evaluated in the yielded block.
- </td>
- </tr>
- <tr>
- <td align="left">
- <tt>assert_no_difference(expressions, message = nil, &amp;block)</tt>
- </td>
- <td align="left">
- Asserts that the numeric result of evaluating an expression is not changed before and after invoking the passed in block.
- </td>
- </tr>
- <tr>
- <td align="left">
- <tt>assert_recognizes(expected_options, path, extras={}, message=nil)</tt>
- </td>
- <td align="left">
- Asserts that the routing of the given path was handled correctly and that the parsed options (given in the expected_options hash) match path. Basically, it asserts that Rails recognizes the route given by expected_options.
- </td>
- </tr>
- <tr>
- <td align="left">
- <tt>assert_generates(expected_path, options, defaults={}, extras = {}, message=nil)</tt>
- </td>
- <td align="left">
- Asserts that the provided options can be used to generate the provided path. This is the inverse of assert_recognizes. The extras parameter is used to tell the request the names and values of additional request parameters that would be in a query string. The message parameter allows you to specify a custom error message for assertion failures.
- </td>
- </tr>
- <tr>
- <td align="left">
- <tt>assert_response(type, message = nil)</tt>
- </td>
- <td align="left">
- Asserts that the response comes with a specific status code. You can specify <tt>:success</tt> to indicate 200, <tt>:redirect</tt> to indicate 300-399, <tt>:missing</tt> to indicate 404, or <tt>:error</tt> to match the 500-599 range
- </td>
- </tr>
- <tr>
- <td align="left">
- <tt>assert_redirected_to(options = {}, message=nil)</tt>
- </td>
- <td align="left">
- Assert that the redirection options passed in match those of the redirect called in the latest action. This match can be partial, such that <tt>assert_redirected_to(:controller &#8658; "weblog")</tt> will also match the redirection of <tt>redirect_to(:controller &#8658; "weblog", :action &#8658; "show")</tt> and so on.
- </td>
- </tr>
- <tr>
- <td align="left">
- <tt>assert_template(expected = nil, message=nil)</tt>
- </td>
- <td align="left">
- Asserts that the request was rendered with the appropriate template file.
- </td>
- </tr>
-</tbody>
-</table>
-</div>
-<div class="para"><p>You'll see the usage of some of these assertions in the next chapter.</p></div>
-</div>
-<h2 id="_functional_tests_for_your_controllers">4. Functional Tests for Your Controllers</h2>
-<div class="sectionbody">
-<div class="para"><p>In Rails, testing the various actions of a single controller is called writing functional tests for that controller. Controllers handle the incoming web requests to your application and eventually respond with a rendered view.</p></div>
-<h3 id="_what_to_include_in_your_functional_tests">4.1. What to include in your Functional Tests</h3>
-<div class="para"><p>You should test for things such as:</p></div>
-<div class="ilist"><ul>
-<li>
-<p>
-was the web request successful?
-</p>
-</li>
-<li>
-<p>
-was the user redirected to the right page?
-</p>
-</li>
-<li>
-<p>
-was the user successfully authenticated?
-</p>
-</li>
-<li>
-<p>
-was the correct object stored in the response template?
-</p>
-</li>
-<li>
-<p>
-was the appropriate message displayed to the user in the view
-</p>
-</li>
-</ul></div>
-<div class="para"><p>Now that we have used Rails scaffold generator for our <tt>Post</tt> resource, it has already created the controller code and functional tests. You can take look at the file <tt>posts_controller_test.rb</tt> in the <tt>test/functional</tt> directory.</p></div>
-<div class="para"><p>Let me take you through one such test, <tt>test_should_get_index</tt> from the file <tt>posts_controller_test.rb</tt>.</p></div>
+<div class="para"><p>1 tests, 0 assertions, 0 failures, 1 errors</p></div>
<div class="listingblock">
-<div class="content"><!-- Generator: GNU source-highlight 2.9
-by Lorenzo Bettini
-http://www.lorenzobettini.it
-http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_should_get_index
- get <span style="color: #990000">:</span>index
- assert_response <span style="color: #990000">:</span>success
- assert_not_nil assigns<span style="color: #990000">(:</span>posts<span style="color: #990000">)</span>
-<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-</tt></pre></div></div>
-<div class="para"><p>In the <tt>test_should_get_index</tt> test, Rails simulates a request on the action called index, making sure the request was successful and also ensuring that it assigns a valid <tt>posts</tt> instance variable.</p></div>
-<div class="para"><p>The <tt>get</tt> method kicks off the web request and populates the results into the response. It accepts 4 arguments:</p></div>
-<div class="ilist"><ul>
-<li>
-<p>
-The action of the controller you are requesting. This can be in the form of a string or a symbol.
-</p>
-</li>
-<li>
-<p>
-An optional hash of request parameters to pass into the action (eg. query string parameters or post variables).
-</p>
-</li>
-<li>
-<p>
-An optional hash of session variables to pass along with the request.
-</p>
-</li>
-<li>
-<p>
-An optional hash of flash values.
-</p>
-</li>
-</ul></div>
-<div class="para"><p>Example: Calling the <tt>:show</tt> action, passing an <tt>id</tt> of 12 as the <tt>params</tt> and setting a <tt>user_id</tt> of 5 in the session:</p></div>
+<div class="content">
+<pre><tt>
+Notice the 'E' in the output. It denotes a test with error.
+
+NOTE: The execution of each test method stops as soon as any error or a assertion failure is encountered, and the test suite continues with the next method. All test methods are executed in alphabetical order.
+
+=== What to Include in Your Unit Tests ===
+
+Ideally you would like to include a test for everything which could possibly break. It's a good practice to have at least one test for each of your validations and at least one test for every method in your model.
+
+=== Assertions Available ===
+
+By now you've caught a glimpse of some of the assertions that are available. Assertions are the worker bees of testing. They are the ones that actually perform the checks to ensure that things are going as planned.
+
+There are a bunch of different types of assertions you can use. Here's the complete list of assertions that ship with +test/unit+, the testing library used by Rails. The +[msg]+ parameter is an optional string message you can specify to make your test failure messages clearer. It's not required.
+
+[grid="all"]
+`-----------------------------------------------------------------`------------------------------------------------------------------------
+Assertion Purpose</tt></pre>
+</div></div>
+<div class="para"><p><tt>assert( boolean, [msg] )</tt> Ensures that the object/expression is true.
+<tt>assert_equal( obj1, obj2, [msg] )</tt> Ensures that <tt>obj1 == obj2</tt> is true.
+<tt>assert_not_equal( obj1, obj2, [msg] )</tt> Ensures that <tt>obj1 == obj2</tt> is false.
+<tt>assert_same( obj1, obj2, [msg] )</tt> Ensures that <tt>obj1.equal?(obj2)</tt> is true.
+<tt>assert_not_same( obj1, obj2, [msg] )</tt> Ensures that <tt>obj1.equal?(obj2)</tt> is false.
+<tt>assert_nil( obj, [msg] )</tt> Ensures that <tt>obj.nil?</tt> is true.
+<tt>assert_not_nil( obj, [msg] )</tt> Ensures that <tt>obj.nil?</tt> is false.
+<tt>assert_match( regexp, string, [msg] )</tt> Ensures that a string matches the regular expression.
+<tt>assert_no_match( regexp, string, [msg] )</tt> Ensures that a string doesn't matches the regular expression.
+<tt>assert_in_delta( expecting, actual, delta, [msg] )</tt> Ensures that the numbers <tt>expecting</tt> and <tt>actual</tt> are within <tt>delta</tt> of each other.
+<tt>assert_throws( symbol, [msg] ) { block }</tt> Ensures that the given block throws the symbol.
+<tt>assert_raises( exception1, exception2, &#8230; ) { block }</tt> Ensures that the given block raises one of the given exceptions.
+<tt>assert_nothing_raised( exception1, exception2, &#8230; ) { block }</tt> Ensures that the given block doesn't raise one of the given exceptions.
+<tt>assert_instance_of( class, obj, [msg] )</tt> Ensures that <tt>obj</tt> is of the <tt>class</tt> type.
+<tt>assert_kind_of( class, obj, [msg] )</tt> Ensures that <tt>obj</tt> is or descends from <tt>class</tt>.
+<tt>assert_respond_to( obj, symbol, [msg] )</tt> Ensures that <tt>obj</tt> has a method called <tt>symbol</tt>.
+<tt>assert_operator( obj1, operator, obj2, [msg] )</tt> Ensures that <tt>obj1.operator(obj2)</tt> is true.
+<tt>assert_send( array, [msg] )</tt> Ensures that executing the method listed in <tt>array[1]</tt> on the object in <tt>array[0]</tt> with the parameters of <tt>array[2 and up]</tt> is true. This one is weird eh?
+<tt>flunk( [msg] )</tt> Ensures failure. This is useful to explicitly mark a test that isn't finished yet.</p></div>
<div class="listingblock">
-<div class="content"><!-- Generator: GNU source-highlight 2.9
-by Lorenzo Bettini
-http://www.lorenzobettini.it
-http://www.gnu.org/software/src-highlite -->
-<pre><tt>get<span style="color: #990000">(:</span>show<span style="color: #990000">,</span> <span style="color: #FF0000">{</span><span style="color: #FF0000">'id'</span> <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"12"</span><span style="color: #FF0000">}</span><span style="color: #990000">,</span> <span style="color: #FF0000">{</span><span style="color: #FF0000">'user_id'</span> <span style="color: #990000">=&gt;</span> <span style="color: #993399">5</span><span style="color: #FF0000">}</span><span style="color: #990000">)</span>
-</tt></pre></div></div>
-<div class="para"><p>Another example: Calling the <tt>:view</tt> action, passing an <tt>id</tt> of 12 as the <tt>params</tt>, this time with no session, but with a flash message.</p></div>
+<div class="content">
+<pre><tt>
+Because of the modular nature of the testing framework, it is possible to create your own assertions. In fact, that's exactly what Rails does. It includes some specialized assertions to make your life easier.
+
+NOTE: Creating your own assertions is an advanced topic that we won't cover in this tutorial.
+
+=== Rails Specific Assertions ===
+
+Rails adds some custom assertions of its own to the +test/unit+ framework:
+
+[grid="all"]
+`----------------------------------------------------------------------------------`-------------------------------------------------------
+Assertion Purpose</tt></pre>
+</div></div>
+<div class="para"><p><tt>assert_valid(record)</tt> Ensures that the passed record is valid by Active Record standards and returns any error messages if it is not.
+<tt>assert_difference(expressions, difference = 1, message = nil) {|| &#8230;}</tt> Test numeric difference between the return value of an expression as a result of what is evaluated in the yielded block.
+<tt>assert_no_difference(expressions, message = nil, &amp;block)</tt> Asserts that the numeric result of evaluating an expression is not changed before and after invoking the passed in block.
+<tt>assert_recognizes(expected_options, path, extras={}, message=nil)</tt> Asserts that the routing of the given path was handled correctly and that the parsed options (given in the expected_options hash) match path. Basically, it asserts that Rails recognizes the route given by expected_options.
+<tt>assert_generates(expected_path, options, defaults={}, extras = {}, message=nil)</tt> Asserts that the provided options can be used to generate the provided path. This is the inverse of assert_recognizes. The extras parameter is used to tell the request the names and values of additional request parameters that would be in a query string. The message parameter allows you to specify a custom error message for assertion failures.
+<tt>assert_response(type, message = nil)</tt> Asserts that the response comes with a specific status code. You can specify <tt>:success</tt> to indicate 200, <tt>:redirect</tt> to indicate 300-399, <tt>:missing</tt> to indicate 404, or <tt>:error</tt> to match the 500-599 range
+<tt>assert_redirected_to(options = {}, message=nil)</tt> Assert that the redirection options passed in match those of the redirect called in the latest action. This match can be partial, such that <tt>assert_redirected_to(:controller &#8658; "weblog")</tt> will also match the redirection of <tt>redirect_to(:controller &#8658; "weblog", :action &#8658; "show")</tt> and so on.
+<tt>assert_template(expected = nil, message=nil)</tt> Asserts that the request was rendered with the appropriate template file.</p></div>
<div class="listingblock">
-<div class="content"><!-- Generator: GNU source-highlight 2.9
-by Lorenzo Bettini
-http://www.lorenzobettini.it
-http://www.gnu.org/software/src-highlite -->
-<pre><tt>get<span style="color: #990000">(:</span>view<span style="color: #990000">,</span> <span style="color: #FF0000">{</span><span style="color: #FF0000">'id'</span> <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">'12'</span><span style="color: #FF0000">}</span><span style="color: #990000">,</span> <span style="font-weight: bold"><span style="color: #0000FF">nil</span></span><span style="color: #990000">,</span> <span style="color: #FF0000">{</span><span style="color: #FF0000">'message'</span> <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">'booya!'</span><span style="color: #FF0000">}</span><span style="color: #990000">)</span>
-</tt></pre></div></div>
-<div class="admonitionblock">
-<table><tr>
-<td class="icon">
-<img src="./images/icons/note.png" alt="Note" />
-</td>
-<td class="content">If you try running <tt>test_should_create_post</tt> test from <tt>posts_controller_test.rb</tt> it will fail on account of the newly added model level validation and rightly so.</td>
-</tr></table>
-</div>
-<div class="para"><p>Let us modify <tt>test_should_create_post</tt> test in <tt>posts_controller_test.rb</tt> so that all our test pass:</p></div>
+<div class="content">
+<pre><tt>
+You'll see the usage of some of these assertions in the next chapter.
+
+== Functional Tests for Your Controllers ==
+
+In Rails, testing the various actions of a single controller is called writing functional tests for that controller. Controllers handle the incoming web requests to your application and eventually respond with a rendered view.
+
+=== What to include in your Functional Tests ===
+
+You should test for things such as:
+
+ * was the web request successful?
+ * was the user redirected to the right page?
+ * was the user successfully authenticated?
+ * was the correct object stored in the response template?
+ * was the appropriate message displayed to the user in the view
+
+Now that we have used Rails scaffold generator for our +Post+ resource, it has already created the controller code and functional tests. You can take look at the file +posts_controller_test.rb+ in the +test/functional+ directory.
+
+Let me take you through one such test, +test_should_get_index+ from the file +posts_controller_test.rb+.
+
+[source,ruby]</tt></pre>
+</div></div>
+<div class="para"><p>def test_should_get_index
+ get :index
+ assert_response :success
+ assert_not_nil assigns(:posts)
+end</p></div>
<div class="listingblock">
-<div class="content"><!-- Generator: GNU source-highlight 2.9
-by Lorenzo Bettini
-http://www.lorenzobettini.it
-http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_should_create_post
- assert_difference<span style="color: #990000">(</span><span style="color: #FF0000">'Post.count'</span><span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">do</span></span>
- post <span style="color: #990000">:</span>create<span style="color: #990000">,</span> <span style="color: #990000">:</span>post <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">{</span> <span style="color: #990000">:</span>title <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">'Some title'</span><span style="color: #FF0000">}</span>
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+<div class="content">
+<pre><tt>
+In the +test_should_get_index+ test, Rails simulates a request on the action called index, making sure the request was successful and also ensuring that it assigns a valid +posts+ instance variable.
- assert_redirected_to post_path<span style="color: #990000">(</span>assigns<span style="color: #990000">(:</span>post<span style="color: #990000">))</span>
-<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-</tt></pre></div></div>
-<div class="para"><p>Now you can try running all the tests and they should pass.</p></div>
-<h3 id="_available_request_types_for_functional_tests">4.2. Available Request Types for Functional Tests</h3>
-<div class="para"><p>If you're familiar with the HTTP protocol, you'll know that <tt>get</tt> is a type of request. There are 5 request types supported in Rails functional tests:</p></div>
-<div class="ilist"><ul>
-<li>
-<p>
-<tt>get</tt>
-</p>
-</li>
-<li>
-<p>
-<tt>post</tt>
-</p>
-</li>
-<li>
-<p>
-<tt>put</tt>
-</p>
-</li>
-<li>
-<p>
-<tt>head</tt>
-</p>
-</li>
-<li>
-<p>
-<tt>delete</tt>
-</p>
-</li>
-</ul></div>
-<div class="para"><p>All of request types are methods that you can use, however, you'll probably end up using the first two more often than the others.</p></div>
-<h3 id="_the_4_hashes_of_the_apocalypse">4.3. The 4 Hashes of the Apocalypse</h3>
-<div class="para"><p>After a request has been made by using one of the 5 methods (<tt>get</tt>, <tt>post</tt>, etc.) and processed, you will have 4 Hash objects ready for use:</p></div>
-<div class="ilist"><ul>
-<li>
-<p>
-<tt>assigns</tt> - Any objects that are stored as instance variables in actions for use in views.
-</p>
-</li>
-<li>
-<p>
-<tt>cookies</tt> - Any cookies that are set.
-</p>
-</li>
-<li>
-<p>
-<tt>flash</tt> - Any objects living in the flash.
-</p>
-</li>
-<li>
-<p>
-<tt>session</tt> - Any object living in session variables.
-</p>
-</li>
-</ul></div>
-<div class="para"><p>As is the case with normal Hash objects, you can access the values by referencing the keys by string. You can also reference them by symbol name, except for <tt>assigns</tt>. For example:</p></div>
+The +get+ method kicks off the web request and populates the results into the response. It accepts 4 arguments:
+
+* The action of the controller you are requesting. This can be in the form of a string or a symbol.
+* An optional hash of request parameters to pass into the action (eg. query string parameters or post variables).
+* An optional hash of session variables to pass along with the request.
+* An optional hash of flash values.
+
+Example: Calling the +:show+ action, passing an +id+ of 12 as the +params+ and setting a +user_id+ of 5 in the session:
+
+[source,ruby]</tt></pre>
+</div></div>
+<div class="para"><p>get(:show, {<em>id</em> &#8658; "12"}, {<em>user_id</em> &#8658; 5})</p></div>
<div class="listingblock">
-<div class="content"><!-- Generator: GNU source-highlight 2.9
-by Lorenzo Bettini
-http://www.lorenzobettini.it
-http://www.gnu.org/software/src-highlite -->
-<pre><tt> flash<span style="color: #990000">[</span><span style="color: #FF0000">"gordon"</span><span style="color: #990000">]</span> flash<span style="color: #990000">[:</span>gordon<span style="color: #990000">]</span>
- session<span style="color: #990000">[</span><span style="color: #FF0000">"shmession"</span><span style="color: #990000">]</span> session<span style="color: #990000">[:</span>shmession<span style="color: #990000">]</span>
- cookies<span style="color: #990000">[</span><span style="color: #FF0000">"are_good_for_u"</span><span style="color: #990000">]</span> cookies<span style="color: #990000">[:</span>are_good_for_u<span style="color: #990000">]</span>
+<div class="content">
+<pre><tt>
+Another example: Calling the +:view+ action, passing an +id+ of 12 as the +params+, this time with no session, but with a flash message.
-<span style="font-style: italic"><span style="color: #9A1900"># Because you can't use assigns[:something] for historical reasons:</span></span>
- assigns<span style="color: #990000">[</span><span style="color: #FF0000">"something"</span><span style="color: #990000">]</span> assigns<span style="color: #990000">(:</span>something<span style="color: #990000">)</span>
-</tt></pre></div></div>
-<h3 id="_instance_variables_available">4.4. Instance Variables Available</h3>
-<div class="para"><p>You also have access to three instance variables in your functional tests:</p></div>
-<div class="ilist"><ul>
-<li>
-<p>
-<tt>@controller</tt> - The controller processing the request
-</p>
-</li>
-<li>
-<p>
-<tt>@request</tt> - The request
-</p>
-</li>
-<li>
-<p>
-<tt>@response</tt> - The response
-</p>
-</li>
-</ul></div>
-<h3 id="_a_fuller_functional_test_example">4.5. A Fuller Functional Test Example</h3>
-<div class="para"><p>Here's another example that uses <tt>flash</tt>, <tt>assert_redirected_to</tt>, and <tt>assert_difference</tt>:</p></div>
+[source,ruby]</tt></pre>
+</div></div>
+<div class="para"><p>get(:view, {<em>id</em> &#8658; <em>12</em>}, nil, {<em>message</em> &#8658; <em>booya!</em>})</p></div>
<div class="listingblock">
-<div class="content"><!-- Generator: GNU source-highlight 2.9
-by Lorenzo Bettini
-http://www.lorenzobettini.it
-http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_should_create_post
- assert_difference<span style="color: #990000">(</span><span style="color: #FF0000">'Post.count'</span><span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">do</span></span>
- post <span style="color: #990000">:</span>create<span style="color: #990000">,</span> <span style="color: #990000">:</span>post <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">{</span> <span style="color: #990000">:</span>title <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">'Hi'</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>body <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">'This is my first post.'</span><span style="color: #FF0000">}</span>
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
- assert_redirected_to post_path<span style="color: #990000">(</span>assigns<span style="color: #990000">(:</span>post<span style="color: #990000">))</span>
- assert_equal <span style="color: #FF0000">'Post was successfully created.'</span><span style="color: #990000">,</span> flash<span style="color: #990000">[:</span>notice<span style="color: #990000">]</span>
-<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-</tt></pre></div></div>
-<h3 id="_testing_views">4.6. Testing Views</h3>
-<div class="para"><p>Testing the response to your request by asserting the presence of key HTML elements and their content is a useful way to test the views of your application. The <tt>assert_select</tt> assertion allows you to do this by using a simple yet powerful syntax.</p></div>
-<div class="admonitionblock">
-<table><tr>
-<td class="icon">
-<img src="./images/icons/note.png" alt="Note" />
-</td>
-<td class="content">You may find references to <tt>assert_tag</tt> in other documentation, but this is now deprecated in favor of <tt>assert_select</tt>.</td>
-</tr></table>
-</div>
-<div class="para"><p>There are two forms of <tt>assert_select</tt>:</p></div>
-<div class="para"><p><tt>assert_select(selector, [equality], [message])`</tt> ensures that the equality condition is met on the selected elements through the selector. The selector may be a CSS selector expression (String), an expression with substitution values, or an <tt>HTML::Selector</tt> object.</p></div>
-<div class="para"><p><tt>assert_select(element, selector, [equality], [message])</tt> ensures that the equality condition is met on all the selected elements through the selector starting from the <em>element</em> (instance of <tt>HTML::Node</tt>) and its descendants.</p></div>
-<div class="para"><p>For example, you could verify the contents on the title element in your response with:</p></div>
+<div class="content">
+<pre><tt>
+NOTE: If you try running +test_should_create_post+ test from +posts_controller_test.rb+ it will fail on account of the newly added model level validation and rightly so.
+
+Let us modify +test_should_create_post+ test in +posts_controller_test.rb+ so that all our test pass:
+
+[source,ruby]</tt></pre>
+</div></div>
+<div class="para"><p>def test_should_create_post
+ assert_difference(<em>Post.count</em>) do
+ post :create, :post &#8658; { :title &#8658; <em>Some title</em>}
+ end</p></div>
+<div class="literalblock">
+<div class="content">
+<pre><tt> assert_redirected_to post_path(assigns(:post))
+end</tt></pre>
+</div></div>
<div class="listingblock">
-<div class="content"><!-- Generator: GNU source-highlight 2.9
-by Lorenzo Bettini
-http://www.lorenzobettini.it
-http://www.gnu.org/software/src-highlite -->
-<pre><tt>assert_select <span style="color: #FF0000">'title'</span><span style="color: #990000">,</span> <span style="color: #FF0000">"Welcome to Rails Testing Guide"</span>
-</tt></pre></div></div>
-<div class="para"><p>You can also use nested <tt>assert_select</tt> blocks. In this case the inner <tt>assert_select</tt> will run the assertion on each element selected by the outer <tt>assert_select</tt> block:</p></div>
+<div class="content">
+<pre><tt>
+Now you can try running all the tests and they should pass.
+
+=== Available Request Types for Functional Tests ===
+
+If you're familiar with the HTTP protocol, you'll know that +get+ is a type of request. There are 5 request types supported in Rails functional tests:
+
+* +get+
+* +post+
+* +put+
+* +head+
+* +delete+
+
+All of request types are methods that you can use, however, you'll probably end up using the first two more often than the others.
+
+=== The 4 Hashes of the Apocalypse ===
+
+After a request has been made by using one of the 5 methods (+get+, +post+, etc.) and processed, you will have 4 Hash objects ready for use:
+
+* +assigns+ - Any objects that are stored as instance variables in actions for use in views.
+* +cookies+ - Any cookies that are set.
+* +flash+ - Any objects living in the flash.
+* +session+ - Any object living in session variables.
+
+As is the case with normal Hash objects, you can access the values by referencing the keys by string. You can also reference them by symbol name, except for +assigns+. For example:
+
+[source,ruby]</tt></pre>
+</div></div>
+<div class="literalblock">
+<div class="content">
+<pre><tt>flash["gordon"] flash[:gordon]
+session["shmession"] session[:shmession]
+cookies["are_good_for_u"] cookies[:are_good_for_u]</tt></pre>
+</div></div>
+<div class="para"><p># Because you can't use assigns[:something] for historical reasons:
+ assigns["something"] assigns(:something)</p></div>
<div class="listingblock">
-<div class="content"><!-- Generator: GNU source-highlight 2.9
-by Lorenzo Bettini
-http://www.lorenzobettini.it
-http://www.gnu.org/software/src-highlite -->
-<pre><tt>assert_select <span style="color: #FF0000">'ul.navigation'</span> <span style="font-weight: bold"><span style="color: #0000FF">do</span></span>
- assert_select <span style="color: #FF0000">'li.menu_item'</span>
-<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-</tt></pre></div></div>
-<div class="para"><p>The <tt>assert_select</tt> assertion is quite powerful. For more advanced usage, refer to its <a href="http://api.rubyonrails.com/classes/ActionController/Assertions/SelectorAssertions.html#M000749">documentation</a>.</p></div>
-<h4 id="_additional_view_based_assertions">4.6.1. Additional View-based Assertions</h4>
-<div class="para"><p>There are more assertions that are primarily used in testing views:</p></div>
-<div class="tableblock">
-<table rules="all"
-frame="hsides"
-cellspacing="0" cellpadding="4">
-<col width="948" />
-<col width="640" />
-<thead>
- <tr>
- <th align="left">
- Assertion
- </th>
- <th align="left">
- Purpose
- </th>
- </tr>
-</thead>
-<tbody valign="top">
- <tr>
- <td align="left">
- <tt>assert_select_email</tt>
- </td>
- <td align="left">
- Allows you to make assertions on the body of an e-mail.
- </td>
- </tr>
- <tr>
- <td align="left">
- <tt>assert_select_rjs</tt>
- </td>
- <td align="left">
- Allows you to make assertions on RJS response. <tt>assert_select_rjs</tt> has variants which allow you to narrow down on the updated element or even a particular operation on an element.
- </td>
- </tr>
- <tr>
- <td align="left">
- <tt>assert_select_encoded</tt>
- </td>
- <td align="left">
- Allows you to make assertions on encoded HTML. It does this by un-encoding the contents of each element and then calling the block with all the un-encoded elements.
- </td>
- </tr>
- <tr>
- <td align="left">
- <tt>css_select(selector)</tt> or <tt>css_select(element, selector)</tt>
- </td>
- <td align="left">
- Returns an array of all the elements selected by the <em>selector</em>. In the second variant it first matches the base <em>element</em> and tries to match the <em>selector</em> expression on any of its children. If there are no matches both variants return an empty array.
- </td>
- </tr>
-</tbody>
-</table>
-</div>
-<div class="para"><p>Here's an example of using <tt>assert_select_email</tt>:</p></div>
+<div class="content">
+<pre><tt>
+=== Instance Variables Available ===
+
+You also have access to three instance variables in your functional tests:
+
+* +@controller+ - The controller processing the request
+* +@request+ - The request
+* +@response+ - The response
+
+=== A Fuller Functional Test Example
+
+Here's another example that uses +flash+, +assert_redirected_to+, and +assert_difference+:
+
+[source,ruby]</tt></pre>
+</div></div>
+<div class="para"><p>def test_should_create_post
+ assert_difference(<em>Post.count</em>) do
+ post :create, :post &#8658; { :title &#8658; <em>Hi</em>, :body &#8658; <em>This is my first post.</em>}
+ end
+ assert_redirected_to post_path(assigns(:post))
+ assert_equal <em>Post was successfully created.</em>, flash[:notice]
+end</p></div>
<div class="listingblock">
-<div class="content"><!-- Generator: GNU source-highlight 2.9
-by Lorenzo Bettini
-http://www.lorenzobettini.it
-http://www.gnu.org/software/src-highlite -->
-<pre><tt>assert_select_email <span style="font-weight: bold"><span style="color: #0000FF">do</span></span>
- assert_select <span style="color: #FF0000">'small'</span><span style="color: #990000">,</span> <span style="color: #FF0000">'Please click the "Unsubscribe" link if you want to opt-out.'</span>
-<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-</tt></pre></div></div>
-</div>
-<h2 id="_integration_testing">5. Integration Testing</h2>
-<div class="sectionbody">
-<div class="para"><p>Integration tests are used to test the interaction among any number of controllers. They are generally used to test important work flows within your application.</p></div>
-<div class="para"><p>Unlike Unit and Functional tests, integration tests have to be explicitly created under the <em>test/integration</em> folder within your application. Rails provides a generator to create an integration test skeleton for you.</p></div>
+<div class="content">
+<pre><tt>
+=== Testing Views ===
+
+Testing the response to your request by asserting the presence of key HTML elements and their content is a useful way to test the views of your application. The +assert_select+ assertion allows you to do this by using a simple yet powerful syntax.
+
+NOTE: You may find references to +assert_tag+ in other documentation, but this is now deprecated in favor of +assert_select+.
+
+There are two forms of +assert_select+:
+
++assert_select(selector, [equality], [message])`+ ensures that the equality condition is met on the selected elements through the selector. The selector may be a CSS selector expression (String), an expression with substitution values, or an +HTML::Selector+ object.
+
++assert_select(element, selector, [equality], [message])+ ensures that the equality condition is met on all the selected elements through the selector starting from the _element_ (instance of +HTML::Node+) and its descendants.
+
+For example, you could verify the contents on the title element in your response with:
+
+[source,ruby]</tt></pre>
+</div></div>
+<div class="para"><p>assert_select <em>title</em>, "Welcome to Rails Testing Guide"</p></div>
<div class="listingblock">
-<div class="content"><!-- Generator: GNU source-highlight 2.9
-by Lorenzo Bettini
-http://www.lorenzobettini.it
-http://www.gnu.org/software/src-highlite -->
-<pre><tt>$ script/generate integration_test user_flows
- exists test/integration<span style="color: #990000">/</span>
- create test/integration/user_flows_test<span style="color: #990000">.</span>rb
-</tt></pre></div></div>
-<div class="para"><p>Here's what a freshly-generated integration test looks like:</p></div>
+<div class="content">
+<pre><tt>
+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:
+
+[source,ruby]</tt></pre>
+</div></div>
+<div class="para"><p>assert_select <em>ul.navigation</em> do
+ assert_select <em>li.menu_item</em>
+end</p></div>
<div class="listingblock">
-<div class="content"><!-- Generator: GNU source-highlight 2.9
-by Lorenzo Bettini
-http://www.lorenzobettini.it
-http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'test_helper'</span>
+<div class="content">
+<pre><tt>
+The +assert_select+ assertion is quite powerful. For more advanced usage, refer to its link:http://api.rubyonrails.com/classes/ActionController/Assertions/SelectorAssertions.html#M000749[documentation].
-<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> UserFlowsTest <span style="color: #990000">&lt;</span> ActionController<span style="color: #990000">::</span>IntegrationTest
- <span style="font-style: italic"><span style="color: #9A1900"># fixtures :your, :models</span></span>
+==== Additional View-based Assertions ====
- <span style="font-style: italic"><span style="color: #9A1900"># Replace this with your real tests.</span></span>
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_truth
- assert <span style="font-weight: bold"><span style="color: #0000FF">true</span></span>
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-</tt></pre></div></div>
-<div class="para"><p>Integration tests inherit from <tt>ActionController::IntegrationTest</tt>. This makes available some additional helpers to use in your integration tests. Also you need to explicitly include the fixtures to be made available to the test.</p></div>
-<h3 id="_helpers_available_for_integration_tests">5.1. Helpers Available for Integration tests</h3>
-<div class="para"><p>In addition to the standard testing helpers, there are some additional helpers available to integration tests:</p></div>
-<div class="tableblock">
-<table rules="all"
-frame="hsides"
-cellspacing="0" cellpadding="4">
-<col width="948" />
-<col width="640" />
-<thead>
- <tr>
- <th align="left">
- Helper
- </th>
- <th align="left">
- Purpose
- </th>
- </tr>
-</thead>
-<tbody valign="top">
- <tr>
- <td align="left">
- <tt>https?</tt>
- </td>
- <td align="left">
- Returns <tt>true</tt> if the session is mimicking a secure HTTPS request.
- </td>
- </tr>
- <tr>
- <td align="left">
- <tt>https!</tt>
- </td>
- <td align="left">
- Allows you to mimic a secure HTTPS request.
- </td>
- </tr>
- <tr>
- <td align="left">
- <tt>host!</tt>
- </td>
- <td align="left">
- Allows you to set the host name to use in the next request.
- </td>
- </tr>
- <tr>
- <td align="left">
- <tt>redirect?</tt>
- </td>
- <td align="left">
- Returns <tt>true</tt> if the last request was a redirect.
- </td>
- </tr>
- <tr>
- <td align="left">
- <tt>follow_redirect!</tt>
- </td>
- <td align="left">
- Follows a single redirect response.
- </td>
- </tr>
- <tr>
- <td align="left">
- <tt>request_via_redirect(http_method, path, [parameters], [headers])</tt>
- </td>
- <td align="left">
- Allows you to make an HTTP request and follow any subsequent redirects.
- </td>
- </tr>
- <tr>
- <td align="left">
- <tt>post_via_redirect(path, [parameters], [headers])</tt>
- </td>
- <td align="left">
- Allows you to make an HTTP POST request and follow any subsequent redirects.
- </td>
- </tr>
- <tr>
- <td align="left">
- <tt>get_via_redirect(path, [parameters], [headers])</tt>
- </td>
- <td align="left">
- Allows you to make an HTTP GET request and follow any subsequent redirects.
- </td>
- </tr>
- <tr>
- <td align="left">
- <tt>put_via_redirect(path, [parameters], [headers])</tt>
- </td>
- <td align="left">
- Allows you to make an HTTP PUT request and follow any subsequent redirects.
- </td>
- </tr>
- <tr>
- <td align="left">
- <tt>delete_via_redirect(path, [parameters], [headers])</tt>
- </td>
- <td align="left">
- Allows you to make an HTTP DELETE request and follow any subsequent redirects.
- </td>
- </tr>
- <tr>
- <td align="left">
- <tt>open_session</tt>
- </td>
- <td align="left">
- Opens a new session instance.
- </td>
- </tr>
-</tbody>
-</table>
-</div>
-<h3 id="_integration_testing_examples">5.2. Integration Testing Examples</h3>
-<div class="para"><p>A simple integration test that exercises multiple controllers:</p></div>
+There are more assertions that are primarily used in testing views:
+
+[grid="all"]
+`----------------------------------------------------------------------------------`-------------------------------------------------------
+Assertion Purpose</tt></pre>
+</div></div>
+<div class="para"><p><tt>assert_select_email</tt> Allows you to make assertions on the body of an e-mail.
+<tt>assert_select_rjs</tt> Allows you to make assertions on RJS response. <tt>assert_select_rjs</tt> has variants which allow you to narrow down on the updated element or even a particular operation on an element.
+<tt>assert_select_encoded</tt> Allows you to make assertions on encoded HTML. It does this by un-encoding the contents of each element and then calling the block with all the un-encoded elements.
+<tt>css_select(selector)</tt> or <tt>css_select(element, selector)</tt> Returns an array of all the elements selected by the <em>selector</em>. In the second variant it first matches the base <em>element</em> and tries to match the <em>selector</em> expression on any of its children. If there are no matches both variants return an empty array.</p></div>
<div class="listingblock">
-<div class="content"><!-- Generator: GNU source-highlight 2.9
-by Lorenzo Bettini
-http://www.lorenzobettini.it
-http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'test_helper'</span>
+<div class="content">
+<pre><tt>
+Here's an example of using +assert_select_email+:
-<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> UserFlowsTest <span style="color: #990000">&lt;</span> ActionController<span style="color: #990000">::</span>IntegrationTest
- fixtures <span style="color: #990000">:</span>users
+[source,ruby]</tt></pre>
+</div></div>
+<div class="para"><p>assert_select_email do
+ assert_select <em>small</em>, <em>Please click the "Unsubscribe" link if you want to opt-out.</em>
+end</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>
+== Integration Testing ==
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_login_and_browse_site
- <span style="font-style: italic"><span style="color: #9A1900"># login via https</span></span>
- https!
- get <span style="color: #FF0000">"/login"</span>
- assert_response <span style="color: #990000">:</span>success
+Integration tests are used to test the interaction among any number of controllers. They are generally used to test important work flows within your application.
- post_via_redirect <span style="color: #FF0000">"/login"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>username <span style="color: #990000">=&gt;</span> users<span style="color: #990000">(:</span>avs<span style="color: #990000">).</span>username<span style="color: #990000">,</span> <span style="color: #990000">:</span>password <span style="color: #990000">=&gt;</span> users<span style="color: #990000">(:</span>avs<span style="color: #990000">).</span>password
- assert_equal <span style="color: #FF0000">'/welcome'</span><span style="color: #990000">,</span> path
- assert_equal <span style="color: #FF0000">'Welcome avs!'</span><span style="color: #990000">,</span> flash<span style="color: #990000">[:</span>notice<span style="color: #990000">]</span>
+Unlike Unit and Functional tests, integration tests have to be explicitly created under the 'test/integration' folder within your application. Rails provides a generator to create an integration test skeleton for you.
- https!<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">false</span></span><span style="color: #990000">)</span>
- get <span style="color: #FF0000">"/posts/all"</span>
- assert_response <span style="color: #990000">:</span>success
- assert assigns<span style="color: #990000">(:</span>products<span style="color: #990000">)</span>
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-</tt></pre></div></div>
-<div class="para"><p>As you can see the integration test involves multiple controllers and exercises the entire stack from database to dispatcher. In addition you can have multiple session instances open simultaneously in a test and extend those instances with assertion methods to create a very powerful testing DSL (domain-specific language) just for your application.</p></div>
-<div class="para"><p>Here's an example of multiple sessions and custom DSL in an integration test</p></div>
+[source, shell]</tt></pre>
+</div></div>
+<div class="para"><p>$ script/generate integration_test user_flows
+ exists test/integration/
+ create test/integration/user_flows_test.rb</p></div>
<div class="listingblock">
-<div class="content"><!-- Generator: GNU source-highlight 2.9
-by Lorenzo Bettini
-http://www.lorenzobettini.it
-http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'test_helper'</span>
+<div class="content">
+<pre><tt>
+Here's what a freshly-generated integration test looks like:
-<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> UserFlowsTest <span style="color: #990000">&lt;</span> ActionController<span style="color: #990000">::</span>IntegrationTest
- fixtures <span style="color: #990000">:</span>users
+[source,ruby]</tt></pre>
+</div></div>
+<div class="para"><p>require <em>test_helper</em></p></div>
+<div class="para"><p>class UserFlowsTest &lt; ActionController::IntegrationTest
+ # fixtures :your, :models</p></div>
+<div class="literalblock">
+<div class="content">
+<pre><tt> # Replace this with your real tests.
+ def test_truth
+ assert true
+ end
+end</tt></pre>
+</div></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>
+Integration tests inherit from +ActionController::IntegrationTest+. This makes available some additional helpers to use in your integration tests. Also you need to explicitly include the fixtures to be made available to the test.
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_login_and_browse_site
+=== Helpers Available for Integration tests ===
- <span style="font-style: italic"><span style="color: #9A1900"># User avs logs in</span></span>
- avs <span style="color: #990000">=</span> login<span style="color: #990000">(:</span>avs<span style="color: #990000">)</span>
- <span style="font-style: italic"><span style="color: #9A1900"># User guest logs in</span></span>
- guest <span style="color: #990000">=</span> login<span style="color: #990000">(:</span>guest<span style="color: #990000">)</span>
+In addition to the standard testing helpers, there are some additional helpers available to integration tests:
- <span style="font-style: italic"><span style="color: #9A1900"># Both are now available in different sessions</span></span>
- assert_equal <span style="color: #FF0000">'Welcome avs!'</span><span style="color: #990000">,</span> avs<span style="color: #990000">.</span>flash<span style="color: #990000">[:</span>notice<span style="color: #990000">]</span>
- assert_equal <span style="color: #FF0000">'Welcome guest!'</span><span style="color: #990000">,</span> guest<span style="color: #990000">.</span>flash<span style="color: #990000">[:</span>notice<span style="color: #990000">]</span>
+[grid="all"]
+`----------------------------------------------------------------------------------`-------------------------------------------------------
+Helper Purpose</tt></pre>
+</div></div>
+<div class="para"><p><tt>https?</tt> Returns <tt>true</tt> if the session is mimicking a secure HTTPS request.
+<tt>https!</tt> Allows you to mimic a secure HTTPS request.
+<tt>host!</tt> Allows you to set the host name to use in the next request.
+<tt>redirect?</tt> Returns <tt>true</tt> if the last request was a redirect.
+<tt>follow_redirect!</tt> Follows a single redirect response.
+<tt>request_via_redirect(http_method, path, [parameters], [headers])</tt> Allows you to make an HTTP request and follow any subsequent redirects.
+<tt>post_via_redirect(path, [parameters], [headers])</tt> Allows you to make an HTTP POST request and follow any subsequent redirects.
+<tt>get_via_redirect(path, [parameters], [headers])</tt> Allows you to make an HTTP GET request and follow any subsequent redirects.
+<tt>put_via_redirect(path, [parameters], [headers])</tt> Allows you to make an HTTP PUT request and follow any subsequent redirects.
+<tt>delete_via_redirect(path, [parameters], [headers])</tt> Allows you to make an HTTP DELETE request and follow any subsequent redirects.
+<tt>open_session</tt> Opens a new session instance.</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>
+=== Integration Testing Examples ===
- <span style="font-style: italic"><span style="color: #9A1900"># User avs can browse site</span></span>
- avs<span style="color: #990000">.</span>browses_site
- <span style="font-style: italic"><span style="color: #9A1900"># User guest can browse site aswell</span></span>
- guest<span style="color: #990000">.</span>browses_site
+A simple integration test that exercises multiple controllers:
- <span style="font-style: italic"><span style="color: #9A1900"># Continue with other assertions</span></span>
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+[source,ruby]</tt></pre>
+</div></div>
+<div class="para"><p>require <em>test_helper</em></p></div>
+<div class="para"><p>class UserFlowsTest &lt; ActionController::IntegrationTest
+ fixtures :users</p></div>
+<div class="literalblock">
+<div class="content">
+<pre><tt>def test_login_and_browse_site
+ # login via https
+ https!
+ get "/login"
+ assert_response :success</tt></pre>
+</div></div>
+<div class="literalblock">
+<div class="content">
+<pre><tt>post_via_redirect "/login", :username =&gt; users(:avs).username, :password =&gt; users(:avs).password
+assert_equal '/welcome', path
+assert_equal 'Welcome avs!', flash[:notice]</tt></pre>
+</div></div>
+<div class="literalblock">
+<div class="content">
+<pre><tt> https!(false)
+ get "/posts/all"
+ assert_response :success
+ assert assigns(:products)
+ end
+end</tt></pre>
+</div></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>
+As you can see the integration test involves multiple controllers and exercises the entire stack from database to dispatcher. In addition you can have multiple session instances open simultaneously in a test and extend those instances with assertion methods to create a very powerful testing DSL (domain-specific language) just for your application.
- private
+Here's an example of multiple sessions and custom DSL in an integration test
- <span style="font-weight: bold"><span style="color: #0000FF">module</span></span> CustomDsl
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> browses_site
- get <span style="color: #FF0000">"/products/all"</span>
- assert_response <span style="color: #990000">:</span>success
- assert assigns<span style="color: #990000">(:</span>products<span style="color: #990000">)</span>
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+[source,ruby]</tt></pre>
+</div></div>
+<div class="para"><p>require <em>test_helper</em></p></div>
+<div class="para"><p>class UserFlowsTest &lt; ActionController::IntegrationTest
+ fixtures :users</p></div>
+<div class="literalblock">
+<div class="content">
+<pre><tt>def test_login_and_browse_site</tt></pre>
+</div></div>
+<div class="literalblock">
+<div class="content">
+<pre><tt># User avs logs in
+avs = login(:avs)
+# User guest logs in
+guest = login(:guest)</tt></pre>
+</div></div>
+<div class="literalblock">
+<div class="content">
+<pre><tt># Both are now available in different sessions
+assert_equal 'Welcome avs!', avs.flash[:notice]
+assert_equal 'Welcome guest!', guest.flash[:notice]</tt></pre>
+</div></div>
+<div class="literalblock">
+<div class="content">
+<pre><tt># User avs can browse site
+avs.browses_site
+# User guest can browse site aswell
+guest.browses_site</tt></pre>
+</div></div>
+<div class="literalblock">
+<div class="content">
+<pre><tt> # Continue with other assertions
+end</tt></pre>
+</div></div>
+<div class="literalblock">
+<div class="content">
+<pre><tt>private</tt></pre>
+</div></div>
+<div class="literalblock">
+<div class="content">
+<pre><tt>module CustomDsl
+ def browses_site
+ get "/products/all"
+ assert_response :success
+ assert assigns(:products)
+ end
+end</tt></pre>
+</div></div>
+<div class="literalblock">
+<div class="content">
+<pre><tt> def login(user)
+ open_session do |sess|
+ sess.extend(CustomDsl)
+ u = users(user)
+ sess.https!
+ sess.post "/login", :username =&gt; u.username, :password =&gt; u.password
+ assert_equal '/welcome', path
+ sess.https!(false)
+ end
+ end
+end</tt></pre>
+</div></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>
+== Rake Tasks for Running your Tests ==
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> login<span style="color: #990000">(</span>user<span style="color: #990000">)</span>
- open_session <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>sess<span style="color: #990000">|</span>
- sess<span style="color: #990000">.</span>extend<span style="color: #990000">(</span>CustomDsl<span style="color: #990000">)</span>
- u <span style="color: #990000">=</span> users<span style="color: #990000">(</span>user<span style="color: #990000">)</span>
- sess<span style="color: #990000">.</span>https!
- sess<span style="color: #990000">.</span>post <span style="color: #FF0000">"/login"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>username <span style="color: #990000">=&gt;</span> u<span style="color: #990000">.</span>username<span style="color: #990000">,</span> <span style="color: #990000">:</span>password <span style="color: #990000">=&gt;</span> u<span style="color: #990000">.</span>password
- assert_equal <span style="color: #FF0000">'/welcome'</span><span style="color: #990000">,</span> path
- sess<span style="color: #990000">.</span>https!<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">false</span></span><span style="color: #990000">)</span>
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-</tt></pre></div></div>
-</div>
-<h2 id="_rake_tasks_for_running_your_tests">6. Rake Tasks for Running your Tests</h2>
-<div class="sectionbody">
-<div class="para"><p>You don't need to set up and run your tests by hand on a test-by-test basis. Rails comes with a number of rake tasks to help in testing. The table below lists all rake tasks that come along in the default Rakefile when you initiate a Rail project.</p></div>
-<div class="para"><p>--------------------------------`----------------------------------------------------
-Tasks Description</p></div>
+You don't need to set up and run your tests by hand on a test-by-test basis. Rails comes with a number of rake tasks to help in testing. The table below lists all rake tasks that come along in the default Rakefile when you initiate a Rail project.
+
+[grid="all"]</tt></pre>
+</div></div>
+<div class="para"><p>Tasks Description</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>+rake test+ Runs all unit, functional and integration tests. You can also simply run +rake+ as the _test_ target is the default.
@@ -1584,7 +1146,7 @@ Tasks Description</p></div>
+rake test:plugins+ Run all the plugin tests from +vendor/plugins/*/**/test+ (or specify with +PLUGIN=_name_+)</tt></pre>
</div></div>
</div>
-<h2 id="_brief_note_about_test_unit">7. Brief Note About Test::Unit</h2>
+<h2 id="_brief_note_about_test_unit">4. Brief Note About Test::Unit</h2>
<div class="sectionbody">
<div class="para"><p>Ruby ships with a boat load of libraries. One little gem of a library is <tt>Test::Unit</tt>, a framework for unit testing in Ruby. All the basic assertions discussed above are actually defined in <tt>Test::Unit::Assertions</tt>. The class <tt>ActiveSupport::TestCase</tt> which we have been using in our unit and functional tests extends <tt>Test::Unit::TestCase</tt> that it is how we can use all the basic assertions in our tests.</p></div>
<div class="admonitionblock">
@@ -1596,7 +1158,7 @@ Tasks Description</p></div>
</tr></table>
</div>
</div>
-<h2 id="_setup_and_teardown">8. Setup and Teardown</h2>
+<h2 id="_setup_and_teardown">5. Setup and Teardown</h2>
<div class="sectionbody">
<div class="para"><p>If you would like to run a block of code before the start of each test and another block of code after the end of each test you have two special callbacks for your rescue. Let's take note of this by looking at an example for our functional test in <tt>Posts</tt> controller:</p></div>
<div class="listingblock">
@@ -1704,7 +1266,7 @@ http://www.gnu.org/software/src-highlite -->
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
</div>
-<h2 id="_testing_routes">9. Testing Routes</h2>
+<h2 id="_testing_routes">6. Testing Routes</h2>
<div class="sectionbody">
<div class="para"><p>Like everything else in you Rails application, it's recommended to test you routes. An example test for a route in the default <tt>show</tt> action of <tt>Posts</tt> controller above should look like:</p></div>
<div class="listingblock">
@@ -1717,10 +1279,10 @@ http://www.gnu.org/software/src-highlite -->
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
</div>
-<h2 id="_testing_your_mailers">10. Testing Your Mailers</h2>
+<h2 id="_testing_your_mailers">7. Testing Your Mailers</h2>
<div class="sectionbody">
<div class="para"><p>Testing mailer classes requires some specific tools to do a thorough job.</p></div>
-<h3 id="_keeping_the_postman_in_check">10.1. Keeping the Postman in Check</h3>
+<h3 id="_keeping_the_postman_in_check">7.1. Keeping the Postman in Check</h3>
<div class="para"><p>Your <tt>ActionMailer</tt> classes &#8212; like every other part of your Rails application &#8212; should be tested to ensure that it is working as expected.</p></div>
<div class="para"><p>The goals of testing your <tt>ActionMailer</tt> classes are to ensure that:</p></div>
<div class="ilist"><ul>
@@ -1740,14 +1302,14 @@ the right emails are being sent at the right times
</p>
</li>
</ul></div>
-<h4 id="_from_all_sides">10.1.1. From All Sides</h4>
+<h4 id="_from_all_sides">7.1.1. From All Sides</h4>
<div class="para"><p>There are two aspects of testing your mailer, the unit tests and the functional tests. In the unit tests, you run the mailer in isolation with tightly controlled inputs and compare the output to a knownvalue (a fixture &#8212; yay! more fixtures!). In the functional tests you don't so much test the minute details produced by the mailer Instead we test that our controllers and models are using the mailer in the right way. You test to prove that the right email was sent at the right time.</p></div>
-<h3 id="_unit_testing">10.2. Unit Testing</h3>
+<h3 id="_unit_testing">7.2. Unit Testing</h3>
<div class="para"><p>In order to test that your mailer is working as expected, you can use unit tests to compare the actual results of the mailer with pre-written examples of what should be produced.</p></div>
-<h4 id="_revenge_of_the_fixtures">10.2.1. Revenge of the Fixtures</h4>
+<h4 id="_revenge_of_the_fixtures">7.2.1. Revenge of the Fixtures</h4>
<div class="para"><p>For the purposes of unit testing a mailer, fixtures are used to provide an example of how the output <em>should</em> look. Because these are example emails, and not Active Record data like the other fixtures, they are kept in their own subdirectory apart from the other fixtures. The name of the directory within <tt>test/fixtures</tt> directly corresponds to the name of the mailer. So, for a mailer named <tt>UserMailer</tt>, the fixtures should reside in <tt>test/fixtures/user_mailer</tt> directory.</p></div>
<div class="para"><p>When you generated your mailer, the generator creates stub fixtures for each of the mailers actions. If you didn't use the generator you'll have to make those files yourself.</p></div>
-<h4 id="_the_basic_test_case">10.2.2. The Basic Test case</h4>
+<h4 id="_the_basic_test_case">7.2.2. The Basic Test case</h4>
<div class="para"><p>Here's a unit test to test a mailer named <tt>UserMailer</tt> whose action <tt>invite</tt> is used to send an invitation to a friend. It is an adapted version of the base test created by the generator for an <tt>invite</tt> action.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -1782,7 +1344,7 @@ Cheers!</tt></pre>
</div></div>
<div class="para"><p>This is the right time to understand a little more about writing tests for your mailers. The line <tt>ActionMailer::Base.delivery_method = :test</tt> in <tt>config/environments/test.rb</tt> sets the delivery method to test mode so that email will not actually be delivered (useful to avoid spamming your users while testing) but instead it will be appended to an array (<tt>ActionMailer::Base.deliveries</tt>).</p></div>
<div class="para"><p>However often in unit tests, mails will not actually be sent, simply constructed, as in the example above, where the precise content of the email is checked against what it should be.</p></div>
-<h3 id="_functional_testing">10.3. Functional Testing</h3>
+<h3 id="_functional_testing">7.3. Functional Testing</h3>
<div class="para"><p>Functional testing for mailers involves more than just checking that the email body, recipients and so forth are correct. In functional mail tests you call the mail deliver methods and check that the appropriate emails have been appended to the delivery list. It is fairly safe to assume that the deliver methods themselves do their job You are probably more interested in is whether your own business logic is sending emails when you expect them to got out. For example, you can check that the invite friend operation is sending an email appropriately:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -1805,7 +1367,7 @@ http://www.gnu.org/software/src-highlite -->
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
</div>
-<h2 id="_other_testing_approaches">11. Other Testing Approaches</h2>
+<h2 id="_other_testing_approaches">8. Other Testing Approaches</h2>
<div class="sectionbody">
<div class="para"><p>The built-in <tt>test/unit</tt> based testing is not the only way to test Rails applications. Rails developers have come up with a wide variety of other approaches and aids for testing, including:</p></div>
<div class="ilist"><ul>
@@ -1831,7 +1393,7 @@ link: <a href="http://rspec.info/">RSpec</a>, a behavior-driven development fram
</li>
</ul></div>
</div>
-<h2 id="_changelog">12. Changelog</h2>
+<h2 id="_changelog">9. Changelog</h2>
<div class="sectionbody">
<div class="para"><p><a href="http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/8">Lighthouse ticket</a></p></div>
<div class="ilist"><ul>
diff --git a/railties/doc/guides/source/activerecord_validations_callbacks.txt b/railties/doc/guides/source/activerecord_validations_callbacks.txt
index 0c82f24e66..e0bb534d0b 100644
--- a/railties/doc/guides/source/activerecord_validations_callbacks.txt
+++ b/railties/doc/guides/source/activerecord_validations_callbacks.txt
@@ -47,7 +47,7 @@ We can see how it works by looking at the following script/console output:
=> false
------------------------------------------------------------------
-Saving new records means sending an SQL insert operation to the database, while saving existing records (by calling either +save+ or +update_attributes+) will result in a SQL update operation. Active Record will use this facts to perform validations upon your objects, avoiding then to be recorded to the database if their inner state is invalid in some way. You can specify validations that will be beformed every time a object is saved, just when you're creating a new record or when you're updating an existing one.
+Saving new records means sending an SQL insert operation to the database, while saving existing records (by calling either +save+ or +update_attributes+) will result in a SQL update operation. Active Record will use these facts to perform validations upon your objects, avoiding then to be recorded to the database if their inner state is invalid in some way. You can specify validations that will be beformed every time a object is saved, just when you're creating a new record or when you're updating an existing one.
CAUTION: There are four methods that when called will trigger validation: +save+, +save!+, +update_attributes+ and +update_attributes!+. There is one method left, which is +update_attribute+. This method will update the value of an attribute without triggering any validation, so be careful when using +update_attribute+, since it can let you save your objects in an invalid state.
@@ -155,7 +155,8 @@ This helper validates that the attributes' values are not included in a given se
[source, ruby]
------------------------------------------------------------------
class MovieFile < ActiveRecord::Base
- validates_exclusion_of :format, :in => %w(mov avi), :message => "Extension %s is not allowed"
+ validates_exclusion_of :format, :in => %w(mov avi),
+ :message => "Extension %s is not allowed"
end
------------------------------------------------------------------
@@ -170,7 +171,8 @@ This helper validates the attributes's values by testing if they match a given p
[source, ruby]
------------------------------------------------------------------
class Product < ActiveRecord::Base
- validates_format_of :description, :with => /^[a-zA-Z]+$/, :message => "Only letters allowed"
+ validates_format_of :description, :with => /^[a-zA-Z]+$/,
+ :message => "Only letters allowed"
end
------------------------------------------------------------------
@@ -183,7 +185,8 @@ This helper validates that the attributes' values are included in a given set. I
[source, ruby]
------------------------------------------------------------------
class Coffee < ActiveRecord::Base
- validates_inclusion_of :size, :in => %w(small medium large), :message => "%s is not a valid size"
+ validates_inclusion_of :size, :in => %w(small medium large),
+ :message => "%s is not a valid size"
end
------------------------------------------------------------------
@@ -223,7 +226,7 @@ end
This helper has an alias called +validates_size_of+, it's the same helper with a different name. You can use it if you'd like to.
-=== The +validates_numericallity_of+ helper
+=== The +validates_numericality_of+ helper
This helper validates that your attributes have only numeric values. By default, it will match an optional sign followed by a integral or floating point number. Using the +:integer_only+ option set to true, you can specify that only integral numbers are allowed.
@@ -232,12 +235,12 @@ If you use +:integer_only+ set to +true+, then it will use the +$$/\A[+\-]?\d+\Z
[source, ruby]
------------------------------------------------------------------
class Player < ActiveRecord::Base
- validates_numericallity_of :points
- validates_numericallity_of :games_played, :integer_only => true
+ validates_numericality_of :points
+ validates_numericality_of :games_played, :integer_only => true
end
------------------------------------------------------------------
-The default error message for +validates_numericallity_of+ is "_is not a number_".
+The default error message for +validates_numericality_of+ is "_is not a number_".
=== The +validates_presence_of+ helper
@@ -282,7 +285,8 @@ There is a +:scope+ option that you can use to specify other attributes that mus
[source, ruby]
------------------------------------------------------------------
class Holiday < ActiveRecord::Base
- validates_uniqueness_of :name, :scope => :year, :message => "Should happen once per year"
+ validates_uniqueness_of :name, :scope => :year,
+ :message => "Should happen once per year"
end
------------------------------------------------------------------
@@ -324,9 +328,14 @@ As stated before, the +:on+ option lets you specify when the validation should h
[source, ruby]
------------------------------------------------------------------
class Person < ActiveRecord::Base
- validates_uniqueness_of :email, :on => :create # => it will be possible to update email with a duplicated value
- validates_numericallity_of :age, :on => :update # => it will be possible to create the record with a 'non-numerical age'
- validates_presence_of :name, :on => :save # => that's the default
+ # => it will be possible to update email with a duplicated value
+ validates_uniqueness_of :email, :on => :create
+
+ # => it will be possible to create the record with a 'non-numerical age'
+ validates_numericality_of :age, :on => :update
+
+ # => the default
+ validates_presence_of :name, :on => :save
end
------------------------------------------------------------------
@@ -367,7 +376,8 @@ Finally, it's possible to associate +:if+ and +:unless+ with a Ruby Proc object
[source, ruby]
------------------------------------------------------------------
class Account < ActiveRecord::Base
- validates_confirmation_of :password, :unless => Proc.new { |a| a.password.blank? }
+ validates_confirmation_of :password,
+ :unless => Proc.new { |a| a.password.blank? }
end
------------------------------------------------------------------
@@ -379,7 +389,8 @@ When the built-in validation helpers are not enough for your needs, you can writ
------------------------------------------------------------------
class Invoice < ActiveRecord::Base
def validate_on_create
- errors.add(:expiration_date, "can't be in the past") if !expiration_date.blank? and expiration_date < Date.today
+ errors.add(:expiration_date, "can't be in the past") if
+ !expiration_date.blank? and expiration_date < Date.today
end
end
------------------------------------------------------------------
@@ -389,14 +400,17 @@ If your validation rules are too complicated and you want to break them in small
[source, ruby]
------------------------------------------------------------------
class Invoice < ActiveRecord::Base
- validate :expiration_date_cannot_be_in_the_past, :discount_cannot_be_more_than_total_value
+ validate :expiration_date_cannot_be_in_the_past,
+ :discount_cannot_be_more_than_total_value
def expiration_date_cannot_be_in_the_past
- errors.add(:expiration_date, "can't be in the past") if !expiration_date.blank? and expiration_date < Date.today
+ errors.add(:expiration_date, "can't be in the past") if
+ !expiration_date.blank? and expiration_date < Date.today
end
def discount_cannot_be_greater_than_total_value
- errors.add(:discount, "can't be greater than total value") unless discount <= total_value
+ errors.add(:discount, "can't be greater than total value") unless
+ discount <= total_value
end
end
------------------------------------------------------------------
@@ -454,14 +468,16 @@ person.errors.on(:name) # => nil
person = Person.new(:name => "JD")
person.valid? # => false
-person.errors.on(:name) # => "is too short (minimum is 3 characters)"
+person.errors.on(:name)
+# => "is too short (minimum is 3 characters)"
person = Person.new
person.valid? # => false
-person.errors.on(:name) # => ["can't be blank", "is too short (minimum is 3 characters)"]
+person.errors.on(:name)
+# => ["can't be blank", "is too short (minimum is 3 characters)"]
------------------------------------------------------------------
-* +clear+ is used when you intentionally wants to clear all the messages in the +errors+ collection.
+* +clear+ is used when you intentionally want to clear all the messages in the +errors+ collection. However, calling +errors.clear+ upon an invalid object won't make it valid: the +errors+ collection will now be empty, but the next time you call +valid?+ or any method that tries to save this object to the database, the validations will run. If any of them fails, the +errors+ collection will get filled again.
[source, ruby]
------------------------------------------------------------------
@@ -471,10 +487,15 @@ class Person < ActiveRecord::Base
end
person = Person.new
-puts person.valid? # => false
-person.errors.on(:name) # => ["can't be blank", "is too short (minimum is 3 characters)"]
+person.valid? # => false
+person.errors.on(:name)
+# => ["can't be blank", "is too short (minimum is 3 characters)"]
+
person.errors.clear
-person.errors # => nil
+person.errors.empty? # => true
+p.save # => false
+p.errors.on(:name)
+# => ["can't be blank", "is too short (minimum is 3 characters)"]
------------------------------------------------------------------
== Callbacks
@@ -587,7 +608,7 @@ The +after_initialize+ and +after_find+ callbacks are a bit different from the o
== Halting Execution
-As you start registering new callbacks for your models, they will be queued for execution. This queue will include all your model's validations, the registered callbacks and the database operation to be executed. However, if at any moment one of the callback methods returns a boolean +false+ (not +nil+) value, this execution chain will be halted and the desired operation will not complete: your model will not get persisted in the database, or your records will not get deleted and so on.
+As you start registering new callbacks for your models, they will be queued for execution. This queue will include all your model's validations, the registered callbacks and the database operation to be executed. However, if at any moment one of the +before_create+, +before_save+, +before_update+ or +before_destroy+ callback methods returns a boolean +false+ (not +nil+) value, this execution chain will be halted and the desired operation will not complete: your model will not get persisted in the database, or your records will not get deleted and so on.
== Callback classes
@@ -667,7 +688,7 @@ end
=== Registering observers
-If you payed attention, you may be wondering where Active Record Observers are referenced in our applications, so they get instantiate and begin to interact with our models. For observers to work we need to register then in our application's *config/environment.rb* file. In this file there is a commented out line where we can define the observers that our application should load at start-up.
+If you payed attention, you may be wondering where Active Record Observers are referenced in our applications, so they get instantiate and begin to interact with our models. For observers to work we need to register them somewhere. The usual place to do that is in our application's *config/environment.rb* file. In this file there is a commented out line where we can define the observers that our application should load at start-up.
[source, ruby]
------------------------------------------------------------------
@@ -675,6 +696,10 @@ If you payed attention, you may be wondering where Active Record Observers are r
config.active_record.observers = :registration_observer, :auditor
------------------------------------------------------------------
+You can uncomment the line with +config.active_record.observers+ and change the symbols for the name of the observers that should be registered.
+
+It's also possible to register callbacks in any of the files living at *config/environments/*, if you want an observer to work only in a specific environment. There is not a +config.active_record.observers+ line at any of those files, but you can simply add it.
+
=== Where to put the observers' source files
By convention, you should always save your observers' source files inside *app/models*.
diff --git a/railties/doc/guides/source/command_line.txt b/railties/doc/guides/source/command_line.txt
index 1ad2e75c51..8a887bd001 100644
--- a/railties/doc/guides/source/command_line.txt
+++ b/railties/doc/guides/source/command_line.txt
@@ -52,7 +52,7 @@ NOTE: This output will seem very familiar when we get to the `generate` command.
=== server ===
-Let's try it! The `server` command launches a small web server written in Ruby named WEBrick which was also installed when you installed Rails. You'll use this any time you want to view your work through a web browser.
+Let's try it! The `server` command launches a small web server named WEBrick which comes bundled with Ruby. You'll use this any time you want to view your work through a web browser.
NOTE: WEBrick isn't your only option for serving Rails. We'll get to that in a later section. [XXX: which section]
@@ -99,7 +99,7 @@ Using generators will save you a large amount of time by writing *boilerplate co
Let's make our own controller with the controller generator. But what command should we use? Let's ask the generator:
-NOTE: All Rails console utilities have help text. For commands that require a lot of input to run correctly, you can try the command without any parameters (like `rails` or `./script/generate`). For others, you can try adding `--help` or `-h` to the end, as in `./script/server --help`.
+NOTE: All Rails console utilities have help text. As with most *NIX utilities, you can try adding `--help` or `-h` to the end, for example `./script/server --help`.
[source,shell]
------------------------------------------------------
@@ -200,24 +200,47 @@ Examples:
creates a Post model with a string title, text body, and published flag.
------------------------------------------------------
-Let's set up a simple model called "HighScore" that will keep track of our highest score on video games we play. Then we'll wire up our controller and view to modify and list our scores.
+But instead of generating a model directly (which we'll be doing later), let's set up a scaffold. A *scaffold* in Rails is a full set of model, database migration for that model, controller to manipulate it, views to view and manipulate the data, and a test suite for each of the above.
+
+Let's set up a simple resource called "HighScore" that will keep track of our highest score on video games we play.
[source,shell]
------------------------------------------------------
-$ ./script/generate model HighScore id:integer game:string score:integer
- exists app/models/
- exists test/unit/
- exists test/fixtures/
- create app/models/high_score.rb
- create test/unit/high_score_test.rb
- create test/fixtures/high_scores.yml
- create db/migrate
- create db/migrate/20081126032945_create_high_scores.rb
+$ ./script/generate scaffold HighScore game:string score:integer
+ exists app/models/
+ exists app/controllers/
+ exists app/helpers/
+ create app/views/high_scores
+ create app/views/layouts/
+ exists test/functional/
+ create test/unit/
+ create public/stylesheets/
+ create app/views/high_scores/index.html.erb
+ create app/views/high_scores/show.html.erb
+ create app/views/high_scores/new.html.erb
+ create app/views/high_scores/edit.html.erb
+ create app/views/layouts/high_scores.html.erb
+ create public/stylesheets/scaffold.css
+ create app/controllers/high_scores_controller.rb
+ create test/functional/high_scores_controller_test.rb
+ create app/helpers/high_scores_helper.rb
+ route map.resources :high_scores
+dependency model
+ exists app/models/
+ exists test/unit/
+ create test/fixtures/
+ create app/models/high_score.rb
+ create test/unit/high_score_test.rb
+ create test/fixtures/high_scores.yml
+ exists db/migrate
+ create db/migrate/20081217071914_create_high_scores.rb
------------------------------------------------------
-Taking it from the top, we have the *models* directory, where all of your data models live. *test/unit*, where all the unit tests live (gasp! -- unit tests!), fixtures for those tests, a test, the *migrate* directory, where the database-modifying migrations live, and a migration to create the `high_scores` table with the right fields.
+Taking it from the top - the generator checks that there exist the directories for models, controllers, helpers, layouts, functional and unit tests, stylesheets, creates the views, controller, model and database migration for HighScore (creating the `high_scores` table and fields), takes care of the route for the *resource*, and new tests for everything.
+
+The migration requires that we *migrate*, that is, run some Ruby code (living in that `20081217071914_create_high_scores.rb`) to modify the schema of our database. Which database? The sqlite3 database that Rails will create for you when we run the `rake db:migrate` command. We'll talk more about Rake in-depth in a little while.
-The migration requires that we *migrate*, that is, run some Ruby code (living in that `20081126032945_create_high_scores.rb`) to modify the schema of our database. Which database? The sqlite3 database that Rails will create for you when we run the `rake db:migrate` command. We'll talk more about Rake in-depth in a little while.
+NOTE: Hey. Install the sqlite3-ruby gem while you're at it. `gem install sqlite3-ruby`
[source,shell]
------------------------------------------------------
@@ -231,23 +254,87 @@ $ rake db:migrate
NOTE: Let's talk about unit tests. Unit tests are code that tests and makes assertions about code. In unit testing, we take a little part of code, say a method of a model, and test its inputs and outputs. Unit tests are your friend. The sooner you make peace with the fact that your quality of life will drastically increase when you unit test your code, the better. Seriously. We'll make one in a moment.
-Yo! Let's shove a small table into our greeting controller and view, listing our sweet scores.
+Let's see the interface Rails created for us. ./script/server; http://localhost:3000/high_scores
-[source,ruby]
+We can create new high scores (55,160 on Space Invaders!)
+
+=== console ===
+The `console` command lets you interact with your Rails application from the command line. On the underside, `script/console` uses IRB, so if you've ever used it, you'll be right at home. This is useful for testing out quick ideas with code and changing data server-side without touching the website.
+
+=== dbconsole ===
+`dbconsole` figures out which database you're using and drops you into whichever command line interface you would use with it (and figures out the command line parameters to give to it, too!). It supports MySQL, PostgreSQL, SQLite and SQLite3.
+
+=== plugin ===
+The `plugin` command simplifies plugin management; think a miniature version of the Gem utility. Let's walk through installing a plugin. You can call the sub-command *discover*, which sifts through repositories looking for plugins, or call *source* to add a specific repository of plugins, or you can specify the plugin location directly.
+
+Let's say you're creating a website for a client who wants a small accounting system. Every event having to do with money must be logged, and must never be deleted. Wouldn't it be great if we could override the behavior of a model to never actually take its record out of the database, but *instead*, just set a field?
+
+There is such a thing! The plugin we're installing is called "acts_as_paranoid", and it lets models implement a "deleted_at" column that gets set when you call destroy. Later, when calling find, the plugin will tack on a database check to filter out "deleted" things.
+
+[source,shell]
+------------------------------------------------------
+$ ./script/plugin install http://svn.techno-weenie.net/projects/plugins/acts_as_paranoid
++ ./CHANGELOG
++ ./MIT-LICENSE
+...
+...
------------------------------------------------------
-class GreetingController < ApplicationController
- def hello
- if request.post?
- score = HighScore.new(params[:high_score])
- if score.save
- flash[:notice] = "New score posted!"
- end
- end
-
- @scores = HighScore.find(:all)
- end
-end
+=== runner ===
+`runner` runs Ruby code in the context of Rails non-interactively. For instance:
+
+[source,shell]
------------------------------------------------------
+$ ./script/runner "Model.long_running_method"
+------------------------------------------------------
+
+=== destroy ===
+Think of `destroy` as the opposite of `generate`. It'll figure out what generate did, and undo it. Believe you-me, the creation of this tutorial used this command many times!
-XXX: Go with scaffolding instead, modifying greeting controller for high scores seems dumb.
+[source,shell]
+------------------------------------------------------
+$ ./script/generate model Oops
+ exists app/models/
+ exists test/unit/
+ exists test/fixtures/
+ create app/models/oops.rb
+ create test/unit/oops_test.rb
+ create test/fixtures/oops.yml
+ exists db/migrate
+ create db/migrate/20081221040817_create_oops.rb
+$ ./script/destroy model Oops
+ notempty db/migrate
+ notempty db
+ rm db/migrate/20081221040817_create_oops.rb
+ rm test/fixtures/oops.yml
+ rm test/unit/oops_test.rb
+ rm app/models/oops.rb
+ notempty test/fixtures
+ notempty test
+ notempty test/unit
+ notempty test
+ notempty app/models
+ notempty app
+------------------------------------------------------
+
+=== about ===
+Check it: Version numbers for Ruby, RubyGems, Rails, the Rails subcomponents, your application's folder, the current Rails environment name, your app's database adapter, and schema version! `about` is useful when you need to ask help, check if a security patch might affect you, or when you need some stats for an existing Rails installation.
+
+[source,shell]
+------------------------------------------------------
+$ ./script/about
+About your application's environment
+Ruby version 1.8.6 (i486-linux)
+RubyGems version 1.3.1
+Rails version 2.2.0
+Active Record version 2.2.0
+Action Pack version 2.2.0
+Active Resource version 2.2.0
+Action Mailer version 2.2.0
+Active Support version 2.2.0
+Edge Rails revision unknown
+Application root /home/commandsapp
+Environment development
+Database adapter sqlite3
+Database schema version 20081217073400
+------------------------------------------------------ \ No newline at end of file
diff --git a/railties/doc/guides/source/finders.txt b/railties/doc/guides/source/finders.txt
index 4c70c2b20b..88e7c15cb6 100644
--- a/railties/doc/guides/source/finders.txt
+++ b/railties/doc/guides/source/finders.txt
@@ -1,7 +1,7 @@
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 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:
* Find records using a variety of methods and conditions
* Specify the order, retrieved attributes, grouping, and other properties of the found records
@@ -50,7 +50,7 @@ Active Record will perform queries on the database for you and is compatible wit
== 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:
+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:
[source, sql]
-------------------------------------------------------
@@ -74,9 +74,9 @@ SELECT * FROM clients WHERE (clients.id IN (1,2))
created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40">]
-------------------------------------------------------
-Note that if you pass in a list of numbers that the result will be returned as an array, not as a single +Client+ object.
+Note that if you pass in a list of numbers that the result will be returned as an array, not as a single Client object.
-NOTE: If +find(id)+ or +find([id1, id2])+ fails to find any records, it will raise a +RecordNotFound+ exception.
+NOTE: If +find(id)+ or +find([id1, id2])+ fails to find any records, it will raise a RecordNotFound exception.
If you wanted to find the first Client object you would simply type +Client.first+ and that would find the first client in your clients table:
@@ -143,7 +143,7 @@ WARNING: Building your own conditions as pure strings can leave you vulnerable t
=== Array Conditions ===
-Now what if that number could vary, say as a parameter 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 +false+ and this will find the first record in the table that has '2' as its value for the +orders_count+ field and +false+ for its locked field.
+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:
@@ -159,7 +159,7 @@ instead of:
Client.first(:conditions => "orders_count = #{params[:orders]}")
-------------------------------------------------------
-is because of parameter 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 parameters directly inside the conditions string.
+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.
TIP: For more information on the dangers of SQL injection, see the link:../security.html#_sql_injection[Ruby on Rails Security Guide].
@@ -185,7 +185,7 @@ SELECT * FROM users WHERE (created_at IN
'2008-12-27','2008-12-28','2008-12-29','2008-12-30','2008-12-31'))
-------------------------------------------------------
-Things can get *really* messy if you pass in time objects as it will attempt to compare your field to *every second* in that range:
+Things can get *really* messy if you pass in Time objects as it will attempt to compare your field to *every second* in that range:
[source, ruby]
-------------------------------------------------------
@@ -224,7 +224,7 @@ Client.all(:conditions =>
["created_at >= ? AND created_at <= ?", params[:start_date], params[:end_date]])
-------------------------------------------------------
-Just like in Ruby.
+Just like in Ruby. If you want a shorter syntax be sure to check out the <<_hash_conditions, Hash Conditions>> section later on in the guide.
=== Placeholder Conditions ===
@@ -238,13 +238,83 @@ Client.all(:conditions =>
This makes for clearer readability if you have a large number of variable conditions.
+=== 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:
+
+[source, ruby]
+-------------------------------------------------------
+Client.all(:conditions => { :locked => true })
+-------------------------------------------------------
+
+The field name does not have to be a symbol it can also be a string:
+
+[source, ruby]
+-------------------------------------------------------
+Client.all(:conditions => { 'locked' => true })
+-------------------------------------------------------
+
+The good thing about this is that we can pass in a range for our fields without it generating a large query as shown in the preamble of this section.
+
+[source, ruby]
+-------------------------------------------------------
+Client.all(:conditions => { :created_at => (Time.now.midnight - 1.day)..Time.now.midnight})
+-------------------------------------------------------
+
+This will find all clients created yesterday by using a BETWEEN sql statement:
+
+[source, sql]
+-------------------------------------------------------
+SELECT * FROM `clients` WHERE (`clients`.`created_at` BETWEEN '2008-12-21 00:00:00' AND '2008-12-22 00:00:00')
+-------------------------------------------------------
+
+This demonstrates a shorter syntax for the examples in <<_array_conditions, Array Conditions>>
+
+You can also join in tables and specify their columns in the hash:
+
+[source, ruby]
+-------------------------------------------------------
+Client.all(:include => "orders", :conditions => { 'orders.created_at' => (Time.now.midnight - 1.day)..Time.now.midnight })
+-------------------------------------------------------
+
+An alternative and cleaner syntax to this is:
+
+[source, ruby]
+-------------------------------------------------------
+Client.all(:include => "orders", :conditions => { :orders => { :created_at => (Time.now.midnight - 1.day)..Time.now.midnight } })
+-------------------------------------------------------
+
+This will find all clients who have orders that were created yesterday, again using a BETWEEN expression.
+
+If you want to find records using the IN expression you can pass an array to the conditions hash:
+
+[source, ruby]
+-------------------------------------------------------
+Client.all(:include => "orders", :conditions => { :orders_count => [1,3,5] }
+-------------------------------------------------------
+
+This code will generate SQL like this:
+
+[source, sql]
+-------------------------------------------------------
+SELECT * FROM `clients` WHERE (`clients`.`orders_count` IN (1,2,3))
+-------------------------------------------------------
+
== Ordering
-If you're getting a set of records and want to force an order, you can use +Client.all(:order => "created_at")+ which by default will sort the records by ascending order. If you'd like to order it in descending order, just tell it to do that using +Client.all(:order => "created_at desc")+
+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")+.
== 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 0,1+ on your database.
+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:
+
+-------------------------------------------------------
+ActiveRecord::MissingAttributeError: missing attribute: <attribute>
+-------------------------------------------------------
+
+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)")+.
@@ -294,16 +364,29 @@ The SQL that would be executed would be something like this:
SELECT * FROM orders GROUP BY date(created_at)
-------------------------------------------------------
+== 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:
+
+[source, ruby]
+-------------------------------------------------------
+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.
+
== 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 +Active Record::ReadOnlyRecord+ exception. To set this option, specify it like this:
++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:
[source, ruby]
-------------------------------------------------------
Client.first(:readonly => true)
-------------------------------------------------------
-If you assign this record to a variable +client+, calling the following code will raise an +ActiveRecord::ReadOnlyRecord+ exception:
+If you assign this record to a variable client, calling the following code will raise an ActiveRecord::ReadOnlyRecord exception:
[source, ruby]
-------------------------------------------------------
@@ -324,13 +407,23 @@ Topic.transaction do
end
-------------------------------------------------------
+You can also pass SQL to this option to allow different types of locks. For example, MySQL has an expression called LOCK IN SHARE MODE where you can lock a record but still allow other queries to read it. To specify this expression just pass it in as the lock option:
+
+[source, ruby]
+-------------------------------------------------------
+Topic.transaction do
+ t = Topic.find(params[:id], :lock => "LOCK IN SHARE MODE")
+ t.increment!(:views)
+end
+-------------------------------------------------------
+
== 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 statement Active Record will use the latter.
+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.
== 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:
+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:
[source, sql]
-------------------------------------------------------
@@ -341,9 +434,10 @@ MailingAddress Load (0.001985) SELECT mailing_addresses.* FROM
mailing_addresses WHERE (mailing_addresses.client_id IN (13,14))
-------------------------------------------------------
-The numbers +13+ and +14+ in the above SQL are the ids of the clients gathered from the +Client.all+ query. Rails will then run a query to gather all the addresses and mailing addresses that have a client_id of 13 or 14. Although this is done in 3 queries, this is more efficient than not eager loading because without eager loading it would run a query for every time you called +address+ or +mailing_address+ on one of the objects in the clients array, which may lead to performance issues if you're loading a large number of records at once.
+The numbers +13+ and +14+ in the above SQL are the ids of the clients gathered from the +Client.all+ query. Rails will then run a query to gather all the addresses and mailing addresses that have a client_id of 13 or 14. Although this is done in 3 queries, this is more efficient than not eager loading because without eager loading it would run a query for every time you called +address+ or +mailing_address+ on one of the objects in the clients array, which may lead to performance issues if you're loading a large number of records at once and is often called the "N+1 query problem". The problem is that the more queries your server has to execute, the slower it will run.
-If you wanted to get all the addresses for a client in the same query you would do +Client.all(:joins => :address)+ and you wanted to find the address and mailing address for that client you would do +Client.all(:joins => [:address, :mailing_address])+. This is more efficient because it does all the SQL in one query, as shown by this example:
+If you wanted to get all the addresses for a client in the same query you would do +Client.all(:joins => :address)+.
+If you wanted to find the address and mailing address for that client you would do +Client.all(:joins => [:address, :mailing_address])+. This is more efficient because it does all the SQL in one query, as shown by this example:
[source, sql]
-------------------------------------------------------
@@ -366,44 +460,44 @@ When using eager loading you can specify conditions for the columns of the table
[source, ruby]
-------------------------------------------------------
Client.first(:include => "orders", :conditions =>
- ["orders.created_at >= ? AND orders.created_at <= ?", Time.now - 2.weeks, Time.now])
+ ["orders.created_at >= ? AND orders.created_at <= ?", 2.weeks.ago, Time.now])
-------------------------------------------------------
== 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+.
+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 parameter.
+You can do +find_last_by_*+ methods too which will find the last record matching your argument.
-You can specify an exclamation point (!) on the end of the dynamic finders to get them to raise an +ActiveRecord::RecordNotFound+ error if they do not return any records, like +Client.find_by_name!('Ryan')+
+You can specify an exclamation point (!) on the end of the dynamic finders to get them to raise an ActiveRecord::RecordNotFound error if they do not return any records, like +Client.find_by_name!("Ryan")+
-If you want to find both by name and locked, you can chain these finders together by simply typing +and+ between the fields for example +Client.find_by_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_name_and_locked("Ryan", true)+.
-There's another set of dynamic finders that let you find or create/initialize objects if they aren't find. These work in a similar fashion to the other finders and can be used like +find_or_create_by_name(params[:name])+. Using this will firstly perform a find and then create if the find returns nil. The SQL looks like this for +Client.find_or_create_by_name('Ryan')+:
+There's another set of dynamic finders that let you find or create/initialize objects if they aren't found. These work in a similar fashion to the other finders and can be used like +find_or_create_by_name(params[:name])+. Using this will firstly perform a find and then create if the find returns nil. The SQL looks like this for +Client.find_or_create_by_name("Ryan")+:
[source,sql]
-------------------------------------------------------
SELECT * FROM clients WHERE (clients.name = 'Ryan') LIMIT 1
BEGIN
INSERT INTO clients (name, updated_at, created_at, orders_count, locked)
- VALUES('Ryan', '2008-09-28 15:39:12', '2008-09-28 15:39:12', '0', '0')
+ VALUES('Ryan', '2008-09-28 15:39:12', '2008-09-28 15:39:12', 0, '0')
COMMIT
-------------------------------------------------------
-+find_or_create+'s sibling, +find_or_initialize+, will find an object and if it does not exist will act similar to calling +new+ with the parameters you passed in. For example:
++find_or_create+'s sibling, +find_or_initialize+, will find an object and if it does not exist will act similar to calling +new+ with the arguments you passed in. For example:
[source, ruby]
-------------------------------------------------------
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 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.
+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.
== Finding By SQL
-If you'd like to use your own SQL to find records a table you can use +find_by_sql+. The +find_by_sql+ method will return an array of objects even if it only returns a single record in it's call to the database. For example you could run this query:
+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:
[source, ruby]
-------------------------------------------------------
@@ -423,7 +517,7 @@ Client.connection.select_all("SELECT * FROM `clients` WHERE `id` = '1'")
== 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 controllers.
+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.
== Named Scopes
@@ -431,7 +525,7 @@ Named scopes are another way to add custom finding behavior to the models in the
=== Simple Named Scopes
-Suppose want to find all clients who are male. You could use this code:
+Suppose we want to find all clients who are male. You could use this code:
[source, ruby]
-------------------------------------------------------
@@ -451,7 +545,7 @@ class Client < ActiveRecord::Base
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])+. Please be aware that the conditions syntax in named_scope and find is different and the two are not interchangeable. If you want to find the first client within this named scope you could do +Client.active.first+.
+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+.
=== Combining Named Scopes
@@ -480,7 +574,7 @@ class Client < ActiveRecord::Base
end
-------------------------------------------------------
-This looks like a standard named scope that defines a method called recent which gathers all records created any time between now and 2 weeks ago. That's correct for the first time the model is loaded but for any time after that, +2.weeks.ago+ is set to that same value, so you will consistently get records from a certain date until your model is reloaded by something like your application restarting. The way to fix this is to put the code in a lambda block:
+This looks like a standard named scope that defines a method called +recent+ which gathers all records created any time between now and 2 weeks ago. That's correct for the first time the model is loaded but for any time after that, +2.weeks.ago+ is set to that same value, so you will consistently get records from a certain date until your model is reloaded by something like your application restarting. The way to fix this is to put the code in a lambda block:
[source, ruby]
-------------------------------------------------------
@@ -489,11 +583,11 @@ class Client < ActiveRecord::Base
end
-------------------------------------------------------
-And now every time the recent named scope is called, the code in the lambda block will be parsed, so you'll get actually 2 weeks ago from the code execution, not 2 weeks ago from the time the model was loaded.
+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.
=== Named Scopes with Multiple Models
-In a named scope you can use +:include+ and +:joins+ options just like in find.
+In a named scope you can use +:include+ and +:joins+ options just like in +find+.
[source, ruby]
-------------------------------------------------------
@@ -507,7 +601,7 @@ This method, called as +Client.active_within_2_weeks.all+, will return all clien
=== Arguments to Named Scopes
-If you want to pass a named scope a compulsory argument, just specify it as a block parameter like this:
+If you want to pass to a named scope a required arugment, just specify it as a block argument like this:
[source, ruby]
-------------------------------------------------------
@@ -516,7 +610,7 @@ class Client < ActiveRecord::Base
end
-------------------------------------------------------
-This will work if you call +Client.recent(2.weeks.ago).all+ but not if you call +Client.recent+. If you want to add an optional argument for this, you have to use the splat operator as the block's parameter.
+This will work if you call +Client.recent(2.weeks.ago).all+ but not if you call +Client.recent+. If you want to add an optional argument for this, you have to use prefix the arugment with an *.
[source, ruby]
-------------------------------------------------------
@@ -553,14 +647,14 @@ Just like named scopes, anonymous scopes can be stacked, either with other anony
== 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.
+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+.
[source, ruby]
-------------------------------------------------------
Client.exists?(1)
-------------------------------------------------------
-The above code will check for the existence of a clients table record with the id of 1 and return true if it exists.
+The +exists?+ method also takes multiple ids, but the catch is that it will return true if any one of those records exists.
[source, ruby]
-------------------------------------------------------
@@ -569,8 +663,6 @@ Client.exists?(1,2,3)
Client.exists?([1,2,3])
-------------------------------------------------------
-The +exists?+ method also takes multiple ids, as shown by the above code, but the catch is that it will return true if any one of those records exists.
-
Further more, +exists+ takes a +conditions+ option much like find:
[source, ruby]
@@ -593,10 +685,10 @@ Which will execute:
[source, sql]
-------------------------------------------------------
-SELECT count(*) AS count_all FROM clients WHERE (first_name = 1)
+SELECT count(*) AS count_all FROM clients WHERE (first_name = 'Ryan')
-------------------------------------------------------
-You can also use +include+ or +joins+ for this to do something a little more complex:
+You can also use +:include+ or +:joins+ for this to do something a little more complex:
[source, ruby]
-------------------------------------------------------
@@ -609,7 +701,7 @@ Which will execute:
-------------------------------------------------------
SELECT count(DISTINCT clients.id) AS count_all FROM clients
LEFT OUTER JOIN orders ON orders.client_id = client.id WHERE
- (clients.first_name = 'name' AND orders.status = 'received')
+ (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.
@@ -619,7 +711,7 @@ This code specifies +clients.first_name+ just in case one of the join tables has
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.
+For options, please see the parent section, <<_calculations, Calculations>>.
=== Average
@@ -632,7 +724,7 @@ 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, Calculations>>
+For options, please see the parent section, <<_calculations, Calculations>>.
=== Minimum
@@ -677,6 +769,14 @@ Thanks to Mike Gunderloy for his tips on creating this guide.
http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16[Lighthouse 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]
diff --git a/railties/doc/guides/source/form_helpers.txt b/railties/doc/guides/source/form_helpers.txt
index 88ca74a557..d09ad15a90 100644
--- a/railties/doc/guides/source/form_helpers.txt
+++ b/railties/doc/guides/source/form_helpers.txt
@@ -247,7 +247,7 @@ A nice thing about `f.text_field` and other helper methods is that they will pre
Relying on record identification
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-In the previous chapter we handled the Article model. This model is directly available to users of our application and, following the best practices for developing with Rails, we should declare it *a resource*.
+In the previous chapter we handled the Article model. This model is directly available to users of our application, so -- following the best practices for developing with Rails -- we should declare it *a resource*.
When dealing with RESTful resources, our calls to `form_for` can get significantly easier if we rely on *record identification*. In short, we can just pass the model instance and have Rails figure out model name and the rest:
@@ -291,15 +291,13 @@ Here we have a list of cities where their names are presented to the user, but i
The select tag and options
~~~~~~~~~~~~~~~~~~~~~~~~~~
-The most generic helper is `select_tag`, which -- as the name implies -- simply generates the `SELECT` tag that encapsulates the options:
+The most generic helper is `select_tag`, which -- as the name implies -- simply generates the `SELECT` tag that encapsulates an options string:
----------------------------------------------------------------------------
<%= select_tag(:city_id, '<option value="1">Lisabon</option>...') %>
----------------------------------------------------------------------------
-This is a start, but it doesn't dynamically create our option tags. We had to pass them in as a string.
-
-We can generate option tags with the `options_for_select` helper:
+This is a start, but it doesn't dynamically create our option tags. We can generate option tags with the `options_for_select` helper:
----------------------------------------------------------------------------
<%= options_for_select([['Lisabon', 1], ['Madrid', 2], ...]) %>
@@ -311,9 +309,9 @@ output:
...
----------------------------------------------------------------------------
-For input data we used a nested array where each element has two elements: visible value (name) and internal value (ID).
+For input data we used a nested array where each item has two elements: option text (city name) and option value (city id).
-Now you can combine `select_tag` and `options_for_select` to achieve the desired, complete markup:
+Knowing this, you can combine `select_tag` and `options_for_select` to achieve the desired, complete markup:
----------------------------------------------------------------------------
<%= select_tag(:city_id, options_for_select(...)) %>
@@ -333,13 +331,114 @@ output:
So whenever Rails sees that the internal value of an option being generated matches this value, it will add the `selected` attribute to that option.
-Select boxes for dealing with models
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+Select helpers for dealing with models
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Until now we've covered how to make generic select boxes, but in most cases our form controls will be tied to a specific database model. So, to continue from our previous examples, let's assume that we have a "Person" model with a `city_id` attribute.
+Consistent with other form helpers, when dealing with models we drop the `"_tag"` suffix from `select_tag` that we used in previous examples:
+
----------------------------------------------------------------------------
-...
+# controller:
+@person = Person.new(:city_id => 2)
+
+# view:
+<%= select(:person, :city_id, [['Lisabon', 1], ['Madrid', 2], ...]) %>
+----------------------------------------------------------------------------
+
+Notice that the third parameter, the options array, is the same kind of argument we pass to `options_for_select`. One thing that we have as an advantage here is that we don't have to worry about pre-selecting the correct city if the user already has one -- Rails will do this for us by reading from `@person.city_id` attribute.
+
+As before, if we were to use `select` helper on a form builder scoped to `@person` object, the syntax would be:
+
+----------------------------------------------------------------------------
+# select on a form builder
+<%= f.select(:city_id, ...) %>
+----------------------------------------------------------------------------
+
+Option tags from a collection of arbitrary objects
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Until now we were generating option tags from nested arrays with the help of `options_for_select` method. Data in our array were raw values:
+
+----------------------------------------------------------------------------
+<%= options_for_select([['Lisabon', 1], ['Madrid', 2], ...]) %>
+----------------------------------------------------------------------------
+
+But what if we had a *City* model (perhaps an ActiveRecord one) and we wanted to generate option tags from a collection of those objects? One solution would be to make a nested array by iterating over them:
+
+----------------------------------------------------------------------------
+<% cities_array = City.find(:all).map { |city| [city.name, city.id] } %>
+<%= options_for_select(cities_array) %>
+----------------------------------------------------------------------------
+
+This is a perfectly valid solution, but Rails provides us with a less verbose alternative: `options_from_collection_for_select`. This helper expects a collection of arbitrary objects and two additional arguments: the names of the methods to read the option *value* and *text* from, respectively:
+
+----------------------------------------------------------------------------
+<%= options_from_collection_for_select(City.all, :id, :name) %>
+----------------------------------------------------------------------------
+
+As the name implies, this only generates option tags. A method to go along with it is `collection_select`:
+
+----------------------------------------------------------------------------
+<%= collection_select(:person, :city_id, City.all, :id, :name) %>
----------------------------------------------------------------------------
-... \ No newline at end of file
+To recap, `options_from_collection_for_select` are to `collection_select` what `options_for_select` are to `select`.
+
+Time zone and country select
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+To leverage time zone support in Rails, we have to ask our users what time zone they are in. Doing so would require generating select options from a list of pre-defined TimeZone objects using `collection_select`, but we can simply use the `time_zone_select` helper that already wraps this:
+
+----------------------------------------------------------------------------
+<%= time_zone_select(:person, :city_id) %>
+----------------------------------------------------------------------------
+
+There is also `time_zone_options_for_select` helper for a more manual (therefore more customizable) way of doing this. Read the API documentation to learn about the possible arguments for these two methods.
+
+When it comes to country select, Rails _used_ to have the built-in helper `country_select` but was extracted to a plugin.
+TODO: plugin URL
+
+
+Miscellaneous
+-------------
+
+File upload form
+~~~~~~~~~~~~~~~~
+
+:multipart - If set to true, the enctype is set to "multipart/form-data".
+
+Scoping out form controls with `fields_for`
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Creates a scope around a specific model object like `form_for`, but doesn’t create the form tags themselves. This makes `fields_for` suitable for specifying additional model objects in the same form:
+
+Making custom form builders
+~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+You can also build forms using a customized FormBuilder class. Subclass FormBuilder and override or define some more helpers, then use your custom builder. For example, let’s say you made a helper to automatically add labels to form inputs.
+
+----------------------------------------------------------------------------
+<% form_for :person, @person, :url => { :action => "update" }, :builder => LabellingFormBuilder do |f| %>
+ <%= f.text_field :first_name %>
+ <%= f.text_field :last_name %>
+ <%= text_area :person, :biography %>
+ <%= check_box_tag "person[admin]", @person.company.admin? %>
+<% end %>
+----------------------------------------------------------------------------
+
+
+* `form_for` within a namespace
+
+----------------------------------------------------------------------------
+select_tag(name, option_tags = nil, html_options = { :multiple, :disabled })
+
+select(object, method, choices, options = {}, html_options = {})
+options_for_select(container, selected = nil)
+
+collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {})
+options_from_collection_for_select(collection, value_method, text_method, selected = nil)
+
+time_zone_options_for_select(selected = nil, priority_zones = nil, model = ::ActiveSupport::TimeZone)
+time_zone_select(object, method, priority_zones = nil, options = {}, html_options = {})
+----------------------------------------------------------------------------
diff --git a/railties/doc/guides/source/getting_started_with_rails.txt b/railties/doc/guides/source/getting_started_with_rails.txt
index b66d2f6f9e..58eff9fd3d 100644
--- a/railties/doc/guides/source/getting_started_with_rails.txt
+++ b/railties/doc/guides/source/getting_started_with_rails.txt
@@ -984,7 +984,7 @@ end
This creates +comments+ as a _nested resource_ within +posts+. This is another part of capturing the hierarchical relationship that exists between posts and comments.
-TIP: For more information on routing, see the link:../routing_outside_in[Rails Routing from the Outside In] guide.
+TIP: For more information on routing, see the link:../routing_outside_in.html[Rails Routing from the Outside In] guide.
=== Generating a Controller
diff --git a/railties/doc/guides/source/i18n.txt b/railties/doc/guides/source/i18n.txt
index 76f081e0bc..ba3cc42a5b 100644
--- a/railties/doc/guides/source/i18n.txt
+++ b/railties/doc/guides/source/i18n.txt
@@ -12,7 +12,7 @@ Internationalization is a complex problem. Natural languages differ in so many w
=== The overall architecture of the library
-To solve this the Ruby I18n gem is split into two parts:
+Thus, the Ruby I18n gem is split into two parts:
* The public API which is just a Ruby module with a bunch of public methods and definitions how the library works.
* A shipped backend (which is intentionally named the Simple backend) that implements these methods.
@@ -29,6 +29,14 @@ translate # lookup translations
localize # localize Date and Time objects to local formats
-------------------------------------------------------
+These have the aliases #t and #l so you can use them like this:
+
+[source, ruby]
+-------------------------------------------------------
+I18n.t 'store.title'
+I18n.l Time.now
+-------------------------------------------------------
+
There are also attribute readers and writers for the following attributes:
[source, ruby]
@@ -46,9 +54,30 @@ There are just a few, simple steps to get up and running with a I18n support for
=== Configure the I18n module
-First of all you want to tell the I18n library where it can find your custom translation files. You might also want to set your default locale to something else than English.
+Rails will wire up all required settings for you with sane defaults. If you need different settings you can overwrite them easily.
+
+The I18n library will use English (:en) as a *default locale* by default. I.e if you don't set a different locale, :en will be used for looking up translations. Also, Rails adds all files from config/locales/*.rb,yml to your translations load path.
+
+The *translations load path* (I18n.load_path) is just a Ruby Array of paths to your translation files that will be loaded automatically and available in your application. You can pick whatever directory and translation file naming scheme makes sense for you.
+
+(Hint: The backend will lazy-load these translations when a translation is looked up for the first time. This makes it possible to just swap the backend with something else even after translations have already been announced.)
-You can pick whatever directory and translation file naming scheme makes sense for you. The simplest thing possible is probably to put the following into an initializer:
+The default environment.rb says:
+
+[source, ruby]
+-------------------------------------------------------
+# The internationalization framework can be changed
+# to have another default locale (standard is :en) or more load paths.
+# All files from config/locales/*.rb,yml are added automatically.
+# config.i18n.load_path << Dir[File.join(RAILS_ROOT, 'my', 'locales', '*.{rb,yml}')]
+# config.i18n.default_locale = :de
+-------------------------------------------------------
+
+=== Optional: custom I18n configuration setup
+
+For the sake of completeness let's mention that if you do not want to use the environment for some reason you can always wire up things manually, too.
+
+To tell the I18n library where it can find your custom translation files you can specify the load path anywhere in your application - just make sure it gets run before any translations are actually looked up. You might also want to change the default locale. The simplest thing possible is to put the following into an initializer:
[source, ruby]
-------------------------------------------------------
@@ -58,14 +87,12 @@ You can pick whatever directory and translation file naming scheme makes sense f
I18n.load_path += Dir[ File.join(RAILS_ROOT, 'lib', 'locale', '*.{rb,yml}') ]
# you can omit this if you're happy with English as a default locale
-I18n.default_locale = :"pt"
+I18n.default_locale = :pt
-------------------------------------------------------
-I18n.load_path is just a Ruby Array of paths to your translation files. The backend will lazy-load these translations when a translation is looked up for the first time. This makes it possible to just swap the backend with something else even after translations have already been announced.
-
=== Set the locale in each request
-By default the I18n library will use the I18n.default_locale for looking up translations (if you do not specify a locale for a lookup) and this will, by default, en (English).
+By default the I18n library will use :en (English) as a I18n.default_locale for looking up translations (if you do not specify a locale for a lookup).
If you want to translate your Rails application to a single language other than English you can set I18n.default_locale to your locale. If you want to change the locale on a per-request basis though you can set it in a before_filter on the ApplicationController like this:
@@ -78,13 +105,15 @@ def set_locale
end
-------------------------------------------------------
-This will already work for URLs where you pass the locale as a query parameter as in example.com?locale=pt-BR (which is what Google also does). (TODO hints about other approaches in the resources section).
+This will already work for URLs where you pass the locale as a query parameter as in example.com?locale=pt (which is what Google also does).
+
+TIP: For other URL designs, see http://rails-i18n.org/wiki/pages/how-to-encode-the-current-locale-in-the-url[How to encode the current locale in the URL].
Now you've initialized I18n support for your application and told it which locale should be used. With that in place you're now ready for the really interesting stuff.
-=== Internationalize your application
+== Internationalize your application
-The process of "internationalization" usually means to abstract all strings and other locale specific bits out of your application (TODO reference to wikipedia). The process of "localization" means to then provide translations and localized formats for these bits.
+The process of "internationalization" usually means to abstract all strings and other locale specific bits out of your application. The process of "localization" means to then provide translations and localized formats for these bits. <<1>>
So, let's internationalize something. You most probably have something like this in one of your applications:
@@ -107,7 +136,9 @@ end
<p><%= flash[:notice] %></p>
-------------------------------------------------------
-TODO screenshot
+image:images/i18n/demo_untranslated.png[rails i18n demo untranslated]
+
+=== Adding Translations
Obviously there are two strings that are localized to English. In order to internationalize this code replace these strings with calls to Rails' #t helper with a key that makes sense for the translation:
@@ -125,39 +156,66 @@ end
<p><%= flash[:notice] %></p>
-------------------------------------------------------
-TODO insert note about #t helper compared to I18n.t
-
-TODO insert note/reference about structuring translation keys
-
When you now render this view it will show an error message that tells you that the translations for the keys :hello_world and :hello_flash are missing.
-TODO screenshot
+image:images/i18n/demo_translation_missing.png[rails i18n demo translation missing]
+
+NOTE: Rails adds a +t+ (+translate+) helper method to your views so that you do not need to spell out +I18n.t+ all the time. Additionally this helper will catch missing translations and wrap the resulting error message into a &lt;span class="translation_missing"&gt;.
So let's add the missing translations (i.e. do the "localization" part):
[source, ruby]
-------------------------------------------------------
-# lib/locale/en.yml
-en-US:
+# config/locale/en.yml
+en:
hello_world: Hello World
hello_flash: Hello Flash
-# lib/locale/pirate.yml
+# config/locale/pirate.yml
pirate:
hello_world: Ahoy World
hello_flash: Ahoy Flash
-------------------------------------------------------
-There you go. Your application now shows:
+There you go. Because you haven't changed the default_locale I18n will use English. Your application now shows:
+
+image:images/i18n/demo_translated_english.png[rails i18n demo translated to english]
-TODO screenshot
+And when you change the URL to pass the pirate locale you get:
+
+image:images/i18n/demo_translated_pirate.png[rails i18n demo translated to pirate]
+
+NOTE You need to restart the server when you add new locale files.
+
+=== Adding Date/Time formats
+
+Ok, let's add a timestamp to the view so we can demo the date/time localization feature as well. To localize the time format you pass the Time object to I18n.l or (preferably) use Rails' #l helper. You can pick a format by passing the :format option, by default the :default format is used.
[source, ruby]
-------------------------------------------------------
-I18n.t 'store.title'
-I18n.l Time.now
+# app/views/home/index.html.erb
+<h1><%=t :hello_world %></h1>
+<p><%= flash[:notice] %></p
+<p><%= l Time.now, :format => :short %></p>
+-------------------------------------------------------
+
+And in our pirate translations file let's add a time format (it's already there in Rails' defaults for English):
+
+[source, ruby]
+-------------------------------------------------------
+# config/locale/pirate.yml
+pirate:
+ time:
+ formats:
+ short: "arrrround %H'ish"
-------------------------------------------------------
+So that would give you:
+
+image:images/i18n/demo_localized_pirate.png[rails i18n demo localized time to pirate]
+
+NOTE Right now you might need to add some more date/time formats in order to make the I18n backend work as expected. See the http://github.com/svenfuchs/rails-i18n/tree/master/rails/locale[rails-i18n repository] for starting points.
+
== Overview of the I18n API features
@@ -218,7 +276,7 @@ I18n.t :missing, :default => 'Not here'
If the default value is a Symbol it will be used as a key and translated. One can provide multiple values as default. The first one that results in a value will be returned.
-E.g. the following first tries to translate the key :missing and then the key :also_missing. As both do not yield a result the string ‘Not here’ will be returned:
+E.g. the following first tries to translate the key :missing and then the key :also_missing. As both do not yield a result the string "Not here" will be returned:
[source, ruby]
-------------------------------------------------------
@@ -246,28 +304,29 @@ I18n.t 'active_record.error_messages'
=== Interpolation
-TODO explain what this is good for
+In many cases you want to abstract your translations so that variables can be interpolated into the translation. For this reason the I18n API provides an interpolation feature.
All options besides :default and :scope that are passed to #translate will be interpolated to the translation:
[source, ruby]
-------------------------------------------------------
-I18n.backend.store_translations 'en', :thanks => 'Thanks {{name}}!'
+I18n.backend.store_translations :en, :thanks => 'Thanks {{name}}!'
I18n.translate :thanks, :name => 'Jeremy'
# => 'Thanks Jeremy!'
-------------------------------------------------------
If a translation uses :default or :scope as a interpolation variable an I18n::ReservedInterpolationKey exception is raised. If a translation expects an interpolation variable but it has not been passed to #translate an I18n::MissingInterpolationArgument exception is raised.
+
=== Pluralization
-TODO explain what this is good for
+In English there's only a singular and a plural form for a given string, e.g. "1 message" and "2 messages". Other languages (http://www.unicode.org/cldr/data/charts/supplemental/language_plural_rules.html#ar[Arabic], http://www.unicode.org/cldr/data/charts/supplemental/language_plural_rules.html#ja[Japanese], http://www.unicode.org/cldr/data/charts/supplemental/language_plural_rules.html#ru[Russian] and many more) have different grammars that have additional or less http://www.unicode.org/cldr/data/charts/supplemental/language_plural_rules.html[plural forms]. Thus, the I18n API provides a flexible pluralization feature.
The :count interpolation variable has a special role in that it both is interpolated to the translation and used to pick a pluralization from the translations according to the pluralization rules defined by CLDR:
[source, ruby]
-------------------------------------------------------
-I18n.backend.store_translations 'en-US', :inbox => { # TODO change this
+I18n.backend.store_translations :en, :inbox => {
:one => '1 message',
:other => '{{count}} messages'
}
@@ -275,7 +334,7 @@ I18n.translate :inbox, :count => 2
# => '2 messages'
-------------------------------------------------------
-The algorithm for pluralizations in en-US is as simple as:
+The algorithm for pluralizations in :en is as simple as:
[source, ruby]
-------------------------------------------------------
@@ -294,7 +353,7 @@ If no locale is passed I18n.locale is used:
[source, ruby]
-------------------------------------------------------
-I18n.locale = :'de'
+I18n.locale = :de
I18n.t :foo
I18n.l Time.now
-------------------------------------------------------
@@ -303,27 +362,27 @@ Explicitely passing a locale:
[source, ruby]
-------------------------------------------------------
-I18n.t :foo, :locale => :'de'
-I18n.l Time.now, :locale => :'de'
+I18n.t :foo, :locale => :de
+I18n.l Time.now, :locale => :de
-------------------------------------------------------
-I18n.locale defaults to I18n.default_locale which defaults to :'en'. The default locale can be set like this:
+I18n.locale defaults to I18n.default_locale which defaults to :en. The default locale can be set like this:
[source, ruby]
-------------------------------------------------------
-I18n.default_locale = :'de'
+I18n.default_locale = :de
-------------------------------------------------------
== How to store your custom translations
-The shipped Simple backend allows you to store translations in both plain Ruby and YAML format. (2)
+The shipped Simple backend allows you to store translations in both plain Ruby and YAML format. <<2>>
For example a Ruby Hash providing translations can look like this:
[source, ruby]
-------------------------------------------------------
{
- :'pt-BR' => {
+ :pt => {
:foo => {
:bar => "baz"
}
@@ -335,18 +394,18 @@ The equivalent YAML file would look like this:
[source, ruby]
-------------------------------------------------------
-"pt-BR":
+pt:
foo:
bar: baz
-------------------------------------------------------
As you see in both cases the toplevel key is the locale. :foo is a namespace key and :bar is the key for the translation "baz".
-Here is a "real" example from the ActiveSupport en-US translations YAML file:
+Here is a "real" example from the ActiveSupport en.yml translations YAML file:
[source, ruby]
-------------------------------------------------------
-"en":
+en:
date:
formats:
default: "%Y-%m-%d"
@@ -364,12 +423,16 @@ I18n.t :short, :scope => 'date.formats'
I18n.t :short, :scope => [:date, :formats]
-------------------------------------------------------
+Generally we recommend using YAML as a format for storing translations. There are cases though where you want to store Ruby lambdas as part of your locale data, e.g. for special date
+
=== Translations for ActiveRecord models
You can use the methods Model.human_name and Model.human_attribute_name(attribute) to transparently lookup translations for your model and attribute names.
For example when you add the following translations:
+[source, ruby]
+-------------------------------------------------------
en:
activerecord:
models:
@@ -378,6 +441,7 @@ en:
user:
login: "Handle"
# will translate User attribute "login" as "Handle"
+-------------------------------------------------------
Then User.human_name will return "Dude" and User.human_attribute_name(:login) will return "Handle".
@@ -396,24 +460,21 @@ class User < ActiveRecord::Base
end
-------------------------------------------------------
-The key for the error message in this case is :blank. So ActiveRecord will first try to look up an error message with:
+The key for the error message in this case is :blank. ActiveRecord will lookup this key in the namespaces:
[source, ruby]
-------------------------------------------------------
-activerecord.errors.messages.models.user.attributes.name.blank
+activerecord.errors.messages.models.[model_name].attributes.[attribute_name]
+activerecord.errors.messages.models.[model_name]
+activerecord.errors.messages
-------------------------------------------------------
-If it's not there it will try:
+Thus, in our example it will try the following keys in this order and return the first result:
[source, ruby]
-------------------------------------------------------
+activerecord.errors.messages.models.user.attributes.name.blank
activerecord.errors.messages.models.user.blank
--------------------------------------------------------
-
-If this is also not there it will use the default message from:
-
-[source, ruby]
--------------------------------------------------------
activerecord.errors.messages.blank
-------------------------------------------------------
@@ -447,28 +508,27 @@ The translated model name and translated attribute name are always available for
So, for example, instead of the default error message "can not be blank" you could use the attribute name like this: "Please fill in your {{attribute}}".
-Count and/or value are available where applicable. Count can be used for pluralization if present:
-
-[grid="all"]
-`---------------------------`----------------`---------------`----------------
-validation with option message interpolation
-validates_confirmation_of - :confirmation -
-validates_acceptance_of - :accepted -
-validates_presence_of - :blank -
-validates_length_of :within, :in :too_short count
-validates_length_of :within, :in :too_long count
-validates_length_of :is :wrong_length count
-validates_length_of :minimum :too_short count
-validates_length_of :maximum :too_long count
-validates_uniqueness_of - :taken value
-validates_format_of - :invalid value
-validates_inclusion_of - :inclusion value
-validates_exclusion_of - :exclusion value
-validates_associated - :invalid value
-validates_numericality_of - :not_a_number value
-validates_numericality_of :odd :odd value
-validates_numericality_of :even :even value
-------------------------------------------------------------------------------
+count and/or value are available where applicable. Count can be used for pluralization if present:
+
+|==================================================================================
+| validation | with option | message | interpolation
+| validates_confirmation_of | - | :confirmation | -
+| validates_acceptance_of | - | :accepted | -
+| validates_presence_of | - | :blank | -
+| validates_length_of | :within, :in | :too_short | count
+| validates_length_of | :within, :in | :too_long | count
+| validates_length_of | :is | :wrong_length | count
+| validates_length_of | :minimum | :too_short | count
+| validates_length_of | :maximum | :too_long | count
+| validates_uniqueness_of | - | :taken | value
+| validates_format_of | - | :invalid | value
+| validates_inclusion_of | - | :inclusion | value
+| validates_exclusion_of | - | :exclusion | value
+| validates_associated | - | :invalid | value
+| validates_numericality_of | - | :not_a_number | value
+| validates_numericality_of | :odd | :odd | value
+| validates_numericality_of | :even | :even | value
+|==================================================================================
==== Translations for the ActiveRecord error_messages_for helper
@@ -479,14 +539,14 @@ Rails ships with the following translations:
[source, ruby]
-------------------------------------------------------
-"en":
+en:
activerecord:
errors:
template:
header:
one: "1 error prohibited this {{model}} from being saved"
other: "{{count}} errors prohibited this {{model}} from being saved"
- body: "There were problems with the following fields:"
+ body: "There were problems with the following fields:"
-------------------------------------------------------
@@ -496,11 +556,12 @@ Rails uses fixed strings and other localizations, such as format strings and oth
TODO list helpers and available keys
+
== Customize your I18n setup
=== Using different backends
-For several reasons the shipped Simple backend only does the "simplest thing that ever could work" _for Ruby on Rails_ (1) ... which means that it is only guaranteed to work for English and, as a side effect, languages that are very similar to English. Also, the simple backend is only capable of reading translations but can not dynamically store them to any format.
+For several reasons the shipped Simple backend only does the "simplest thing that ever could work" _for Ruby on Rails_ <<3>> ... which means that it is only guaranteed to work for English and, as a side effect, languages that are very similar to English. Also, the simple backend is only capable of reading translations but can not dynamically store them to any format.
That does not mean you're stuck with these limitations though. The Ruby I18n gem makes it very easy to exchange the Simple backend implementation with something else that fits better for your needs. E.g. you could exchange it with Globalize's Static backend:
@@ -509,30 +570,59 @@ That does not mean you're stuck with these limitations though. The Ruby I18n gem
I18n.backend = Globalize::Backend::Static.new
-------------------------------------------------------
-TODO expand this ...? list some backends and their features?
-
=== Using different exception handlers
-TODO
+The I18n API defines the following exceptions that will be raised by backends when the corresponding unexpected conditions occur:
-* Explain what exceptions are raised and why we are using exceptions for communication from backend to frontend.
-* Explain the default behaviour.
-* Explain the :raise option
+[source, ruby]
+-------------------------------------------------------
+MissingTranslationData # no translation was found for the requested key
+InvalidLocale # the locale set to I18n.locale is invalid (e.g. nil)
+InvalidPluralizationData # a count option was passed but the translation data is not suitable for pluralization
+MissingInterpolationArgument # the translation expects an interpolation argument that has not been passed
+ReservedInterpolationKey # the translation contains a reserved interpolation variable name (i.e. one of: scope, default)
+UnknownFileType # the backend does not know how to handle a file type that was added to I18n.load_path
+-------------------------------------------------------
+
+The I18n API will catch all of these exceptions when they were thrown in the backend and pass them to the default_exception_handler method. This method will re-raise all exceptions except for MissingTranslationData exceptions. When a MissingTranslationData exception has been caught it will return the exception’s error message string containing the missing key/scope.
+
+The reason for this is that during development you'd usually want your views to still render even though a translation is missing.
+
+In other contexts you might want to change this behaviour though. E.g. the default exception handling does not allow to catch missing translations during automated tests easily. For this purpose a different exception handler can be specified. The specified exception handler must be a method on the I18n module:
-* Example 1: the Rails #t helper uses a custom exception handler that catches I18n::MissingTranslationData and wraps the message into a span with the CSS class "translation_missing"
-* Example 2: for tests you might want a handler that just raises all exceptions all the time
-* Example 3: a handler
+[source, ruby]
+-------------------------------------------------------
+module I18n
+ def just_raise_that_exception(*args)
+ raise args.first
+ end
+end
+
+I18n.exception_handler = :just_raise_that_exception
+-------------------------------------------------------
+
+This would re-raise all caught exceptions including MissingTranslationData.
+
+Another example where the default behaviour is less desirable is the Rails TranslationHelper which provides the method #t (as well as #translate). When a MissingTranslationData exception occurs in this context the helper wraps the message into a span with the css class translation_missing.
+
+To do so the helper forces I18n#translate to raise exceptions no matter what exception handler is defined by setting the :raise option:
+
+[source, ruby]
+-------------------------------------------------------
+I18n.t :foo, :raise => true # always re-raises exceptions from the backend
+-------------------------------------------------------
== Resources
-* http://rails-i18n.org
== Footnotes
-(1) One of these reasons is that we don't want to any unnecessary load for applications that do not need any I18n capabilities, so we need to keep the I18n library as simple as possible for English. Another reason is that it is virtually impossible to implement a one-fits-all solution for all problems related to I18n for all existing languages. So a solution that allows us to exchange the entire implementation easily is appropriate anyway. This also makes it much easier to experiment with custom features and extensions.
+[[[1]]] Or, to quote http://en.wikipedia.org/wiki/Internationalization_and_localization[Wikipedia]: _"Internationalization is the process of designing a software application so that it can be adapted to various languages and regions without engineering changes. Localization is the process of adapting software for a specific region or language by adding locale-specific components and translating text."_
+
+[[[2]]] Other backends might allow or require to use other formats, e.g. a GetText backend might allow to read GetText files.
-(2) Other backends might allow or require to use other formats, e.g. a GetText backend might allow to read GetText files.
+[[[3]]] One of these reasons is that we don't want to any unnecessary load for applications that do not need any I18n capabilities, so we need to keep the I18n library as simple as possible for English. Another reason is that it is virtually impossible to implement a one-fits-all solution for all problems related to I18n for all existing languages. So a solution that allows us to exchange the entire implementation easily is appropriate anyway. This also makes it much easier to experiment with custom features and extensions.
== Credits
diff --git a/railties/doc/guides/source/images/i18n/demo_localized_pirate.png b/railties/doc/guides/source/images/i18n/demo_localized_pirate.png
new file mode 100644
index 0000000000..22b93416a0
--- /dev/null
+++ b/railties/doc/guides/source/images/i18n/demo_localized_pirate.png
Binary files differ
diff --git a/railties/doc/guides/source/images/i18n/demo_translated_en.png b/railties/doc/guides/source/images/i18n/demo_translated_en.png
new file mode 100644
index 0000000000..7ea0c437a5
--- /dev/null
+++ b/railties/doc/guides/source/images/i18n/demo_translated_en.png
Binary files differ
diff --git a/railties/doc/guides/source/images/i18n/demo_translated_pirate.png b/railties/doc/guides/source/images/i18n/demo_translated_pirate.png
new file mode 100644
index 0000000000..60ef370158
--- /dev/null
+++ b/railties/doc/guides/source/images/i18n/demo_translated_pirate.png
Binary files differ
diff --git a/railties/doc/guides/source/images/i18n/demo_translation_missing.png b/railties/doc/guides/source/images/i18n/demo_translation_missing.png
new file mode 100644
index 0000000000..86a3121cc1
--- /dev/null
+++ b/railties/doc/guides/source/images/i18n/demo_translation_missing.png
Binary files differ
diff --git a/railties/doc/guides/source/images/i18n/demo_untranslated.png b/railties/doc/guides/source/images/i18n/demo_untranslated.png
new file mode 100644
index 0000000000..e6717fb7d1
--- /dev/null
+++ b/railties/doc/guides/source/images/i18n/demo_untranslated.png
Binary files differ
diff --git a/railties/doc/guides/source/testing_rails_applications.txt b/railties/doc/guides/source/testing_rails_applications.txt
index b492fdb300..cb77829fc1 100644
--- a/railties/doc/guides/source/testing_rails_applications.txt
+++ b/railties/doc/guides/source/testing_rails_applications.txt
@@ -226,18 +226,18 @@ Above +rake db:migrate+ runs any pending migrations on the _developemnt_ environ
NOTE: +db:test:prepare+ will fail with an error if db/schema.rb doesn't exists.
-==== Rake Tasks for Preparing you Application for Testing ==
+==== Rake Tasks for Preparing your Application for Testing ====
[grid="all"]
-------------------------------------------------------------------------------------
-Tasks Description
-------------------------------------------------------------------------------------
-+rake db:test:clone+ Recreate the test database from the current environment's database schema
-+rake db:test:clone_structure+ Recreate the test databases from the development structure
-+rake db:test:load+ Recreate the test database from the current +schema.rb+
-+rake db:test:prepare+ Check for pending migrations and load the test schema
-+rake db:test:purge+ Empty the test database.
-------------------------------------------------------------------------------------
+|------------------------------------------------------------------------------------
+|Tasks Description
+|------------------------------------------------------------------------------------
+|+rake db:test:clone+ Recreate the test database from the current environment's database schema
+|+rake db:test:clone_structure+ Recreate the test databases from the development structure
+|+rake db:test:load+ Recreate the test database from the current +schema.rb+
+|+rake db:test:prepare+ Check for pending migrations and load the test schema
+|+rake db:test:purge+ Empty the test database.
+|------------------------------------------------------------------------------------
TIP: You can see all these rake tasks and their descriptions by running +rake \-\-tasks \-\-describe+
diff --git a/railties/lib/commands/about.rb b/railties/lib/commands/about.rb
index 7f53ac8a2e..bc2cfcb948 100644
--- a/railties/lib/commands/about.rb
+++ b/railties/lib/commands/about.rb
@@ -1,3 +1,3 @@
-require 'environment'
+require "#{RAILS_ROOT}/config/environment"
require 'rails/info'
puts Rails::Info
diff --git a/railties/lib/commands/dbconsole.rb b/railties/lib/commands/dbconsole.rb
index 6ff895aa30..06848d3c91 100644
--- a/railties/lib/commands/dbconsole.rb
+++ b/railties/lib/commands/dbconsole.rb
@@ -41,7 +41,7 @@ when "mysql"
if config['password'] && include_password
args << "--password=#{config['password']}"
- elsif config['password'] && !config['password'].empty?
+ elsif config['password'] && !config['password'].to_s.empty?
args << "-p"
end
diff --git a/railties/lib/commands/runner.rb b/railties/lib/commands/runner.rb
index 2411c3d270..510128318a 100644
--- a/railties/lib/commands/runner.rb
+++ b/railties/lib/commands/runner.rb
@@ -48,5 +48,7 @@ begin
eval(code_or_file)
end
ensure
- RAILS_DEFAULT_LOGGER.flush if RAILS_DEFAULT_LOGGER
+ if defined? Rails
+ Rails.logger.flush if Rails.logger.respond_to?(:flush)
+ end
end
diff --git a/railties/lib/commands/server.rb b/railties/lib/commands/server.rb
index 7057fcc33f..43b18004c0 100644
--- a/railties/lib/commands/server.rb
+++ b/railties/lib/commands/server.rb
@@ -84,7 +84,7 @@ else
end
app = Rack::Builder.new {
- use Rails::Rack::Logger
+ use Rails::Rack::LogTailer unless options[:detach]
use Rails::Rack::Static
use Rails::Rack::Debugger if options[:debugger]
run inner_app
diff --git a/railties/lib/initializer.rb b/railties/lib/initializer.rb
index 06a3332c42..619701460d 100644
--- a/railties/lib/initializer.rb
+++ b/railties/lib/initializer.rb
@@ -39,7 +39,7 @@ module Rails
nil
end
end
-
+
def backtrace_cleaner
@@backtrace_cleaner ||= begin
# Relies on ActiveSupport, so we have to lazy load to postpone definition until AS has been loaded
@@ -148,7 +148,6 @@ module Rails
initialize_dependency_mechanism
initialize_whiny_nils
- initialize_temporary_session_directory
initialize_time_zone
initialize_i18n
@@ -156,6 +155,8 @@ module Rails
initialize_framework_settings
initialize_framework_views
+ initialize_metal
+
add_support_load_paths
load_gems
@@ -369,8 +370,9 @@ Run `rake gems:install` to install the missing gems.
def load_view_paths
if configuration.frameworks.include?(:action_view)
if configuration.cache_classes
- ActionController::Base.view_paths.load if configuration.frameworks.include?(:action_controller)
- ActionMailer::Base.template_root.load if configuration.frameworks.include?(:action_mailer)
+ view_path = ActionView::Template::EagerPath.new(configuration.view_path)
+ ActionController::Base.view_paths = view_path if configuration.frameworks.include?(:action_controller)
+ ActionMailer::Base.template_root = view_path if configuration.frameworks.include?(:action_mailer)
end
end
end
@@ -472,7 +474,7 @@ Run `rake gems:install` to install the missing gems.
# set to use Configuration#view_path.
def initialize_framework_views
if configuration.frameworks.include?(:action_view)
- view_path = ActionView::PathSet::Path.new(configuration.view_path, false)
+ view_path = ActionView::Template::Path.new(configuration.view_path)
ActionMailer::Base.template_root ||= view_path if configuration.frameworks.include?(:action_mailer)
ActionController::Base.view_paths = view_path if configuration.frameworks.include?(:action_controller) && ActionController::Base.view_paths.empty?
end
@@ -501,13 +503,6 @@ Run `rake gems:install` to install the missing gems.
require('active_support/whiny_nil') if configuration.whiny_nils
end
- def initialize_temporary_session_directory
- if configuration.frameworks.include?(:action_controller)
- session_path = "#{configuration.root_path}/tmp/sessions/"
- ActionController::Base.session_options[:tmpdir] = File.exist?(session_path) ? session_path : Dir::tmpdir
- end
- end
-
# Sets the default value for Time.zone, and turns on ActiveRecord::Base#time_zone_aware_attributes.
# If assigned value cannot be matched to a TimeZone, an exception will be raised.
def initialize_time_zone
@@ -529,7 +524,7 @@ Run `rake gems:install` to install the missing gems.
end
end
- # Set the i18n configuration from config.i18n but special-case for the load_path which should be
+ # Set the i18n configuration from config.i18n but special-case for the load_path which should be
# appended to what's already set instead of overwritten.
def initialize_i18n
configuration.i18n.each do |setting, value|
@@ -541,6 +536,10 @@ Run `rake gems:install` to install the missing gems.
end
end
+ def initialize_metal
+ configuration.middleware.insert_before(:"ActionController::VerbPiggybacking", Rails::Rack::Metal)
+ end
+
# Initializes framework-specific settings for each of the loaded frameworks
# (Configuration#frameworks). The available settings map to the accessors
# on each of the corresponding Base classes.
@@ -923,6 +922,7 @@ Run `rake gems:install` to install the missing gems.
# Followed by the standard includes.
paths.concat %w(
app
+ app/metal
app/models
app/controllers
app/helpers
@@ -941,6 +941,7 @@ Run `rake gems:install` to install the missing gems.
def default_eager_load_paths
%w(
+ app/metal
app/models
app/controllers
app/helpers
diff --git a/railties/lib/rails/backtrace_cleaner.rb b/railties/lib/rails/backtrace_cleaner.rb
index f344c6477d..e1b422716d 100644
--- a/railties/lib/rails/backtrace_cleaner.rb
+++ b/railties/lib/rails/backtrace_cleaner.rb
@@ -2,21 +2,25 @@ module Rails
class BacktraceCleaner < ActiveSupport::BacktraceCleaner
ERB_METHOD_SIG = /:in `_run_erb_.*/
- VENDOR_DIRS = %w( vendor/plugins vendor/gems vendor/rails )
+ VENDOR_DIRS = %w( vendor/gems vendor/rails )
SERVER_DIRS = %w( lib/mongrel bin/mongrel
lib/passenger bin/passenger-spawn-server
lib/rack )
RAILS_NOISE = %w( script/server )
RUBY_NOISE = %w( rubygems/custom_require benchmark.rb )
+ GEMS_DIR = Gem.default_dir
+
ALL_NOISE = VENDOR_DIRS + SERVER_DIRS + RAILS_NOISE + RUBY_NOISE
def initialize
super
- add_filter { |line| line.sub(RAILS_ROOT, '') }
+ add_filter { |line| line.sub("#{RAILS_ROOT}/", '') }
add_filter { |line| line.sub(ERB_METHOD_SIG, '') }
add_filter { |line| line.sub('./', '/') } # for tests
+ add_filter { |line| line.sub(/(#{GEMS_DIR})\/gems\/([a-z]+)-([0-9.]+)\/(.*)/, '\2 (\3) \4')} # http://gist.github.com/30430
add_silencer { |line| ALL_NOISE.any? { |dir| line.include?(dir) } }
+ add_silencer { |line| line =~ %r(vendor/plugins/[^\/]+/lib) }
end
end
diff --git a/railties/lib/rails/plugin/locator.rb b/railties/lib/rails/plugin/locator.rb
index 678b295dc9..a6fc388a8e 100644
--- a/railties/lib/rails/plugin/locator.rb
+++ b/railties/lib/rails/plugin/locator.rb
@@ -30,7 +30,7 @@ module Rails
end
# The Rails::Plugin::FileSystemLocator will try to locate plugins by examining the directories
- # the the paths given in configuration.plugin_paths. Any plugins that can be found are returned
+ # in the paths given in configuration.plugin_paths. Any plugins that can be found are returned
# in a list.
#
# The criteria for a valid plugin in this case is found in Rails::Plugin#valid?, although
diff --git a/railties/lib/rails/rack.rb b/railties/lib/rails/rack.rb
index 90535674e9..9705f65e52 100644
--- a/railties/lib/rails/rack.rb
+++ b/railties/lib/rails/rack.rb
@@ -1,7 +1,8 @@
module Rails
module Rack
autoload :Debugger, "rails/rack/debugger"
- autoload :Logger, "rails/rack/logger"
+ autoload :LogTailer, "rails/rack/log_tailer"
+ autoload :Metal, "rails/rack/metal"
autoload :Static, "rails/rack/static"
end
end
diff --git a/railties/lib/rails/rack/log_tailer.rb b/railties/lib/rails/rack/log_tailer.rb
new file mode 100644
index 0000000000..a237cee6bc
--- /dev/null
+++ b/railties/lib/rails/rack/log_tailer.rb
@@ -0,0 +1,35 @@
+module Rails
+ module Rack
+ class LogTailer
+ EnvironmentLog = "#{File.expand_path(Rails.root)}/log/#{Rails.env}.log"
+
+ def initialize(app, log = nil)
+ @app = app
+
+ path = Pathname.new(log || EnvironmentLog).cleanpath
+ @cursor = ::File.size(path)
+ @last_checked = Time.now.to_f
+
+ @file = ::File.open(path, 'r')
+ end
+
+ def call(env)
+ response = @app.call(env)
+ tail_log
+ response
+ end
+
+ def tail_log
+ @file.seek @cursor
+
+ mod = @file.mtime.to_f
+ if mod > @last_checked
+ contents = @file.read
+ @last_checked = mod
+ @cursor += contents.size
+ $stdout.print contents
+ end
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/rack/logger.rb b/railties/lib/rails/rack/logger.rb
deleted file mode 100644
index 89d02e45a9..0000000000
--- a/railties/lib/rails/rack/logger.rb
+++ /dev/null
@@ -1,28 +0,0 @@
-module Rails
- module Rack
- class Logger
- EnvironmentLog = "#{File.expand_path(Rails.root)}/log/#{Rails.env}.log"
-
- def initialize(app, log = nil)
- @app = app
- @path = Pathname.new(log || EnvironmentLog).cleanpath
- @cursor = ::File.size(@path)
- @last_checked = Time.now
- end
-
- def call(env)
- response = @app.call(env)
- ::File.open(@path, 'r') do |f|
- f.seek @cursor
- if f.mtime > @last_checked
- contents = f.read
- @last_checked = f.mtime
- @cursor += contents.length
- print contents
- end
- end
- response
- end
- end
- end
-end
diff --git a/railties/lib/rails/rack/metal.rb b/railties/lib/rails/rack/metal.rb
new file mode 100644
index 0000000000..b185227234
--- /dev/null
+++ b/railties/lib/rails/rack/metal.rb
@@ -0,0 +1,36 @@
+require 'active_support/ordered_hash'
+
+module Rails
+ module Rack
+ class Metal
+ NotFoundResponse = [404, {}, []].freeze
+ NotFound = lambda { NotFoundResponse }
+
+ def self.metals
+ base = "#{Rails.root}/app/metal"
+ matcher = /\A#{Regexp.escape(base)}\/(.*)\.rb\Z/
+
+ Dir["#{base}/**/*.rb"].sort.map do |file|
+ file.sub!(matcher, '\1')
+ require file
+ file.classify.constantize
+ end
+ end
+
+ def initialize(app)
+ @app = app
+ @metals = ActiveSupport::OrderedHash.new
+ self.class.metals.each { |app| @metals[app] = true }
+ freeze
+ end
+
+ def call(env)
+ @metals.keys.each do |app|
+ result = app.call(env)
+ return result unless result[0].to_i == 404
+ end
+ @app.call(env)
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails_generator/commands.rb b/railties/lib/rails_generator/commands.rb
index cacb3807d6..299044c3d7 100644
--- a/railties/lib/rails_generator/commands.rb
+++ b/railties/lib/rails_generator/commands.rb
@@ -294,7 +294,7 @@ HELP
file(relative_source, relative_destination, template_options) do |file|
# Evaluate any assignments in a temporary, throwaway binding.
vars = template_options[:assigns] || {}
- b = binding
+ b = template_options[:binding] || binding
vars.each { |k,v| eval "#{k} = vars[:#{k}] || vars['#{k}']", b }
# Render the source file with the temporary binding.
diff --git a/railties/lib/rails_generator/generators/applications/app/template_runner.rb b/railties/lib/rails_generator/generators/applications/app/template_runner.rb
index c6113648e6..bb7bd0e6f4 100644
--- a/railties/lib/rails_generator/generators/applications/app/template_runner.rb
+++ b/railties/lib/rails_generator/generators/applications/app/template_runner.rb
@@ -8,23 +8,24 @@ require 'fileutils'
module Rails
class TemplateRunner
attr_reader :root
+ attr_writer :logger
def initialize(template, root = '') # :nodoc:
- @root = File.join(Dir.pwd, root)
+ @root = File.expand_path(File.directory?(root) ? root : File.join(Dir.pwd, root))
- puts "applying template: #{template}"
+ log 'applying', "template: #{template}"
load_template(template)
- puts "#{template} applied."
+ log 'applied', "#{template}"
end
def load_template(template)
begin
code = open(template).read
in_root { self.instance_eval(code) }
- rescue LoadError
- raise "The template [#{template}] could not be loaded."
+ rescue LoadError, Errno::ENOENT => e
+ raise "The template [#{template}] could not be loaded. Error: #{e}"
end
end
@@ -41,8 +42,8 @@ module Rails
#
# file("config/apach.conf", "your apache config")
#
- def file(filename, data = nil, &block)
- puts "creating file #{filename}"
+ def file(filename, data = nil, log_action = true, &block)
+ log 'file', filename if log_action
dir, file = [File.dirname(filename), File.basename(filename)]
inside(dir) do
@@ -66,7 +67,7 @@ module Rails
# plugin 'restful-authentication', :svn => 'svn://svnhub.com/technoweenie/restful-authentication/trunk'
#
def plugin(name, options)
- puts "installing plugin #{name}"
+ log 'plugin', name
if options[:git] && options[:submodule]
in_root do
@@ -74,28 +75,36 @@ module Rails
end
elsif options[:git] || options[:svn]
in_root do
- `script/plugin install #{options[:svn] || options[:git]}`
+ run("script/plugin install #{options[:svn] || options[:git]}", false)
end
else
- puts "! no git or svn provided for #{name}. skipping..."
+ log "! no git or svn provided for #{name}. skipping..."
end
end
# Adds an entry into config/environment.rb for the supplied gem :
def gem(name, options = {})
- puts "adding gem #{name}"
+ log 'gem', name
- sentinel = 'Rails::Initializer.run do |config|'
gems_code = "config.gem '#{name}'"
if options.any?
- opts = options.inject([]) {|result, h| result << [":#{h[0]} => '#{h[1]}'"] }.join(", ")
+ opts = options.inject([]) {|result, h| result << [":#{h[0]} => '#{h[1]}'"] }.sort.join(", ")
gems_code << ", #{opts}"
end
+ environment gems_code
+ end
+
+ # Adds a line inside the Initializer block for config/environment.rb. Used by #gem
+ def environment(data = nil, &block)
+ sentinel = 'Rails::Initializer.run do |config|'
+
+ data = block.call if !data && block_given?
+
in_root do
gsub_file 'config/environment.rb', /(#{Regexp.escape(sentinel)})/mi do |match|
- "#{match}\n #{gems_code}"
+ "#{match}\n " << data
end
end
end
@@ -111,11 +120,11 @@ module Rails
def git(command = {})
in_root do
if command.is_a?(Symbol)
- puts "running git #{command}"
+ log 'running', "git #{command}"
Git.run(command.to_s)
else
command.each do |command, options|
- puts "running git #{command} #{options}"
+ log 'running', "git #{command} #{options}"
Git.run("#{command} #{options}")
end
end
@@ -135,16 +144,8 @@ module Rails
# vendor("foreign.rb", "# Foreign code is fun")
#
def vendor(filename, data = nil, &block)
- puts "vendoring file #{filename}"
- inside("vendor") do |folder|
- File.open("#{folder}/#{filename}", "w") do |f|
- if block_given?
- f.write(block.call)
- else
- f.write(data)
- end
- end
- end
+ log 'vendoring', filename
+ file("vendor/#{filename}", data, false, &block)
end
# Create a new file in the lib/ directory. Code can be specified
@@ -158,17 +159,9 @@ module Rails
#
# lib("foreign.rb", "# Foreign code is fun")
#
- def lib(filename, data = nil)
- puts "add lib file #{filename}"
- inside("lib") do |folder|
- File.open("#{folder}/#{filename}", "w") do |f|
- if block_given?
- f.write(block.call)
- else
- f.write(data)
- end
- end
- end
+ def lib(filename, data = nil, &block)
+ log 'lib', filename
+ file("lib/#{filename}", data, false, &block)
end
# Create a new Rakefile with the provided code (either in a block or a string).
@@ -190,16 +183,8 @@ module Rails
# rakefile("seed.rake", "puts 'im plantin ur seedz'")
#
def rakefile(filename, data = nil, &block)
- puts "adding rakefile #{filename}"
- inside("lib/tasks") do |folder|
- File.open("#{folder}/#{filename}", "w") do |f|
- if block_given?
- f.write(block.call)
- else
- f.write(data)
- end
- end
- end
+ log 'rakefile', filename
+ file("lib/tasks/#{filename}", data, false, &block)
end
# Create a new initializer with the provided code (either in a block or a string).
@@ -219,16 +204,8 @@ module Rails
# initializer("api.rb", "API_KEY = '123456'")
#
def initializer(filename, data = nil, &block)
- puts "adding initializer #{filename}"
- inside("config/initializers") do |folder|
- File.open("#{folder}/#{filename}", "w") do |f|
- if block_given?
- f.write(block.call)
- else
- f.write(data)
- end
- end
- end
+ log 'initializer', filename
+ file("config/initializers/#{filename}", data, false, &block)
end
# Generate something using a generator from Rails or a plugin.
@@ -240,10 +217,10 @@ module Rails
# generate(:authenticated, "user session")
#
def generate(what, *args)
- puts "generating #{what}"
+ log 'generating', what
argument = args.map(&:to_s).flatten.join(" ")
- in_root { `#{root}/script/generate #{what} #{argument}` }
+ in_root { run("script/generate #{what} #{argument}", false) }
end
# Executes a command
@@ -254,8 +231,8 @@ module Rails
# run('ln -s ~/edge rails)
# end
#
- def run(command)
- puts "executing #{command} from #{Dir.pwd}"
+ def run(command, log_action = true)
+ log 'executing', "#{command} from #{Dir.pwd}" if log_action
`#{command}`
end
@@ -268,10 +245,10 @@ module Rails
# rake("gems:install", :sudo => true)
#
def rake(command, options = {})
- puts "running rake task #{command}"
+ log 'rake', command
env = options[:env] || 'development'
sudo = options[:sudo] ? 'sudo ' : ''
- in_root { `#{sudo}rake #{command} RAILS_ENV=#{env}` }
+ in_root { run("#{sudo}rake #{command} RAILS_ENV=#{env}", false) }
end
# Just run the capify command in root
@@ -281,7 +258,8 @@ module Rails
# capify!
#
def capify!
- in_root { `capify .` }
+ log 'capifying'
+ in_root { run('capify .', false) }
end
# Add Rails to /vendor/rails
@@ -291,8 +269,8 @@ module Rails
# freeze!
#
def freeze!(args = {})
- puts "vendoring rails edge"
- in_root { `rake rails:freeze:edge` }
+ log 'vendor', 'rails edge'
+ in_root { run('rake rails:freeze:edge', false) }
end
# Make an entry in Rails routing file conifg/routes.rb
@@ -302,6 +280,7 @@ module Rails
# route "map.root :controller => :welcome"
#
def route(routing_code)
+ log 'route', routing_code
sentinel = 'ActionController::Routing::Routes.draw do |map|'
in_root do
@@ -321,7 +300,7 @@ module Rails
# freeze! if ask("Should I freeze the latest Rails?") == "yes"
#
def ask(string)
- puts string
+ log '', string
gets.strip
end
@@ -368,5 +347,23 @@ module Rails
def destination_path(relative_destination)
File.join(root, relative_destination)
end
+
+ def log(action, message = '')
+ logger.log(action, message)
+ end
+
+ def logger
+ @logger ||= Rails::Generator::Base.logger
+ end
+
+ def logger
+ @logger ||= if defined?(Rails::Generator::Base)
+ Rails::Generator::Base.logger
+ else
+ require 'rails_generator/simple_logger'
+ Rails::Generator::SimpleLogger.new(STDOUT)
+ end
+ end
+
end
end \ No newline at end of file
diff --git a/railties/lib/rails_generator/generators/components/metal/USAGE b/railties/lib/rails_generator/generators/components/metal/USAGE
new file mode 100644
index 0000000000..123ec6c03f
--- /dev/null
+++ b/railties/lib/rails_generator/generators/components/metal/USAGE
@@ -0,0 +1,8 @@
+Description:
+ Cast some metal!
+
+Examples:
+ `./script/generate metal poller`
+
+ This will create:
+ Metal: app/metal/poller.rb
diff --git a/railties/lib/rails_generator/generators/components/metal/metal_generator.rb b/railties/lib/rails_generator/generators/components/metal/metal_generator.rb
new file mode 100644
index 0000000000..64f49d929d
--- /dev/null
+++ b/railties/lib/rails_generator/generators/components/metal/metal_generator.rb
@@ -0,0 +1,8 @@
+class MetalGenerator < Rails::Generator::NamedBase
+ def manifest
+ record do |m|
+ m.directory 'app/metal'
+ m.template 'metal.rb', File.join('app/metal', "#{file_name}.rb")
+ end
+ end
+end
diff --git a/railties/lib/rails_generator/generators/components/metal/templates/metal.rb b/railties/lib/rails_generator/generators/components/metal/templates/metal.rb
new file mode 100644
index 0000000000..e94982b69a
--- /dev/null
+++ b/railties/lib/rails_generator/generators/components/metal/templates/metal.rb
@@ -0,0 +1,12 @@
+# Allow the metal piece to run in isolation
+require(File.dirname(__FILE__) + "/../../config/environment") unless defined?(Rails)
+
+class <%= class_name %>
+ def self.call(env)
+ if env["PATH_INFO"] =~ /^\/<%= file_name %>/
+ [200, {"Content-Type" => "text/html"}, ["Hello, World!"]]
+ else
+ [404, {"Content-Type" => "text/html"}, ["Not Found"]]
+ end
+ end
+end
diff --git a/railties/lib/tasks/databases.rake b/railties/lib/tasks/databases.rake
index 3a576063fa..68ffefae0b 100644
--- a/railties/lib/tasks/databases.rake
+++ b/railties/lib/tasks/databases.rake
@@ -380,7 +380,7 @@ namespace :db do
end
namespace :sessions do
- desc "Creates a sessions migration for use with CGI::Session::ActiveRecordStore"
+ desc "Creates a sessions migration for use with ActiveRecord::SessionStore"
task :create => :environment do
raise "Task unavailable to this database (no migration support)" unless ActiveRecord::Base.connection.supports_migrations?
require 'rails_generator'
diff --git a/railties/lib/tasks/middleware.rake b/railties/lib/tasks/middleware.rake
index e0dcf50307..05f159184e 100644
--- a/railties/lib/tasks/middleware.rake
+++ b/railties/lib/tasks/middleware.rake
@@ -1,6 +1,6 @@
desc 'Prints out your Rack middleware stack'
task :middleware => :environment do
- ActionController::Dispatcher.middleware.each do |middleware|
+ ActionController::Dispatcher.middleware.active.each do |middleware|
puts "use #{middleware.inspect}"
end
puts "run ActionController::Dispatcher.new"
diff --git a/railties/lib/tasks/tmp.rake b/railties/lib/tasks/tmp.rake
index b191039d63..fea15058bb 100644
--- a/railties/lib/tasks/tmp.rake
+++ b/railties/lib/tasks/tmp.rake
@@ -2,7 +2,7 @@ namespace :tmp do
desc "Clear session, cache, and socket files from tmp/"
task :clear => [ "tmp:sessions:clear", "tmp:cache:clear", "tmp:sockets:clear"]
- desc "Creates tmp directories for sessions, cache, and sockets"
+ desc "Creates tmp directories for sessions, cache, sockets, and pids"
task :create do
FileUtils.mkdir_p(%w( tmp/sessions tmp/cache tmp/sockets tmp/pids ))
end
@@ -34,4 +34,4 @@ namespace :tmp do
FileUtils.rm(Dir['tmp/pids/[^.]*'])
end
end
-end \ No newline at end of file
+end
diff --git a/railties/lib/test_help.rb b/railties/lib/test_help.rb
index b5c92c1790..ee24ea3a45 100644
--- a/railties/lib/test_help.rb
+++ b/railties/lib/test_help.rb
@@ -3,7 +3,6 @@
silence_warnings { RAILS_ENV = "test" }
require 'test/unit'
-require 'active_support/test_case'
require 'action_controller/test_case'
require 'action_view/test_case'
require 'action_controller/integration'
diff --git a/railties/test/console_app_test.rb b/railties/test/console_app_test.rb
index 6cfc907b80..f419fe0d8d 100644
--- a/railties/test/console_app_test.rb
+++ b/railties/test/console_app_test.rb
@@ -4,6 +4,7 @@ require 'action_controller' # console_app uses 'action_controller/integration'
unless defined? ApplicationController
class ApplicationController < ActionController::Base; end
+ ActionController::Base.session_store = nil
end
require 'dispatcher'
@@ -13,6 +14,15 @@ require 'console_app'
Test::Unit.run = false
class ConsoleAppTest < Test::Unit::TestCase
+ def test_app_method_should_return_integration_session
+ assert_nothing_thrown do
+ console_session = app
+ assert_not_nil console_session
+ assert_instance_of ActionController::Integration::Session,
+ console_session
+ end
+ end
+
uses_mocha 'console reload test' do
def test_reload_should_fire_preparation_callbacks
a = b = c = nil
diff --git a/railties/test/error_page_test.rb b/railties/test/error_page_test.rb
index 844f889aad..f819e468e8 100644
--- a/railties/test/error_page_test.rb
+++ b/railties/test/error_page_test.rb
@@ -1,6 +1,6 @@
require 'abstract_unit'
require 'action_controller'
-require 'action_controller/test_process'
+require 'action_controller/test_case'
RAILS_ENV = "test"
CURRENT_DIR = File.expand_path(File.dirname(__FILE__))
@@ -22,13 +22,10 @@ ActionController::Routing::Routes.draw do |map|
map.connect ':controller/:action/:id'
end
-class ErrorPageControllerTest < Test::Unit::TestCase
+class ErrorPageControllerTest < ActionController::TestCase
def setup
- @controller = ErrorPageController.new
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
-
ActionController::Base.consider_all_requests_local = false
+ rescue_action_in_public!
end
def test_500_error_page_instructs_system_administrator_to_check_log_file
@@ -38,6 +35,6 @@ class ErrorPageControllerTest < Test::Unit::TestCase
end
get :crash
expected_log_file = "#{RAILS_ENV}.log"
- assert_not_nil @response.body.index(expected_log_file)
+ assert_not_nil @response.body.index(expected_log_file), @response.body
end
end
diff --git a/railties/test/fcgi_dispatcher_test.rb b/railties/test/fcgi_dispatcher_test.rb
index cc054c24aa..c469c5dd01 100644
--- a/railties/test/fcgi_dispatcher_test.rb
+++ b/railties/test/fcgi_dispatcher_test.rb
@@ -1,10 +1,9 @@
require 'abstract_unit'
begin
+require 'action_controller'
require 'fcgi_handler'
-module ActionController; module Routing; module Routes; end end end
-
class RailsFCGIHandlerTest < Test::Unit::TestCase
def setup
@log = StringIO.new
@@ -131,19 +130,11 @@ class RailsFCGIHandlerSignalsTest < Test::Unit::TestCase
end
end
- class ::Dispatcher
- class << self
- attr_accessor :signal
- alias_method :old_dispatch, :dispatch
- def dispatch(cgi)
- signal ? Process.kill(signal, $$) : old_dispatch
- end
- end
- end
-
def setup
@log = StringIO.new
@handler = RailsFCGIHandler.new(@log)
+ @dispatcher = mock
+ Dispatcher.stubs(:new).returns(@dispatcher)
end
def test_interrupted_via_HUP_when_not_in_request
@@ -159,19 +150,6 @@ class RailsFCGIHandlerSignalsTest < Test::Unit::TestCase
assert_equal :reload, @handler.when_ready
end
- def test_interrupted_via_HUP_when_in_request
- cgi = mock
- FCGI.expects(:each_cgi).once.yields(cgi)
- Dispatcher.expects(:signal).times(2).returns('HUP')
-
- @handler.expects(:reload!).once
- @handler.expects(:close_connection).never
- @handler.expects(:exit).never
-
- @handler.process!
- assert_equal :reload, @handler.when_ready
- end
-
def test_interrupted_via_USR1_when_not_in_request
cgi = mock
FCGI.expects(:each_cgi).once.yields(cgi)
@@ -186,19 +164,6 @@ class RailsFCGIHandlerSignalsTest < Test::Unit::TestCase
assert_nil @handler.when_ready
end
- def test_interrupted_via_USR1_when_in_request
- cgi = mock
- FCGI.expects(:each_cgi).once.yields(cgi)
- Dispatcher.expects(:signal).times(2).returns('USR1')
-
- @handler.expects(:reload!).never
- @handler.expects(:close_connection).with(cgi).once
- @handler.expects(:exit).never
-
- @handler.process!
- assert_equal :exit, @handler.when_ready
- end
-
def test_restart_via_USR2_when_in_request
cgi = mock
FCGI.expects(:each_cgi).once.yields(cgi)
@@ -217,7 +182,7 @@ class RailsFCGIHandlerSignalsTest < Test::Unit::TestCase
def test_interrupted_via_TERM
cgi = mock
FCGI.expects(:each_cgi).once.yields(cgi)
- Dispatcher.expects(:signal).times(2).returns('TERM')
+ ::Rack::Handler::FastCGI.expects(:serve).once.returns('TERM')
@handler.expects(:reload!).never
@handler.expects(:close_connection).never
@@ -238,7 +203,7 @@ class RailsFCGIHandlerSignalsTest < Test::Unit::TestCase
cgi = mock
error = RuntimeError.new('foo')
FCGI.expects(:each_cgi).once.yields(cgi)
- Dispatcher.expects(:dispatch).once.with(cgi).raises(error)
+ ::Rack::Handler::FastCGI.expects(:serve).once.raises(error)
@handler.expects(:dispatcher_error).with(error, regexp_matches(/^unhandled/))
@handler.process!
end
@@ -254,7 +219,7 @@ class RailsFCGIHandlerSignalsTest < Test::Unit::TestCase
cgi = mock
error = SignalException.new('USR2')
FCGI.expects(:each_cgi).once.yields(cgi)
- Dispatcher.expects(:dispatch).once.with(cgi).raises(error)
+ ::Rack::Handler::FastCGI.expects(:serve).once.raises(error)
@handler.expects(:dispatcher_error).with(error, regexp_matches(/^stopping/))
@handler.process!
end
@@ -284,7 +249,7 @@ class RailsFCGIHandlerPeriodicGCTest < Test::Unit::TestCase
cgi = mock
FCGI.expects(:each_cgi).times(10).yields(cgi)
- Dispatcher.expects(:dispatch).times(10).with(cgi)
+ Dispatcher.expects(:new).times(10)
@handler.expects(:run_gc!).never
9.times { @handler.process! }
diff --git a/railties/test/gem_dependency_test.rb b/railties/test/gem_dependency_test.rb
index 1d4f2b18b3..6c1f0961a1 100644
--- a/railties/test/gem_dependency_test.rb
+++ b/railties/test/gem_dependency_test.rb
@@ -9,33 +9,33 @@ Rails::VendorGemSourceIndex.silence_spec_warnings = true
uses_mocha "Plugin Tests" do
class GemDependencyTest < Test::Unit::TestCase
def setup
- @gem = Rails::GemDependency.new "hpricot"
- @gem_with_source = Rails::GemDependency.new "hpricot", :source => "http://code.whytheluckystiff.net"
- @gem_with_version = Rails::GemDependency.new "hpricot", :version => "= 0.6"
- @gem_with_lib = Rails::GemDependency.new "aws-s3", :lib => "aws/s3"
- @gem_without_load = Rails::GemDependency.new "hpricot", :lib => false
+ @gem = Rails::GemDependency.new "xhpricotx"
+ @gem_with_source = Rails::GemDependency.new "xhpricotx", :source => "http://code.whytheluckystiff.net"
+ @gem_with_version = Rails::GemDependency.new "xhpricotx", :version => "= 0.6"
+ @gem_with_lib = Rails::GemDependency.new "xaws-s3x", :lib => "aws/s3"
+ @gem_without_load = Rails::GemDependency.new "xhpricotx", :lib => false
end
def test_configuration_adds_gem_dependency
config = Rails::Configuration.new
- config.gem "aws-s3", :lib => "aws/s3", :version => "0.4.0"
- assert_equal [["install", "aws-s3", "--version", '"= 0.4.0"']], config.gems.collect(&:install_command)
+ config.gem "xaws-s3x", :lib => "aws/s3", :version => "0.4.0"
+ assert_equal [["install", "xaws-s3x", "--version", '"= 0.4.0"']], config.gems.collect(&:install_command)
end
def test_gem_creates_install_command
- assert_equal %w(install hpricot), @gem.install_command
+ assert_equal %w(install xhpricotx), @gem.install_command
end
def test_gem_with_source_creates_install_command
- assert_equal %w(install hpricot --source http://code.whytheluckystiff.net), @gem_with_source.install_command
+ assert_equal %w(install xhpricotx --source http://code.whytheluckystiff.net), @gem_with_source.install_command
end
def test_gem_with_version_creates_install_command
- assert_equal ["install", "hpricot", "--version", '"= 0.6"'], @gem_with_version.install_command
+ assert_equal ["install", "xhpricotx", "--version", '"= 0.6"'], @gem_with_version.install_command
end
def test_gem_creates_unpack_command
- assert_equal %w(unpack hpricot), @gem.unpack_command
+ assert_equal %w(unpack xhpricotx), @gem.unpack_command
end
def test_gem_with_version_unpack_install_command
@@ -43,7 +43,7 @@ uses_mocha "Plugin Tests" do
mock_spec = mock()
mock_spec.stubs(:version).returns('0.6')
@gem_with_version.stubs(:specification).returns(mock_spec)
- assert_equal ["unpack", "hpricot", "--version", '= 0.6'], @gem_with_version.unpack_command
+ assert_equal ["unpack", "xhpricotx", "--version", '= 0.6'], @gem_with_version.unpack_command
end
def test_gem_adds_load_paths
@@ -134,7 +134,6 @@ uses_mocha "Plugin Tests" do
dummy_gem.add_load_paths
dummy_gem.load
assert dummy_gem.loaded?
- debugger
assert_equal 2, dummy_gem.dependencies.size
assert_nothing_raised do
dummy_gem.dependencies.each do |g|
diff --git a/railties/test/generators/rails_template_runner_test.rb b/railties/test/generators/rails_template_runner_test.rb
new file mode 100644
index 0000000000..fcc020603d
--- /dev/null
+++ b/railties/test/generators/rails_template_runner_test.rb
@@ -0,0 +1,190 @@
+require 'abstract_unit'
+require 'generators/generator_test_helper'
+
+class RailsTemplateRunnerTest < GeneratorTestCase
+ def setup
+ Rails::Generator::Base.use_application_sources!
+ run_generator('app', [RAILS_ROOT])
+ # generate empty template
+ @template_path = File.join(RAILS_ROOT, 'template.rb')
+ File.open(File.join(@template_path), 'w') {|f| f << '' }
+
+ @git_plugin_uri = 'git://github.com/technoweenie/restful-authentication.git'
+ @svn_plugin_uri = 'svn://svnhub.com/technoweenie/restful-authentication/trunk'
+ end
+
+ def teardown
+ super
+ rm_rf "#{RAILS_ROOT}/README"
+ rm_rf "#{RAILS_ROOT}/Rakefile"
+ rm_rf "#{RAILS_ROOT}/doc"
+ rm_rf "#{RAILS_ROOT}/lib"
+ rm_rf "#{RAILS_ROOT}/log"
+ rm_rf "#{RAILS_ROOT}/script"
+ rm_rf "#{RAILS_ROOT}/vendor"
+ rm_rf "#{RAILS_ROOT}/tmp"
+ rm_rf "#{RAILS_ROOT}/Capfile"
+ rm_rf @template_path
+ end
+
+ def test_initialize_should_load_template
+ Rails::TemplateRunner.any_instance.expects(:load_template).with(@template_path)
+ silence_generator do
+ Rails::TemplateRunner.new(@template_path, RAILS_ROOT)
+ end
+ end
+
+ def test_initialize_should_raise_error_on_missing_template_file
+ assert_raise(RuntimeError) do
+ silence_generator do
+ Rails::TemplateRunner.new('non/existent/path/to/template.rb', RAILS_ROOT)
+ end
+ end
+ end
+
+ def test_file_should_write_data_to_file_path
+ run_template_method(:file, 'lib/test_file.rb', 'heres test data')
+ assert_generated_file_with_data 'lib/test_file.rb', 'heres test data'
+ end
+
+ def test_file_should_write_block_contents_to_file_path
+ run_template_method(:file, 'lib/test_file.rb') { 'heres block data' }
+ assert_generated_file_with_data 'lib/test_file.rb', 'heres block data'
+ end
+
+ def test_plugin_with_git_option_should_run_plugin_install
+ expects_run_with_command("script/plugin install #{@git_plugin_uri}")
+ run_template_method(:plugin, 'restful-authentication', :git => @git_plugin_uri)
+ end
+
+ def test_plugin_with_svn_option_should_run_plugin_install
+ expects_run_with_command("script/plugin install #{@svn_plugin_uri}")
+ run_template_method(:plugin, 'restful-authentication', :svn => @svn_plugin_uri)
+ end
+
+ def test_plugin_with_git_option_and_submodule_should_use_git_scm
+ Rails::Git.expects(:run).with("submodule add #{@git_plugin_uri} vendor/plugins/rest_auth")
+ run_template_method(:plugin, 'rest_auth', :git => @git_plugin_uri, :submodule => true)
+ end
+
+ def test_plugin_with_no_options_should_skip_method
+ Rails::TemplateRunner.any_instance.expects(:run).never
+ run_template_method(:plugin, 'rest_auth', {})
+ end
+
+ def test_gem_should_put_gem_dependency_in_enviroment
+ run_template_method(:gem, 'will-paginate')
+ assert_rails_initializer_includes("config.gem 'will-paginate'")
+ end
+
+ def test_gem_with_options_should_include_options_in_gem_dependency_in_environment
+ run_template_method(:gem, 'mislav-will-paginate', :lib => 'will-paginate', :source => 'http://gems.github.com')
+ assert_rails_initializer_includes("config.gem 'mislav-will-paginate', :lib => 'will-paginate', :source => 'http://gems.github.com'")
+ end
+
+ def test_environment_should_include_data_in_environment_initializer_block
+ load_paths = 'config.load_paths += %w["#{RAILS_ROOT}/app/extras"]'
+ run_template_method(:environment, load_paths)
+ assert_rails_initializer_includes(load_paths)
+ end
+
+ def test_environment_with_block_should_include_block_contents_in_environment_initializer_block
+ run_template_method(:environment) do
+ '# This wont be added'
+ '# This will be added'
+ end
+ assert_rails_initializer_includes('# This will be added')
+ end
+
+ def test_git_with_symbol_should_run_command_using_git_scm
+ Rails::Git.expects(:run).once.with('init')
+ run_template_method(:git, :init)
+ end
+
+ def test_git_with_hash_should_run_each_command_using_git_scm
+ Rails::Git.expects(:run).times(2)
+ run_template_method(:git, {:init => '', :add => '.'})
+ end
+
+ def test_vendor_should_write_data_to_file_in_vendor
+ run_template_method(:vendor, 'vendor_file.rb', '# vendor data')
+ assert_generated_file_with_data('vendor/vendor_file.rb', '# vendor data')
+ end
+
+ def test_lib_should_write_data_to_file_in_lib
+ run_template_method(:lib, 'my_library.rb', 'class MyLibrary')
+ assert_generated_file_with_data('lib/my_library.rb', 'class MyLibrary')
+ end
+
+ def test_rakefile_should_write_date_to_file_in_lib_tasks
+ run_template_method(:rakefile, 'myapp.rake', 'task :run => [:environment]')
+ assert_generated_file_with_data('lib/tasks/myapp.rake', 'task :run => [:environment]')
+ end
+
+ def test_initializer_should_write_date_to_file_in_config_initializers
+ run_template_method(:initializer, 'constants.rb', 'MY_CONSTANT = 42')
+ assert_generated_file_with_data('config/initializers/constants.rb', 'MY_CONSTANT = 42')
+ end
+
+ def test_generate_should_run_script_generate_with_argument_and_options
+ expects_run_with_command('script/generate model MyModel')
+ run_template_method(:generate, 'model', 'MyModel')
+ end
+
+ def test_rake_should_run_rake_command_with_development_env
+ expects_run_with_command('rake log:clear RAILS_ENV=development')
+ run_template_method(:rake, 'log:clear')
+ end
+
+ def test_rake_with_env_option_should_run_rake_command_in_env
+ expects_run_with_command('rake log:clear RAILS_ENV=production')
+ run_template_method(:rake, 'log:clear', :env => 'production')
+ end
+
+ def test_rake_with_sudo_option_should_run_rake_command_with_sudo
+ expects_run_with_command('sudo rake log:clear RAILS_ENV=development')
+ run_template_method(:rake, 'log:clear', :sudo => true)
+ end
+
+ def test_capify_should_run_the_capify_command
+ expects_run_with_command('capify .')
+ run_template_method(:capify!)
+ end
+
+ def test_freeze_should_freeze_rails_edge
+ expects_run_with_command('rake rails:freeze:edge')
+ run_template_method(:freeze!)
+ end
+
+ def test_route_should_add_data_to_the_routes_block_in_config_routes
+ route_command = "map.route '/login', :controller => 'sessions', :action => 'new'"
+ run_template_method(:route, route_command)
+ assert_generated_file_with_data 'config/routes.rb', route_command
+ end
+
+ protected
+ def run_template_method(method_name, *args, &block)
+ silence_generator do
+ @template_runner = Rails::TemplateRunner.new(@template_path, RAILS_ROOT)
+ @template_runner.send(method_name, *args, &block)
+ end
+ end
+
+ def expects_run_with_command(command)
+ Rails::TemplateRunner.any_instance.stubs(:run).once.with(command, false)
+ end
+
+ def assert_rails_initializer_includes(data, message = nil)
+ message ||= "Rails::Initializer should include #{data}"
+ assert_generated_file 'config/environment.rb' do |body|
+ assert_match(/#{Regexp.escape("Rails::Initializer.run do |config|")}.+#{Regexp.escape(data)}.+end/m, body, message)
+ end
+ end
+
+ def assert_generated_file_with_data(file, data, message = nil)
+ message ||= "#{file} should include '#{data}'"
+ assert_generated_file(file) do |file|
+ assert_match(/#{Regexp.escape(data)}/,file, message)
+ end
+ end
+end \ No newline at end of file