From 5e1362572e1cfde237c6ae585ea34d2c11d61c25 Mon Sep 17 00:00:00 2001 From: Prem Sichanugrist Date: Thu, 6 Sep 2012 22:51:44 -0400 Subject: Move all the legacy guides to Markdown --- guides/source/2_2_release_notes.md | 422 ++++++++++++++++++++++ guides/source/2_2_release_notes.textile | 422 ---------------------- guides/source/2_3_release_notes.md | 610 ++++++++++++++++++++++++++++++++ guides/source/2_3_release_notes.textile | 610 -------------------------------- guides/source/3_0_release_notes.md | 595 +++++++++++++++++++++++++++++++ guides/source/3_0_release_notes.textile | 595 ------------------------------- guides/source/3_1_release_notes.md | 538 ++++++++++++++++++++++++++++ guides/source/3_1_release_notes.textile | 538 ---------------------------- guides/source/3_2_release_notes.md | 552 +++++++++++++++++++++++++++++ guides/source/3_2_release_notes.textile | 552 ----------------------------- 10 files changed, 2717 insertions(+), 2717 deletions(-) create mode 100644 guides/source/2_2_release_notes.md delete mode 100644 guides/source/2_2_release_notes.textile create mode 100644 guides/source/2_3_release_notes.md delete mode 100644 guides/source/2_3_release_notes.textile create mode 100644 guides/source/3_0_release_notes.md delete mode 100644 guides/source/3_0_release_notes.textile create mode 100644 guides/source/3_1_release_notes.md delete mode 100644 guides/source/3_1_release_notes.textile create mode 100644 guides/source/3_2_release_notes.md delete mode 100644 guides/source/3_2_release_notes.textile (limited to 'guides/source') diff --git a/guides/source/2_2_release_notes.md b/guides/source/2_2_release_notes.md new file mode 100644 index 0000000000..eb4b32329b --- /dev/null +++ b/guides/source/2_2_release_notes.md @@ -0,0 +1,422 @@ +h2. Ruby on Rails 2.2 Release Notes + +Rails 2.2 delivers a number of new and improved features. This list covers the major upgrades, but doesn't include every little bug fix and change. If you want to see everything, check out the "list of commits":http://github.com/rails/rails/commits/master in the main Rails repository on GitHub. + +Along with Rails, 2.2 marks the launch of the "Ruby on Rails Guides":http://guides.rubyonrails.org/, the first results of the ongoing "Rails Guides hackfest":http://hackfest.rubyonrails.org/guide. This site will deliver high-quality documentation of the major features of Rails. + +endprologue. + +h3. Infrastructure + +Rails 2.2 is a significant release for the infrastructure that keeps Rails humming along and connected to the rest of the world. + +h4. Internationalization + +Rails 2.2 supplies an easy system for internationalization (or i18n, for those of you tired of typing). + +* Lead Contributors: Rails i18 Team +* More information : +** "Official Rails i18 website":http://rails-i18n.org +** "Finally. Ruby on Rails gets internationalized":http://www.artweb-design.de/2008/7/18/finally-ruby-on-rails-gets-internationalized +** "Localizing Rails : Demo application":http://github.com/clemens/i18n_demo_app + +h4. Compatibility with Ruby 1.9 and JRuby + +Along with thread safety, a lot of work has been done to make Rails work well with JRuby and the upcoming Ruby 1.9. With Ruby 1.9 being a moving target, running edge Rails on edge Ruby is still a hit-or-miss proposition, but Rails is ready to make the transition to Ruby 1.9 when the latter is released. + +h3. Documentation + +The internal documentation of Rails, in the form of code comments, has been improved in numerous places. In addition, the "Ruby on Rails Guides":http://guides.rubyonrails.org/ project is the definitive source for information on major Rails components. In its first official release, the Guides page includes: + +* "Getting Started with Rails":http://guides.rubyonrails.org/getting_started.html +* "Rails Database Migrations":http://guides.rubyonrails.org/migrations.html +* "Active Record Associations":http://guides.rubyonrails.org/association_basics.html +* "Active Record Query Interface":http://guides.rubyonrails.org/active_record_querying.html +* "Layouts and Rendering in Rails":http://guides.rubyonrails.org/layouts_and_rendering.html +* "Action View Form Helpers":http://guides.rubyonrails.org/form_helpers.html +* "Rails Routing from the Outside In":http://guides.rubyonrails.org/routing.html +* "Action Controller Overview":http://guides.rubyonrails.org/action_controller_overview.html +* "Rails Caching":http://guides.rubyonrails.org/caching_with_rails.html +* "A Guide to Testing Rails Applications":http://guides.rubyonrails.org/testing.html +* "Securing Rails Applications":http://guides.rubyonrails.org/security.html +* "Debugging Rails Applications":http://guides.rubyonrails.org/debugging_rails_applications.html +* "Performance Testing Rails Applications":http://guides.rubyonrails.org/performance_testing.html +* "The Basics of Creating Rails Plugins":http://guides.rubyonrails.org/plugins.html + +All told, the Guides provide tens of thousands of words of guidance for beginning and intermediate Rails developers. + +If you want to generate these guides locally, inside your application: + + +rake doc:guides + + +This will put the guides inside +Rails.root/doc/guides+ and you may start surfing straight away by opening +Rails.root/doc/guides/index.html+ in your favourite browser. + +* Lead Contributors: "Rails Documentation Team":credits.html +* Major contributions from "Xavier Noria":http://advogato.org/person/fxn/diary.html and "Hongli Lai":http://izumi.plan99.net/blog/. +* More information: +** "Rails Guides hackfest":http://hackfest.rubyonrails.org/guide +** "Help improve Rails documentation on Git branch":http://weblog.rubyonrails.org/2008/5/2/help-improve-rails-documentation-on-git-branch + +h3. Better integration with HTTP : Out of the box ETag support + +Supporting the etag and last modified timestamp in HTTP headers means that Rails can now send back an empty response if it gets a request for a resource that hasn't been modified lately. This allows you to check whether a response needs to be sent at all. + + +class ArticlesController < ApplicationController + def show_with_respond_to_block + @article = Article.find(params[:id]) + + # If the request sends headers that differs from the options provided to stale?, then + # the request is indeed stale and the respond_to block is triggered (and the options + # to the stale? call is set on the response). + # + # If the request headers match, then the request is fresh and the respond_to block is + # not triggered. Instead the default render will occur, which will check the last-modified + # and etag headers and conclude that it only needs to send a "304 Not Modified" instead + # of rendering the template. + if stale?(:last_modified => @article.published_at.utc, :etag => @article) + respond_to do |wants| + # normal response processing + end + end + end + + def show_with_implied_render + @article = Article.find(params[:id]) + + # Sets the response headers and checks them against the request, if the request is stale + # (i.e. no match of either etag or last-modified), then the default render of the template happens. + # If the request is fresh, then the default render will return a "304 Not Modified" + # instead of rendering the template. + fresh_when(:last_modified => @article.published_at.utc, :etag => @article) + end +end + + +h3. Thread Safety + +The work done to make Rails thread-safe is rolling out in Rails 2.2. Depending on your web server infrastructure, this means you can handle more requests with fewer copies of Rails in memory, leading to better server performance and higher utilization of multiple cores. + +To enable multithreaded dispatching in production mode of your application, add the following line in your +config/environments/production.rb+: + + +config.threadsafe! + + +* More information : +** "Thread safety for your Rails":http://m.onkey.org/2008/10/23/thread-safety-for-your-rails +** "Thread safety project announcement":http://weblog.rubyonrails.org/2008/8/16/josh-peek-officially-joins-the-rails-core +** "Q/A: What Thread-safe Rails Means":http://blog.headius.com/2008/08/qa-what-thread-safe-rails-means.html + +h3. Active Record + +There are two big additions to talk about here: transactional migrations and pooled database transactions. There's also a new (and cleaner) syntax for join table conditions, as well as a number of smaller improvements. + +h4. Transactional Migrations + +Historically, multiple-step Rails migrations have been a source of trouble. If something went wrong during a migration, everything before the error changed the database and everything after the error wasn't applied. Also, the migration version was stored as having been executed, which means that it couldn't be simply rerun by +rake db:migrate:redo+ after you fix the problem. Transactional migrations change this by wrapping migration steps in a DDL transaction, so that if any of them fail, the entire migration is undone. In Rails 2.2, transactional migrations are supported on PostgreSQL out of the box. The code is extensible to other database types in the future - and IBM has already extended it to support the DB2 adapter. + +* Lead Contributor: "Adam Wiggins":http://adam.heroku.com/ +* More information: +** "DDL Transactions":http://adam.heroku.com/past/2008/9/3/ddl_transactions/ +** "A major milestone for DB2 on Rails":http://db2onrails.com/2008/11/08/a-major-milestone-for-db2-on-rails/ + +h4. Connection Pooling + +Connection pooling lets Rails distribute database requests across a pool of database connections that will grow to a maximum size (by default 5, but you can add a +pool+ key to your +database.yml+ to adjust this). This helps remove bottlenecks in applications that support many concurrent users. There's also a +wait_timeout+ that defaults to 5 seconds before giving up. +ActiveRecord::Base.connection_pool+ gives you direct access to the pool if you need it. + + +development: + adapter: mysql + username: root + database: sample_development + pool: 10 + wait_timeout: 10 + + +* Lead Contributor: "Nick Sieger":http://blog.nicksieger.com/ +* More information: +** "What's New in Edge Rails: Connection Pools":http://ryandaigle.com/articles/2008/9/7/what-s-new-in-edge-rails-connection-pools + +h4. Hashes for Join Table Conditions + +You can now specify conditions on join tables using a hash. This is a big help if you need to query across complex joins. + + +class Photo < ActiveRecord::Base + belongs_to :product +end + +class Product < ActiveRecord::Base + has_many :photos +end + +# Get all products with copyright-free photos: +Product.all(:joins => :photos, :conditions => { :photos => { :copyright => false }}) + + +* More information: +** "What's New in Edge Rails: Easy Join Table Conditions":http://ryandaigle.com/articles/2008/7/7/what-s-new-in-edge-rails-easy-join-table-conditions + +h4. New Dynamic Finders + +Two new sets of methods have been added to Active Record's dynamic finders family. + +h5. +find_last_by_attribute+ + +The +find_last_by_attribute+ method is equivalent to +Model.last(:conditions => {:attribute => value})+ + + +# Get the last user who signed up from London +User.find_last_by_city('London') + + +* Lead Contributor: "Emilio Tagua":http://www.workingwithrails.com/person/9147-emilio-tagua + +h5. +find_by_attribute!+ + +The new bang! version of +find_by_attribute!+ is equivalent to +Model.first(:conditions => {:attribute => value}) || raise ActiveRecord::RecordNotFound+ Instead of returning +nil+ if it can't find a matching record, this method will raise an exception if it cannot find a match. + + +# Raise ActiveRecord::RecordNotFound exception if 'Moby' hasn't signed up yet! +User.find_by_name!('Moby') + + +* Lead Contributor: "Josh Susser":http://blog.hasmanythrough.com + +h4. Associations Respect Private/Protected Scope + +Active Record association proxies now respect the scope of methods on the proxied object. Previously (given User has_one :account) +@user.account.private_method+ would call the private method on the associated Account object. That fails in Rails 2.2; if you need this functionality, you should use +@user.account.send(:private_method)+ (or make the method public instead of private or protected). Please note that if you're overriding +method_missing+, you should also override +respond_to+ to match the behavior in order for associations to function normally. + +* Lead Contributor: Adam Milligan +* More information: +** "Rails 2.2 Change: Private Methods on Association Proxies are Private":http://afreshcup.com/2008/10/24/rails-22-change-private-methods-on-association-proxies-are-private/ + +h4. Other ActiveRecord Changes + +* +rake db:migrate:redo+ now accepts an optional VERSION to target that specific migration to redo +* Set +config.active_record.timestamped_migrations = false+ to have migrations with numeric prefix instead of UTC timestamp. +* Counter cache columns (for associations declared with +:counter_cache => true+) do not need to be initialized to zero any longer. +* +ActiveRecord::Base.human_name+ for an internationalization-aware humane translation of model names + +h3. Action Controller + +On the controller side, there are several changes that will help tidy up your routes. There are also some internal changes in the routing engine to lower memory usage on complex applications. + +h4. Shallow Route Nesting + +Shallow route nesting provides a solution to the well-known difficulty of using deeply-nested resources. With shallow nesting, you need only supply enough information to uniquely identify the resource that you want to work with. + + +map.resources :publishers, :shallow => true do |publisher| + publisher.resources :magazines do |magazine| + magazine.resources :photos + end +end + + +This will enable recognition of (among others) these routes: + + +/publishers/1 ==> publisher_path(1) +/publishers/1/magazines ==> publisher_magazines_path(1) +/magazines/2 ==> magazine_path(2) +/magazines/2/photos ==> magazines_photos_path(2) +/photos/3 ==> photo_path(3) + + +* Lead Contributor: "S. Brent Faulkner":http://www.unwwwired.net/ +* More information: +** "Rails Routing from the Outside In":http://guides.rubyonrails.org/routing.html#nested-resources +** "What's New in Edge Rails: Shallow Routes":http://ryandaigle.com/articles/2008/9/7/what-s-new-in-edge-rails-shallow-routes + +h4. Method Arrays for Member or Collection Routes + +You can now supply an array of methods for new member or collection routes. This removes the annoyance of having to define a route as accepting any verb as soon as you need it to handle more than one. With Rails 2.2, this is a legitimate route declaration: + + +map.resources :photos, :collection => { :search => [:get, :post] } + + +* Lead Contributor: "Brennan Dunn":http://brennandunn.com/ + +h4. Resources With Specific Actions + +By default, when you use +map.resources+ to create a route, Rails generates routes for seven default actions (index, show, create, new, edit, update, and destroy). But each of these routes takes up memory in your application, and causes Rails to generate additional routing logic. Now you can use the +:only+ and +:except+ options to fine-tune the routes that Rails will generate for resources. You can supply a single action, an array of actions, or the special +:all+ or +:none+ options. These options are inherited by nested resources. + + +map.resources :photos, :only => [:index, :show] +map.resources :products, :except => :destroy + + +* Lead Contributor: "Tom Stuart":http://experthuman.com/ + +h4. Other Action Controller Changes + +* You can now easily "show a custom error page":http://m.onkey.org/2008/7/20/rescue-from-dispatching for exceptions raised while routing a request. +* The HTTP Accept header is disabled by default now. You should prefer the use of formatted URLs (such as +/customers/1.xml+) to indicate the format that you want. If you need the Accept headers, you can turn them back on with +config.action_controller.use_accept_header = true+. +* Benchmarking numbers are now reported in milliseconds rather than tiny fractions of seconds +* Rails now supports HTTP-only cookies (and uses them for sessions), which help mitigate some cross-site scripting risks in newer browsers. +* +redirect_to+ now fully supports URI schemes (so, for example, you can redirect to a svn+ssh: URI). +* +render+ now supports a +:js+ option to render plain vanilla JavaScript with the right mime type. +* Request forgery protection has been tightened up to apply to HTML-formatted content requests only. +* Polymorphic URLs behave more sensibly if a passed parameter is nil. For example, calling +polymorphic_path([@project, @date, @area])+ with a nil date will give you +project_area_path+. + +h3. Action View + +* +javascript_include_tag+ and +stylesheet_link_tag+ support a new +:recursive+ option to be used along with +:all+, so that you can load an entire tree of files with a single line of code. +* The included Prototype JavaScript library has been upgraded to version 1.6.0.3. +* +RJS#page.reload+ to reload the browser's current location via JavaScript +* The +atom_feed+ helper now takes an +:instruct+ option to let you insert XML processing instructions. + +h3. Action Mailer + +Action Mailer now supports mailer layouts. You can make your HTML emails as pretty as your in-browser views by supplying an appropriately-named layout - for example, the +CustomerMailer+ class expects to use +layouts/customer_mailer.html.erb+. + +* More information: +** "What's New in Edge Rails: Mailer Layouts":http://ryandaigle.com/articles/2008/9/7/what-s-new-in-edge-rails-mailer-layouts + +Action Mailer now offers built-in support for GMail's SMTP servers, by turning on STARTTLS automatically. This requires Ruby 1.8.7 to be installed. + +h3. Active Support + +Active Support now offers built-in memoization for Rails applications, the +each_with_object+ method, prefix support on delegates, and various other new utility methods. + +h4. Memoization + +Memoization is a pattern of initializing a method once and then stashing its value away for repeat use. You've probably used this pattern in your own applications: + + +def full_name + @full_name ||= "#{first_name} #{last_name}" +end + + +Memoization lets you handle this task in a declarative fashion: + + +extend ActiveSupport::Memoizable + +def full_name + "#{first_name} #{last_name}" +end +memoize :full_name + + +Other features of memoization include +unmemoize+, +unmemoize_all+, and +memoize_all+ to turn memoization on or off. + +* Lead Contributor: "Josh Peek":http://joshpeek.com/ +* More information: +** "What's New in Edge Rails: Easy Memoization":http://ryandaigle.com/articles/2008/7/16/what-s-new-in-edge-rails-memoization +** "Memo-what? A Guide to Memoization":http://www.railway.at/articles/2008/09/20/a-guide-to-memoization + +h4. each_with_object + +The +each_with_object+ method provides an alternative to +inject+, using a method backported from Ruby 1.9. It iterates over a collection, passing the current element and the memo into the block. + + +%w(foo bar).each_with_object({}) { |str, hsh| hsh[str] = str.upcase } #=> {'foo' => 'FOO', 'bar' => 'BAR'} + + +Lead Contributor: "Adam Keys":http://therealadam.com/ + +h4. Delegates With Prefixes + +If you delegate behavior from one class to another, you can now specify a prefix that will be used to identify the delegated methods. For example: + + +class Vendor < ActiveRecord::Base + has_one :account + delegate :email, :password, :to => :account, :prefix => true +end + + +This will produce delegated methods +vendor#account_email+ and +vendor#account_password+. You can also specify a custom prefix: + + +class Vendor < ActiveRecord::Base + has_one :account + delegate :email, :password, :to => :account, :prefix => :owner +end + + +This will produce delegated methods +vendor#owner_email+ and +vendor#owner_password+. + +Lead Contributor: "Daniel Schierbeck":http://workingwithrails.com/person/5830-daniel-schierbeck + +h4. Other Active Support Changes + +* Extensive updates to +ActiveSupport::Multibyte+, including Ruby 1.9 compatibility fixes. +* The addition of +ActiveSupport::Rescuable+ allows any class to mix in the +rescue_from+ syntax. +* +past?+, +today?+ and +future?+ for +Date+ and +Time+ classes to facilitate date/time comparisons. +* +Array#second+ through +Array#fifth+ as aliases for +Array#[1]+ through +Array#[4]+ +* +Enumerable#many?+ to encapsulate +collection.size > 1+ +* +Inflector#parameterize+ produces a URL-ready version of its input, for use in +to_param+. +* +Time#advance+ recognizes fractional days and weeks, so you can do +1.7.weeks.ago+, +1.5.hours.since+, and so on. +* The included TzInfo library has been upgraded to version 0.3.12. +* +ActiveSuport::StringInquirer+ gives you a pretty way to test for equality in strings: +ActiveSupport::StringInquirer.new("abc").abc? => true+ + +h3. Railties + +In Railties (the core code of Rails itself) the biggest changes are in the +config.gems+ mechanism. + +h4. config.gems + +To avoid deployment issues and make Rails applications more self-contained, it's possible to place copies of all of the gems that your Rails application requires in +/vendor/gems+. This capability first appeared in Rails 2.1, but it's much more flexible and robust in Rails 2.2, handling complicated dependencies between gems. Gem management in Rails includes these commands: + +* +config.gem _gem_name_+ in your +config/environment.rb+ file +* +rake gems+ to list all configured gems, as well as whether they (and their dependencies) are installed, frozen, or framework (framework gems are those loaded by Rails before the gem dependency code is executed; such gems cannot be frozen) +* +rake gems:install+ to install missing gems to the computer +* +rake gems:unpack+ to place a copy of the required gems into +/vendor/gems+ +* +rake gems:unpack:dependencies+ to get copies of the required gems and their dependencies into +/vendor/gems+ +* +rake gems:build+ to build any missing native extensions +* +rake gems:refresh_specs+ to bring vendored gems created with Rails 2.1 into alignment with the Rails 2.2 way of storing them + +You can unpack or install a single gem by specifying +GEM=_gem_name_+ on the command line. + +* Lead Contributor: "Matt Jones":http://github.com/al2o3cr +* More information: +** "What's New in Edge Rails: Gem Dependencies":http://ryandaigle.com/articles/2008/4/1/what-s-new-in-edge-rails-gem-dependencies +** "Rails 2.1.2 and 2.2RC1: Update Your RubyGems":http://afreshcup.com/2008/10/25/rails-212-and-22rc1-update-your-rubygems/ +** "Detailed discussion on Lighthouse":http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/1128 + +h4. Other Railties Changes + +* If you're a fan of the "Thin":http://code.macournoyer.com/thin/ web server, you'll be happy to know that +script/server+ now supports Thin directly. +* +script/plugin install <plugin> -r <revision>+ now works with git-based as well as svn-based plugins. +* +script/console+ now supports a +--debugger+ option +* Instructions for setting up a continuous integration server to build Rails itself are included in the Rails source +* +rake notes:custom ANNOTATION=MYFLAG+ lets you list out custom annotations. +* Wrapped +Rails.env+ in +StringInquirer+ so you can do +Rails.env.development?+ +* To eliminate deprecation warnings and properly handle gem dependencies, Rails now requires rubygems 1.3.1 or higher. + +h3. Deprecated + +A few pieces of older code are deprecated in this release: + +* +Rails::SecretKeyGenerator+ has been replaced by +ActiveSupport::SecureRandom+ +* +render_component+ is deprecated. There's a "render_components plugin":http://github.com/rails/render_component/tree/master available if you need this functionality. +* Implicit local assignments when rendering partials has been deprecated. + + +def partial_with_implicit_local_assignment + @customer = Customer.new("Marcel") + render :partial => "customer" +end + + +Previously the above code made available a local variable called +customer+ inside the partial 'customer'. You should explicitly pass all the variables via :locals hash now. + +* +country_select+ has been removed. See the "deprecation page":http://www.rubyonrails.org/deprecation/list-of-countries for more information and a plugin replacement. +* +ActiveRecord::Base.allow_concurrency+ no longer has any effect. +* +ActiveRecord::Errors.default_error_messages+ has been deprecated in favor of +I18n.translate('activerecord.errors.messages')+ +* The +%s+ and +%d+ interpolation syntax for internationalization is deprecated. +* +String#chars+ has been deprecated in favor of +String#mb_chars+. +* Durations of fractional months or fractional years are deprecated. Use Ruby's core +Date+ and +Time+ class arithmetic instead. +* +Request#relative_url_root+ is deprecated. Use +ActionController::Base.relative_url_root+ instead. + +h3. Credits + +Release notes compiled by "Mike Gunderloy":http://afreshcup.com diff --git a/guides/source/2_2_release_notes.textile b/guides/source/2_2_release_notes.textile deleted file mode 100644 index eb4b32329b..0000000000 --- a/guides/source/2_2_release_notes.textile +++ /dev/null @@ -1,422 +0,0 @@ -h2. Ruby on Rails 2.2 Release Notes - -Rails 2.2 delivers a number of new and improved features. This list covers the major upgrades, but doesn't include every little bug fix and change. If you want to see everything, check out the "list of commits":http://github.com/rails/rails/commits/master in the main Rails repository on GitHub. - -Along with Rails, 2.2 marks the launch of the "Ruby on Rails Guides":http://guides.rubyonrails.org/, the first results of the ongoing "Rails Guides hackfest":http://hackfest.rubyonrails.org/guide. This site will deliver high-quality documentation of the major features of Rails. - -endprologue. - -h3. Infrastructure - -Rails 2.2 is a significant release for the infrastructure that keeps Rails humming along and connected to the rest of the world. - -h4. Internationalization - -Rails 2.2 supplies an easy system for internationalization (or i18n, for those of you tired of typing). - -* Lead Contributors: Rails i18 Team -* More information : -** "Official Rails i18 website":http://rails-i18n.org -** "Finally. Ruby on Rails gets internationalized":http://www.artweb-design.de/2008/7/18/finally-ruby-on-rails-gets-internationalized -** "Localizing Rails : Demo application":http://github.com/clemens/i18n_demo_app - -h4. Compatibility with Ruby 1.9 and JRuby - -Along with thread safety, a lot of work has been done to make Rails work well with JRuby and the upcoming Ruby 1.9. With Ruby 1.9 being a moving target, running edge Rails on edge Ruby is still a hit-or-miss proposition, but Rails is ready to make the transition to Ruby 1.9 when the latter is released. - -h3. Documentation - -The internal documentation of Rails, in the form of code comments, has been improved in numerous places. In addition, the "Ruby on Rails Guides":http://guides.rubyonrails.org/ project is the definitive source for information on major Rails components. In its first official release, the Guides page includes: - -* "Getting Started with Rails":http://guides.rubyonrails.org/getting_started.html -* "Rails Database Migrations":http://guides.rubyonrails.org/migrations.html -* "Active Record Associations":http://guides.rubyonrails.org/association_basics.html -* "Active Record Query Interface":http://guides.rubyonrails.org/active_record_querying.html -* "Layouts and Rendering in Rails":http://guides.rubyonrails.org/layouts_and_rendering.html -* "Action View Form Helpers":http://guides.rubyonrails.org/form_helpers.html -* "Rails Routing from the Outside In":http://guides.rubyonrails.org/routing.html -* "Action Controller Overview":http://guides.rubyonrails.org/action_controller_overview.html -* "Rails Caching":http://guides.rubyonrails.org/caching_with_rails.html -* "A Guide to Testing Rails Applications":http://guides.rubyonrails.org/testing.html -* "Securing Rails Applications":http://guides.rubyonrails.org/security.html -* "Debugging Rails Applications":http://guides.rubyonrails.org/debugging_rails_applications.html -* "Performance Testing Rails Applications":http://guides.rubyonrails.org/performance_testing.html -* "The Basics of Creating Rails Plugins":http://guides.rubyonrails.org/plugins.html - -All told, the Guides provide tens of thousands of words of guidance for beginning and intermediate Rails developers. - -If you want to generate these guides locally, inside your application: - - -rake doc:guides - - -This will put the guides inside +Rails.root/doc/guides+ and you may start surfing straight away by opening +Rails.root/doc/guides/index.html+ in your favourite browser. - -* Lead Contributors: "Rails Documentation Team":credits.html -* Major contributions from "Xavier Noria":http://advogato.org/person/fxn/diary.html and "Hongli Lai":http://izumi.plan99.net/blog/. -* More information: -** "Rails Guides hackfest":http://hackfest.rubyonrails.org/guide -** "Help improve Rails documentation on Git branch":http://weblog.rubyonrails.org/2008/5/2/help-improve-rails-documentation-on-git-branch - -h3. Better integration with HTTP : Out of the box ETag support - -Supporting the etag and last modified timestamp in HTTP headers means that Rails can now send back an empty response if it gets a request for a resource that hasn't been modified lately. This allows you to check whether a response needs to be sent at all. - - -class ArticlesController < ApplicationController - def show_with_respond_to_block - @article = Article.find(params[:id]) - - # If the request sends headers that differs from the options provided to stale?, then - # the request is indeed stale and the respond_to block is triggered (and the options - # to the stale? call is set on the response). - # - # If the request headers match, then the request is fresh and the respond_to block is - # not triggered. Instead the default render will occur, which will check the last-modified - # and etag headers and conclude that it only needs to send a "304 Not Modified" instead - # of rendering the template. - if stale?(:last_modified => @article.published_at.utc, :etag => @article) - respond_to do |wants| - # normal response processing - end - end - end - - def show_with_implied_render - @article = Article.find(params[:id]) - - # Sets the response headers and checks them against the request, if the request is stale - # (i.e. no match of either etag or last-modified), then the default render of the template happens. - # If the request is fresh, then the default render will return a "304 Not Modified" - # instead of rendering the template. - fresh_when(:last_modified => @article.published_at.utc, :etag => @article) - end -end - - -h3. Thread Safety - -The work done to make Rails thread-safe is rolling out in Rails 2.2. Depending on your web server infrastructure, this means you can handle more requests with fewer copies of Rails in memory, leading to better server performance and higher utilization of multiple cores. - -To enable multithreaded dispatching in production mode of your application, add the following line in your +config/environments/production.rb+: - - -config.threadsafe! - - -* More information : -** "Thread safety for your Rails":http://m.onkey.org/2008/10/23/thread-safety-for-your-rails -** "Thread safety project announcement":http://weblog.rubyonrails.org/2008/8/16/josh-peek-officially-joins-the-rails-core -** "Q/A: What Thread-safe Rails Means":http://blog.headius.com/2008/08/qa-what-thread-safe-rails-means.html - -h3. Active Record - -There are two big additions to talk about here: transactional migrations and pooled database transactions. There's also a new (and cleaner) syntax for join table conditions, as well as a number of smaller improvements. - -h4. Transactional Migrations - -Historically, multiple-step Rails migrations have been a source of trouble. If something went wrong during a migration, everything before the error changed the database and everything after the error wasn't applied. Also, the migration version was stored as having been executed, which means that it couldn't be simply rerun by +rake db:migrate:redo+ after you fix the problem. Transactional migrations change this by wrapping migration steps in a DDL transaction, so that if any of them fail, the entire migration is undone. In Rails 2.2, transactional migrations are supported on PostgreSQL out of the box. The code is extensible to other database types in the future - and IBM has already extended it to support the DB2 adapter. - -* Lead Contributor: "Adam Wiggins":http://adam.heroku.com/ -* More information: -** "DDL Transactions":http://adam.heroku.com/past/2008/9/3/ddl_transactions/ -** "A major milestone for DB2 on Rails":http://db2onrails.com/2008/11/08/a-major-milestone-for-db2-on-rails/ - -h4. Connection Pooling - -Connection pooling lets Rails distribute database requests across a pool of database connections that will grow to a maximum size (by default 5, but you can add a +pool+ key to your +database.yml+ to adjust this). This helps remove bottlenecks in applications that support many concurrent users. There's also a +wait_timeout+ that defaults to 5 seconds before giving up. +ActiveRecord::Base.connection_pool+ gives you direct access to the pool if you need it. - - -development: - adapter: mysql - username: root - database: sample_development - pool: 10 - wait_timeout: 10 - - -* Lead Contributor: "Nick Sieger":http://blog.nicksieger.com/ -* More information: -** "What's New in Edge Rails: Connection Pools":http://ryandaigle.com/articles/2008/9/7/what-s-new-in-edge-rails-connection-pools - -h4. Hashes for Join Table Conditions - -You can now specify conditions on join tables using a hash. This is a big help if you need to query across complex joins. - - -class Photo < ActiveRecord::Base - belongs_to :product -end - -class Product < ActiveRecord::Base - has_many :photos -end - -# Get all products with copyright-free photos: -Product.all(:joins => :photos, :conditions => { :photos => { :copyright => false }}) - - -* More information: -** "What's New in Edge Rails: Easy Join Table Conditions":http://ryandaigle.com/articles/2008/7/7/what-s-new-in-edge-rails-easy-join-table-conditions - -h4. New Dynamic Finders - -Two new sets of methods have been added to Active Record's dynamic finders family. - -h5. +find_last_by_attribute+ - -The +find_last_by_attribute+ method is equivalent to +Model.last(:conditions => {:attribute => value})+ - - -# Get the last user who signed up from London -User.find_last_by_city('London') - - -* Lead Contributor: "Emilio Tagua":http://www.workingwithrails.com/person/9147-emilio-tagua - -h5. +find_by_attribute!+ - -The new bang! version of +find_by_attribute!+ is equivalent to +Model.first(:conditions => {:attribute => value}) || raise ActiveRecord::RecordNotFound+ Instead of returning +nil+ if it can't find a matching record, this method will raise an exception if it cannot find a match. - - -# Raise ActiveRecord::RecordNotFound exception if 'Moby' hasn't signed up yet! -User.find_by_name!('Moby') - - -* Lead Contributor: "Josh Susser":http://blog.hasmanythrough.com - -h4. Associations Respect Private/Protected Scope - -Active Record association proxies now respect the scope of methods on the proxied object. Previously (given User has_one :account) +@user.account.private_method+ would call the private method on the associated Account object. That fails in Rails 2.2; if you need this functionality, you should use +@user.account.send(:private_method)+ (or make the method public instead of private or protected). Please note that if you're overriding +method_missing+, you should also override +respond_to+ to match the behavior in order for associations to function normally. - -* Lead Contributor: Adam Milligan -* More information: -** "Rails 2.2 Change: Private Methods on Association Proxies are Private":http://afreshcup.com/2008/10/24/rails-22-change-private-methods-on-association-proxies-are-private/ - -h4. Other ActiveRecord Changes - -* +rake db:migrate:redo+ now accepts an optional VERSION to target that specific migration to redo -* Set +config.active_record.timestamped_migrations = false+ to have migrations with numeric prefix instead of UTC timestamp. -* Counter cache columns (for associations declared with +:counter_cache => true+) do not need to be initialized to zero any longer. -* +ActiveRecord::Base.human_name+ for an internationalization-aware humane translation of model names - -h3. Action Controller - -On the controller side, there are several changes that will help tidy up your routes. There are also some internal changes in the routing engine to lower memory usage on complex applications. - -h4. Shallow Route Nesting - -Shallow route nesting provides a solution to the well-known difficulty of using deeply-nested resources. With shallow nesting, you need only supply enough information to uniquely identify the resource that you want to work with. - - -map.resources :publishers, :shallow => true do |publisher| - publisher.resources :magazines do |magazine| - magazine.resources :photos - end -end - - -This will enable recognition of (among others) these routes: - - -/publishers/1 ==> publisher_path(1) -/publishers/1/magazines ==> publisher_magazines_path(1) -/magazines/2 ==> magazine_path(2) -/magazines/2/photos ==> magazines_photos_path(2) -/photos/3 ==> photo_path(3) - - -* Lead Contributor: "S. Brent Faulkner":http://www.unwwwired.net/ -* More information: -** "Rails Routing from the Outside In":http://guides.rubyonrails.org/routing.html#nested-resources -** "What's New in Edge Rails: Shallow Routes":http://ryandaigle.com/articles/2008/9/7/what-s-new-in-edge-rails-shallow-routes - -h4. Method Arrays for Member or Collection Routes - -You can now supply an array of methods for new member or collection routes. This removes the annoyance of having to define a route as accepting any verb as soon as you need it to handle more than one. With Rails 2.2, this is a legitimate route declaration: - - -map.resources :photos, :collection => { :search => [:get, :post] } - - -* Lead Contributor: "Brennan Dunn":http://brennandunn.com/ - -h4. Resources With Specific Actions - -By default, when you use +map.resources+ to create a route, Rails generates routes for seven default actions (index, show, create, new, edit, update, and destroy). But each of these routes takes up memory in your application, and causes Rails to generate additional routing logic. Now you can use the +:only+ and +:except+ options to fine-tune the routes that Rails will generate for resources. You can supply a single action, an array of actions, or the special +:all+ or +:none+ options. These options are inherited by nested resources. - - -map.resources :photos, :only => [:index, :show] -map.resources :products, :except => :destroy - - -* Lead Contributor: "Tom Stuart":http://experthuman.com/ - -h4. Other Action Controller Changes - -* You can now easily "show a custom error page":http://m.onkey.org/2008/7/20/rescue-from-dispatching for exceptions raised while routing a request. -* The HTTP Accept header is disabled by default now. You should prefer the use of formatted URLs (such as +/customers/1.xml+) to indicate the format that you want. If you need the Accept headers, you can turn them back on with +config.action_controller.use_accept_header = true+. -* Benchmarking numbers are now reported in milliseconds rather than tiny fractions of seconds -* Rails now supports HTTP-only cookies (and uses them for sessions), which help mitigate some cross-site scripting risks in newer browsers. -* +redirect_to+ now fully supports URI schemes (so, for example, you can redirect to a svn+ssh: URI). -* +render+ now supports a +:js+ option to render plain vanilla JavaScript with the right mime type. -* Request forgery protection has been tightened up to apply to HTML-formatted content requests only. -* Polymorphic URLs behave more sensibly if a passed parameter is nil. For example, calling +polymorphic_path([@project, @date, @area])+ with a nil date will give you +project_area_path+. - -h3. Action View - -* +javascript_include_tag+ and +stylesheet_link_tag+ support a new +:recursive+ option to be used along with +:all+, so that you can load an entire tree of files with a single line of code. -* The included Prototype JavaScript library has been upgraded to version 1.6.0.3. -* +RJS#page.reload+ to reload the browser's current location via JavaScript -* The +atom_feed+ helper now takes an +:instruct+ option to let you insert XML processing instructions. - -h3. Action Mailer - -Action Mailer now supports mailer layouts. You can make your HTML emails as pretty as your in-browser views by supplying an appropriately-named layout - for example, the +CustomerMailer+ class expects to use +layouts/customer_mailer.html.erb+. - -* More information: -** "What's New in Edge Rails: Mailer Layouts":http://ryandaigle.com/articles/2008/9/7/what-s-new-in-edge-rails-mailer-layouts - -Action Mailer now offers built-in support for GMail's SMTP servers, by turning on STARTTLS automatically. This requires Ruby 1.8.7 to be installed. - -h3. Active Support - -Active Support now offers built-in memoization for Rails applications, the +each_with_object+ method, prefix support on delegates, and various other new utility methods. - -h4. Memoization - -Memoization is a pattern of initializing a method once and then stashing its value away for repeat use. You've probably used this pattern in your own applications: - - -def full_name - @full_name ||= "#{first_name} #{last_name}" -end - - -Memoization lets you handle this task in a declarative fashion: - - -extend ActiveSupport::Memoizable - -def full_name - "#{first_name} #{last_name}" -end -memoize :full_name - - -Other features of memoization include +unmemoize+, +unmemoize_all+, and +memoize_all+ to turn memoization on or off. - -* Lead Contributor: "Josh Peek":http://joshpeek.com/ -* More information: -** "What's New in Edge Rails: Easy Memoization":http://ryandaigle.com/articles/2008/7/16/what-s-new-in-edge-rails-memoization -** "Memo-what? A Guide to Memoization":http://www.railway.at/articles/2008/09/20/a-guide-to-memoization - -h4. each_with_object - -The +each_with_object+ method provides an alternative to +inject+, using a method backported from Ruby 1.9. It iterates over a collection, passing the current element and the memo into the block. - - -%w(foo bar).each_with_object({}) { |str, hsh| hsh[str] = str.upcase } #=> {'foo' => 'FOO', 'bar' => 'BAR'} - - -Lead Contributor: "Adam Keys":http://therealadam.com/ - -h4. Delegates With Prefixes - -If you delegate behavior from one class to another, you can now specify a prefix that will be used to identify the delegated methods. For example: - - -class Vendor < ActiveRecord::Base - has_one :account - delegate :email, :password, :to => :account, :prefix => true -end - - -This will produce delegated methods +vendor#account_email+ and +vendor#account_password+. You can also specify a custom prefix: - - -class Vendor < ActiveRecord::Base - has_one :account - delegate :email, :password, :to => :account, :prefix => :owner -end - - -This will produce delegated methods +vendor#owner_email+ and +vendor#owner_password+. - -Lead Contributor: "Daniel Schierbeck":http://workingwithrails.com/person/5830-daniel-schierbeck - -h4. Other Active Support Changes - -* Extensive updates to +ActiveSupport::Multibyte+, including Ruby 1.9 compatibility fixes. -* The addition of +ActiveSupport::Rescuable+ allows any class to mix in the +rescue_from+ syntax. -* +past?+, +today?+ and +future?+ for +Date+ and +Time+ classes to facilitate date/time comparisons. -* +Array#second+ through +Array#fifth+ as aliases for +Array#[1]+ through +Array#[4]+ -* +Enumerable#many?+ to encapsulate +collection.size > 1+ -* +Inflector#parameterize+ produces a URL-ready version of its input, for use in +to_param+. -* +Time#advance+ recognizes fractional days and weeks, so you can do +1.7.weeks.ago+, +1.5.hours.since+, and so on. -* The included TzInfo library has been upgraded to version 0.3.12. -* +ActiveSuport::StringInquirer+ gives you a pretty way to test for equality in strings: +ActiveSupport::StringInquirer.new("abc").abc? => true+ - -h3. Railties - -In Railties (the core code of Rails itself) the biggest changes are in the +config.gems+ mechanism. - -h4. config.gems - -To avoid deployment issues and make Rails applications more self-contained, it's possible to place copies of all of the gems that your Rails application requires in +/vendor/gems+. This capability first appeared in Rails 2.1, but it's much more flexible and robust in Rails 2.2, handling complicated dependencies between gems. Gem management in Rails includes these commands: - -* +config.gem _gem_name_+ in your +config/environment.rb+ file -* +rake gems+ to list all configured gems, as well as whether they (and their dependencies) are installed, frozen, or framework (framework gems are those loaded by Rails before the gem dependency code is executed; such gems cannot be frozen) -* +rake gems:install+ to install missing gems to the computer -* +rake gems:unpack+ to place a copy of the required gems into +/vendor/gems+ -* +rake gems:unpack:dependencies+ to get copies of the required gems and their dependencies into +/vendor/gems+ -* +rake gems:build+ to build any missing native extensions -* +rake gems:refresh_specs+ to bring vendored gems created with Rails 2.1 into alignment with the Rails 2.2 way of storing them - -You can unpack or install a single gem by specifying +GEM=_gem_name_+ on the command line. - -* Lead Contributor: "Matt Jones":http://github.com/al2o3cr -* More information: -** "What's New in Edge Rails: Gem Dependencies":http://ryandaigle.com/articles/2008/4/1/what-s-new-in-edge-rails-gem-dependencies -** "Rails 2.1.2 and 2.2RC1: Update Your RubyGems":http://afreshcup.com/2008/10/25/rails-212-and-22rc1-update-your-rubygems/ -** "Detailed discussion on Lighthouse":http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/1128 - -h4. Other Railties Changes - -* If you're a fan of the "Thin":http://code.macournoyer.com/thin/ web server, you'll be happy to know that +script/server+ now supports Thin directly. -* +script/plugin install <plugin> -r <revision>+ now works with git-based as well as svn-based plugins. -* +script/console+ now supports a +--debugger+ option -* Instructions for setting up a continuous integration server to build Rails itself are included in the Rails source -* +rake notes:custom ANNOTATION=MYFLAG+ lets you list out custom annotations. -* Wrapped +Rails.env+ in +StringInquirer+ so you can do +Rails.env.development?+ -* To eliminate deprecation warnings and properly handle gem dependencies, Rails now requires rubygems 1.3.1 or higher. - -h3. Deprecated - -A few pieces of older code are deprecated in this release: - -* +Rails::SecretKeyGenerator+ has been replaced by +ActiveSupport::SecureRandom+ -* +render_component+ is deprecated. There's a "render_components plugin":http://github.com/rails/render_component/tree/master available if you need this functionality. -* Implicit local assignments when rendering partials has been deprecated. - - -def partial_with_implicit_local_assignment - @customer = Customer.new("Marcel") - render :partial => "customer" -end - - -Previously the above code made available a local variable called +customer+ inside the partial 'customer'. You should explicitly pass all the variables via :locals hash now. - -* +country_select+ has been removed. See the "deprecation page":http://www.rubyonrails.org/deprecation/list-of-countries for more information and a plugin replacement. -* +ActiveRecord::Base.allow_concurrency+ no longer has any effect. -* +ActiveRecord::Errors.default_error_messages+ has been deprecated in favor of +I18n.translate('activerecord.errors.messages')+ -* The +%s+ and +%d+ interpolation syntax for internationalization is deprecated. -* +String#chars+ has been deprecated in favor of +String#mb_chars+. -* Durations of fractional months or fractional years are deprecated. Use Ruby's core +Date+ and +Time+ class arithmetic instead. -* +Request#relative_url_root+ is deprecated. Use +ActionController::Base.relative_url_root+ instead. - -h3. Credits - -Release notes compiled by "Mike Gunderloy":http://afreshcup.com diff --git a/guides/source/2_3_release_notes.md b/guides/source/2_3_release_notes.md new file mode 100644 index 0000000000..36f425574b --- /dev/null +++ b/guides/source/2_3_release_notes.md @@ -0,0 +1,610 @@ +h2. Ruby on Rails 2.3 Release Notes + +Rails 2.3 delivers a variety of new and improved features, including pervasive Rack integration, refreshed support for Rails Engines, nested transactions for Active Record, dynamic and default scopes, unified rendering, more efficient routing, application templates, and quiet backtraces. This list covers the major upgrades, but doesn't include every little bug fix and change. If you want to see everything, check out the "list of commits":http://github.com/rails/rails/commits/master in the main Rails repository on GitHub or review the +CHANGELOG+ files for the individual Rails components. + +endprologue. + +h3. Application Architecture + +There are two major changes in the architecture of Rails applications: complete integration of the "Rack":http://rack.rubyforge.org/ modular web server interface, and renewed support for Rails Engines. + +h4. Rack Integration + +Rails has now broken with its CGI past, and uses Rack everywhere. This required and resulted in a tremendous number of internal changes (but if you use CGI, don't worry; Rails now supports CGI through a proxy interface.) Still, this is a major change to Rails internals. After upgrading to 2.3, you should test on your local environment and your production environment. Some things to test: + +* Sessions +* Cookies +* File uploads +* JSON/XML APIs + +Here's a summary of the rack-related changes: + +* +script/server+ has been switched to use Rack, which means it supports any Rack compatible server. +script/server+ will also pick up a rackup configuration file if one exists. By default, it will look for a +config.ru+ file, but you can override this with the +-c+ switch. +* The FCGI handler goes through Rack. +* +ActionController::Dispatcher+ maintains its own default middleware stack. Middlewares can be injected in, reordered, and removed. The stack is compiled into a chain on boot. You can configure the middleware stack in +environment.rb+. +* The +rake middleware+ task has been added to inspect the middleware stack. This is useful for debugging the order of the middleware stack. +* The integration test runner has been modified to execute the entire middleware and application stack. This makes integration tests perfect for testing Rack middleware. +* +ActionController::CGIHandler+ is a backwards compatible CGI wrapper around Rack. The +CGIHandler+ is meant to take an old CGI object and convert its environment information into a Rack compatible form. +* +CgiRequest+ and +CgiResponse+ have been removed. +* Session stores are now lazy loaded. If you never access the session object during a request, it will never attempt to load the session data (parse the cookie, load the data from memcache, or lookup an Active Record object). +* You no longer need to use +CGI::Cookie.new+ in your tests for setting a cookie value. Assigning a +String+ value to request.cookies["foo"] now sets the cookie as expected. +* +CGI::Session::CookieStore+ has been replaced by +ActionController::Session::CookieStore+. +* +CGI::Session::MemCacheStore+ has been replaced by +ActionController::Session::MemCacheStore+. +* +CGI::Session::ActiveRecordStore+ has been replaced by +ActiveRecord::SessionStore+. +* You can still change your session store with +ActionController::Base.session_store = :active_record_store+. +* Default sessions options are still set with +ActionController::Base.session = { :key => "..." }+. However, the +:session_domain+ option has been renamed to +:domain+. +* The mutex that normally wraps your entire request has been moved into middleware, +ActionController::Lock+. +* +ActionController::AbstractRequest+ and +ActionController::Request+ have been unified. The new +ActionController::Request+ inherits from +Rack::Request+. This affects access to +response.headers['type']+ in test requests. Use +response.content_type+ instead. +* +ActiveRecord::QueryCache+ middleware is automatically inserted onto the middleware stack if +ActiveRecord+ has been loaded. This middleware sets up and flushes the per-request Active Record query cache. +* The Rails router and controller classes follow the Rack spec. You can call a controller directly with +SomeController.call(env)+. The router stores the routing parameters in +rack.routing_args+. +* +ActionController::Request+ inherits from +Rack::Request+. +* Instead of +config.action_controller.session = { :session_key => 'foo', ...+ use +config.action_controller.session = { :key => 'foo', ...+. +* Using the +ParamsParser+ middleware preprocesses any XML, JSON, or YAML requests so they can be read normally with any +Rack::Request+ object after it. + +h4. Renewed Support for Rails Engines + +After some versions without an upgrade, Rails 2.3 offers some new features for Rails Engines (Rails applications that can be embedded within other applications). First, routing files in engines are automatically loaded and reloaded now, just like your +routes.rb+ file (this also applies to routing files in other plugins). Second, if your plugin has an app folder, then app/[models|controllers|helpers] will automatically be added to the Rails load path. Engines also support adding view paths now, and Action Mailer as well as Action View will use views from engines and other plugins. + +h3. Documentation + +The "Ruby on Rails guides":http://guides.rubyonrails.org/ project has published several additional guides for Rails 2.3. In addition, a "separate site":http://edgeguides.rubyonrails.org/ maintains updated copies of the Guides for Edge Rails. Other documentation efforts include a relaunch of the "Rails wiki":http://newwiki.rubyonrails.org/ and early planning for a Rails Book. + +* More Information: "Rails Documentation Projects":http://weblog.rubyonrails.org/2009/1/15/rails-documentation-projects. + +h3. Ruby 1.9.1 Support + +Rails 2.3 should pass all of its own tests whether you are running on Ruby 1.8 or the now-released Ruby 1.9.1. You should be aware, though, that moving to 1.9.1 entails checking all of the data adapters, plugins, and other code that you depend on for Ruby 1.9.1 compatibility, as well as Rails core. + +h3. Active Record + +Active Record gets quite a number of new features and bug fixes in Rails 2.3. The highlights include nested attributes, nested transactions, dynamic and default scopes, and batch processing. + +h4. Nested Attributes + +Active Record can now update the attributes on nested models directly, provided you tell it to do so: + + +class Book < ActiveRecord::Base + has_one :author + has_many :pages + + accepts_nested_attributes_for :author, :pages +end + + +Turning on nested attributes enables a number of things: automatic (and atomic) saving of a record together with its associated children, child-aware validations, and support for nested forms (discussed later). + +You can also specify requirements for any new records that are added via nested attributes using the +:reject_if+ option: + + +accepts_nested_attributes_for :author, + :reject_if => proc { |attributes| attributes['name'].blank? } + + +* Lead Contributor: "Eloy Duran":http://superalloy.nl/ +* More Information: "Nested Model Forms":http://weblog.rubyonrails.org/2009/1/26/nested-model-forms + +h4. Nested Transactions + +Active Record now supports nested transactions, a much-requested feature. Now you can write code like this: + + +User.transaction do + User.create(:username => 'Admin') + User.transaction(:requires_new => true) do + User.create(:username => 'Regular') + raise ActiveRecord::Rollback + end + end + + User.find(:all) # => Returns only Admin + + +Nested transactions let you roll back an inner transaction without affecting the state of the outer transaction. If you want a transaction to be nested, you must explicitly add the +:requires_new+ option; otherwise, a nested transaction simply becomes part of the parent transaction (as it does currently on Rails 2.2). Under the covers, nested transactions are "using savepoints":http://rails.lighthouseapp.com/projects/8994/tickets/383, so they're supported even on databases that don't have true nested transactions. There is also a bit of magic going on to make these transactions play well with transactional fixtures during testing. + +* Lead Contributors: "Jonathan Viney":http://www.workingwithrails.com/person/4985-jonathan-viney and "Hongli Lai":http://izumi.plan99.net/blog/ + +h4. Dynamic Scopes + +You know about dynamic finders in Rails (which allow you to concoct methods like +find_by_color_and_flavor+ on the fly) and named scopes (which allow you to encapsulate reusable query conditions into friendly names like +currently_active+). Well, now you can have dynamic scope methods. The idea is to put together syntax that allows filtering on the fly _and_ method chaining. For example: + + +Order.scoped_by_customer_id(12) +Order.scoped_by_customer_id(12).find(:all, + :conditions => "status = 'open'") +Order.scoped_by_customer_id(12).scoped_by_status("open") + + +There's nothing to define to use dynamic scopes: they just work. + +* Lead Contributor: "Yaroslav Markin":http://evilmartians.com/ +* More Information: "What's New in Edge Rails: Dynamic Scope Methods":http://ryandaigle.com/articles/2008/12/29/what-s-new-in-edge-rails-dynamic-scope-methods. + +h4. Default Scopes + +Rails 2.3 will introduce the notion of _default scopes_ similar to named scopes, but applying to all named scopes or find methods within the model. For example, you can write +default_scope :order => 'name ASC'+ and any time you retrieve records from that model they'll come out sorted by name (unless you override the option, of course). + +* Lead Contributor: Paweł Kondzior +* More Information: "What's New in Edge Rails: Default Scoping":http://ryandaigle.com/articles/2008/11/18/what-s-new-in-edge-rails-default-scoping + +h4. Batch Processing + +You can now process large numbers of records from an ActiveRecord model with less pressure on memory by using +find_in_batches+: + + +Customer.find_in_batches(:conditions => {:active => true}) do |customer_group| + customer_group.each { |customer| customer.update_account_balance! } +end + + +You can pass most of the +find+ options into +find_in_batches+. However, you cannot specify the order that records will be returned in (they will always be returned in ascending order of primary key, which must be an integer), or use the +:limit+ option. Instead, use the +:batch_size+ option, which defaults to 1000, to set the number of records that will be returned in each batch. + +The new +find_each+ method provides a wrapper around +find_in_batches+ that returns individual records, with the find itself being done in batches (of 1000 by default): + + +Customer.find_each do |customer| + customer.update_account_balance! +end + + +Note that you should only use this method for batch processing: for small numbers of records (less than 1000), you should just use the regular find methods with your own loop. + +* More Information (at that point the convenience method was called just +each+): +** "Rails 2.3: Batch Finding":http://afreshcup.com/2009/02/23/rails-23-batch-finding/ +** "What's New in Edge Rails: Batched Find":http://ryandaigle.com/articles/2009/2/23/what-s-new-in-edge-rails-batched-find + +h4. Multiple Conditions for Callbacks + +When using Active Record callbacks, you can now combine +:if+ and +:unless+ options on the same callback, and supply multiple conditions as an array: + + +before_save :update_credit_rating, :if => :active, + :unless => [:admin, :cash_only] + +* Lead Contributor: L. Caviola + +h4. Find with having + +Rails now has a +:having+ option on find (as well as on +has_many+ and +has_and_belongs_to_many+ associations) for filtering records in grouped finds. As those with heavy SQL backgrounds know, this allows filtering based on grouped results: + + +developers = Developer.find(:all, :group => "salary", + :having => "sum(salary) > 10000", :select => "salary") + + +* Lead Contributor: "Emilio Tagua":http://github.com/miloops + +h4. Reconnecting MySQL Connections + +MySQL supports a reconnect flag in its connections - if set to true, then the client will try reconnecting to the server before giving up in case of a lost connection. You can now set +reconnect = true+ for your MySQL connections in +database.yml+ to get this behavior from a Rails application. The default is +false+, so the behavior of existing applications doesn't change. + +* Lead Contributor: "Dov Murik":http://twitter.com/dubek +* More information: +** "Controlling Automatic Reconnection Behavior":http://dev.mysql.com/doc/refman/5.0/en/auto-reconnect.html +** "MySQL auto-reconnect revisited":http://groups.google.com/group/rubyonrails-core/browse_thread/thread/49d2a7e9c96cb9f4 + +h4. Other Active Record Changes + +* An extra +AS+ was removed from the generated SQL for +has_and_belongs_to_many+ preloading, making it work better for some databases. +* +ActiveRecord::Base#new_record?+ now returns +false+ rather than +nil+ when confronted with an existing record. +* A bug in quoting table names in some +has_many :through+ associations was fixed. +* You can now specify a particular timestamp for +updated_at+ timestamps: +cust = Customer.create(:name => "ABC Industries", :updated_at => 1.day.ago)+ +* Better error messages on failed +find_by_attribute!+ calls. +* Active Record's +to_xml+ support gets just a little bit more flexible with the addition of a +:camelize+ option. +* A bug in canceling callbacks from +before_update+ or +before_create+ was fixed. +* Rake tasks for testing databases via JDBC have been added. +* +validates_length_of+ will use a custom error message with the +:in+ or +:within+ options (if one is supplied). +* Counts on scoped selects now work properly, so you can do things like +Account.scoped(:select => "DISTINCT credit_limit").count+. +* +ActiveRecord::Base#invalid?+ now works as the opposite of +ActiveRecord::Base#valid?+. + +h3. Action Controller + +Action Controller rolls out some significant changes to rendering, as well as improvements in routing and other areas, in this release. + +h4. Unified Rendering + ++ActionController::Base#render+ is a lot smarter about deciding what to render. Now you can just tell it what to render and expect to get the right results. In older versions of Rails, you often need to supply explicit information to render: + + +render :file => '/tmp/random_file.erb' +render :template => 'other_controller/action' +render :action => 'show' + + +Now in Rails 2.3, you can just supply what you want to render: + + +render '/tmp/random_file.erb' +render 'other_controller/action' +render 'show' +render :show + +Rails chooses between file, template, and action depending on whether there is a leading slash, an embedded slash, or no slash at all in what's to be rendered. Note that you can also use a symbol instead of a string when rendering an action. Other rendering styles (+:inline+, +:text+, +:update+, +:nothing+, +:json+, +:xml+, +:js+) still require an explicit option. + +h4. Application Controller Renamed + +If you're one of the people who has always been bothered by the special-case naming of +application.rb+, rejoice! It's been reworked to be application_controller.rb in Rails 2.3. In addition, there's a new rake task, +rake rails:update:application_controller+ to do this automatically for you - and it will be run as part of the normal +rake rails:update+ process. + +* More Information: +** "The Death of Application.rb":http://afreshcup.com/2008/11/17/rails-2x-the-death-of-applicationrb/ +** "What's New in Edge Rails: Application.rb Duality is no More":http://ryandaigle.com/articles/2008/11/19/what-s-new-in-edge-rails-application-rb-duality-is-no-more + +h4. HTTP Digest Authentication Support + +Rails now has built-in support for HTTP digest authentication. To use it, you call +authenticate_or_request_with_http_digest+ with a block that returns the user’s password (which is then hashed and compared against the transmitted credentials): + + +class PostsController < ApplicationController + Users = {"dhh" => "secret"} + before_filter :authenticate + + def secret + render :text => "Password Required!" + end + + private + def authenticate + realm = "Application" + authenticate_or_request_with_http_digest(realm) do |name| + Users[name] + end + end +end + + +* Lead Contributor: "Gregg Kellogg":http://www.kellogg-assoc.com/ +* More Information: "What's New in Edge Rails: HTTP Digest Authentication":http://ryandaigle.com/articles/2009/1/30/what-s-new-in-edge-rails-http-digest-authentication + +h4. More Efficient Routing + +There are a couple of significant routing changes in Rails 2.3. The +formatted_+ route helpers are gone, in favor just passing in +:format+ as an option. This cuts down the route generation process by 50% for any resource - and can save a substantial amount of memory (up to 100MB on large applications). If your code uses the +formatted_+ helpers, it will still work for the time being - but that behavior is deprecated and your application will be more efficient if you rewrite those routes using the new standard. Another big change is that Rails now supports multiple routing files, not just +routes.rb+. You can use +RouteSet#add_configuration_file+ to bring in more routes at any time - without clearing the currently-loaded routes. While this change is most useful for Engines, you can use it in any application that needs to load routes in batches. + +* Lead Contributors: "Aaron Batalion":http://blog.hungrymachine.com/ + +h4. Rack-based Lazy-loaded Sessions + +A big change pushed the underpinnings of Action Controller session storage down to the Rack level. This involved a good deal of work in the code, though it should be completely transparent to your Rails applications (as a bonus, some icky patches around the old CGI session handler got removed). It's still significant, though, for one simple reason: non-Rails Rack applications have access to the same session storage handlers (and therefore the same session) as your Rails applications. In addition, sessions are now lazy-loaded (in line with the loading improvements to the rest of the framework). This means that you no longer need to explicitly disable sessions if you don't want them; just don't refer to them and they won't load. + +h4. MIME Type Handling Changes + +There are a couple of changes to the code for handling MIME types in Rails. First, +MIME::Type+ now implements the +=~+ operator, making things much cleaner when you need to check for the presence of a type that has synonyms: + + +if content_type && Mime::JS =~ content_type + # do something cool +end + +Mime::JS =~ "text/javascript" => true +Mime::JS =~ "application/javascript" => true + + +The other change is that the framework now uses the +Mime::JS+ when checking for JavaScript in various spots, making it handle those alternatives cleanly. + +* Lead Contributor: "Seth Fitzsimmons":http://www.workingwithrails.com/person/5510-seth-fitzsimmons + +h4. Optimization of +respond_to+ + +In some of the first fruits of the Rails-Merb team merger, Rails 2.3 includes some optimizations for the +respond_to+ method, which is of course heavily used in many Rails applications to allow your controller to format results differently based on the MIME type of the incoming request. After eliminating a call to +method_missing+ and some profiling and tweaking, we're seeing an 8% improvement in the number of requests per second served with a simple +respond_to+ that switches between three formats. The best part? No change at all required to the code of your application to take advantage of this speedup. + +h4. Improved Caching Performance + +Rails now keeps a per-request local cache of read from the remote cache stores, cutting down on unnecessary reads and leading to better site performance. While this work was originally limited to +MemCacheStore+, it is available to any remote store than implements the required methods. + +* Lead Contributor: "Nahum Wild":http://www.motionstandingstill.com/ + +h4. Localized Views + +Rails can now provide localized views, depending on the locale that you have set. For example, suppose you have a +Posts+ controller with a +show+ action. By default, this will render +app/views/posts/show.html.erb+. But if you set +I18n.locale = :da+, it will render +app/views/posts/show.da.html.erb+. If the localized template isn't present, the undecorated version will be used. Rails also includes +I18n#available_locales+ and +I18n::SimpleBackend#available_locales+, which return an array of the translations that are available in the current Rails project. + +In addition, you can use the same scheme to localize the rescue files in the +public+ directory: +public/500.da.html+ or +public/404.en.html+ work, for example. + +h4. Partial Scoping for Translations + +A change to the translation API makes things easier and less repetitive to write key translations within partials. If you call +translate(".foo")+ from the +people/index.html.erb+ template, you'll actually be calling +I18n.translate("people.index.foo")+ If you don't prepend the key with a period, then the API doesn't scope, just as before. + +h4. Other Action Controller Changes + +* ETag handling has been cleaned up a bit: Rails will now skip sending an ETag header when there's no body to the response or when sending files with +send_file+. +* The fact that Rails checks for IP spoofing can be a nuisance for sites that do heavy traffic with cell phones, because their proxies don't generally set things up right. If that's you, you can now set +ActionController::Base.ip_spoofing_check = false+ to disable the check entirely. +* +ActionController::Dispatcher+ now implements its own middleware stack, which you can see by running +rake middleware+. +* Cookie sessions now have persistent session identifiers, with API compatibility with the server-side stores. +* You can now use symbols for the +:type+ option of +send_file+ and +send_data+, like this: +send_file("fabulous.png", :type => :png)+. +* The +:only+ and +:except+ options for +map.resources+ are no longer inherited by nested resources. +* The bundled memcached client has been updated to version 1.6.4.99. +* The +expires_in+, +stale?+, and +fresh_when+ methods now accept a +:public+ option to make them work well with proxy caching. +* The +:requirements+ option now works properly with additional RESTful member routes. +* Shallow routes now properly respect namespaces. +* +polymorphic_url+ does a better job of handling objects with irregular plural names. + +h3. Action View + +Action View in Rails 2.3 picks up nested model forms, improvements to +render+, more flexible prompts for the date select helpers, and a speedup in asset caching, among other things. + +h4. Nested Object Forms + +Provided the parent model accepts nested attributes for the child objects (as discussed in the Active Record section), you can create nested forms using +form_for+ and +field_for+. These forms can be nested arbitrarily deep, allowing you to edit complex object hierarchies on a single view without excessive code. For example, given this model: + + +class Customer < ActiveRecord::Base + has_many :orders + + accepts_nested_attributes_for :orders, :allow_destroy => true +end + + +You can write this view in Rails 2.3: + + +<% form_for @customer do |customer_form| %> +
+ <%= customer_form.label :name, 'Customer Name:' %> + <%= customer_form.text_field :name %> +
+ + + <% customer_form.fields_for :orders do |order_form| %> +

+

+ <%= order_form.label :number, 'Order Number:' %> + <%= order_form.text_field :number %> +
+ + + <% unless order_form.object.new_record? %> +
+ <%= order_form.label :_delete, 'Remove:' %> + <%= order_form.check_box :_delete %> +
+ <% end %> +

+ <% end %> + + <%= customer_form.submit %> +<% end %> +
+ +* Lead Contributor: "Eloy Duran":http://superalloy.nl/ +* More Information: +** "Nested Model Forms":http://weblog.rubyonrails.org/2009/1/26/nested-model-forms +** "complex-form-examples":http://github.com/alloy/complex-form-examples +** "What's New in Edge Rails: Nested Object Forms":http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes + +h4. Smart Rendering of Partials + +The render method has been getting smarter over the years, and it's even smarter now. If you have an object or a collection and an appropriate partial, and the naming matches up, you can now just render the object and things will work. For example, in Rails 2.3, these render calls will work in your view (assuming sensible naming): + + +# Equivalent of render :partial => 'articles/_article', +# :object => @article +render @article + +# Equivalent of render :partial => 'articles/_article', +# :collection => @articles +render @articles + + +* More Information: "What's New in Edge Rails: render Stops Being High-Maintenance":http://ryandaigle.com/articles/2008/11/20/what-s-new-in-edge-rails-render-stops-being-high-maintenance + +h4. Prompts for Date Select Helpers + +In Rails 2.3, you can supply custom prompts for the various date select helpers (+date_select+, +time_select+, and +datetime_select+), the same way you can with collection select helpers. You can supply a prompt string or a hash of individual prompt strings for the various components. You can also just set +:prompt+ to +true+ to use the custom generic prompt: + + +select_datetime(DateTime.now, :prompt => true) + +select_datetime(DateTime.now, :prompt => "Choose date and time") + +select_datetime(DateTime.now, :prompt => + {:day => 'Choose day', :month => 'Choose month', + :year => 'Choose year', :hour => 'Choose hour', + :minute => 'Choose minute'}) + + +* Lead Contributor: "Sam Oliver":http://samoliver.com/ + +h4. AssetTag Timestamp Caching + +You're likely familiar with Rails' practice of adding timestamps to static asset paths as a "cache buster." This helps ensure that stale copies of things like images and stylesheets don't get served out of the user's browser cache when you change them on the server. You can now modify this behavior with the +cache_asset_timestamps+ configuration option for Action View. If you enable the cache, then Rails will calculate the timestamp once when it first serves an asset, and save that value. This means fewer (expensive) file system calls to serve static assets - but it also means that you can't modify any of the assets while the server is running and expect the changes to get picked up by clients. + +h4. Asset Hosts as Objects + +Asset hosts get more flexible in edge Rails with the ability to declare an asset host as a specific object that responds to a call. This allows you to implement any complex logic you need in your asset hosting. + +* More Information: "asset-hosting-with-minimum-ssl":http://github.com/dhh/asset-hosting-with-minimum-ssl/tree/master + +h4. grouped_options_for_select Helper Method + +Action View already had a bunch of helpers to aid in generating select controls, but now there's one more: +grouped_options_for_select+. This one accepts an array or hash of strings, and converts them into a string of +option+ tags wrapped with +optgroup+ tags. For example: + + +grouped_options_for_select([["Hats", ["Baseball Cap","Cowboy Hat"]]], + "Cowboy Hat", "Choose a product...") + + +returns + + + + + + + + + +h4. Disabled Option Tags for Form Select Helpers + +The form select helpers (such as +select+ and +options_for_select+) now support a +:disabled+ option, which can take a single value or an array of values to be disabled in the resulting tags: + + +select(:post, :category, Post::CATEGORIES, :disabled => ‘private‘) + + +returns + + + + + +You can also use an anonymous function to determine at runtime which options from collections will be selected and/or disabled: + + +options_from_collection_for_select(@product.sizes, :name, :id, :disabled => lambda{|size| size.out_of_stock?}) + + +* Lead Contributor: "Tekin Suleyman":http://tekin.co.uk/ +* More Information: "New in rails 2.3 - disabled option tags and lambdas for selecting and disabling options from collections":http://tekin.co.uk/2009/03/new-in-rails-23-disabled-option-tags-and-lambdas-for-selecting-and-disabling-options-from-collections/ + +h4. A Note About Template Loading + +Rails 2.3 includes the ability to enable or disable cached templates for any particular environment. Cached templates give you a speed boost because they don't check for a new template file when they're rendered - but they also mean that you can't replace a template "on the fly" without restarting the server. + +In most cases, you'll want template caching to be turned on in production, which you can do by making a setting in your +production.rb+ file: + + +config.action_view.cache_template_loading = true + + +This line will be generated for you by default in a new Rails 2.3 application. If you've upgraded from an older version of Rails, Rails will default to caching templates in production and test but not in development. + +h4. Other Action View Changes + +* Token generation for CSRF protection has been simplified; now Rails uses a simple random string generated by +ActiveSupport::SecureRandom+ rather than mucking around with session IDs. +* +auto_link+ now properly applies options (such as +:target+ and +:class+) to generated e-mail links. +* The +autolink+ helper has been refactored to make it a bit less messy and more intuitive. +* +current_page?+ now works properly even when there are multiple query parameters in the URL. + +h3. Active Support + +Active Support has a few interesting changes, including the introduction of +Object#try+. + +h4. Object#try + +A lot of folks have adopted the notion of using try() to attempt operations on objects. It's especially helpful in views where you can avoid nil-checking by writing code like +<%= @person.try(:name) %>+. Well, now it's baked right into Rails. As implemented in Rails, it raises +NoMethodError+ on private methods and always returns +nil+ if the object is nil. + +* More Information: "try()":http://ozmm.org/posts/try.html. + +h4. Object#tap Backport + ++Object#tap+ is an addition to "Ruby 1.9":http://www.ruby-doc.org/core-1.9/classes/Object.html#M000309 and 1.8.7 that is similar to the +returning+ method that Rails has had for a while: it yields to a block, and then returns the object that was yielded. Rails now includes code to make this available under older versions of Ruby as well. + +h4. Swappable Parsers for XMLmini + +The support for XML parsing in ActiveSupport has been made more flexible by allowing you to swap in different parsers. By default, it uses the standard REXML implementation, but you can easily specify the faster LibXML or Nokogiri implementations for your own applications, provided you have the appropriate gems installed: + + +XmlMini.backend = 'LibXML' + + +* Lead Contributor: "Bart ten Brinke":http://www.movesonrails.com/ +* Lead Contributor: "Aaron Patterson":http://tenderlovemaking.com/ + +h4. Fractional seconds for TimeWithZone + +The +Time+ and +TimeWithZone+ classes include an +xmlschema+ method to return the time in an XML-friendly string. As of Rails 2.3, +TimeWithZone+ supports the same argument for specifying the number of digits in the fractional second part of the returned string that +Time+ does: + + +>> Time.zone.now.xmlschema(6) +=> "2009-01-16T13:00:06.13653Z" + + +* Lead Contributor: "Nicholas Dainty":http://www.workingwithrails.com/person/13536-nicholas-dainty + +h4. JSON Key Quoting + +If you look up the spec on the "json.org" site, you'll discover that all keys in a JSON structure must be strings, and they must be quoted with double quotes. Starting with Rails 2.3, we do the right thing here, even with numeric keys. + +h4. Other Active Support Changes + +* You can use +Enumerable#none?+ to check that none of the elements match the supplied block. +* If you're using Active Support "delegates":http://afreshcup.com/2008/10/19/coming-in-rails-22-delegate-prefixes/, the new +:allow_nil+ option lets you return +nil+ instead of raising an exception when the target object is nil. +* +ActiveSupport::OrderedHash+: now implements +each_key+ and +each_value+. +* +ActiveSupport::MessageEncryptor+ provides a simple way to encrypt information for storage in an untrusted location (like cookies). +* Active Support's +from_xml+ no longer depends on XmlSimple. Instead, Rails now includes its own XmlMini implementation, with just the functionality that it requires. This lets Rails dispense with the bundled copy of XmlSimple that it's been carting around. +* If you memoize a private method, the result will now be private. +* +String#parameterize+ accepts an optional separator: +"Quick Brown Fox".parameterize('_') => "quick_brown_fox"+. +* +number_to_phone+ accepts 7-digit phone numbers now. +* +ActiveSupport::Json.decode+ now handles +\u0000+ style escape sequences. + +h3. Railties + +In addition to the Rack changes covered above, Railties (the core code of Rails itself) sports a number of significant changes, including Rails Metal, application templates, and quiet backtraces. + +h4. Rails Metal + +Rails Metal is a new mechanism that provides superfast endpoints inside of your Rails applications. Metal classes bypass routing and Action Controller to give you raw speed (at the cost of all the things in Action Controller, of course). This builds on all of the recent foundation work to make Rails a Rack application with an exposed middleware stack. Metal endpoints can be loaded from your application or from plugins. + +* More Information: +** "Introducing Rails Metal":http://weblog.rubyonrails.org/2008/12/17/introducing-rails-metal +** "Rails Metal: a micro-framework with the power of Rails":http://soylentfoo.jnewland.com/articles/2008/12/16/rails-metal-a-micro-framework-with-the-power-of-rails-m +** "Metal: Super-fast Endpoints within your Rails Apps":http://www.railsinside.com/deployment/180-metal-super-fast-endpoints-within-your-rails-apps.html +** "What's New in Edge Rails: Rails Metal":http://ryandaigle.com/articles/2008/12/18/what-s-new-in-edge-rails-rails-metal + +h4. Application Templates + +Rails 2.3 incorporates Jeremy McAnally's "rg":http://github.com/jeremymcanally/rg/tree/master application generator. What this means is that we now have template-based application generation built right into Rails; if you have a set of plugins you include in every application (among many other use cases), you can just set up a template once and use it over and over again when you run the +rails+ command. There's also a rake task to apply a template to an existing application: + + +rake rails:template LOCATION=~/template.rb + + +This will layer the changes from the template on top of whatever code the project already contains. + +* Lead Contributor: "Jeremy McAnally":http://www.jeremymcanally.com/ +* More Info:"Rails templates":http://m.onkey.org/2008/12/4/rails-templates + +h4. Quieter Backtraces + +Building on Thoughtbot's "Quiet Backtrace":https://github.com/thoughtbot/quietbacktrace plugin, which allows you to selectively remove lines from +Test::Unit+ backtraces, Rails 2.3 implements +ActiveSupport::BacktraceCleaner+ and +Rails::BacktraceCleaner+ in core. This supports both filters (to perform regex-based substitutions on backtrace lines) and silencers (to remove backtrace lines entirely). Rails automatically adds silencers to get rid of the most common noise in a new application, and builds a +config/backtrace_silencers.rb+ file to hold your own additions. This feature also enables prettier printing from any gem in the backtrace. + +h4. Faster Boot Time in Development Mode with Lazy Loading/Autoload + +Quite a bit of work was done to make sure that bits of Rails (and its dependencies) are only brought into memory when they're actually needed. The core frameworks - Active Support, Active Record, Action Controller, Action Mailer and Action View - are now using +autoload+ to lazy-load their individual classes. This work should help keep the memory footprint down and improve overall Rails performance. + +You can also specify (by using the new +preload_frameworks+ option) whether the core libraries should be autoloaded at startup. This defaults to +false+ so that Rails autoloads itself piece-by-piece, but there are some circumstances where you still need to bring in everything at once - Passenger and JRuby both want to see all of Rails loaded together. + +h4. rake gem Task Rewrite + +The internals of the various rake gem tasks have been substantially revised, to make the system work better for a variety of cases. The gem system now knows the difference between development and runtime dependencies, has a more robust unpacking system, gives better information when querying for the status of gems, and is less prone to "chicken and egg" dependency issues when you're bringing things up from scratch. There are also fixes for using gem commands under JRuby and for dependencies that try to bring in external copies of gems that are already vendored. + +* Lead Contributor: "David Dollar":http://www.workingwithrails.com/person/12240-david-dollar + +h4. Other Railties Changes + +* The instructions for updating a CI server to build Rails have been updated and expanded. +* Internal Rails testing has been switched from +Test::Unit::TestCase+ to +ActiveSupport::TestCase+, and the Rails core requires Mocha to test. +* The default +environment.rb+ file has been decluttered. +* The dbconsole script now lets you use an all-numeric password without crashing. +* +Rails.root+ now returns a +Pathname+ object, which means you can use it directly with the +join+ method to "clean up existing code":http://afreshcup.com/2008/12/05/a-little-rails_root-tidiness/ that uses +File.join+. +* Various files in /public that deal with CGI and FCGI dispatching are no longer generated in every Rails application by default (you can still get them if you need them by adding +--with-dispatchers+ when you run the +rails+ command, or add them later with +rake rails:update:generate_dispatchers+). +* Rails Guides have been converted from AsciiDoc to Textile markup. +* Scaffolded views and controllers have been cleaned up a bit. +* +script/server+ now accepts a --path argument to mount a Rails application from a specific path. +* If any configured gems are missing, the gem rake tasks will skip loading much of the environment. This should solve many of the "chicken-and-egg" problems where rake gems:install couldn't run because gems were missing. +* Gems are now unpacked exactly once. This fixes issues with gems (hoe, for instance) which are packed with read-only permissions on the files. + +h3. Deprecated + +A few pieces of older code are deprecated in this release: + +* If you're one of the (fairly rare) Rails developers who deploys in a fashion that depends on the inspector, reaper, and spawner scripts, you'll need to know that those scripts are no longer included in core Rails. If you need them, you'll be able to pick up copies via the "irs_process_scripts":http://github.com/rails/irs_process_scripts/tree plugin. +* +render_component+ goes from "deprecated" to "nonexistent" in Rails 2.3. If you still need it, you can install the "render_component plugin":http://github.com/rails/render_component/tree/master. +* Support for Rails components has been removed. +* If you were one of the people who got used to running +script/performance/request+ to look at performance based on integration tests, you need to learn a new trick: that script has been removed from core Rails now. There’s a new request_profiler plugin that you can install to get the exact same functionality back. +* +ActionController::Base#session_enabled?+ is deprecated because sessions are lazy-loaded now. +* The +:digest+ and +:secret+ options to +protect_from_forgery+ are deprecated and have no effect. +* Some integration test helpers have been removed. +response.headers["Status"]+ and +headers["Status"]+ will no longer return anything. Rack does not allow "Status" in its return headers. However you can still use the +status+ and +status_message+ helpers. +response.headers["cookie"]+ and +headers["cookie"]+ will no longer return any CGI cookies. You can inspect +headers["Set-Cookie"]+ to see the raw cookie header or use the +cookies+ helper to get a hash of the cookies sent to the client. +* +formatted_polymorphic_url+ is deprecated. Use +polymorphic_url+ with +:format+ instead. +* The +:http_only+ option in +ActionController::Response#set_cookie+ has been renamed to +:httponly+. +* The +:connector+ and +:skip_last_comma+ options of +to_sentence+ have been replaced by +:words_connnector+, +:two_words_connector+, and +:last_word_connector+ options. +* Posting a multipart form with an empty +file_field+ control used to submit an empty string to the controller. Now it submits a nil, due to differences between Rack's multipart parser and the old Rails one. + +h3. Credits + +Release notes compiled by "Mike Gunderloy":http://afreshcup.com. This version of the Rails 2.3 release notes was compiled based on RC2 of Rails 2.3. diff --git a/guides/source/2_3_release_notes.textile b/guides/source/2_3_release_notes.textile deleted file mode 100644 index 36f425574b..0000000000 --- a/guides/source/2_3_release_notes.textile +++ /dev/null @@ -1,610 +0,0 @@ -h2. Ruby on Rails 2.3 Release Notes - -Rails 2.3 delivers a variety of new and improved features, including pervasive Rack integration, refreshed support for Rails Engines, nested transactions for Active Record, dynamic and default scopes, unified rendering, more efficient routing, application templates, and quiet backtraces. This list covers the major upgrades, but doesn't include every little bug fix and change. If you want to see everything, check out the "list of commits":http://github.com/rails/rails/commits/master in the main Rails repository on GitHub or review the +CHANGELOG+ files for the individual Rails components. - -endprologue. - -h3. Application Architecture - -There are two major changes in the architecture of Rails applications: complete integration of the "Rack":http://rack.rubyforge.org/ modular web server interface, and renewed support for Rails Engines. - -h4. Rack Integration - -Rails has now broken with its CGI past, and uses Rack everywhere. This required and resulted in a tremendous number of internal changes (but if you use CGI, don't worry; Rails now supports CGI through a proxy interface.) Still, this is a major change to Rails internals. After upgrading to 2.3, you should test on your local environment and your production environment. Some things to test: - -* Sessions -* Cookies -* File uploads -* JSON/XML APIs - -Here's a summary of the rack-related changes: - -* +script/server+ has been switched to use Rack, which means it supports any Rack compatible server. +script/server+ will also pick up a rackup configuration file if one exists. By default, it will look for a +config.ru+ file, but you can override this with the +-c+ switch. -* The FCGI handler goes through Rack. -* +ActionController::Dispatcher+ maintains its own default middleware stack. Middlewares can be injected in, reordered, and removed. The stack is compiled into a chain on boot. You can configure the middleware stack in +environment.rb+. -* The +rake middleware+ task has been added to inspect the middleware stack. This is useful for debugging the order of the middleware stack. -* The integration test runner has been modified to execute the entire middleware and application stack. This makes integration tests perfect for testing Rack middleware. -* +ActionController::CGIHandler+ is a backwards compatible CGI wrapper around Rack. The +CGIHandler+ is meant to take an old CGI object and convert its environment information into a Rack compatible form. -* +CgiRequest+ and +CgiResponse+ have been removed. -* Session stores are now lazy loaded. If you never access the session object during a request, it will never attempt to load the session data (parse the cookie, load the data from memcache, or lookup an Active Record object). -* You no longer need to use +CGI::Cookie.new+ in your tests for setting a cookie value. Assigning a +String+ value to request.cookies["foo"] now sets the cookie as expected. -* +CGI::Session::CookieStore+ has been replaced by +ActionController::Session::CookieStore+. -* +CGI::Session::MemCacheStore+ has been replaced by +ActionController::Session::MemCacheStore+. -* +CGI::Session::ActiveRecordStore+ has been replaced by +ActiveRecord::SessionStore+. -* You can still change your session store with +ActionController::Base.session_store = :active_record_store+. -* Default sessions options are still set with +ActionController::Base.session = { :key => "..." }+. However, the +:session_domain+ option has been renamed to +:domain+. -* The mutex that normally wraps your entire request has been moved into middleware, +ActionController::Lock+. -* +ActionController::AbstractRequest+ and +ActionController::Request+ have been unified. The new +ActionController::Request+ inherits from +Rack::Request+. This affects access to +response.headers['type']+ in test requests. Use +response.content_type+ instead. -* +ActiveRecord::QueryCache+ middleware is automatically inserted onto the middleware stack if +ActiveRecord+ has been loaded. This middleware sets up and flushes the per-request Active Record query cache. -* The Rails router and controller classes follow the Rack spec. You can call a controller directly with +SomeController.call(env)+. The router stores the routing parameters in +rack.routing_args+. -* +ActionController::Request+ inherits from +Rack::Request+. -* Instead of +config.action_controller.session = { :session_key => 'foo', ...+ use +config.action_controller.session = { :key => 'foo', ...+. -* Using the +ParamsParser+ middleware preprocesses any XML, JSON, or YAML requests so they can be read normally with any +Rack::Request+ object after it. - -h4. Renewed Support for Rails Engines - -After some versions without an upgrade, Rails 2.3 offers some new features for Rails Engines (Rails applications that can be embedded within other applications). First, routing files in engines are automatically loaded and reloaded now, just like your +routes.rb+ file (this also applies to routing files in other plugins). Second, if your plugin has an app folder, then app/[models|controllers|helpers] will automatically be added to the Rails load path. Engines also support adding view paths now, and Action Mailer as well as Action View will use views from engines and other plugins. - -h3. Documentation - -The "Ruby on Rails guides":http://guides.rubyonrails.org/ project has published several additional guides for Rails 2.3. In addition, a "separate site":http://edgeguides.rubyonrails.org/ maintains updated copies of the Guides for Edge Rails. Other documentation efforts include a relaunch of the "Rails wiki":http://newwiki.rubyonrails.org/ and early planning for a Rails Book. - -* More Information: "Rails Documentation Projects":http://weblog.rubyonrails.org/2009/1/15/rails-documentation-projects. - -h3. Ruby 1.9.1 Support - -Rails 2.3 should pass all of its own tests whether you are running on Ruby 1.8 or the now-released Ruby 1.9.1. You should be aware, though, that moving to 1.9.1 entails checking all of the data adapters, plugins, and other code that you depend on for Ruby 1.9.1 compatibility, as well as Rails core. - -h3. Active Record - -Active Record gets quite a number of new features and bug fixes in Rails 2.3. The highlights include nested attributes, nested transactions, dynamic and default scopes, and batch processing. - -h4. Nested Attributes - -Active Record can now update the attributes on nested models directly, provided you tell it to do so: - - -class Book < ActiveRecord::Base - has_one :author - has_many :pages - - accepts_nested_attributes_for :author, :pages -end - - -Turning on nested attributes enables a number of things: automatic (and atomic) saving of a record together with its associated children, child-aware validations, and support for nested forms (discussed later). - -You can also specify requirements for any new records that are added via nested attributes using the +:reject_if+ option: - - -accepts_nested_attributes_for :author, - :reject_if => proc { |attributes| attributes['name'].blank? } - - -* Lead Contributor: "Eloy Duran":http://superalloy.nl/ -* More Information: "Nested Model Forms":http://weblog.rubyonrails.org/2009/1/26/nested-model-forms - -h4. Nested Transactions - -Active Record now supports nested transactions, a much-requested feature. Now you can write code like this: - - -User.transaction do - User.create(:username => 'Admin') - User.transaction(:requires_new => true) do - User.create(:username => 'Regular') - raise ActiveRecord::Rollback - end - end - - User.find(:all) # => Returns only Admin - - -Nested transactions let you roll back an inner transaction without affecting the state of the outer transaction. If you want a transaction to be nested, you must explicitly add the +:requires_new+ option; otherwise, a nested transaction simply becomes part of the parent transaction (as it does currently on Rails 2.2). Under the covers, nested transactions are "using savepoints":http://rails.lighthouseapp.com/projects/8994/tickets/383, so they're supported even on databases that don't have true nested transactions. There is also a bit of magic going on to make these transactions play well with transactional fixtures during testing. - -* Lead Contributors: "Jonathan Viney":http://www.workingwithrails.com/person/4985-jonathan-viney and "Hongli Lai":http://izumi.plan99.net/blog/ - -h4. Dynamic Scopes - -You know about dynamic finders in Rails (which allow you to concoct methods like +find_by_color_and_flavor+ on the fly) and named scopes (which allow you to encapsulate reusable query conditions into friendly names like +currently_active+). Well, now you can have dynamic scope methods. The idea is to put together syntax that allows filtering on the fly _and_ method chaining. For example: - - -Order.scoped_by_customer_id(12) -Order.scoped_by_customer_id(12).find(:all, - :conditions => "status = 'open'") -Order.scoped_by_customer_id(12).scoped_by_status("open") - - -There's nothing to define to use dynamic scopes: they just work. - -* Lead Contributor: "Yaroslav Markin":http://evilmartians.com/ -* More Information: "What's New in Edge Rails: Dynamic Scope Methods":http://ryandaigle.com/articles/2008/12/29/what-s-new-in-edge-rails-dynamic-scope-methods. - -h4. Default Scopes - -Rails 2.3 will introduce the notion of _default scopes_ similar to named scopes, but applying to all named scopes or find methods within the model. For example, you can write +default_scope :order => 'name ASC'+ and any time you retrieve records from that model they'll come out sorted by name (unless you override the option, of course). - -* Lead Contributor: Paweł Kondzior -* More Information: "What's New in Edge Rails: Default Scoping":http://ryandaigle.com/articles/2008/11/18/what-s-new-in-edge-rails-default-scoping - -h4. Batch Processing - -You can now process large numbers of records from an ActiveRecord model with less pressure on memory by using +find_in_batches+: - - -Customer.find_in_batches(:conditions => {:active => true}) do |customer_group| - customer_group.each { |customer| customer.update_account_balance! } -end - - -You can pass most of the +find+ options into +find_in_batches+. However, you cannot specify the order that records will be returned in (they will always be returned in ascending order of primary key, which must be an integer), or use the +:limit+ option. Instead, use the +:batch_size+ option, which defaults to 1000, to set the number of records that will be returned in each batch. - -The new +find_each+ method provides a wrapper around +find_in_batches+ that returns individual records, with the find itself being done in batches (of 1000 by default): - - -Customer.find_each do |customer| - customer.update_account_balance! -end - - -Note that you should only use this method for batch processing: for small numbers of records (less than 1000), you should just use the regular find methods with your own loop. - -* More Information (at that point the convenience method was called just +each+): -** "Rails 2.3: Batch Finding":http://afreshcup.com/2009/02/23/rails-23-batch-finding/ -** "What's New in Edge Rails: Batched Find":http://ryandaigle.com/articles/2009/2/23/what-s-new-in-edge-rails-batched-find - -h4. Multiple Conditions for Callbacks - -When using Active Record callbacks, you can now combine +:if+ and +:unless+ options on the same callback, and supply multiple conditions as an array: - - -before_save :update_credit_rating, :if => :active, - :unless => [:admin, :cash_only] - -* Lead Contributor: L. Caviola - -h4. Find with having - -Rails now has a +:having+ option on find (as well as on +has_many+ and +has_and_belongs_to_many+ associations) for filtering records in grouped finds. As those with heavy SQL backgrounds know, this allows filtering based on grouped results: - - -developers = Developer.find(:all, :group => "salary", - :having => "sum(salary) > 10000", :select => "salary") - - -* Lead Contributor: "Emilio Tagua":http://github.com/miloops - -h4. Reconnecting MySQL Connections - -MySQL supports a reconnect flag in its connections - if set to true, then the client will try reconnecting to the server before giving up in case of a lost connection. You can now set +reconnect = true+ for your MySQL connections in +database.yml+ to get this behavior from a Rails application. The default is +false+, so the behavior of existing applications doesn't change. - -* Lead Contributor: "Dov Murik":http://twitter.com/dubek -* More information: -** "Controlling Automatic Reconnection Behavior":http://dev.mysql.com/doc/refman/5.0/en/auto-reconnect.html -** "MySQL auto-reconnect revisited":http://groups.google.com/group/rubyonrails-core/browse_thread/thread/49d2a7e9c96cb9f4 - -h4. Other Active Record Changes - -* An extra +AS+ was removed from the generated SQL for +has_and_belongs_to_many+ preloading, making it work better for some databases. -* +ActiveRecord::Base#new_record?+ now returns +false+ rather than +nil+ when confronted with an existing record. -* A bug in quoting table names in some +has_many :through+ associations was fixed. -* You can now specify a particular timestamp for +updated_at+ timestamps: +cust = Customer.create(:name => "ABC Industries", :updated_at => 1.day.ago)+ -* Better error messages on failed +find_by_attribute!+ calls. -* Active Record's +to_xml+ support gets just a little bit more flexible with the addition of a +:camelize+ option. -* A bug in canceling callbacks from +before_update+ or +before_create+ was fixed. -* Rake tasks for testing databases via JDBC have been added. -* +validates_length_of+ will use a custom error message with the +:in+ or +:within+ options (if one is supplied). -* Counts on scoped selects now work properly, so you can do things like +Account.scoped(:select => "DISTINCT credit_limit").count+. -* +ActiveRecord::Base#invalid?+ now works as the opposite of +ActiveRecord::Base#valid?+. - -h3. Action Controller - -Action Controller rolls out some significant changes to rendering, as well as improvements in routing and other areas, in this release. - -h4. Unified Rendering - -+ActionController::Base#render+ is a lot smarter about deciding what to render. Now you can just tell it what to render and expect to get the right results. In older versions of Rails, you often need to supply explicit information to render: - - -render :file => '/tmp/random_file.erb' -render :template => 'other_controller/action' -render :action => 'show' - - -Now in Rails 2.3, you can just supply what you want to render: - - -render '/tmp/random_file.erb' -render 'other_controller/action' -render 'show' -render :show - -Rails chooses between file, template, and action depending on whether there is a leading slash, an embedded slash, or no slash at all in what's to be rendered. Note that you can also use a symbol instead of a string when rendering an action. Other rendering styles (+:inline+, +:text+, +:update+, +:nothing+, +:json+, +:xml+, +:js+) still require an explicit option. - -h4. Application Controller Renamed - -If you're one of the people who has always been bothered by the special-case naming of +application.rb+, rejoice! It's been reworked to be application_controller.rb in Rails 2.3. In addition, there's a new rake task, +rake rails:update:application_controller+ to do this automatically for you - and it will be run as part of the normal +rake rails:update+ process. - -* More Information: -** "The Death of Application.rb":http://afreshcup.com/2008/11/17/rails-2x-the-death-of-applicationrb/ -** "What's New in Edge Rails: Application.rb Duality is no More":http://ryandaigle.com/articles/2008/11/19/what-s-new-in-edge-rails-application-rb-duality-is-no-more - -h4. HTTP Digest Authentication Support - -Rails now has built-in support for HTTP digest authentication. To use it, you call +authenticate_or_request_with_http_digest+ with a block that returns the user’s password (which is then hashed and compared against the transmitted credentials): - - -class PostsController < ApplicationController - Users = {"dhh" => "secret"} - before_filter :authenticate - - def secret - render :text => "Password Required!" - end - - private - def authenticate - realm = "Application" - authenticate_or_request_with_http_digest(realm) do |name| - Users[name] - end - end -end - - -* Lead Contributor: "Gregg Kellogg":http://www.kellogg-assoc.com/ -* More Information: "What's New in Edge Rails: HTTP Digest Authentication":http://ryandaigle.com/articles/2009/1/30/what-s-new-in-edge-rails-http-digest-authentication - -h4. More Efficient Routing - -There are a couple of significant routing changes in Rails 2.3. The +formatted_+ route helpers are gone, in favor just passing in +:format+ as an option. This cuts down the route generation process by 50% for any resource - and can save a substantial amount of memory (up to 100MB on large applications). If your code uses the +formatted_+ helpers, it will still work for the time being - but that behavior is deprecated and your application will be more efficient if you rewrite those routes using the new standard. Another big change is that Rails now supports multiple routing files, not just +routes.rb+. You can use +RouteSet#add_configuration_file+ to bring in more routes at any time - without clearing the currently-loaded routes. While this change is most useful for Engines, you can use it in any application that needs to load routes in batches. - -* Lead Contributors: "Aaron Batalion":http://blog.hungrymachine.com/ - -h4. Rack-based Lazy-loaded Sessions - -A big change pushed the underpinnings of Action Controller session storage down to the Rack level. This involved a good deal of work in the code, though it should be completely transparent to your Rails applications (as a bonus, some icky patches around the old CGI session handler got removed). It's still significant, though, for one simple reason: non-Rails Rack applications have access to the same session storage handlers (and therefore the same session) as your Rails applications. In addition, sessions are now lazy-loaded (in line with the loading improvements to the rest of the framework). This means that you no longer need to explicitly disable sessions if you don't want them; just don't refer to them and they won't load. - -h4. MIME Type Handling Changes - -There are a couple of changes to the code for handling MIME types in Rails. First, +MIME::Type+ now implements the +=~+ operator, making things much cleaner when you need to check for the presence of a type that has synonyms: - - -if content_type && Mime::JS =~ content_type - # do something cool -end - -Mime::JS =~ "text/javascript" => true -Mime::JS =~ "application/javascript" => true - - -The other change is that the framework now uses the +Mime::JS+ when checking for JavaScript in various spots, making it handle those alternatives cleanly. - -* Lead Contributor: "Seth Fitzsimmons":http://www.workingwithrails.com/person/5510-seth-fitzsimmons - -h4. Optimization of +respond_to+ - -In some of the first fruits of the Rails-Merb team merger, Rails 2.3 includes some optimizations for the +respond_to+ method, which is of course heavily used in many Rails applications to allow your controller to format results differently based on the MIME type of the incoming request. After eliminating a call to +method_missing+ and some profiling and tweaking, we're seeing an 8% improvement in the number of requests per second served with a simple +respond_to+ that switches between three formats. The best part? No change at all required to the code of your application to take advantage of this speedup. - -h4. Improved Caching Performance - -Rails now keeps a per-request local cache of read from the remote cache stores, cutting down on unnecessary reads and leading to better site performance. While this work was originally limited to +MemCacheStore+, it is available to any remote store than implements the required methods. - -* Lead Contributor: "Nahum Wild":http://www.motionstandingstill.com/ - -h4. Localized Views - -Rails can now provide localized views, depending on the locale that you have set. For example, suppose you have a +Posts+ controller with a +show+ action. By default, this will render +app/views/posts/show.html.erb+. But if you set +I18n.locale = :da+, it will render +app/views/posts/show.da.html.erb+. If the localized template isn't present, the undecorated version will be used. Rails also includes +I18n#available_locales+ and +I18n::SimpleBackend#available_locales+, which return an array of the translations that are available in the current Rails project. - -In addition, you can use the same scheme to localize the rescue files in the +public+ directory: +public/500.da.html+ or +public/404.en.html+ work, for example. - -h4. Partial Scoping for Translations - -A change to the translation API makes things easier and less repetitive to write key translations within partials. If you call +translate(".foo")+ from the +people/index.html.erb+ template, you'll actually be calling +I18n.translate("people.index.foo")+ If you don't prepend the key with a period, then the API doesn't scope, just as before. - -h4. Other Action Controller Changes - -* ETag handling has been cleaned up a bit: Rails will now skip sending an ETag header when there's no body to the response or when sending files with +send_file+. -* The fact that Rails checks for IP spoofing can be a nuisance for sites that do heavy traffic with cell phones, because their proxies don't generally set things up right. If that's you, you can now set +ActionController::Base.ip_spoofing_check = false+ to disable the check entirely. -* +ActionController::Dispatcher+ now implements its own middleware stack, which you can see by running +rake middleware+. -* Cookie sessions now have persistent session identifiers, with API compatibility with the server-side stores. -* You can now use symbols for the +:type+ option of +send_file+ and +send_data+, like this: +send_file("fabulous.png", :type => :png)+. -* The +:only+ and +:except+ options for +map.resources+ are no longer inherited by nested resources. -* The bundled memcached client has been updated to version 1.6.4.99. -* The +expires_in+, +stale?+, and +fresh_when+ methods now accept a +:public+ option to make them work well with proxy caching. -* The +:requirements+ option now works properly with additional RESTful member routes. -* Shallow routes now properly respect namespaces. -* +polymorphic_url+ does a better job of handling objects with irregular plural names. - -h3. Action View - -Action View in Rails 2.3 picks up nested model forms, improvements to +render+, more flexible prompts for the date select helpers, and a speedup in asset caching, among other things. - -h4. Nested Object Forms - -Provided the parent model accepts nested attributes for the child objects (as discussed in the Active Record section), you can create nested forms using +form_for+ and +field_for+. These forms can be nested arbitrarily deep, allowing you to edit complex object hierarchies on a single view without excessive code. For example, given this model: - - -class Customer < ActiveRecord::Base - has_many :orders - - accepts_nested_attributes_for :orders, :allow_destroy => true -end - - -You can write this view in Rails 2.3: - - -<% form_for @customer do |customer_form| %> -
- <%= customer_form.label :name, 'Customer Name:' %> - <%= customer_form.text_field :name %> -
- - - <% customer_form.fields_for :orders do |order_form| %> -

-

- <%= order_form.label :number, 'Order Number:' %> - <%= order_form.text_field :number %> -
- - - <% unless order_form.object.new_record? %> -
- <%= order_form.label :_delete, 'Remove:' %> - <%= order_form.check_box :_delete %> -
- <% end %> -

- <% end %> - - <%= customer_form.submit %> -<% end %> -
- -* Lead Contributor: "Eloy Duran":http://superalloy.nl/ -* More Information: -** "Nested Model Forms":http://weblog.rubyonrails.org/2009/1/26/nested-model-forms -** "complex-form-examples":http://github.com/alloy/complex-form-examples -** "What's New in Edge Rails: Nested Object Forms":http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes - -h4. Smart Rendering of Partials - -The render method has been getting smarter over the years, and it's even smarter now. If you have an object or a collection and an appropriate partial, and the naming matches up, you can now just render the object and things will work. For example, in Rails 2.3, these render calls will work in your view (assuming sensible naming): - - -# Equivalent of render :partial => 'articles/_article', -# :object => @article -render @article - -# Equivalent of render :partial => 'articles/_article', -# :collection => @articles -render @articles - - -* More Information: "What's New in Edge Rails: render Stops Being High-Maintenance":http://ryandaigle.com/articles/2008/11/20/what-s-new-in-edge-rails-render-stops-being-high-maintenance - -h4. Prompts for Date Select Helpers - -In Rails 2.3, you can supply custom prompts for the various date select helpers (+date_select+, +time_select+, and +datetime_select+), the same way you can with collection select helpers. You can supply a prompt string or a hash of individual prompt strings for the various components. You can also just set +:prompt+ to +true+ to use the custom generic prompt: - - -select_datetime(DateTime.now, :prompt => true) - -select_datetime(DateTime.now, :prompt => "Choose date and time") - -select_datetime(DateTime.now, :prompt => - {:day => 'Choose day', :month => 'Choose month', - :year => 'Choose year', :hour => 'Choose hour', - :minute => 'Choose minute'}) - - -* Lead Contributor: "Sam Oliver":http://samoliver.com/ - -h4. AssetTag Timestamp Caching - -You're likely familiar with Rails' practice of adding timestamps to static asset paths as a "cache buster." This helps ensure that stale copies of things like images and stylesheets don't get served out of the user's browser cache when you change them on the server. You can now modify this behavior with the +cache_asset_timestamps+ configuration option for Action View. If you enable the cache, then Rails will calculate the timestamp once when it first serves an asset, and save that value. This means fewer (expensive) file system calls to serve static assets - but it also means that you can't modify any of the assets while the server is running and expect the changes to get picked up by clients. - -h4. Asset Hosts as Objects - -Asset hosts get more flexible in edge Rails with the ability to declare an asset host as a specific object that responds to a call. This allows you to implement any complex logic you need in your asset hosting. - -* More Information: "asset-hosting-with-minimum-ssl":http://github.com/dhh/asset-hosting-with-minimum-ssl/tree/master - -h4. grouped_options_for_select Helper Method - -Action View already had a bunch of helpers to aid in generating select controls, but now there's one more: +grouped_options_for_select+. This one accepts an array or hash of strings, and converts them into a string of +option+ tags wrapped with +optgroup+ tags. For example: - - -grouped_options_for_select([["Hats", ["Baseball Cap","Cowboy Hat"]]], - "Cowboy Hat", "Choose a product...") - - -returns - - - - - - - - - -h4. Disabled Option Tags for Form Select Helpers - -The form select helpers (such as +select+ and +options_for_select+) now support a +:disabled+ option, which can take a single value or an array of values to be disabled in the resulting tags: - - -select(:post, :category, Post::CATEGORIES, :disabled => ‘private‘) - - -returns - - - - - -You can also use an anonymous function to determine at runtime which options from collections will be selected and/or disabled: - - -options_from_collection_for_select(@product.sizes, :name, :id, :disabled => lambda{|size| size.out_of_stock?}) - - -* Lead Contributor: "Tekin Suleyman":http://tekin.co.uk/ -* More Information: "New in rails 2.3 - disabled option tags and lambdas for selecting and disabling options from collections":http://tekin.co.uk/2009/03/new-in-rails-23-disabled-option-tags-and-lambdas-for-selecting-and-disabling-options-from-collections/ - -h4. A Note About Template Loading - -Rails 2.3 includes the ability to enable or disable cached templates for any particular environment. Cached templates give you a speed boost because they don't check for a new template file when they're rendered - but they also mean that you can't replace a template "on the fly" without restarting the server. - -In most cases, you'll want template caching to be turned on in production, which you can do by making a setting in your +production.rb+ file: - - -config.action_view.cache_template_loading = true - - -This line will be generated for you by default in a new Rails 2.3 application. If you've upgraded from an older version of Rails, Rails will default to caching templates in production and test but not in development. - -h4. Other Action View Changes - -* Token generation for CSRF protection has been simplified; now Rails uses a simple random string generated by +ActiveSupport::SecureRandom+ rather than mucking around with session IDs. -* +auto_link+ now properly applies options (such as +:target+ and +:class+) to generated e-mail links. -* The +autolink+ helper has been refactored to make it a bit less messy and more intuitive. -* +current_page?+ now works properly even when there are multiple query parameters in the URL. - -h3. Active Support - -Active Support has a few interesting changes, including the introduction of +Object#try+. - -h4. Object#try - -A lot of folks have adopted the notion of using try() to attempt operations on objects. It's especially helpful in views where you can avoid nil-checking by writing code like +<%= @person.try(:name) %>+. Well, now it's baked right into Rails. As implemented in Rails, it raises +NoMethodError+ on private methods and always returns +nil+ if the object is nil. - -* More Information: "try()":http://ozmm.org/posts/try.html. - -h4. Object#tap Backport - -+Object#tap+ is an addition to "Ruby 1.9":http://www.ruby-doc.org/core-1.9/classes/Object.html#M000309 and 1.8.7 that is similar to the +returning+ method that Rails has had for a while: it yields to a block, and then returns the object that was yielded. Rails now includes code to make this available under older versions of Ruby as well. - -h4. Swappable Parsers for XMLmini - -The support for XML parsing in ActiveSupport has been made more flexible by allowing you to swap in different parsers. By default, it uses the standard REXML implementation, but you can easily specify the faster LibXML or Nokogiri implementations for your own applications, provided you have the appropriate gems installed: - - -XmlMini.backend = 'LibXML' - - -* Lead Contributor: "Bart ten Brinke":http://www.movesonrails.com/ -* Lead Contributor: "Aaron Patterson":http://tenderlovemaking.com/ - -h4. Fractional seconds for TimeWithZone - -The +Time+ and +TimeWithZone+ classes include an +xmlschema+ method to return the time in an XML-friendly string. As of Rails 2.3, +TimeWithZone+ supports the same argument for specifying the number of digits in the fractional second part of the returned string that +Time+ does: - - ->> Time.zone.now.xmlschema(6) -=> "2009-01-16T13:00:06.13653Z" - - -* Lead Contributor: "Nicholas Dainty":http://www.workingwithrails.com/person/13536-nicholas-dainty - -h4. JSON Key Quoting - -If you look up the spec on the "json.org" site, you'll discover that all keys in a JSON structure must be strings, and they must be quoted with double quotes. Starting with Rails 2.3, we do the right thing here, even with numeric keys. - -h4. Other Active Support Changes - -* You can use +Enumerable#none?+ to check that none of the elements match the supplied block. -* If you're using Active Support "delegates":http://afreshcup.com/2008/10/19/coming-in-rails-22-delegate-prefixes/, the new +:allow_nil+ option lets you return +nil+ instead of raising an exception when the target object is nil. -* +ActiveSupport::OrderedHash+: now implements +each_key+ and +each_value+. -* +ActiveSupport::MessageEncryptor+ provides a simple way to encrypt information for storage in an untrusted location (like cookies). -* Active Support's +from_xml+ no longer depends on XmlSimple. Instead, Rails now includes its own XmlMini implementation, with just the functionality that it requires. This lets Rails dispense with the bundled copy of XmlSimple that it's been carting around. -* If you memoize a private method, the result will now be private. -* +String#parameterize+ accepts an optional separator: +"Quick Brown Fox".parameterize('_') => "quick_brown_fox"+. -* +number_to_phone+ accepts 7-digit phone numbers now. -* +ActiveSupport::Json.decode+ now handles +\u0000+ style escape sequences. - -h3. Railties - -In addition to the Rack changes covered above, Railties (the core code of Rails itself) sports a number of significant changes, including Rails Metal, application templates, and quiet backtraces. - -h4. Rails Metal - -Rails Metal is a new mechanism that provides superfast endpoints inside of your Rails applications. Metal classes bypass routing and Action Controller to give you raw speed (at the cost of all the things in Action Controller, of course). This builds on all of the recent foundation work to make Rails a Rack application with an exposed middleware stack. Metal endpoints can be loaded from your application or from plugins. - -* More Information: -** "Introducing Rails Metal":http://weblog.rubyonrails.org/2008/12/17/introducing-rails-metal -** "Rails Metal: a micro-framework with the power of Rails":http://soylentfoo.jnewland.com/articles/2008/12/16/rails-metal-a-micro-framework-with-the-power-of-rails-m -** "Metal: Super-fast Endpoints within your Rails Apps":http://www.railsinside.com/deployment/180-metal-super-fast-endpoints-within-your-rails-apps.html -** "What's New in Edge Rails: Rails Metal":http://ryandaigle.com/articles/2008/12/18/what-s-new-in-edge-rails-rails-metal - -h4. Application Templates - -Rails 2.3 incorporates Jeremy McAnally's "rg":http://github.com/jeremymcanally/rg/tree/master application generator. What this means is that we now have template-based application generation built right into Rails; if you have a set of plugins you include in every application (among many other use cases), you can just set up a template once and use it over and over again when you run the +rails+ command. There's also a rake task to apply a template to an existing application: - - -rake rails:template LOCATION=~/template.rb - - -This will layer the changes from the template on top of whatever code the project already contains. - -* Lead Contributor: "Jeremy McAnally":http://www.jeremymcanally.com/ -* More Info:"Rails templates":http://m.onkey.org/2008/12/4/rails-templates - -h4. Quieter Backtraces - -Building on Thoughtbot's "Quiet Backtrace":https://github.com/thoughtbot/quietbacktrace plugin, which allows you to selectively remove lines from +Test::Unit+ backtraces, Rails 2.3 implements +ActiveSupport::BacktraceCleaner+ and +Rails::BacktraceCleaner+ in core. This supports both filters (to perform regex-based substitutions on backtrace lines) and silencers (to remove backtrace lines entirely). Rails automatically adds silencers to get rid of the most common noise in a new application, and builds a +config/backtrace_silencers.rb+ file to hold your own additions. This feature also enables prettier printing from any gem in the backtrace. - -h4. Faster Boot Time in Development Mode with Lazy Loading/Autoload - -Quite a bit of work was done to make sure that bits of Rails (and its dependencies) are only brought into memory when they're actually needed. The core frameworks - Active Support, Active Record, Action Controller, Action Mailer and Action View - are now using +autoload+ to lazy-load their individual classes. This work should help keep the memory footprint down and improve overall Rails performance. - -You can also specify (by using the new +preload_frameworks+ option) whether the core libraries should be autoloaded at startup. This defaults to +false+ so that Rails autoloads itself piece-by-piece, but there are some circumstances where you still need to bring in everything at once - Passenger and JRuby both want to see all of Rails loaded together. - -h4. rake gem Task Rewrite - -The internals of the various rake gem tasks have been substantially revised, to make the system work better for a variety of cases. The gem system now knows the difference between development and runtime dependencies, has a more robust unpacking system, gives better information when querying for the status of gems, and is less prone to "chicken and egg" dependency issues when you're bringing things up from scratch. There are also fixes for using gem commands under JRuby and for dependencies that try to bring in external copies of gems that are already vendored. - -* Lead Contributor: "David Dollar":http://www.workingwithrails.com/person/12240-david-dollar - -h4. Other Railties Changes - -* The instructions for updating a CI server to build Rails have been updated and expanded. -* Internal Rails testing has been switched from +Test::Unit::TestCase+ to +ActiveSupport::TestCase+, and the Rails core requires Mocha to test. -* The default +environment.rb+ file has been decluttered. -* The dbconsole script now lets you use an all-numeric password without crashing. -* +Rails.root+ now returns a +Pathname+ object, which means you can use it directly with the +join+ method to "clean up existing code":http://afreshcup.com/2008/12/05/a-little-rails_root-tidiness/ that uses +File.join+. -* Various files in /public that deal with CGI and FCGI dispatching are no longer generated in every Rails application by default (you can still get them if you need them by adding +--with-dispatchers+ when you run the +rails+ command, or add them later with +rake rails:update:generate_dispatchers+). -* Rails Guides have been converted from AsciiDoc to Textile markup. -* Scaffolded views and controllers have been cleaned up a bit. -* +script/server+ now accepts a --path argument to mount a Rails application from a specific path. -* If any configured gems are missing, the gem rake tasks will skip loading much of the environment. This should solve many of the "chicken-and-egg" problems where rake gems:install couldn't run because gems were missing. -* Gems are now unpacked exactly once. This fixes issues with gems (hoe, for instance) which are packed with read-only permissions on the files. - -h3. Deprecated - -A few pieces of older code are deprecated in this release: - -* If you're one of the (fairly rare) Rails developers who deploys in a fashion that depends on the inspector, reaper, and spawner scripts, you'll need to know that those scripts are no longer included in core Rails. If you need them, you'll be able to pick up copies via the "irs_process_scripts":http://github.com/rails/irs_process_scripts/tree plugin. -* +render_component+ goes from "deprecated" to "nonexistent" in Rails 2.3. If you still need it, you can install the "render_component plugin":http://github.com/rails/render_component/tree/master. -* Support for Rails components has been removed. -* If you were one of the people who got used to running +script/performance/request+ to look at performance based on integration tests, you need to learn a new trick: that script has been removed from core Rails now. There’s a new request_profiler plugin that you can install to get the exact same functionality back. -* +ActionController::Base#session_enabled?+ is deprecated because sessions are lazy-loaded now. -* The +:digest+ and +:secret+ options to +protect_from_forgery+ are deprecated and have no effect. -* Some integration test helpers have been removed. +response.headers["Status"]+ and +headers["Status"]+ will no longer return anything. Rack does not allow "Status" in its return headers. However you can still use the +status+ and +status_message+ helpers. +response.headers["cookie"]+ and +headers["cookie"]+ will no longer return any CGI cookies. You can inspect +headers["Set-Cookie"]+ to see the raw cookie header or use the +cookies+ helper to get a hash of the cookies sent to the client. -* +formatted_polymorphic_url+ is deprecated. Use +polymorphic_url+ with +:format+ instead. -* The +:http_only+ option in +ActionController::Response#set_cookie+ has been renamed to +:httponly+. -* The +:connector+ and +:skip_last_comma+ options of +to_sentence+ have been replaced by +:words_connnector+, +:two_words_connector+, and +:last_word_connector+ options. -* Posting a multipart form with an empty +file_field+ control used to submit an empty string to the controller. Now it submits a nil, due to differences between Rack's multipart parser and the old Rails one. - -h3. Credits - -Release notes compiled by "Mike Gunderloy":http://afreshcup.com. This version of the Rails 2.3 release notes was compiled based on RC2 of Rails 2.3. diff --git a/guides/source/3_0_release_notes.md b/guides/source/3_0_release_notes.md new file mode 100644 index 0000000000..d22c76dd81 --- /dev/null +++ b/guides/source/3_0_release_notes.md @@ -0,0 +1,595 @@ +h2. Ruby on Rails 3.0 Release Notes + +Rails 3.0 is ponies and rainbows! It's going to cook you dinner and fold your laundry. You're going to wonder how life was ever possible before it arrived. It's the Best Version of Rails We've Ever Done! + +But seriously now, it's really good stuff. There are all the good ideas brought over from when the Merb team joined the party and brought a focus on framework agnosticism, slimmer and faster internals, and a handful of tasty APIs. If you're coming to Rails 3.0 from Merb 1.x, you should recognize lots. If you're coming from Rails 2.x, you're going to love it too. + +Even if you don't give a hoot about any of our internal cleanups, Rails 3.0 is going to delight. We have a bunch of new features and improved APIs. It's never been a better time to be a Rails developer. Some of the highlights are: + +* Brand new router with an emphasis on RESTful declarations +* New Action Mailer API modeled after Action Controller (now without the agonizing pain of sending multipart messages!) +* New Active Record chainable query language built on top of relational algebra +* Unobtrusive JavaScript helpers with drivers for Prototype, jQuery, and more coming (end of inline JS) +* Explicit dependency management with Bundler + +On top of all that, we've tried our best to deprecate the old APIs with nice warnings. That means that you can move your existing application to Rails 3 without immediately rewriting all your old code to the latest best practices. + +These release notes cover the major upgrades, but don't include every little bug fix and change. Rails 3.0 consists of almost 4,000 commits by more than 250 authors! If you want to see everything, check out the "list of commits":http://github.com/rails/rails/commits/master in the main Rails repository on GitHub. + +endprologue. + +To install Rails 3: + + +# Use sudo if your setup requires it +$ gem install rails + + + +h3. Upgrading to Rails 3 + +If you're upgrading an existing application, it's a great idea to have good test coverage before going in. You should also first upgrade to Rails 2.3.5 and make sure your application still runs as expected before attempting to update to Rails 3. Then take heed of the following changes: + +h4. Rails 3 requires at least Ruby 1.8.7 + +Rails 3.0 requires Ruby 1.8.7 or higher. Support for all of the previous Ruby versions has been dropped officially and you should upgrade as early as possible. Rails 3.0 is also compatible with Ruby 1.9.2. + +TIP: Note that Ruby 1.8.7 p248 and p249 have marshaling bugs that crash Rails 3.0. Ruby Enterprise Edition have these fixed since release 1.8.7-2010.02 though. On the 1.9 front, Ruby 1.9.1 is not usable because it outright segfaults on Rails 3.0, so if you want to use Rails 3 with 1.9.x jump on 1.9.2 for smooth sailing. + +h4. Rails Application object + +As part of the groundwork for supporting running multiple Rails applications in the same process, Rails 3 introduces the concept of an Application object. An application object holds all the application specific configurations and is very similar in nature to +config/environment.rb+ from the previous versions of Rails. + +Each Rails application now must have a corresponding application object. The application object is defined in +config/application.rb+. If you're upgrading an existing application to Rails 3, you must add this file and move the appropriate configurations from +config/environment.rb+ to +config/application.rb+. + +h4. script/* replaced by script/rails + +The new script/rails replaces all the scripts that used to be in the script directory. You do not run script/rails directly though, the +rails+ command detects it is being invoked in the root of a Rails application and runs the script for you. Intended usage is: + + +$ rails console # instead of script/console +$ rails g scaffold post title:string # instead of script/generate scaffold post title:string + + +Run rails --help for a list of all the options. + +h4. Dependencies and config.gem + +The +config.gem+ method is gone and has been replaced by using +bundler+ and a +Gemfile+, see "Vendoring Gems":#vendoring-gems below. + +h4. Upgrade Process + +To help with the upgrade process, a plugin named "Rails Upgrade":http://github.com/rails/rails_upgrade has been created to automate part of it. + +Simply install the plugin, then run +rake rails:upgrade:check+ to check your app for pieces that need to be updated (with links to information on how to update them). It also offers a task to generate a +Gemfile+ based on your current +config.gem+ calls and a task to generate a new routes file from your current one. To get the plugin, simply run the following: + + +$ ruby script/plugin install git://github.com/rails/rails_upgrade.git + + +You can see an example of how that works at "Rails Upgrade is now an Official Plugin":http://omgbloglol.com/post/364624593/rails-upgrade-is-now-an-official-plugin + +Aside from Rails Upgrade tool, if you need more help, there are people on IRC and "rubyonrails-talk":http://groups.google.com/group/rubyonrails-talk that are probably doing the same thing, possibly hitting the same issues. Be sure to blog your own experiences when upgrading so others can benefit from your knowledge! + +More information - "The Path to Rails 3: Approaching the upgrade":http://omgbloglol.com/post/353978923/the-path-to-rails-3-approaching-the-upgrade + +h3. Creating a Rails 3.0 application + + +# You should have the 'rails' rubygem installed +$ rails new myapp +$ cd myapp + + +h4. Vendoring Gems + +Rails now uses a +Gemfile+ in the application root to determine the gems you require for your application to start. This +Gemfile+ is processed by the "Bundler":http://github.com/carlhuda/bundler, which then installs all your dependencies. It can even install all the dependencies locally to your application so that it doesn't depend on the system gems. + +More information: - "bundler homepage":http://gembundler.com + +h4. Living on the Edge + ++Bundler+ and +Gemfile+ makes freezing your Rails application easy as pie with the new dedicated bundle command, so rake freeze is no longer relevant and has been dropped. + +If you want to bundle straight from the Git repository, you can pass the +--edge+ flag: + + +$ rails new myapp --edge + + +If you have a local checkout of the Rails repository and want to generate an application using that, you can pass the +--dev+ flag: + + +$ ruby /path/to/rails/bin/rails new myapp --dev + + +h3. Rails Architectural Changes + +There are six major changes in the architecture of Rails. + +h4. Railties Restrung + +Railties was updated to provide a consistent plugin API for the entire Rails framework as well as a total rewrite of generators and the Rails bindings, the result is that developers can now hook into any significant stage of the generators and application framework in a consistent, defined manner. + +h4. All Rails core components are decoupled + +With the merge of Merb and Rails, one of the big jobs was to remove the tight coupling between Rails core components. This has now been achieved, and all Rails core components are now using the same API that you can use for developing plugins. This means any plugin you make, or any core component replacement (like DataMapper or Sequel) can access all the functionality that the Rails core components have access to and extend and enhance at will. + +More information: - "The Great Decoupling":http://yehudakatz.com/2009/07/19/rails-3-the-great-decoupling/ + + +h4. Active Model Abstraction + +Part of decoupling the core components was extracting all ties to Active Record from Action Pack. This has now been completed. All new ORM plugins now just need to implement Active Model interfaces to work seamlessly with Action Pack. + +More information: - "Make Any Ruby Object Feel Like ActiveRecord":http://yehudakatz.com/2010/01/10/activemodel-make-any-ruby-object-feel-like-activerecord/ + + +h4. Controller Abstraction + +Another big part of decoupling the core components was creating a base superclass that is separated from the notions of HTTP in order to handle rendering of views etc. This creation of +AbstractController+ allowed +ActionController+ and +ActionMailer+ to be greatly simplified with common code removed from all these libraries and put into Abstract Controller. + +More Information: - "Rails Edge Architecture":http://yehudakatz.com/2009/06/11/rails-edge-architecture/ + + +h4. Arel Integration + +"Arel":http://github.com/brynary/arel (or Active Relation) has been taken on as the underpinnings of Active Record and is now required for Rails. Arel provides an SQL abstraction that simplifies out Active Record and provides the underpinnings for the relation functionality in Active Record. + +More information: - "Why I wrote Arel":http://magicscalingsprinkles.wordpress.com/2010/01/28/why-i-wrote-arel/. + + +h4. Mail Extraction + +Action Mailer ever since its beginnings has had monkey patches, pre parsers and even delivery and receiver agents, all in addition to having TMail vendored in the source tree. Version 3 changes that with all email message related functionality abstracted out to the "Mail":http://github.com/mikel/mail gem. This again reduces code duplication and helps create definable boundaries between Action Mailer and the email parser. + +More information: - "New Action Mailer API in Rails 3":http://lindsaar.net/2010/1/26/new-actionmailer-api-in-rails-3 + + +h3. Documentation + +The documentation in the Rails tree is being updated with all the API changes, additionally, the "Rails Edge Guides":http://edgeguides.rubyonrails.org/ are being updated one by one to reflect the changes in Rails 3.0. The guides at "guides.rubyonrails.org":http://guides.rubyonrails.org/ however will continue to contain only the stable version of Rails (at this point, version 2.3.5, until 3.0 is released). + +More Information: - "Rails Documentation Projects":http://weblog.rubyonrails.org/2009/1/15/rails-documentation-projects. + + +h3. Internationalization + +A large amount of work has been done with I18n support in Rails 3, including the latest "I18n":http://github.com/svenfuchs/i18n gem supplying many speed improvements. + +* I18n for any object - I18n behavior can be added to any object by including ActiveModel::Translation and ActiveModel::Validations. There is also an errors.messages fallback for translations. +* Attributes can have default translations. +* Form Submit Tags automatically pull the correct status (Create or Update) depending on the object status, and so pull the correct translation. +* Labels with I18n also now work by just passing the attribute name. + +More Information: - "Rails 3 I18n changes":http://blog.plataformatec.com.br/2010/02/rails-3-i18n-changes/ + + +h3. Railties + +With the decoupling of the main Rails frameworks, Railties got a huge overhaul so as to make linking up frameworks, engines or plugins as painless and extensible as possible: + +* Each application now has its own name space, application is started with YourAppName.boot for example, makes interacting with other applications a lot easier. +* Anything under Rails.root/app is now added to the load path, so you can make app/observers/user_observer.rb and Rails will load it without any modifications. +* Rails 3.0 now provides a Rails.config object, which provides a central repository of all sorts of Rails wide configuration options. + +Application generation has received extra flags allowing you to skip the installation of test-unit, Active Record, Prototype and Git. Also a new --dev flag has been added which sets the application up with the +Gemfile+ pointing to your Rails checkout (which is determined by the path to the +rails+ binary). See rails --help for more info. + +Railties generators got a huge amount of attention in Rails 3.0, basically: + +* Generators were completely rewritten and are backwards incompatible. +* Rails templates API and generators API were merged (they are the same as the former). +* Generators are no longer loaded from special paths anymore, they are just found in the Ruby load path, so calling rails generate foo will look for generators/foo_generator. +* New generators provide hooks, so any template engine, ORM, test framework can easily hook in. +* New generators allow you to override the templates by placing a copy at Rails.root/lib/templates. +* Rails::Generators::TestCase is also supplied so you can create your own generators and test them. + +Also, the views generated by Railties generators had some overhaul: + +* Views now use +div+ tags instead of +p+ tags. +* Scaffolds generated now make use of _form partials, instead of duplicated code in the edit and new views. +* Scaffold forms now use f.submit which returns "Create ModelName" or "Update ModelName" depending on the state of the object passed in. + +Finally a couple of enhancements were added to the rake tasks: + +* rake db:forward was added, allowing you to roll forward your migrations individually or in groups. +* rake routes CONTROLLER=x was added allowing you to just view the routes for one controller. + +Railties now deprecates: + +* RAILS_ROOT in favor of Rails.root, +* RAILS_ENV in favor of Rails.env, and +* RAILS_DEFAULT_LOGGER in favor of Rails.logger. + +PLUGIN/rails/tasks, and PLUGIN/tasks are no longer loaded all tasks now must be in PLUGIN/lib/tasks. + +More information: +* "Discovering Rails 3 generators":http://blog.plataformatec.com.br/2010/01/discovering-rails-3-generators +* "Making Generators for Rails 3 with Thor":http://caffeinedd.com/guides/331-making-generators-for-rails-3-with-thor +* "The Rails Module (in Rails 3)":http://litanyagainstfear.com/blog/2010/02/03/the-rails-module/ + +h3. Action Pack + +There have been significant internal and external changes in Action Pack. + + +h4. Abstract Controller + +Abstract Controller pulls out the generic parts of Action Controller into a reusable module that any library can use to render templates, render partials, helpers, translations, logging, any part of the request response cycle. This abstraction allowed ActionMailer::Base to now just inherit from +AbstractController+ and just wrap the Rails DSL onto the Mail gem. + +It also provided an opportunity to clean up Action Controller, abstracting out what could to simplify the code. + +Note however that Abstract Controller is not a user facing API, you will not run into it in your day to day use of Rails. + +More Information: - "Rails Edge Architecture":http://yehudakatz.com/2009/06/11/rails-edge-architecture/ + + +h4. Action Controller + +* application_controller.rb now has protect_from_forgery on by default. +* The cookie_verifier_secret has been deprecated and now instead it is assigned through Rails.application.config.cookie_secret and moved into its own file: config/initializers/cookie_verification_secret.rb. +* The session_store was configured in ActionController::Base.session, and that is now moved to Rails.application.config.session_store. Defaults are set up in config/initializers/session_store.rb. +* cookies.secure allowing you to set encrypted values in cookies with cookie.secure[:key] => value. +* cookies.permanent allowing you to set permanent values in the cookie hash cookie.permanent[:key] => value that raise exceptions on signed values if verification failures. +* You can now pass :notice => 'This is a flash message' or :alert => 'Something went wrong' to the format call inside a +respond_to+ block. The flash[] hash still works as previously. +* respond_with method has now been added to your controllers simplifying the venerable +format+ blocks. +* ActionController::Responder added allowing you flexibility in how your responses get generated. + +Deprecations: + +* filter_parameter_logging is deprecated in favor of config.filter_parameters << :password. + +More Information: +* "Render Options in Rails 3":http://www.engineyard.com/blog/2010/render-options-in-rails-3/ +* "Three reasons to love ActionController::Responder":http://weblog.rubyonrails.org/2009/8/31/three-reasons-love-responder + + +h4. Action Dispatch + +Action Dispatch is new in Rails 3.0 and provides a new, cleaner implementation for routing. + +* Big clean up and re-write of the router, the Rails router is now +rack_mount+ with a Rails DSL on top, it is a stand alone piece of software. +* Routes defined by each application are now name spaced within your Application module, that is: + + +# Instead of: + +ActionController::Routing::Routes.draw do |map| + map.resources :posts +end + +# You do: + +AppName::Application.routes do + resources :posts +end + + +* Added +match+ method to the router, you can also pass any Rack application to the matched route. +* Added +constraints+ method to the router, allowing you to guard routers with defined constraints. +* Added +scope+ method to the router, allowing you to namespace routes for different languages or different actions, for example: + + +scope 'es' do + resources :projects, :path_names => { :edit => 'cambiar' }, :path => 'proyecto' +end + +# Gives you the edit action with /es/proyecto/1/cambiar + + +* Added +root+ method to the router as a short cut for match '/', :to => path. +* You can pass optional segments into the match, for example match "/:controller(/:action(/:id))(.:format)", each parenthesized segment is optional. +* Routes can be expressed via blocks, for example you can call controller :home { match '/:action' }. + +NOTE. The old style map commands still work as before with a backwards compatibility layer, however this will be removed in the 3.1 release. + +Deprecations + +* The catch all route for non-REST applications (/:controller/:action/:id) is now commented out. +* Routes :path_prefix no longer exists and :name_prefix now automatically adds "_" at the end of the given value. + +More Information: +* "The Rails 3 Router: Rack it Up":http://yehudakatz.com/2009/12/26/the-rails-3-router-rack-it-up/ +* "Revamped Routes in Rails 3":http://rizwanreza.com/2009/12/20/revamped-routes-in-rails-3 +* "Generic Actions in Rails 3":http://yehudakatz.com/2009/12/20/generic-actions-in-rails-3/ + + +h4. Action View + +h5. Unobtrusive JavaScript + +Major re-write was done in the Action View helpers, implementing Unobtrusive JavaScript (UJS) hooks and removing the old inline AJAX commands. This enables Rails to use any compliant UJS driver to implement the UJS hooks in the helpers. + +What this means is that all previous remote_<method> helpers have been removed from Rails core and put into the "Prototype Legacy Helper":http://github.com/rails/prototype_legacy_helper. To get UJS hooks into your HTML, you now pass :remote => true instead. For example: + + +form_for @post, :remote => true + + +Produces: + + +
+ + +h5. Helpers with Blocks + +Helpers like +form_for+ or +div_for+ that insert content from a block use +<%=+ now: + + +<%= form_for @post do |f| %> + ... +<% end %> + + +Your own helpers of that kind are expected to return a string, rather than appending to the output buffer by hand. + +Helpers that do something else, like +cache+ or +content_for+, are not affected by this change, they need +<%+ as before. + +h5. Other Changes + +* You no longer need to call h(string) to escape HTML output, it is on by default in all view templates. If you want the unescaped string, call raw(string). +* Helpers now output HTML 5 by default. +* Form label helper now pulls values from I18n with a single value, so f.label :name will pull the :name translation. +* I18n select label on should now be :en.helpers.select instead of :en.support.select. +* You no longer need to place a minus sign at the end of a ruby interpolation inside an ERb template to remove the trailing carriage return in the HTML output. +* Added +grouped_collection_select+ helper to Action View. +* +content_for?+ has been added allowing you to check for the existence of content in a view before rendering. +* passing +:value => nil+ to form helpers will set the field's +value+ attribute to nil as opposed to using the default value +* passing +:id => nil+ to form helpers will cause those fields to be rendered with no +id+ attribute +* passing +:alt => nil+ to +image_tag+ will cause the +img+ tag to render with no +alt+ attribute + +h3. Active Model + +Active Model is new in Rails 3.0. It provides an abstraction layer for any ORM libraries to use to interact with Rails by implementing an Active Model interface. + + +h4. ORM Abstraction and Action Pack Interface + +Part of decoupling the core components was extracting all ties to Active Record from Action Pack. This has now been completed. All new ORM plugins now just need to implement Active Model interfaces to work seamlessly with Action Pack. + +More Information: - "Make Any Ruby Object Feel Like ActiveRecord":http://yehudakatz.com/2010/01/10/activemodel-make-any-ruby-object-feel-like-activerecord/ + + +h4. Validations + +Validations have been moved from Active Record into Active Model, providing an interface to validations that works across ORM libraries in Rails 3. + +* There is now a validates :attribute, options_hash shortcut method that allows you to pass options for all the validates class methods, you can pass more than one option to a validate method. +* The +validates+ method has the following options: +** :acceptance => Boolean. +** :confirmation => Boolean. +** :exclusion => { :in => Enumerable }. +** :inclusion => { :in => Enumerable }. +** :format => { :with => Regexp, :on => :create }. +** :length => { :maximum => Fixnum }. +** :numericality => Boolean. +** :presence => Boolean. +** :uniqueness => Boolean. + +NOTE: All the Rails version 2.3 style validation methods are still supported in Rails 3.0, the new validates method is designed as an additional aid in your model validations, not a replacement for the existing API. + +You can also pass in a validator object, which you can then reuse between objects that use Active Model: + + +class TitleValidator < ActiveModel::EachValidator + Titles = ['Mr.', 'Mrs.', 'Dr.'] + def validate_each(record, attribute, value) + unless Titles.include?(value) + record.errors[attribute] << 'must be a valid title' + end + end +end + + + +class Person + include ActiveModel::Validations + attr_accessor :title + validates :title, :presence => true, :title => true +end + +# Or for Active Record + +class Person < ActiveRecord::Base + validates :title, :presence => true, :title => true +end + + +There's also support for introspection: + + +User.validators +User.validators_on(:login) + + +More Information: +* "Sexy Validation in Rails 3":http://thelucid.com/2010/01/08/sexy-validation-in-edge-rails-rails-3/ +* "Rails 3 Validations Explained":http://lindsaar.net/2010/1/31/validates_rails_3_awesome_is_true + + +h3. Active Record + +Active Record received a lot of attention in Rails 3.0, including abstraction into Active Model, a full update to the Query interface using Arel, validation updates and many enhancements and fixes. All of the Rails 2.x API will be usable through a compatibility layer that will be supported until version 3.1. + + +h4. Query Interface + +Active Record, through the use of Arel, now returns relations on its core methods. The existing API in Rails 2.3.x is still supported and will not be deprecated until Rails 3.1 and not removed until Rails 3.2, however, the new API provides the following new methods that all return relations allowing them to be chained together: + +* where - provides conditions on the relation, what gets returned. +* select - choose what attributes of the models you wish to have returned from the database. +* group - groups the relation on the attribute supplied. +* having - provides an expression limiting group relations (GROUP BY constraint). +* joins - joins the relation to another table. +* clause - provides an expression limiting join relations (JOIN constraint). +* includes - includes other relations pre-loaded. +* order - orders the relation based on the expression supplied. +* limit - limits the relation to the number of records specified. +* lock - locks the records returned from the table. +* readonly - returns an read only copy of the data. +* from - provides a way to select relationships from more than one table. +* scope - (previously +named_scope+) return relations and can be chained together with the other relation methods. +* with_scope - and +with_exclusive_scope+ now also return relations and so can be chained. +* default_scope - also works with relations. + +More Information: +* "Active Record Query Interface":http://m.onkey.org/2010/1/22/active-record-query-interface +* "Let your SQL Growl in Rails 3":http://hasmanyquestions.wordpress.com/2010/01/17/let-your-sql-growl-in-rails-3/ + + +h4. Enhancements + +* Added :destroyed? to Active Record objects. +* Added :inverse_of to Active Record associations allowing you to pull the instance of an already loaded association without hitting the database. + + +h4. Patches and Deprecations + +Additionally, many fixes in the Active Record branch: + +* SQLite 2 support has been dropped in favor of SQLite 3. +* MySQL support for column order. +* PostgreSQL adapter has had its +TIME ZONE+ support fixed so it no longer inserts incorrect values. +* Support multiple schemas in table names for PostgreSQL. +* PostgreSQL support for the XML data type column. +* +table_name+ is now cached. +* A large amount of work done on the Oracle adapter as well with many bug fixes. + +As well as the following deprecations: + +* +named_scope+ in an Active Record class is deprecated and has been renamed to just +scope+. +* In +scope+ methods, you should move to using the relation methods, instead of a :conditions => {} finder method, for example scope :since, lambda {|time| where("created_at > ?", time) }. +* save(false) is deprecated, in favor of save(:validate => false). +* I18n error messages for ActiveRecord should be changed from :en.activerecord.errors.template to :en.errors.template. +* model.errors.on is deprecated in favor of model.errors[] +* validates_presence_of => validates... :presence => true +* ActiveRecord::Base.colorize_logging and config.active_record.colorize_logging are deprecated in favor of Rails::LogSubscriber.colorize_logging or config.colorize_logging + +NOTE: While an implementation of State Machine has been in Active Record edge for some months now, it has been removed from the Rails 3.0 release. + + +h3. Active Resource + +Active Resource was also extracted out to Active Model allowing you to use Active Resource objects with Action Pack seamlessly. + +* Added validations through Active Model. +* Added observing hooks. +* HTTP proxy support. +* Added support for digest authentication. +* Moved model naming into Active Model. +* Changed Active Resource attributes to a Hash with indifferent access. +* Added +first+, +last+ and +all+ aliases for equivalent find scopes. +* find_every now does not return a +ResourceNotFound+ error if nothing returned. +* Added save! which raises ResourceInvalid unless the object is valid?. +* update_attribute and update_attributes added to Active Resource models. +* Added exists?. +* Renamed SchemaDefinition to Schema and define_schema to schema. +* Use the format of Active Resources rather than the content-type of remote errors to load errors. +* Use instance_eval for schema block. +* Fix ActiveResource::ConnectionError#to_s when +@response+ does not respond to #code or #message, handles Ruby 1.9 compatibility. +* Add support for errors in JSON format. +* Ensure load works with numeric arrays. +* Recognizes a 410 response from remote resource as the resource has been deleted. +* Add ability to set SSL options on Active Resource connections. +* Setting connection timeout also affects +Net::HTTP+ open_timeout. + +Deprecations: + +* save(false) is deprecated, in favor of save(:validate => false). +* Ruby 1.9.2: URI.parse and .decode are deprecated and are no longer used in the library. + + +h3. Active Support + +A large effort was made in Active Support to make it cherry pickable, that is, you no longer have to require the entire Active Support library to get pieces of it. This allows the various core components of Rails to run slimmer. + +These are the main changes in Active Support: + +* Large clean up of the library removing unused methods throughout. +* Active Support no longer provides vendored versions of "TZInfo":http://tzinfo.rubyforge.org/, "Memcache Client":http://deveiate.org/projects/RMemCache/ and "Builder":http://builder.rubyforge.org/, these are all included as dependencies and installed via the bundle install command. +* Safe buffers are implemented in ActiveSupport::SafeBuffer. +* Added Array.uniq_by and Array.uniq_by!. +* Removed Array#rand and backported Array#sample from Ruby 1.9. +* Fixed bug on +TimeZone.seconds_to_utc_offset+ returning wrong value. +* Added ActiveSupport::Notifications middleware. +* ActiveSupport.use_standard_json_time_format now defaults to true. +* ActiveSupport.escape_html_entities_in_json now defaults to false. +* Integer#multiple_of? accepts zero as an argument, returns false unless the receiver is zero. +* +string.chars+ has been renamed to +string.mb_chars+. +* +ActiveSupport::OrderedHash+ now can de-serialize through YAML. +* Added SAX-based parser for XmlMini, using LibXML and Nokogiri. +* Added Object#presence that returns the object if it's #present? otherwise returns +nil+. +* Added String#exclude? core extension that returns the inverse of #include?. +* Added to_i to +DateTime+ in +ActiveSupport+ so to_yaml works correctly on models with +DateTime+ attributes. +* Added Enumerable#exclude? to bring parity to Enumerable#include? and avoid if !x.include?. +* Switch to on-by-default XSS escaping for rails. +* Support deep-merging in +ActiveSupport::HashWithIndifferentAccess+. +* Enumerable#sum now works will all enumerables, even if they don't respond to :size. +* inspect on a zero length duration returns '0 seconds' instead of empty string. +* Add element and collection to ModelName. +* String#to_time and String#to_datetime handle fractional seconds. +* Added support to new callbacks for around filter object that respond to :before and :after used in before and after callbacks. +* The ActiveSupport::OrderedHash#to_a method returns an ordered set of arrays. Matches Ruby 1.9's Hash#to_a. +* MissingSourceFile exists as a constant but it is now just equals to LoadError. +* Added Class#class_attribute, to be able to declare a class-level attribute whose value is inheritable and overwritable by subclasses. +* Finally removed +DeprecatedCallbacks+ in ActiveRecord::Associations. +* +Object#metaclass+ is now +Kernel#singleton_class+ to match Ruby. + +The following methods have been removed because they are now available in Ruby 1.8.7 and 1.9. + +* Integer#even? and Integer#odd? +* String#each_char +* String#start_with? and String#end_with? (3rd person aliases still kept) +* String#bytesize +* Object#tap +* Symbol#to_proc +* Object#instance_variable_defined? +* Enumerable#none? + +The security patch for REXML remains in Active Support because early patch-levels of Ruby 1.8.7 still need it. Active Support knows whether it has to apply it or not. + +The following methods have been removed because they are no longer used in the framework: + +* +Kernel#daemonize+ +* Object#remove_subclasses_of Object#extend_with_included_modules_from, Object#extended_by +* Class#remove_class +* Regexp#number_of_captures, Regexp.unoptionalize, Regexp.optionalize, Regexp#number_of_captures + + +h3. Action Mailer + +Action Mailer has been given a new API with TMail being replaced out with the new "Mail":http://github.com/mikel/mail as the Email library. Action Mailer itself has been given an almost complete re-write with pretty much every line of code touched. The result is that Action Mailer now simply inherits from Abstract Controller and wraps the Mail gem in a Rails DSL. This reduces the amount of code and duplication of other libraries in Action Mailer considerably. + +* All mailers are now in app/mailers by default. +* Can now send email using new API with three methods: +attachments+, +headers+ and +mail+. +* ActionMailer now has native support for inline attachments using the attachments.inline method. +* Action Mailer emailing methods now return Mail::Message objects, which can then be sent the +deliver+ message to send itself. +* All delivery methods are now abstracted out to the Mail gem. +* The mail delivery method can accept a hash of all valid mail header fields with their value pair. +* The +mail+ delivery method acts in a similar way to Action Controller's +respond_to+, and you can explicitly or implicitly render templates. Action Mailer will turn the email into a multipart email as needed. +* You can pass a proc to the format.mime_type calls within the mail block and explicitly render specific types of text, or add layouts or different templates. The +render+ call inside the proc is from Abstract Controller and supports the same options. +* What were mailer unit tests have been moved to functional tests. +* Action Mailer now delegates all auto encoding of header fields and bodies to Mail Gem +* Action Mailer will auto encode email bodies and headers for you + +Deprecations: + +* :charset, :content_type, :mime_version, :implicit_parts_order are all deprecated in favor of ActionMailer.default :key => value style declarations. +* Mailer dynamic create_method_name and deliver_method_name are deprecated, just call method_name which now returns a Mail::Message object. +* ActionMailer.deliver(message) is deprecated, just call message.deliver. +* template_root is deprecated, pass options to a render call inside a proc from the format.mime_type method inside the mail generation block +* The +body+ method to define instance variables is deprecated (body {:ivar => value}), just declare instance variables in the method directly and they will be available in the view. +* Mailers being in app/models is deprecated, use app/mailers instead. + +More Information: +* "New Action Mailer API in Rails 3":http://lindsaar.net/2010/1/26/new-actionmailer-api-in-rails-3 +* "New Mail Gem for Ruby":http://lindsaar.net/2010/1/23/mail-gem-version-2-released + + +h3. Credits + +See the "full list of contributors to Rails":http://contributors.rubyonrails.org/ for the many people who spent many hours making Rails 3. Kudos to all of them. + +Rails 3.0 Release Notes were compiled by "Mikel Lindsaar":http://lindsaar.net. + diff --git a/guides/source/3_0_release_notes.textile b/guides/source/3_0_release_notes.textile deleted file mode 100644 index d22c76dd81..0000000000 --- a/guides/source/3_0_release_notes.textile +++ /dev/null @@ -1,595 +0,0 @@ -h2. Ruby on Rails 3.0 Release Notes - -Rails 3.0 is ponies and rainbows! It's going to cook you dinner and fold your laundry. You're going to wonder how life was ever possible before it arrived. It's the Best Version of Rails We've Ever Done! - -But seriously now, it's really good stuff. There are all the good ideas brought over from when the Merb team joined the party and brought a focus on framework agnosticism, slimmer and faster internals, and a handful of tasty APIs. If you're coming to Rails 3.0 from Merb 1.x, you should recognize lots. If you're coming from Rails 2.x, you're going to love it too. - -Even if you don't give a hoot about any of our internal cleanups, Rails 3.0 is going to delight. We have a bunch of new features and improved APIs. It's never been a better time to be a Rails developer. Some of the highlights are: - -* Brand new router with an emphasis on RESTful declarations -* New Action Mailer API modeled after Action Controller (now without the agonizing pain of sending multipart messages!) -* New Active Record chainable query language built on top of relational algebra -* Unobtrusive JavaScript helpers with drivers for Prototype, jQuery, and more coming (end of inline JS) -* Explicit dependency management with Bundler - -On top of all that, we've tried our best to deprecate the old APIs with nice warnings. That means that you can move your existing application to Rails 3 without immediately rewriting all your old code to the latest best practices. - -These release notes cover the major upgrades, but don't include every little bug fix and change. Rails 3.0 consists of almost 4,000 commits by more than 250 authors! If you want to see everything, check out the "list of commits":http://github.com/rails/rails/commits/master in the main Rails repository on GitHub. - -endprologue. - -To install Rails 3: - - -# Use sudo if your setup requires it -$ gem install rails - - - -h3. Upgrading to Rails 3 - -If you're upgrading an existing application, it's a great idea to have good test coverage before going in. You should also first upgrade to Rails 2.3.5 and make sure your application still runs as expected before attempting to update to Rails 3. Then take heed of the following changes: - -h4. Rails 3 requires at least Ruby 1.8.7 - -Rails 3.0 requires Ruby 1.8.7 or higher. Support for all of the previous Ruby versions has been dropped officially and you should upgrade as early as possible. Rails 3.0 is also compatible with Ruby 1.9.2. - -TIP: Note that Ruby 1.8.7 p248 and p249 have marshaling bugs that crash Rails 3.0. Ruby Enterprise Edition have these fixed since release 1.8.7-2010.02 though. On the 1.9 front, Ruby 1.9.1 is not usable because it outright segfaults on Rails 3.0, so if you want to use Rails 3 with 1.9.x jump on 1.9.2 for smooth sailing. - -h4. Rails Application object - -As part of the groundwork for supporting running multiple Rails applications in the same process, Rails 3 introduces the concept of an Application object. An application object holds all the application specific configurations and is very similar in nature to +config/environment.rb+ from the previous versions of Rails. - -Each Rails application now must have a corresponding application object. The application object is defined in +config/application.rb+. If you're upgrading an existing application to Rails 3, you must add this file and move the appropriate configurations from +config/environment.rb+ to +config/application.rb+. - -h4. script/* replaced by script/rails - -The new script/rails replaces all the scripts that used to be in the script directory. You do not run script/rails directly though, the +rails+ command detects it is being invoked in the root of a Rails application and runs the script for you. Intended usage is: - - -$ rails console # instead of script/console -$ rails g scaffold post title:string # instead of script/generate scaffold post title:string - - -Run rails --help for a list of all the options. - -h4. Dependencies and config.gem - -The +config.gem+ method is gone and has been replaced by using +bundler+ and a +Gemfile+, see "Vendoring Gems":#vendoring-gems below. - -h4. Upgrade Process - -To help with the upgrade process, a plugin named "Rails Upgrade":http://github.com/rails/rails_upgrade has been created to automate part of it. - -Simply install the plugin, then run +rake rails:upgrade:check+ to check your app for pieces that need to be updated (with links to information on how to update them). It also offers a task to generate a +Gemfile+ based on your current +config.gem+ calls and a task to generate a new routes file from your current one. To get the plugin, simply run the following: - - -$ ruby script/plugin install git://github.com/rails/rails_upgrade.git - - -You can see an example of how that works at "Rails Upgrade is now an Official Plugin":http://omgbloglol.com/post/364624593/rails-upgrade-is-now-an-official-plugin - -Aside from Rails Upgrade tool, if you need more help, there are people on IRC and "rubyonrails-talk":http://groups.google.com/group/rubyonrails-talk that are probably doing the same thing, possibly hitting the same issues. Be sure to blog your own experiences when upgrading so others can benefit from your knowledge! - -More information - "The Path to Rails 3: Approaching the upgrade":http://omgbloglol.com/post/353978923/the-path-to-rails-3-approaching-the-upgrade - -h3. Creating a Rails 3.0 application - - -# You should have the 'rails' rubygem installed -$ rails new myapp -$ cd myapp - - -h4. Vendoring Gems - -Rails now uses a +Gemfile+ in the application root to determine the gems you require for your application to start. This +Gemfile+ is processed by the "Bundler":http://github.com/carlhuda/bundler, which then installs all your dependencies. It can even install all the dependencies locally to your application so that it doesn't depend on the system gems. - -More information: - "bundler homepage":http://gembundler.com - -h4. Living on the Edge - -+Bundler+ and +Gemfile+ makes freezing your Rails application easy as pie with the new dedicated bundle command, so rake freeze is no longer relevant and has been dropped. - -If you want to bundle straight from the Git repository, you can pass the +--edge+ flag: - - -$ rails new myapp --edge - - -If you have a local checkout of the Rails repository and want to generate an application using that, you can pass the +--dev+ flag: - - -$ ruby /path/to/rails/bin/rails new myapp --dev - - -h3. Rails Architectural Changes - -There are six major changes in the architecture of Rails. - -h4. Railties Restrung - -Railties was updated to provide a consistent plugin API for the entire Rails framework as well as a total rewrite of generators and the Rails bindings, the result is that developers can now hook into any significant stage of the generators and application framework in a consistent, defined manner. - -h4. All Rails core components are decoupled - -With the merge of Merb and Rails, one of the big jobs was to remove the tight coupling between Rails core components. This has now been achieved, and all Rails core components are now using the same API that you can use for developing plugins. This means any plugin you make, or any core component replacement (like DataMapper or Sequel) can access all the functionality that the Rails core components have access to and extend and enhance at will. - -More information: - "The Great Decoupling":http://yehudakatz.com/2009/07/19/rails-3-the-great-decoupling/ - - -h4. Active Model Abstraction - -Part of decoupling the core components was extracting all ties to Active Record from Action Pack. This has now been completed. All new ORM plugins now just need to implement Active Model interfaces to work seamlessly with Action Pack. - -More information: - "Make Any Ruby Object Feel Like ActiveRecord":http://yehudakatz.com/2010/01/10/activemodel-make-any-ruby-object-feel-like-activerecord/ - - -h4. Controller Abstraction - -Another big part of decoupling the core components was creating a base superclass that is separated from the notions of HTTP in order to handle rendering of views etc. This creation of +AbstractController+ allowed +ActionController+ and +ActionMailer+ to be greatly simplified with common code removed from all these libraries and put into Abstract Controller. - -More Information: - "Rails Edge Architecture":http://yehudakatz.com/2009/06/11/rails-edge-architecture/ - - -h4. Arel Integration - -"Arel":http://github.com/brynary/arel (or Active Relation) has been taken on as the underpinnings of Active Record and is now required for Rails. Arel provides an SQL abstraction that simplifies out Active Record and provides the underpinnings for the relation functionality in Active Record. - -More information: - "Why I wrote Arel":http://magicscalingsprinkles.wordpress.com/2010/01/28/why-i-wrote-arel/. - - -h4. Mail Extraction - -Action Mailer ever since its beginnings has had monkey patches, pre parsers and even delivery and receiver agents, all in addition to having TMail vendored in the source tree. Version 3 changes that with all email message related functionality abstracted out to the "Mail":http://github.com/mikel/mail gem. This again reduces code duplication and helps create definable boundaries between Action Mailer and the email parser. - -More information: - "New Action Mailer API in Rails 3":http://lindsaar.net/2010/1/26/new-actionmailer-api-in-rails-3 - - -h3. Documentation - -The documentation in the Rails tree is being updated with all the API changes, additionally, the "Rails Edge Guides":http://edgeguides.rubyonrails.org/ are being updated one by one to reflect the changes in Rails 3.0. The guides at "guides.rubyonrails.org":http://guides.rubyonrails.org/ however will continue to contain only the stable version of Rails (at this point, version 2.3.5, until 3.0 is released). - -More Information: - "Rails Documentation Projects":http://weblog.rubyonrails.org/2009/1/15/rails-documentation-projects. - - -h3. Internationalization - -A large amount of work has been done with I18n support in Rails 3, including the latest "I18n":http://github.com/svenfuchs/i18n gem supplying many speed improvements. - -* I18n for any object - I18n behavior can be added to any object by including ActiveModel::Translation and ActiveModel::Validations. There is also an errors.messages fallback for translations. -* Attributes can have default translations. -* Form Submit Tags automatically pull the correct status (Create or Update) depending on the object status, and so pull the correct translation. -* Labels with I18n also now work by just passing the attribute name. - -More Information: - "Rails 3 I18n changes":http://blog.plataformatec.com.br/2010/02/rails-3-i18n-changes/ - - -h3. Railties - -With the decoupling of the main Rails frameworks, Railties got a huge overhaul so as to make linking up frameworks, engines or plugins as painless and extensible as possible: - -* Each application now has its own name space, application is started with YourAppName.boot for example, makes interacting with other applications a lot easier. -* Anything under Rails.root/app is now added to the load path, so you can make app/observers/user_observer.rb and Rails will load it without any modifications. -* Rails 3.0 now provides a Rails.config object, which provides a central repository of all sorts of Rails wide configuration options. - -Application generation has received extra flags allowing you to skip the installation of test-unit, Active Record, Prototype and Git. Also a new --dev flag has been added which sets the application up with the +Gemfile+ pointing to your Rails checkout (which is determined by the path to the +rails+ binary). See rails --help for more info. - -Railties generators got a huge amount of attention in Rails 3.0, basically: - -* Generators were completely rewritten and are backwards incompatible. -* Rails templates API and generators API were merged (they are the same as the former). -* Generators are no longer loaded from special paths anymore, they are just found in the Ruby load path, so calling rails generate foo will look for generators/foo_generator. -* New generators provide hooks, so any template engine, ORM, test framework can easily hook in. -* New generators allow you to override the templates by placing a copy at Rails.root/lib/templates. -* Rails::Generators::TestCase is also supplied so you can create your own generators and test them. - -Also, the views generated by Railties generators had some overhaul: - -* Views now use +div+ tags instead of +p+ tags. -* Scaffolds generated now make use of _form partials, instead of duplicated code in the edit and new views. -* Scaffold forms now use f.submit which returns "Create ModelName" or "Update ModelName" depending on the state of the object passed in. - -Finally a couple of enhancements were added to the rake tasks: - -* rake db:forward was added, allowing you to roll forward your migrations individually or in groups. -* rake routes CONTROLLER=x was added allowing you to just view the routes for one controller. - -Railties now deprecates: - -* RAILS_ROOT in favor of Rails.root, -* RAILS_ENV in favor of Rails.env, and -* RAILS_DEFAULT_LOGGER in favor of Rails.logger. - -PLUGIN/rails/tasks, and PLUGIN/tasks are no longer loaded all tasks now must be in PLUGIN/lib/tasks. - -More information: -* "Discovering Rails 3 generators":http://blog.plataformatec.com.br/2010/01/discovering-rails-3-generators -* "Making Generators for Rails 3 with Thor":http://caffeinedd.com/guides/331-making-generators-for-rails-3-with-thor -* "The Rails Module (in Rails 3)":http://litanyagainstfear.com/blog/2010/02/03/the-rails-module/ - -h3. Action Pack - -There have been significant internal and external changes in Action Pack. - - -h4. Abstract Controller - -Abstract Controller pulls out the generic parts of Action Controller into a reusable module that any library can use to render templates, render partials, helpers, translations, logging, any part of the request response cycle. This abstraction allowed ActionMailer::Base to now just inherit from +AbstractController+ and just wrap the Rails DSL onto the Mail gem. - -It also provided an opportunity to clean up Action Controller, abstracting out what could to simplify the code. - -Note however that Abstract Controller is not a user facing API, you will not run into it in your day to day use of Rails. - -More Information: - "Rails Edge Architecture":http://yehudakatz.com/2009/06/11/rails-edge-architecture/ - - -h4. Action Controller - -* application_controller.rb now has protect_from_forgery on by default. -* The cookie_verifier_secret has been deprecated and now instead it is assigned through Rails.application.config.cookie_secret and moved into its own file: config/initializers/cookie_verification_secret.rb. -* The session_store was configured in ActionController::Base.session, and that is now moved to Rails.application.config.session_store. Defaults are set up in config/initializers/session_store.rb. -* cookies.secure allowing you to set encrypted values in cookies with cookie.secure[:key] => value. -* cookies.permanent allowing you to set permanent values in the cookie hash cookie.permanent[:key] => value that raise exceptions on signed values if verification failures. -* You can now pass :notice => 'This is a flash message' or :alert => 'Something went wrong' to the format call inside a +respond_to+ block. The flash[] hash still works as previously. -* respond_with method has now been added to your controllers simplifying the venerable +format+ blocks. -* ActionController::Responder added allowing you flexibility in how your responses get generated. - -Deprecations: - -* filter_parameter_logging is deprecated in favor of config.filter_parameters << :password. - -More Information: -* "Render Options in Rails 3":http://www.engineyard.com/blog/2010/render-options-in-rails-3/ -* "Three reasons to love ActionController::Responder":http://weblog.rubyonrails.org/2009/8/31/three-reasons-love-responder - - -h4. Action Dispatch - -Action Dispatch is new in Rails 3.0 and provides a new, cleaner implementation for routing. - -* Big clean up and re-write of the router, the Rails router is now +rack_mount+ with a Rails DSL on top, it is a stand alone piece of software. -* Routes defined by each application are now name spaced within your Application module, that is: - - -# Instead of: - -ActionController::Routing::Routes.draw do |map| - map.resources :posts -end - -# You do: - -AppName::Application.routes do - resources :posts -end - - -* Added +match+ method to the router, you can also pass any Rack application to the matched route. -* Added +constraints+ method to the router, allowing you to guard routers with defined constraints. -* Added +scope+ method to the router, allowing you to namespace routes for different languages or different actions, for example: - - -scope 'es' do - resources :projects, :path_names => { :edit => 'cambiar' }, :path => 'proyecto' -end - -# Gives you the edit action with /es/proyecto/1/cambiar - - -* Added +root+ method to the router as a short cut for match '/', :to => path. -* You can pass optional segments into the match, for example match "/:controller(/:action(/:id))(.:format)", each parenthesized segment is optional. -* Routes can be expressed via blocks, for example you can call controller :home { match '/:action' }. - -NOTE. The old style map commands still work as before with a backwards compatibility layer, however this will be removed in the 3.1 release. - -Deprecations - -* The catch all route for non-REST applications (/:controller/:action/:id) is now commented out. -* Routes :path_prefix no longer exists and :name_prefix now automatically adds "_" at the end of the given value. - -More Information: -* "The Rails 3 Router: Rack it Up":http://yehudakatz.com/2009/12/26/the-rails-3-router-rack-it-up/ -* "Revamped Routes in Rails 3":http://rizwanreza.com/2009/12/20/revamped-routes-in-rails-3 -* "Generic Actions in Rails 3":http://yehudakatz.com/2009/12/20/generic-actions-in-rails-3/ - - -h4. Action View - -h5. Unobtrusive JavaScript - -Major re-write was done in the Action View helpers, implementing Unobtrusive JavaScript (UJS) hooks and removing the old inline AJAX commands. This enables Rails to use any compliant UJS driver to implement the UJS hooks in the helpers. - -What this means is that all previous remote_<method> helpers have been removed from Rails core and put into the "Prototype Legacy Helper":http://github.com/rails/prototype_legacy_helper. To get UJS hooks into your HTML, you now pass :remote => true instead. For example: - - -form_for @post, :remote => true - - -Produces: - - - - - -h5. Helpers with Blocks - -Helpers like +form_for+ or +div_for+ that insert content from a block use +<%=+ now: - - -<%= form_for @post do |f| %> - ... -<% end %> - - -Your own helpers of that kind are expected to return a string, rather than appending to the output buffer by hand. - -Helpers that do something else, like +cache+ or +content_for+, are not affected by this change, they need +<%+ as before. - -h5. Other Changes - -* You no longer need to call h(string) to escape HTML output, it is on by default in all view templates. If you want the unescaped string, call raw(string). -* Helpers now output HTML 5 by default. -* Form label helper now pulls values from I18n with a single value, so f.label :name will pull the :name translation. -* I18n select label on should now be :en.helpers.select instead of :en.support.select. -* You no longer need to place a minus sign at the end of a ruby interpolation inside an ERb template to remove the trailing carriage return in the HTML output. -* Added +grouped_collection_select+ helper to Action View. -* +content_for?+ has been added allowing you to check for the existence of content in a view before rendering. -* passing +:value => nil+ to form helpers will set the field's +value+ attribute to nil as opposed to using the default value -* passing +:id => nil+ to form helpers will cause those fields to be rendered with no +id+ attribute -* passing +:alt => nil+ to +image_tag+ will cause the +img+ tag to render with no +alt+ attribute - -h3. Active Model - -Active Model is new in Rails 3.0. It provides an abstraction layer for any ORM libraries to use to interact with Rails by implementing an Active Model interface. - - -h4. ORM Abstraction and Action Pack Interface - -Part of decoupling the core components was extracting all ties to Active Record from Action Pack. This has now been completed. All new ORM plugins now just need to implement Active Model interfaces to work seamlessly with Action Pack. - -More Information: - "Make Any Ruby Object Feel Like ActiveRecord":http://yehudakatz.com/2010/01/10/activemodel-make-any-ruby-object-feel-like-activerecord/ - - -h4. Validations - -Validations have been moved from Active Record into Active Model, providing an interface to validations that works across ORM libraries in Rails 3. - -* There is now a validates :attribute, options_hash shortcut method that allows you to pass options for all the validates class methods, you can pass more than one option to a validate method. -* The +validates+ method has the following options: -** :acceptance => Boolean. -** :confirmation => Boolean. -** :exclusion => { :in => Enumerable }. -** :inclusion => { :in => Enumerable }. -** :format => { :with => Regexp, :on => :create }. -** :length => { :maximum => Fixnum }. -** :numericality => Boolean. -** :presence => Boolean. -** :uniqueness => Boolean. - -NOTE: All the Rails version 2.3 style validation methods are still supported in Rails 3.0, the new validates method is designed as an additional aid in your model validations, not a replacement for the existing API. - -You can also pass in a validator object, which you can then reuse between objects that use Active Model: - - -class TitleValidator < ActiveModel::EachValidator - Titles = ['Mr.', 'Mrs.', 'Dr.'] - def validate_each(record, attribute, value) - unless Titles.include?(value) - record.errors[attribute] << 'must be a valid title' - end - end -end - - - -class Person - include ActiveModel::Validations - attr_accessor :title - validates :title, :presence => true, :title => true -end - -# Or for Active Record - -class Person < ActiveRecord::Base - validates :title, :presence => true, :title => true -end - - -There's also support for introspection: - - -User.validators -User.validators_on(:login) - - -More Information: -* "Sexy Validation in Rails 3":http://thelucid.com/2010/01/08/sexy-validation-in-edge-rails-rails-3/ -* "Rails 3 Validations Explained":http://lindsaar.net/2010/1/31/validates_rails_3_awesome_is_true - - -h3. Active Record - -Active Record received a lot of attention in Rails 3.0, including abstraction into Active Model, a full update to the Query interface using Arel, validation updates and many enhancements and fixes. All of the Rails 2.x API will be usable through a compatibility layer that will be supported until version 3.1. - - -h4. Query Interface - -Active Record, through the use of Arel, now returns relations on its core methods. The existing API in Rails 2.3.x is still supported and will not be deprecated until Rails 3.1 and not removed until Rails 3.2, however, the new API provides the following new methods that all return relations allowing them to be chained together: - -* where - provides conditions on the relation, what gets returned. -* select - choose what attributes of the models you wish to have returned from the database. -* group - groups the relation on the attribute supplied. -* having - provides an expression limiting group relations (GROUP BY constraint). -* joins - joins the relation to another table. -* clause - provides an expression limiting join relations (JOIN constraint). -* includes - includes other relations pre-loaded. -* order - orders the relation based on the expression supplied. -* limit - limits the relation to the number of records specified. -* lock - locks the records returned from the table. -* readonly - returns an read only copy of the data. -* from - provides a way to select relationships from more than one table. -* scope - (previously +named_scope+) return relations and can be chained together with the other relation methods. -* with_scope - and +with_exclusive_scope+ now also return relations and so can be chained. -* default_scope - also works with relations. - -More Information: -* "Active Record Query Interface":http://m.onkey.org/2010/1/22/active-record-query-interface -* "Let your SQL Growl in Rails 3":http://hasmanyquestions.wordpress.com/2010/01/17/let-your-sql-growl-in-rails-3/ - - -h4. Enhancements - -* Added :destroyed? to Active Record objects. -* Added :inverse_of to Active Record associations allowing you to pull the instance of an already loaded association without hitting the database. - - -h4. Patches and Deprecations - -Additionally, many fixes in the Active Record branch: - -* SQLite 2 support has been dropped in favor of SQLite 3. -* MySQL support for column order. -* PostgreSQL adapter has had its +TIME ZONE+ support fixed so it no longer inserts incorrect values. -* Support multiple schemas in table names for PostgreSQL. -* PostgreSQL support for the XML data type column. -* +table_name+ is now cached. -* A large amount of work done on the Oracle adapter as well with many bug fixes. - -As well as the following deprecations: - -* +named_scope+ in an Active Record class is deprecated and has been renamed to just +scope+. -* In +scope+ methods, you should move to using the relation methods, instead of a :conditions => {} finder method, for example scope :since, lambda {|time| where("created_at > ?", time) }. -* save(false) is deprecated, in favor of save(:validate => false). -* I18n error messages for ActiveRecord should be changed from :en.activerecord.errors.template to :en.errors.template. -* model.errors.on is deprecated in favor of model.errors[] -* validates_presence_of => validates... :presence => true -* ActiveRecord::Base.colorize_logging and config.active_record.colorize_logging are deprecated in favor of Rails::LogSubscriber.colorize_logging or config.colorize_logging - -NOTE: While an implementation of State Machine has been in Active Record edge for some months now, it has been removed from the Rails 3.0 release. - - -h3. Active Resource - -Active Resource was also extracted out to Active Model allowing you to use Active Resource objects with Action Pack seamlessly. - -* Added validations through Active Model. -* Added observing hooks. -* HTTP proxy support. -* Added support for digest authentication. -* Moved model naming into Active Model. -* Changed Active Resource attributes to a Hash with indifferent access. -* Added +first+, +last+ and +all+ aliases for equivalent find scopes. -* find_every now does not return a +ResourceNotFound+ error if nothing returned. -* Added save! which raises ResourceInvalid unless the object is valid?. -* update_attribute and update_attributes added to Active Resource models. -* Added exists?. -* Renamed SchemaDefinition to Schema and define_schema to schema. -* Use the format of Active Resources rather than the content-type of remote errors to load errors. -* Use instance_eval for schema block. -* Fix ActiveResource::ConnectionError#to_s when +@response+ does not respond to #code or #message, handles Ruby 1.9 compatibility. -* Add support for errors in JSON format. -* Ensure load works with numeric arrays. -* Recognizes a 410 response from remote resource as the resource has been deleted. -* Add ability to set SSL options on Active Resource connections. -* Setting connection timeout also affects +Net::HTTP+ open_timeout. - -Deprecations: - -* save(false) is deprecated, in favor of save(:validate => false). -* Ruby 1.9.2: URI.parse and .decode are deprecated and are no longer used in the library. - - -h3. Active Support - -A large effort was made in Active Support to make it cherry pickable, that is, you no longer have to require the entire Active Support library to get pieces of it. This allows the various core components of Rails to run slimmer. - -These are the main changes in Active Support: - -* Large clean up of the library removing unused methods throughout. -* Active Support no longer provides vendored versions of "TZInfo":http://tzinfo.rubyforge.org/, "Memcache Client":http://deveiate.org/projects/RMemCache/ and "Builder":http://builder.rubyforge.org/, these are all included as dependencies and installed via the bundle install command. -* Safe buffers are implemented in ActiveSupport::SafeBuffer. -* Added Array.uniq_by and Array.uniq_by!. -* Removed Array#rand and backported Array#sample from Ruby 1.9. -* Fixed bug on +TimeZone.seconds_to_utc_offset+ returning wrong value. -* Added ActiveSupport::Notifications middleware. -* ActiveSupport.use_standard_json_time_format now defaults to true. -* ActiveSupport.escape_html_entities_in_json now defaults to false. -* Integer#multiple_of? accepts zero as an argument, returns false unless the receiver is zero. -* +string.chars+ has been renamed to +string.mb_chars+. -* +ActiveSupport::OrderedHash+ now can de-serialize through YAML. -* Added SAX-based parser for XmlMini, using LibXML and Nokogiri. -* Added Object#presence that returns the object if it's #present? otherwise returns +nil+. -* Added String#exclude? core extension that returns the inverse of #include?. -* Added to_i to +DateTime+ in +ActiveSupport+ so to_yaml works correctly on models with +DateTime+ attributes. -* Added Enumerable#exclude? to bring parity to Enumerable#include? and avoid if !x.include?. -* Switch to on-by-default XSS escaping for rails. -* Support deep-merging in +ActiveSupport::HashWithIndifferentAccess+. -* Enumerable#sum now works will all enumerables, even if they don't respond to :size. -* inspect on a zero length duration returns '0 seconds' instead of empty string. -* Add element and collection to ModelName. -* String#to_time and String#to_datetime handle fractional seconds. -* Added support to new callbacks for around filter object that respond to :before and :after used in before and after callbacks. -* The ActiveSupport::OrderedHash#to_a method returns an ordered set of arrays. Matches Ruby 1.9's Hash#to_a. -* MissingSourceFile exists as a constant but it is now just equals to LoadError. -* Added Class#class_attribute, to be able to declare a class-level attribute whose value is inheritable and overwritable by subclasses. -* Finally removed +DeprecatedCallbacks+ in ActiveRecord::Associations. -* +Object#metaclass+ is now +Kernel#singleton_class+ to match Ruby. - -The following methods have been removed because they are now available in Ruby 1.8.7 and 1.9. - -* Integer#even? and Integer#odd? -* String#each_char -* String#start_with? and String#end_with? (3rd person aliases still kept) -* String#bytesize -* Object#tap -* Symbol#to_proc -* Object#instance_variable_defined? -* Enumerable#none? - -The security patch for REXML remains in Active Support because early patch-levels of Ruby 1.8.7 still need it. Active Support knows whether it has to apply it or not. - -The following methods have been removed because they are no longer used in the framework: - -* +Kernel#daemonize+ -* Object#remove_subclasses_of Object#extend_with_included_modules_from, Object#extended_by -* Class#remove_class -* Regexp#number_of_captures, Regexp.unoptionalize, Regexp.optionalize, Regexp#number_of_captures - - -h3. Action Mailer - -Action Mailer has been given a new API with TMail being replaced out with the new "Mail":http://github.com/mikel/mail as the Email library. Action Mailer itself has been given an almost complete re-write with pretty much every line of code touched. The result is that Action Mailer now simply inherits from Abstract Controller and wraps the Mail gem in a Rails DSL. This reduces the amount of code and duplication of other libraries in Action Mailer considerably. - -* All mailers are now in app/mailers by default. -* Can now send email using new API with three methods: +attachments+, +headers+ and +mail+. -* ActionMailer now has native support for inline attachments using the attachments.inline method. -* Action Mailer emailing methods now return Mail::Message objects, which can then be sent the +deliver+ message to send itself. -* All delivery methods are now abstracted out to the Mail gem. -* The mail delivery method can accept a hash of all valid mail header fields with their value pair. -* The +mail+ delivery method acts in a similar way to Action Controller's +respond_to+, and you can explicitly or implicitly render templates. Action Mailer will turn the email into a multipart email as needed. -* You can pass a proc to the format.mime_type calls within the mail block and explicitly render specific types of text, or add layouts or different templates. The +render+ call inside the proc is from Abstract Controller and supports the same options. -* What were mailer unit tests have been moved to functional tests. -* Action Mailer now delegates all auto encoding of header fields and bodies to Mail Gem -* Action Mailer will auto encode email bodies and headers for you - -Deprecations: - -* :charset, :content_type, :mime_version, :implicit_parts_order are all deprecated in favor of ActionMailer.default :key => value style declarations. -* Mailer dynamic create_method_name and deliver_method_name are deprecated, just call method_name which now returns a Mail::Message object. -* ActionMailer.deliver(message) is deprecated, just call message.deliver. -* template_root is deprecated, pass options to a render call inside a proc from the format.mime_type method inside the mail generation block -* The +body+ method to define instance variables is deprecated (body {:ivar => value}), just declare instance variables in the method directly and they will be available in the view. -* Mailers being in app/models is deprecated, use app/mailers instead. - -More Information: -* "New Action Mailer API in Rails 3":http://lindsaar.net/2010/1/26/new-actionmailer-api-in-rails-3 -* "New Mail Gem for Ruby":http://lindsaar.net/2010/1/23/mail-gem-version-2-released - - -h3. Credits - -See the "full list of contributors to Rails":http://contributors.rubyonrails.org/ for the many people who spent many hours making Rails 3. Kudos to all of them. - -Rails 3.0 Release Notes were compiled by "Mikel Lindsaar":http://lindsaar.net. - diff --git a/guides/source/3_1_release_notes.md b/guides/source/3_1_release_notes.md new file mode 100644 index 0000000000..f88d8624ba --- /dev/null +++ b/guides/source/3_1_release_notes.md @@ -0,0 +1,538 @@ +h2. Ruby on Rails 3.1 Release Notes + +Highlights in Rails 3.1: + +* Streaming +* Reversible Migrations +* Assets Pipeline +* jQuery as the default JavaScript library + +This release notes cover the major changes, but don't include every little bug fix and change. If you want to see everything, check out the "list of commits":https://github.com/rails/rails/commits/master in the main Rails repository on GitHub. + +endprologue. + +h3. Upgrading to Rails 3.1 + +If you're upgrading an existing application, it's a great idea to have good test coverage before going in. You should also first upgrade to Rails 3 in case you haven't and make sure your application still runs as expected before attempting to update to Rails 3.1. Then take heed of the following changes: + +h4. Rails 3.1 requires at least Ruby 1.8.7 + +Rails 3.1 requires Ruby 1.8.7 or higher. Support for all of the previous Ruby versions has been dropped officially and you should upgrade as early as possible. Rails 3.1 is also compatible with Ruby 1.9.2. + +TIP: Note that Ruby 1.8.7 p248 and p249 have marshaling bugs that crash Rails. Ruby Enterprise Edition have these fixed since release 1.8.7-2010.02 though. On the 1.9 front, Ruby 1.9.1 is not usable because it outright segfaults, so if you want to use 1.9.x jump on 1.9.2 for smooth sailing. + +h4. What to update in your apps + +The following changes are meant for upgrading your application to Rails 3.1.3, the latest 3.1.x version of Rails. + +h5. Gemfile + +Make the following changes to your +Gemfile+. + + +gem 'rails', '= 3.1.3' +gem 'mysql2' + +# Needed for the new asset pipeline +group :assets do + gem 'sass-rails', "~> 3.1.5" + gem 'coffee-rails', "~> 3.1.1" + gem 'uglifier', ">= 1.0.3" +end + +# jQuery is the default JavaScript library in Rails 3.1 +gem 'jquery-rails' + + +h5. config/application.rb + +* The asset pipeline requires the following additions: + + +config.assets.enabled = true +config.assets.version = '1.0' + + +* If your application is using the "/assets" route for a resource you may want change the prefix used for assets to avoid conflicts: + + +# Defaults to '/assets' +config.assets.prefix = '/asset-files' + + +h5. config/environments/development.rb + +* Remove the RJS setting config.action_view.debug_rjs = true. + +* Add the following, if you enable the asset pipeline. + + +# Do not compress assets +config.assets.compress = false + +# Expands the lines which load the assets +config.assets.debug = true + + +h5. config/environments/production.rb + +* Again, most of the changes below are for the asset pipeline. You can read more about these in the "Asset Pipeline":asset_pipeline.html guide. + + +# Compress JavaScripts and CSS +config.assets.compress = true + +# Don't fallback to assets pipeline if a precompiled asset is missed +config.assets.compile = false + +# Generate digests for assets URLs +config.assets.digest = true + +# Defaults to Rails.root.join("public/assets") +# config.assets.manifest = YOUR_PATH + +# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added) +# config.assets.precompile += %w( search.js ) + + +# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. +# config.force_ssl = true + + + +h5. config/environments/test.rb + + +# Configure static asset server for tests with Cache-Control for performance +config.serve_static_assets = true +config.static_cache_control = "public, max-age=3600" + + +h5. config/initializers/wrap_parameters.rb + +* Add this file with the following contents, if you wish to wrap parameters into a nested hash. This is on by default in new applications. + + +# Be sure to restart your server when you modify this file. +# This file contains settings for ActionController::ParamsWrapper which +# is enabled by default. + +# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. +ActiveSupport.on_load(:action_controller) do + wrap_parameters :format => [:json] +end + +# Disable root element in JSON by default. +ActiveSupport.on_load(:active_record) do + self.include_root_in_json = false +end + + +h3. Creating a Rails 3.1 application + + +# You should have the 'rails' rubygem installed +$ rails new myapp +$ cd myapp + + +h4. Vendoring Gems + +Rails now uses a +Gemfile+ in the application root to determine the gems you require for your application to start. This +Gemfile+ is processed by the "Bundler":https://github.com/carlhuda/bundler gem, which then installs all your dependencies. It can even install all the dependencies locally to your application so that it doesn't depend on the system gems. + +More information: - "bundler homepage":http://gembundler.com + +h4. Living on the Edge + ++Bundler+ and +Gemfile+ makes freezing your Rails application easy as pie with the new dedicated +bundle+ command. If you want to bundle straight from the Git repository, you can pass the +--edge+ flag: + + +$ rails new myapp --edge + + +If you have a local checkout of the Rails repository and want to generate an application using that, you can pass the +--dev+ flag: + + +$ ruby /path/to/rails/railties/bin/rails new myapp --dev + + +h3. Rails Architectural Changes + +h4. Assets Pipeline + +The major change in Rails 3.1 is the Assets Pipeline. It makes CSS and JavaScript first-class code citizens and enables proper organization, including use in plugins and engines. + +The assets pipeline is powered by "Sprockets":https://github.com/sstephenson/sprockets and is covered in the "Asset Pipeline":asset_pipeline.html guide. + +h4. HTTP Streaming + +HTTP Streaming is another change that is new in Rails 3.1. This lets the browser download your stylesheets and JavaScript files while the server is still generating the response. This requires Ruby 1.9.2, is opt-in and requires support from the web server as well, but the popular combo of nginx and unicorn is ready to take advantage of it. + +h4. Default JS library is now jQuery + +jQuery is the default JavaScript library that ships with Rails 3.1. But if you use Prototype, it's simple to switch. + + +$ rails new myapp -j prototype + + +h4. Identity Map + +Active Record has an Identity Map in Rails 3.1. An identity map keeps previously instantiated records and returns the object associated with the record if accessed again. The identity map is created on a per-request basis and is flushed at request completion. + +Rails 3.1 comes with the identity map turned off by default. + +h3. Railties + +* jQuery is the new default JavaScript library. + +* jQuery and Prototype are no longer vendored and is provided from now on by the jquery-rails and prototype-rails gems. + +* The application generator accepts an option +-j+ which can be an arbitrary string. If passed "foo", the gem "foo-rails" is added to the +Gemfile+, and the application JavaScript manifest requires "foo" and "foo_ujs". Currently only "prototype-rails" and "jquery-rails" exist and provide those files via the asset pipeline. + +* Generating an application or a plugin runs +bundle install+ unless +--skip-gemfile+ or +--skip-bundle+ is specified. + +* The controller and resource generators will now automatically produce asset stubs (this can be turned off with +--skip-assets+). These stubs will use CoffeeScript and Sass, if those libraries are available. + +* Scaffold and app generators use the Ruby 1.9 style hash when running on Ruby 1.9. To generate old style hash, +--old-style-hash+ can be passed. + +* Scaffold controller generator creates format block for JSON instead of XML. + +* Active Record logging is directed to STDOUT and shown inline in the console. + +* Added +config.force_ssl+ configuration which loads Rack::SSL middleware and force all requests to be under HTTPS protocol. + +* Added +rails plugin new+ command which generates a Rails plugin with gemspec, tests and a dummy application for testing. + +* Added Rack::Etag and Rack::ConditionalGet to the default middleware stack. + +* Added Rack::Cache to the default middleware stack. + +* Engines received a major update - You can mount them at any path, enable assets, run generators etc. + +h3. Action Pack + +h4. Action Controller + +* A warning is given out if the CSRF token authenticity cannot be verified. + +* Specify +force_ssl+ in a controller to force the browser to transfer data via HTTPS protocol on that particular controller. To limit to specific actions, +:only+ or +:except+ can be used. + +* Sensitive query string parameters specified in config.filter_parameters will now be filtered out from the request paths in the log. + +* URL parameters which return +nil+ for +to_param+ are now removed from the query string. + +* Added ActionController::ParamsWrapper to wrap parameters into a nested hash, and will be turned on for JSON request in new applications by default. This can be customized in config/initializers/wrap_parameters.rb. + +* Added config.action_controller.include_all_helpers. By default helper :all is done in ActionController::Base, which includes all the helpers by default. Setting +include_all_helpers+ to +false+ will result in including only application_helper and the helper corresponding to controller (like foo_helper for foo_controller). + +* +url_for+ and named url helpers now accept +:subdomain+ and +:domain+ as options. + +* Added +Base.http_basic_authenticate_with+ to do simple http basic authentication with a single class method call. + + +class PostsController < ApplicationController + USER_NAME, PASSWORD = "dhh", "secret" + + before_filter :authenticate, :except => [ :index ] + + def index + render :text => "Everyone can see me!" + end + + def edit + render :text => "I'm only accessible if you know the password" + end + + private + def authenticate + authenticate_or_request_with_http_basic do |user_name, password| + user_name == USER_NAME && password == PASSWORD + end + end +end + + +..can now be written as + + +class PostsController < ApplicationController + http_basic_authenticate_with :name => "dhh", :password => "secret", :except => :index + + def index + render :text => "Everyone can see me!" + end + + def edit + render :text => "I'm only accessible if you know the password" + end +end + + +* Added streaming support, you can enable it with: + + +class PostsController < ActionController::Base + stream +end + + +You can restrict it to some actions by using +:only+ or +:except+. Please read the docs at "ActionController::Streaming":http://api.rubyonrails.org/classes/ActionController/Streaming.html for more information. + +* The redirect route method now also accepts a hash of options which will only change the parts of the url in question, or an object which responds to call, allowing for redirects to be reused. + +h4. Action Dispatch + +* config.action_dispatch.x_sendfile_header now defaults to +nil+ and config/environments/production.rb doesn't set any particular value for it. This allows servers to set it through X-Sendfile-Type. + +* ActionDispatch::MiddlewareStack now uses composition over inheritance and is no longer an array. + +* Added ActionDispatch::Request.ignore_accept_header to ignore accept headers. + +* Added Rack::Cache to the default stack. + +* Moved etag responsibility from ActionDispatch::Response to the middleware stack. + +* Rely on Rack::Session stores API for more compatibility across the Ruby world. This is backwards incompatible since Rack::Session expects #get_session to accept four arguments and requires #destroy_session instead of simply #destroy. + +* Template lookup now searches further up in the inheritance chain. + +h4. Action View + +* Added an +:authenticity_token+ option to +form_tag+ for custom handling or to omit the token by passing :authenticity_token => false. + +* Created ActionView::Renderer and specified an API for ActionView::Context. + +* In place +SafeBuffer+ mutation is prohibited in Rails 3.1. + +* Added HTML5 +button_tag+ helper. + +* +file_field+ automatically adds :multipart => true to the enclosing form. + +* Added a convenience idiom to generate HTML5 data-* attributes in tag helpers from a +:data+ hash of options: + + +tag("div", :data => {:name => 'Stephen', :city_state => %w(Chicago IL)}) +# =>
+ + +Keys are dasherized. Values are JSON-encoded, except for strings and symbols. + +* +csrf_meta_tag+ is renamed to +csrf_meta_tags+ and aliases +csrf_meta_tag+ for backwards compatibility. + +* The old template handler API is deprecated and the new API simply requires a template handler to respond to call. + +* rhtml and rxml are finally removed as template handlers. + +* config.action_view.cache_template_loading is brought back which allows to decide whether templates should be cached or not. + +* The submit form helper does not generate an id "object_name_id" anymore. + +* Allows FormHelper#form_for to specify the +:method+ as a direct option instead of through the +:html+ hash. form_for(==@==post, remote: true, method: :delete) instead of form_for(==@==post, remote: true, html: { method: :delete }). + +* Provided JavaScriptHelper#j() as an alias for JavaScriptHelper#escape_javascript(). This supersedes the Object#j() method that the JSON gem adds within templates using the JavaScriptHelper. + +* Allows AM/PM format in datetime selectors. + +* +auto_link+ has been removed from Rails and extracted into the "rails_autolink gem":https://github.com/tenderlove/rails_autolink + +h3. Active Record + +* Added a class method pluralize_table_names to singularize/pluralize table names of individual models. Previously this could only be set globally for all models through ActiveRecord::Base.pluralize_table_names. + +class User < ActiveRecord::Base + self.pluralize_table_names = false +end + + +* Added block setting of attributes to singular associations. The block will get called after the instance is initialized. + + +class User < ActiveRecord::Base + has_one :account +end + +user.build_account{ |a| a.credit_limit = 100.0 } + + +* Added ActiveRecord::Base.attribute_names to return a list of attribute names. This will return an empty array if the model is abstract or the table does not exist. + +* CSV Fixtures are deprecated and support will be removed in Rails 3.2.0. + +* ActiveRecord#new, ActiveRecord#create and ActiveRecord#update_attributes all accept a second hash as an option that allows you to specify which role to consider when assigning attributes. This is built on top of Active Model's new mass assignment capabilities: + + +class Post < ActiveRecord::Base + attr_accessible :title + attr_accessible :title, :published_at, :as => :admin +end + +Post.new(params[:post], :as => :admin) + + +* +default_scope+ can now take a block, lambda, or any other object which responds to call for lazy evaluation. + +* Default scopes are now evaluated at the latest possible moment, to avoid problems where scopes would be created which would implicitly contain the default scope, which would then be impossible to get rid of via Model.unscoped. + +* PostgreSQL adapter only supports PostgreSQL version 8.2 and higher. + +* +ConnectionManagement+ middleware is changed to clean up the connection pool after the rack body has been flushed. + +* Added an +update_column+ method on Active Record. This new method updates a given attribute on an object, skipping validations and callbacks. It is recommended to use +update_attributes+ or +update_attribute+ unless you are sure you do not want to execute any callback, including the modification of the +updated_at+ column. It should not be called on new records. + +* Associations with a +:through+ option can now use any association as the through or source association, including other associations which have a +:through+ option and +has_and_belongs_to_many+ associations. + +* The configuration for the current database connection is now accessible via ActiveRecord::Base.connection_config. + +* limits and offsets are removed from COUNT queries unless both are supplied. + +People.limit(1).count # => 'SELECT COUNT(*) FROM people' +People.offset(1).count # => 'SELECT COUNT(*) FROM people' +People.limit(1).offset(1).count # => 'SELECT COUNT(*) FROM people LIMIT 1 OFFSET 1' + + +* ActiveRecord::Associations::AssociationProxy has been split. There is now an +Association+ class (and subclasses) which are responsible for operating on associations, and then a separate, thin wrapper called +CollectionProxy+, which proxies collection associations. This prevents namespace pollution, separates concerns, and will allow further refactorings. + +* Singular associations (+has_one+, +belongs_to+) no longer have a proxy and simply returns the associated record or +nil+. This means that you should not use undocumented methods such as +bob.mother.create+ - use +bob.create_mother+ instead. + +* Support the :dependent option on has_many :through associations. For historical and practical reasons, +:delete_all+ is the default deletion strategy employed by association.delete(*records), despite the fact that the default strategy is +:nullify+ for regular has_many. Also, this only works at all if the source reflection is a belongs_to. For other situations, you should directly modify the through association. + +* The behavior of +association.destroy+ for +has_and_belongs_to_many+ and has_many :through is changed. From now on, 'destroy' or 'delete' on an association will be taken to mean 'get rid of the link', not (necessarily) 'get rid of the associated records'. + +* Previously, has_and_belongs_to_many.destroy(*records) would destroy the records themselves. It would not delete any records in the join table. Now, it deletes the records in the join table. + +* Previously, has_many_through.destroy(*records) would destroy the records themselves, and the records in the join table. [Note: This has not always been the case; previous version of Rails only deleted the records themselves.] Now, it destroys only the records in the join table. + +* Note that this change is backwards-incompatible to an extent, but there is unfortunately no way to 'deprecate' it before changing it. The change is being made in order to have consistency as to the meaning of 'destroy' or 'delete' across the different types of associations. If you wish to destroy the records themselves, you can do records.association.each(&:destroy). + +* Add :bulk => true option to +change_table+ to make all the schema changes defined in a block using a single ALTER statement. + + +change_table(:users, :bulk => true) do |t| + t.string :company_name + t.change :birthdate, :datetime +end + + +* Removed support for accessing attributes on a +has_and_belongs_to_many+ join table. has_many :through needs to be used. + +* Added a +create_association!+ method for +has_one+ and +belongs_to+ associations. + +* Migrations are now reversible, meaning that Rails will figure out how to reverse your migrations. To use reversible migrations, just define the +change+ method. + +class MyMigration < ActiveRecord::Migration + def change + create_table(:horses) do |t| + t.column :content, :text + t.column :remind_at, :datetime + end + end +end + + +* Some things cannot be automatically reversed for you. If you know how to reverse those things, you should define +up+ and +down+ in your migration. If you define something in change that cannot be reversed, an +IrreversibleMigration+ exception will be raised when going down. + +* Migrations now use instance methods rather than class methods: + +class FooMigration < ActiveRecord::Migration + def up # Not self.up + ... + end +end + + +* Migration files generated from model and constructive migration generators (for example, add_name_to_users) use the reversible migration's +change+ method instead of the ordinary +up+ and +down+ methods. + +* Removed support for interpolating string SQL conditions on associations. Instead, a proc should be used. + + +has_many :things, :conditions => 'foo = #{bar}' # before +has_many :things, :conditions => proc { "foo = #{bar}" } # after + + +Inside the proc, +self+ is the object which is the owner of the association, unless you are eager loading the association, in which case +self+ is the class which the association is within. + +You can have any "normal" conditions inside the proc, so the following will work too: + + +has_many :things, :conditions => proc { ["foo = ?", bar] } + + +* Previously +:insert_sql+ and +:delete_sql+ on +has_and_belongs_to_many+ association allowed you to call 'record' to get the record being inserted or deleted. This is now passed as an argument to the proc. + +* Added ActiveRecord::Base#has_secure_password (via ActiveModel::SecurePassword) to encapsulate dead-simple password usage with BCrypt encryption and salting. + + +# Schema: User(name:string, password_digest:string, password_salt:string) +class User < ActiveRecord::Base + has_secure_password +end + + +* When a model is generated +add_index+ is added by default for +belongs_to+ or +references+ columns. + +* Setting the id of a +belongs_to+ object will update the reference to the object. + +* ActiveRecord::Base#dup and ActiveRecord::Base#clone semantics have changed to closer match normal Ruby dup and clone semantics. + +* Calling ActiveRecord::Base#clone will result in a shallow copy of the record, including copying the frozen state. No callbacks will be called. + +* Calling ActiveRecord::Base#dup will duplicate the record, including calling after initialize hooks. Frozen state will not be copied, and all associations will be cleared. A duped record will return +true+ for new_record?, have a +nil+ id field, and is saveable. + +* The query cache now works with prepared statements. No changes in the applications are required. + +h3. Active Model + +* +attr_accessible+ accepts an option +:as+ to specify a role. + +* +InclusionValidator+, +ExclusionValidator+, and +FormatValidator+ now accepts an option which can be a proc, a lambda, or anything that respond to +call+. This option will be called with the current record as an argument and returns an object which respond to +include?+ for +InclusionValidator+ and +ExclusionValidator+, and returns a regular expression object for +FormatValidator+. + +* Added ActiveModel::SecurePassword to encapsulate dead-simple password usage with BCrypt encryption and salting. + +* ActiveModel::AttributeMethods allows attributes to be defined on demand. + +* Added support for selectively enabling and disabling observers. + +* Alternate I18n namespace lookup is no longer supported. + +h3. Active Resource + +* The default format has been changed to JSON for all requests. If you want to continue to use XML you will need to set self.format = :xml in the class. For example, + + +class User < ActiveResource::Base + self.format = :xml +end + + +h3. Active Support + +* ActiveSupport::Dependencies now raises +NameError+ if it finds an existing constant in +load_missing_constant+. + +* Added a new reporting method Kernel#quietly which silences both +STDOUT+ and +STDERR+. + +* Added String#inquiry as a convenience method for turning a String into a +StringInquirer+ object. + +* Added Object#in? to test if an object is included in another object. + +* +LocalCache+ strategy is now a real middleware class and no longer an anonymous class. + +* ActiveSupport::Dependencies::ClassCache class has been introduced for holding references to reloadable classes. + +* ActiveSupport::Dependencies::Reference has been refactored to take direct advantage of the new +ClassCache+. + +* Backports Range#cover? as an alias for Range#include? in Ruby 1.8. + +* Added +weeks_ago+ and +prev_week+ to Date/DateTime/Time. + +* Added +before_remove_const+ callback to ActiveSupport::Dependencies.remove_unloadable_constants!. + +Deprecations: + +* ActiveSupport::SecureRandom is deprecated in favor of +SecureRandom+ from the Ruby standard library. + +h3. Credits + +See the "full list of contributors to Rails":http://contributors.rubyonrails.org/ for the many people who spent many hours making Rails, the stable and robust framework it is. Kudos to all of them. + +Rails 3.1 Release Notes were compiled by "Vijay Dev":https://github.com/vijaydev. diff --git a/guides/source/3_1_release_notes.textile b/guides/source/3_1_release_notes.textile deleted file mode 100644 index f88d8624ba..0000000000 --- a/guides/source/3_1_release_notes.textile +++ /dev/null @@ -1,538 +0,0 @@ -h2. Ruby on Rails 3.1 Release Notes - -Highlights in Rails 3.1: - -* Streaming -* Reversible Migrations -* Assets Pipeline -* jQuery as the default JavaScript library - -This release notes cover the major changes, but don't include every little bug fix and change. If you want to see everything, check out the "list of commits":https://github.com/rails/rails/commits/master in the main Rails repository on GitHub. - -endprologue. - -h3. Upgrading to Rails 3.1 - -If you're upgrading an existing application, it's a great idea to have good test coverage before going in. You should also first upgrade to Rails 3 in case you haven't and make sure your application still runs as expected before attempting to update to Rails 3.1. Then take heed of the following changes: - -h4. Rails 3.1 requires at least Ruby 1.8.7 - -Rails 3.1 requires Ruby 1.8.7 or higher. Support for all of the previous Ruby versions has been dropped officially and you should upgrade as early as possible. Rails 3.1 is also compatible with Ruby 1.9.2. - -TIP: Note that Ruby 1.8.7 p248 and p249 have marshaling bugs that crash Rails. Ruby Enterprise Edition have these fixed since release 1.8.7-2010.02 though. On the 1.9 front, Ruby 1.9.1 is not usable because it outright segfaults, so if you want to use 1.9.x jump on 1.9.2 for smooth sailing. - -h4. What to update in your apps - -The following changes are meant for upgrading your application to Rails 3.1.3, the latest 3.1.x version of Rails. - -h5. Gemfile - -Make the following changes to your +Gemfile+. - - -gem 'rails', '= 3.1.3' -gem 'mysql2' - -# Needed for the new asset pipeline -group :assets do - gem 'sass-rails', "~> 3.1.5" - gem 'coffee-rails', "~> 3.1.1" - gem 'uglifier', ">= 1.0.3" -end - -# jQuery is the default JavaScript library in Rails 3.1 -gem 'jquery-rails' - - -h5. config/application.rb - -* The asset pipeline requires the following additions: - - -config.assets.enabled = true -config.assets.version = '1.0' - - -* If your application is using the "/assets" route for a resource you may want change the prefix used for assets to avoid conflicts: - - -# Defaults to '/assets' -config.assets.prefix = '/asset-files' - - -h5. config/environments/development.rb - -* Remove the RJS setting config.action_view.debug_rjs = true. - -* Add the following, if you enable the asset pipeline. - - -# Do not compress assets -config.assets.compress = false - -# Expands the lines which load the assets -config.assets.debug = true - - -h5. config/environments/production.rb - -* Again, most of the changes below are for the asset pipeline. You can read more about these in the "Asset Pipeline":asset_pipeline.html guide. - - -# Compress JavaScripts and CSS -config.assets.compress = true - -# Don't fallback to assets pipeline if a precompiled asset is missed -config.assets.compile = false - -# Generate digests for assets URLs -config.assets.digest = true - -# Defaults to Rails.root.join("public/assets") -# config.assets.manifest = YOUR_PATH - -# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added) -# config.assets.precompile += %w( search.js ) - - -# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. -# config.force_ssl = true - - - -h5. config/environments/test.rb - - -# Configure static asset server for tests with Cache-Control for performance -config.serve_static_assets = true -config.static_cache_control = "public, max-age=3600" - - -h5. config/initializers/wrap_parameters.rb - -* Add this file with the following contents, if you wish to wrap parameters into a nested hash. This is on by default in new applications. - - -# Be sure to restart your server when you modify this file. -# This file contains settings for ActionController::ParamsWrapper which -# is enabled by default. - -# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. -ActiveSupport.on_load(:action_controller) do - wrap_parameters :format => [:json] -end - -# Disable root element in JSON by default. -ActiveSupport.on_load(:active_record) do - self.include_root_in_json = false -end - - -h3. Creating a Rails 3.1 application - - -# You should have the 'rails' rubygem installed -$ rails new myapp -$ cd myapp - - -h4. Vendoring Gems - -Rails now uses a +Gemfile+ in the application root to determine the gems you require for your application to start. This +Gemfile+ is processed by the "Bundler":https://github.com/carlhuda/bundler gem, which then installs all your dependencies. It can even install all the dependencies locally to your application so that it doesn't depend on the system gems. - -More information: - "bundler homepage":http://gembundler.com - -h4. Living on the Edge - -+Bundler+ and +Gemfile+ makes freezing your Rails application easy as pie with the new dedicated +bundle+ command. If you want to bundle straight from the Git repository, you can pass the +--edge+ flag: - - -$ rails new myapp --edge - - -If you have a local checkout of the Rails repository and want to generate an application using that, you can pass the +--dev+ flag: - - -$ ruby /path/to/rails/railties/bin/rails new myapp --dev - - -h3. Rails Architectural Changes - -h4. Assets Pipeline - -The major change in Rails 3.1 is the Assets Pipeline. It makes CSS and JavaScript first-class code citizens and enables proper organization, including use in plugins and engines. - -The assets pipeline is powered by "Sprockets":https://github.com/sstephenson/sprockets and is covered in the "Asset Pipeline":asset_pipeline.html guide. - -h4. HTTP Streaming - -HTTP Streaming is another change that is new in Rails 3.1. This lets the browser download your stylesheets and JavaScript files while the server is still generating the response. This requires Ruby 1.9.2, is opt-in and requires support from the web server as well, but the popular combo of nginx and unicorn is ready to take advantage of it. - -h4. Default JS library is now jQuery - -jQuery is the default JavaScript library that ships with Rails 3.1. But if you use Prototype, it's simple to switch. - - -$ rails new myapp -j prototype - - -h4. Identity Map - -Active Record has an Identity Map in Rails 3.1. An identity map keeps previously instantiated records and returns the object associated with the record if accessed again. The identity map is created on a per-request basis and is flushed at request completion. - -Rails 3.1 comes with the identity map turned off by default. - -h3. Railties - -* jQuery is the new default JavaScript library. - -* jQuery and Prototype are no longer vendored and is provided from now on by the jquery-rails and prototype-rails gems. - -* The application generator accepts an option +-j+ which can be an arbitrary string. If passed "foo", the gem "foo-rails" is added to the +Gemfile+, and the application JavaScript manifest requires "foo" and "foo_ujs". Currently only "prototype-rails" and "jquery-rails" exist and provide those files via the asset pipeline. - -* Generating an application or a plugin runs +bundle install+ unless +--skip-gemfile+ or +--skip-bundle+ is specified. - -* The controller and resource generators will now automatically produce asset stubs (this can be turned off with +--skip-assets+). These stubs will use CoffeeScript and Sass, if those libraries are available. - -* Scaffold and app generators use the Ruby 1.9 style hash when running on Ruby 1.9. To generate old style hash, +--old-style-hash+ can be passed. - -* Scaffold controller generator creates format block for JSON instead of XML. - -* Active Record logging is directed to STDOUT and shown inline in the console. - -* Added +config.force_ssl+ configuration which loads Rack::SSL middleware and force all requests to be under HTTPS protocol. - -* Added +rails plugin new+ command which generates a Rails plugin with gemspec, tests and a dummy application for testing. - -* Added Rack::Etag and Rack::ConditionalGet to the default middleware stack. - -* Added Rack::Cache to the default middleware stack. - -* Engines received a major update - You can mount them at any path, enable assets, run generators etc. - -h3. Action Pack - -h4. Action Controller - -* A warning is given out if the CSRF token authenticity cannot be verified. - -* Specify +force_ssl+ in a controller to force the browser to transfer data via HTTPS protocol on that particular controller. To limit to specific actions, +:only+ or +:except+ can be used. - -* Sensitive query string parameters specified in config.filter_parameters will now be filtered out from the request paths in the log. - -* URL parameters which return +nil+ for +to_param+ are now removed from the query string. - -* Added ActionController::ParamsWrapper to wrap parameters into a nested hash, and will be turned on for JSON request in new applications by default. This can be customized in config/initializers/wrap_parameters.rb. - -* Added config.action_controller.include_all_helpers. By default helper :all is done in ActionController::Base, which includes all the helpers by default. Setting +include_all_helpers+ to +false+ will result in including only application_helper and the helper corresponding to controller (like foo_helper for foo_controller). - -* +url_for+ and named url helpers now accept +:subdomain+ and +:domain+ as options. - -* Added +Base.http_basic_authenticate_with+ to do simple http basic authentication with a single class method call. - - -class PostsController < ApplicationController - USER_NAME, PASSWORD = "dhh", "secret" - - before_filter :authenticate, :except => [ :index ] - - def index - render :text => "Everyone can see me!" - end - - def edit - render :text => "I'm only accessible if you know the password" - end - - private - def authenticate - authenticate_or_request_with_http_basic do |user_name, password| - user_name == USER_NAME && password == PASSWORD - end - end -end - - -..can now be written as - - -class PostsController < ApplicationController - http_basic_authenticate_with :name => "dhh", :password => "secret", :except => :index - - def index - render :text => "Everyone can see me!" - end - - def edit - render :text => "I'm only accessible if you know the password" - end -end - - -* Added streaming support, you can enable it with: - - -class PostsController < ActionController::Base - stream -end - - -You can restrict it to some actions by using +:only+ or +:except+. Please read the docs at "ActionController::Streaming":http://api.rubyonrails.org/classes/ActionController/Streaming.html for more information. - -* The redirect route method now also accepts a hash of options which will only change the parts of the url in question, or an object which responds to call, allowing for redirects to be reused. - -h4. Action Dispatch - -* config.action_dispatch.x_sendfile_header now defaults to +nil+ and config/environments/production.rb doesn't set any particular value for it. This allows servers to set it through X-Sendfile-Type. - -* ActionDispatch::MiddlewareStack now uses composition over inheritance and is no longer an array. - -* Added ActionDispatch::Request.ignore_accept_header to ignore accept headers. - -* Added Rack::Cache to the default stack. - -* Moved etag responsibility from ActionDispatch::Response to the middleware stack. - -* Rely on Rack::Session stores API for more compatibility across the Ruby world. This is backwards incompatible since Rack::Session expects #get_session to accept four arguments and requires #destroy_session instead of simply #destroy. - -* Template lookup now searches further up in the inheritance chain. - -h4. Action View - -* Added an +:authenticity_token+ option to +form_tag+ for custom handling or to omit the token by passing :authenticity_token => false. - -* Created ActionView::Renderer and specified an API for ActionView::Context. - -* In place +SafeBuffer+ mutation is prohibited in Rails 3.1. - -* Added HTML5 +button_tag+ helper. - -* +file_field+ automatically adds :multipart => true to the enclosing form. - -* Added a convenience idiom to generate HTML5 data-* attributes in tag helpers from a +:data+ hash of options: - - -tag("div", :data => {:name => 'Stephen', :city_state => %w(Chicago IL)}) -# =>
- - -Keys are dasherized. Values are JSON-encoded, except for strings and symbols. - -* +csrf_meta_tag+ is renamed to +csrf_meta_tags+ and aliases +csrf_meta_tag+ for backwards compatibility. - -* The old template handler API is deprecated and the new API simply requires a template handler to respond to call. - -* rhtml and rxml are finally removed as template handlers. - -* config.action_view.cache_template_loading is brought back which allows to decide whether templates should be cached or not. - -* The submit form helper does not generate an id "object_name_id" anymore. - -* Allows FormHelper#form_for to specify the +:method+ as a direct option instead of through the +:html+ hash. form_for(==@==post, remote: true, method: :delete) instead of form_for(==@==post, remote: true, html: { method: :delete }). - -* Provided JavaScriptHelper#j() as an alias for JavaScriptHelper#escape_javascript(). This supersedes the Object#j() method that the JSON gem adds within templates using the JavaScriptHelper. - -* Allows AM/PM format in datetime selectors. - -* +auto_link+ has been removed from Rails and extracted into the "rails_autolink gem":https://github.com/tenderlove/rails_autolink - -h3. Active Record - -* Added a class method pluralize_table_names to singularize/pluralize table names of individual models. Previously this could only be set globally for all models through ActiveRecord::Base.pluralize_table_names. - -class User < ActiveRecord::Base - self.pluralize_table_names = false -end - - -* Added block setting of attributes to singular associations. The block will get called after the instance is initialized. - - -class User < ActiveRecord::Base - has_one :account -end - -user.build_account{ |a| a.credit_limit = 100.0 } - - -* Added ActiveRecord::Base.attribute_names to return a list of attribute names. This will return an empty array if the model is abstract or the table does not exist. - -* CSV Fixtures are deprecated and support will be removed in Rails 3.2.0. - -* ActiveRecord#new, ActiveRecord#create and ActiveRecord#update_attributes all accept a second hash as an option that allows you to specify which role to consider when assigning attributes. This is built on top of Active Model's new mass assignment capabilities: - - -class Post < ActiveRecord::Base - attr_accessible :title - attr_accessible :title, :published_at, :as => :admin -end - -Post.new(params[:post], :as => :admin) - - -* +default_scope+ can now take a block, lambda, or any other object which responds to call for lazy evaluation. - -* Default scopes are now evaluated at the latest possible moment, to avoid problems where scopes would be created which would implicitly contain the default scope, which would then be impossible to get rid of via Model.unscoped. - -* PostgreSQL adapter only supports PostgreSQL version 8.2 and higher. - -* +ConnectionManagement+ middleware is changed to clean up the connection pool after the rack body has been flushed. - -* Added an +update_column+ method on Active Record. This new method updates a given attribute on an object, skipping validations and callbacks. It is recommended to use +update_attributes+ or +update_attribute+ unless you are sure you do not want to execute any callback, including the modification of the +updated_at+ column. It should not be called on new records. - -* Associations with a +:through+ option can now use any association as the through or source association, including other associations which have a +:through+ option and +has_and_belongs_to_many+ associations. - -* The configuration for the current database connection is now accessible via ActiveRecord::Base.connection_config. - -* limits and offsets are removed from COUNT queries unless both are supplied. - -People.limit(1).count # => 'SELECT COUNT(*) FROM people' -People.offset(1).count # => 'SELECT COUNT(*) FROM people' -People.limit(1).offset(1).count # => 'SELECT COUNT(*) FROM people LIMIT 1 OFFSET 1' - - -* ActiveRecord::Associations::AssociationProxy has been split. There is now an +Association+ class (and subclasses) which are responsible for operating on associations, and then a separate, thin wrapper called +CollectionProxy+, which proxies collection associations. This prevents namespace pollution, separates concerns, and will allow further refactorings. - -* Singular associations (+has_one+, +belongs_to+) no longer have a proxy and simply returns the associated record or +nil+. This means that you should not use undocumented methods such as +bob.mother.create+ - use +bob.create_mother+ instead. - -* Support the :dependent option on has_many :through associations. For historical and practical reasons, +:delete_all+ is the default deletion strategy employed by association.delete(*records), despite the fact that the default strategy is +:nullify+ for regular has_many. Also, this only works at all if the source reflection is a belongs_to. For other situations, you should directly modify the through association. - -* The behavior of +association.destroy+ for +has_and_belongs_to_many+ and has_many :through is changed. From now on, 'destroy' or 'delete' on an association will be taken to mean 'get rid of the link', not (necessarily) 'get rid of the associated records'. - -* Previously, has_and_belongs_to_many.destroy(*records) would destroy the records themselves. It would not delete any records in the join table. Now, it deletes the records in the join table. - -* Previously, has_many_through.destroy(*records) would destroy the records themselves, and the records in the join table. [Note: This has not always been the case; previous version of Rails only deleted the records themselves.] Now, it destroys only the records in the join table. - -* Note that this change is backwards-incompatible to an extent, but there is unfortunately no way to 'deprecate' it before changing it. The change is being made in order to have consistency as to the meaning of 'destroy' or 'delete' across the different types of associations. If you wish to destroy the records themselves, you can do records.association.each(&:destroy). - -* Add :bulk => true option to +change_table+ to make all the schema changes defined in a block using a single ALTER statement. - - -change_table(:users, :bulk => true) do |t| - t.string :company_name - t.change :birthdate, :datetime -end - - -* Removed support for accessing attributes on a +has_and_belongs_to_many+ join table. has_many :through needs to be used. - -* Added a +create_association!+ method for +has_one+ and +belongs_to+ associations. - -* Migrations are now reversible, meaning that Rails will figure out how to reverse your migrations. To use reversible migrations, just define the +change+ method. - -class MyMigration < ActiveRecord::Migration - def change - create_table(:horses) do |t| - t.column :content, :text - t.column :remind_at, :datetime - end - end -end - - -* Some things cannot be automatically reversed for you. If you know how to reverse those things, you should define +up+ and +down+ in your migration. If you define something in change that cannot be reversed, an +IrreversibleMigration+ exception will be raised when going down. - -* Migrations now use instance methods rather than class methods: - -class FooMigration < ActiveRecord::Migration - def up # Not self.up - ... - end -end - - -* Migration files generated from model and constructive migration generators (for example, add_name_to_users) use the reversible migration's +change+ method instead of the ordinary +up+ and +down+ methods. - -* Removed support for interpolating string SQL conditions on associations. Instead, a proc should be used. - - -has_many :things, :conditions => 'foo = #{bar}' # before -has_many :things, :conditions => proc { "foo = #{bar}" } # after - - -Inside the proc, +self+ is the object which is the owner of the association, unless you are eager loading the association, in which case +self+ is the class which the association is within. - -You can have any "normal" conditions inside the proc, so the following will work too: - - -has_many :things, :conditions => proc { ["foo = ?", bar] } - - -* Previously +:insert_sql+ and +:delete_sql+ on +has_and_belongs_to_many+ association allowed you to call 'record' to get the record being inserted or deleted. This is now passed as an argument to the proc. - -* Added ActiveRecord::Base#has_secure_password (via ActiveModel::SecurePassword) to encapsulate dead-simple password usage with BCrypt encryption and salting. - - -# Schema: User(name:string, password_digest:string, password_salt:string) -class User < ActiveRecord::Base - has_secure_password -end - - -* When a model is generated +add_index+ is added by default for +belongs_to+ or +references+ columns. - -* Setting the id of a +belongs_to+ object will update the reference to the object. - -* ActiveRecord::Base#dup and ActiveRecord::Base#clone semantics have changed to closer match normal Ruby dup and clone semantics. - -* Calling ActiveRecord::Base#clone will result in a shallow copy of the record, including copying the frozen state. No callbacks will be called. - -* Calling ActiveRecord::Base#dup will duplicate the record, including calling after initialize hooks. Frozen state will not be copied, and all associations will be cleared. A duped record will return +true+ for new_record?, have a +nil+ id field, and is saveable. - -* The query cache now works with prepared statements. No changes in the applications are required. - -h3. Active Model - -* +attr_accessible+ accepts an option +:as+ to specify a role. - -* +InclusionValidator+, +ExclusionValidator+, and +FormatValidator+ now accepts an option which can be a proc, a lambda, or anything that respond to +call+. This option will be called with the current record as an argument and returns an object which respond to +include?+ for +InclusionValidator+ and +ExclusionValidator+, and returns a regular expression object for +FormatValidator+. - -* Added ActiveModel::SecurePassword to encapsulate dead-simple password usage with BCrypt encryption and salting. - -* ActiveModel::AttributeMethods allows attributes to be defined on demand. - -* Added support for selectively enabling and disabling observers. - -* Alternate I18n namespace lookup is no longer supported. - -h3. Active Resource - -* The default format has been changed to JSON for all requests. If you want to continue to use XML you will need to set self.format = :xml in the class. For example, - - -class User < ActiveResource::Base - self.format = :xml -end - - -h3. Active Support - -* ActiveSupport::Dependencies now raises +NameError+ if it finds an existing constant in +load_missing_constant+. - -* Added a new reporting method Kernel#quietly which silences both +STDOUT+ and +STDERR+. - -* Added String#inquiry as a convenience method for turning a String into a +StringInquirer+ object. - -* Added Object#in? to test if an object is included in another object. - -* +LocalCache+ strategy is now a real middleware class and no longer an anonymous class. - -* ActiveSupport::Dependencies::ClassCache class has been introduced for holding references to reloadable classes. - -* ActiveSupport::Dependencies::Reference has been refactored to take direct advantage of the new +ClassCache+. - -* Backports Range#cover? as an alias for Range#include? in Ruby 1.8. - -* Added +weeks_ago+ and +prev_week+ to Date/DateTime/Time. - -* Added +before_remove_const+ callback to ActiveSupport::Dependencies.remove_unloadable_constants!. - -Deprecations: - -* ActiveSupport::SecureRandom is deprecated in favor of +SecureRandom+ from the Ruby standard library. - -h3. Credits - -See the "full list of contributors to Rails":http://contributors.rubyonrails.org/ for the many people who spent many hours making Rails, the stable and robust framework it is. Kudos to all of them. - -Rails 3.1 Release Notes were compiled by "Vijay Dev":https://github.com/vijaydev. diff --git a/guides/source/3_2_release_notes.md b/guides/source/3_2_release_notes.md new file mode 100644 index 0000000000..3524ea6595 --- /dev/null +++ b/guides/source/3_2_release_notes.md @@ -0,0 +1,552 @@ +h2. Ruby on Rails 3.2 Release Notes + +Highlights in Rails 3.2: + +* Faster Development Mode +* New Routing Engine +* Automatic Query Explains +* Tagged Logging + +These release notes cover the major changes, but do not include each bug-fix and changes. If you want to see everything, check out the "list of commits":https://github.com/rails/rails/commits/3-2-stable in the main Rails repository on GitHub. + +endprologue. + +h3. Upgrading to Rails 3.2 + +If you're upgrading an existing application, it's a great idea to have good test coverage before going in. You should also first upgrade to Rails 3.1 in case you haven't and make sure your application still runs as expected before attempting an update to Rails 3.2. Then take heed of the following changes: + +h4. Rails 3.2 requires at least Ruby 1.8.7 + +Rails 3.2 requires Ruby 1.8.7 or higher. Support for all of the previous Ruby versions has been dropped officially and you should upgrade as early as possible. Rails 3.2 is also compatible with Ruby 1.9.2. + +TIP: Note that Ruby 1.8.7 p248 and p249 have marshaling bugs that crash Rails. Ruby Enterprise Edition has these fixed since the release of 1.8.7-2010.02. On the 1.9 front, Ruby 1.9.1 is not usable because it outright segfaults, so if you want to use 1.9.x, jump on to 1.9.2 or 1.9.3 for smooth sailing. + +h4. What to update in your apps + +* Update your Gemfile to depend on +** rails = 3.2.0 +** sass-rails ~> 3.2.3 +** coffee-rails ~> 3.2.1 +** uglifier >= 1.0.3 + +* Rails 3.2 deprecates vendor/plugins and Rails 4.0 will remove them completely. You can start replacing these plugins by extracting them as gems and adding them in your Gemfile. If you choose not to make them gems, you can move them into, say, lib/my_plugin/* and add an appropriate initializer in config/initializers/my_plugin.rb. + +* There are a couple of new configuration changes you'd want to add in config/environments/development.rb: + + +# Raise exception on mass assignment protection for Active Record models +config.active_record.mass_assignment_sanitizer = :strict + +# Log the query plan for queries taking more than this (works +# with SQLite, MySQL, and PostgreSQL) +config.active_record.auto_explain_threshold_in_seconds = 0.5 + + +The mass_assignment_sanitizer config also needs to be added in config/environments/test.rb: + + +# Raise exception on mass assignment protection for Active Record models +config.active_record.mass_assignment_sanitizer = :strict + + +h4. What to update in your engines + +Replace the code beneath the comment in script/rails with the following content: + + +ENGINE_ROOT = File.expand_path('../..', __FILE__) +ENGINE_PATH = File.expand_path('../../lib/your_engine_name/engine', __FILE__) + +require 'rails/all' +require 'rails/engine/commands' + + +h3. Creating a Rails 3.2 application + + +# You should have the 'rails' rubygem installed +$ rails new myapp +$ cd myapp + + +h4. Vendoring Gems + +Rails now uses a +Gemfile+ in the application root to determine the gems you require for your application to start. This +Gemfile+ is processed by the "Bundler":https://github.com/carlhuda/bundler gem, which then installs all your dependencies. It can even install all the dependencies locally to your application so that it doesn't depend on the system gems. + +More information: "Bundler homepage":http://gembundler.com + +h4. Living on the Edge + ++Bundler+ and +Gemfile+ makes freezing your Rails application easy as pie with the new dedicated +bundle+ command. If you want to bundle straight from the Git repository, you can pass the +--edge+ flag: + + +$ rails new myapp --edge + + +If you have a local checkout of the Rails repository and want to generate an application using that, you can pass the +--dev+ flag: + + +$ ruby /path/to/rails/railties/bin/rails new myapp --dev + + +h3. Major Features + +h4. Faster Development Mode & Routing + +Rails 3.2 comes with a development mode that's noticeably faster. Inspired by "Active Reload":https://github.com/paneq/active_reload, Rails reloads classes only when files actually change. The performance gains are dramatic on a larger application. Route recognition also got a bunch faster thanks to the new "Journey":https://github.com/rails/journey engine. + +h4. Automatic Query Explains + +Rails 3.2 comes with a nice feature that explains queries generated by ARel by defining an +explain+ method in ActiveRecord::Relation. For example, you can run something like puts Person.active.limit(5).explain and the query ARel produces is explained. This allows to check for the proper indexes and further optimizations. + +Queries that take more than half a second to run are *automatically* explained in the development mode. This threshold, of course, can be changed. + +h4. Tagged Logging + +When running a multi-user, multi-account application, it's a great help to be able to filter the log by who did what. TaggedLogging in Active Support helps in doing exactly that by stamping log lines with subdomains, request ids, and anything else to aid debugging such applications. + +h3. Documentation + +From Rails 3.2, the Rails guides are available for the Kindle and free Kindle Reading Apps for the iPad, iPhone, Mac, Android, etc. + +h3. Railties + +* Speed up development by only reloading classes if dependencies files changed. This can be turned off by setting config.reload_classes_only_on_change to false. + +* New applications get a flag config.active_record.auto_explain_threshold_in_seconds in the environments configuration files. With a value of 0.5 in development.rb and commented out in production.rb. No mention in test.rb. + +* Added config.exceptions_app to set the exceptions application invoked by the +ShowException+ middleware when an exception happens. Defaults to ActionDispatch::PublicExceptions.new(Rails.public_path). + +* Added a DebugExceptions middleware which contains features extracted from ShowExceptions middleware. + +* Display mounted engines' routes in rake routes. + +* Allow to change the loading order of railties with config.railties_order like: + + +config.railties_order = [Blog::Engine, :main_app, :all] + + +* Scaffold returns 204 No Content for API requests without content. This makes scaffold work with jQuery out of the box. + +* Update Rails::Rack::Logger middleware to apply any tags set in config.log_tags to ActiveSupport::TaggedLogging. This makes it easy to tag log lines with debug information like subdomain and request id -- both very helpful in debugging multi-user production applications. + +* Default options to +rails new+ can be set in ~/.railsrc. You can specify extra command-line arguments to be used every time 'rails new' runs in the .railsrc configuration file in your home directory. + +* Add an alias +d+ for +destroy+. This works for engines too. + +* Attributes on scaffold and model generators default to string. This allows the following: rails g scaffold Post title body:text author + +* Allow scaffold/model/migration generators to accept "index" and "uniq" modifiers. For example, + + +rails g scaffold Post title:string:index author:uniq price:decimal{7,2} + + +will create indexes for +title+ and +author+ with the latter being an unique index. Some types such as decimal accept custom options. In the example, +price+ will be a decimal column with precision and scale set to 7 and 2 respectively. + +* Turn gem has been removed from default Gemfile. + +* Remove old plugin generator +rails generate plugin+ in favor of +rails plugin new+ command. + +* Remove old config.paths.app.controller API in favor of config.paths["app/controller"]. + +h4(#railties_deprecations). Deprecations + +* +Rails::Plugin+ is deprecated and will be removed in Rails 4.0. Instead of adding plugins to +vendor/plugins+ use gems or bundler with path or git dependencies. + +h3. Action Mailer + +* Upgraded mail version to 2.4.0. + +* Removed the old Action Mailer API which was deprecated since Rails 3.0. + +h3. Action Pack + +h4. Action Controller + +* Make ActiveSupport::Benchmarkable a default module for ActionController::Base, so the #benchmark method is once again available in the controller context like it used to be. + +* Added +:gzip+ option to +caches_page+. The default option can be configured globally using page_cache_compression. + +* Rails will now use your default layout (such as "layouts/application") when you specify a layout with :only and :except condition, and those conditions fail. + + +class CarsController + layout 'single_car', :only => :show +end + + +Rails will use 'layouts/single_car' when a request comes in :show action, and use 'layouts/application' (or 'layouts/cars', if exists) when a request comes in for any other actions. + +* form_for is changed to use "#{action}_#{as}" as the css class and id if +:as+ option is provided. Earlier versions used "#{as}_#{action}". + +* ActionController::ParamsWrapper on ActiveRecord models now only wrap attr_accessible attributes if they were set. If not, only the attributes returned by the class method +attribute_names+ will be wrapped. This fixes the wrapping of nested attributes by adding them to +attr_accessible+. + +* Log "Filter chain halted as CALLBACKNAME rendered or redirected" every time a before callback halts. + +* ActionDispatch::ShowExceptions is refactored. The controller is responsible for choosing to show exceptions. It's possible to override +show_detailed_exceptions?+ in controllers to specify which requests should provide debugging information on errors. + +* Responders now return 204 No Content for API requests without a response body (as in the new scaffold). + +* ActionController::TestCase cookies is refactored. Assigning cookies for test cases should now use cookies[] + + +cookies[:email] = 'user@example.com' +get :index +assert_equal 'user@example.com', cookies[:email] + + +To clear the cookies, use +clear+. + + +cookies.clear +get :index +assert_nil cookies[:email] + + +We now no longer write out HTTP_COOKIE and the cookie jar is persistent between requests so if you need to manipulate the environment for your test you need to do it before the cookie jar is created. + +* send_file now guesses the MIME type from the file extension if +:type+ is not provided. + +* MIME type entries for PDF, ZIP and other formats were added. + +* Allow fresh_when/stale? to take a record instead of an options hash. + +* Changed log level of warning for missing CSRF token from :debug to :warn. + +* Assets should use the request protocol by default or default to relative if no request is available. + +h5(#actioncontroller_deprecations). Deprecations + +* Deprecated implied layout lookup in controllers whose parent had a explicit layout set: + + +class ApplicationController + layout "application" +end + +class PostsController < ApplicationController +end + + +In the example above, Posts controller will no longer automatically look up for a posts layout. If you need this functionality you could either remove layout "application" from +ApplicationController+ or explicitly set it to +nil+ in +PostsController+. + +* Deprecated ActionController::UnknownAction in favour of AbstractController::ActionNotFound. + +* Deprecated ActionController::DoubleRenderError in favour of AbstractController::DoubleRenderError. + +* Deprecated method_missing in favour of +action_missing+ for missing actions. + +* Deprecated ActionController#rescue_action, ActionController#initialize_template_class and ActionController#assign_shortcuts. + +h4. Action Dispatch + +* Add config.action_dispatch.default_charset to configure default charset for ActionDispatch::Response. + +* Added ActionDispatch::RequestId middleware that'll make a unique X-Request-Id header available to the response and enables the ActionDispatch::Request#uuid method. This makes it easy to trace requests from end-to-end in the stack and to identify individual requests in mixed logs like Syslog. + +* The ShowExceptions middleware now accepts a exceptions application that is responsible to render an exception when the application fails. The application is invoked with a copy of the exception in +env["action_dispatch.exception"]+ and with the PATH_INFO rewritten to the status code. + +* Allow rescue responses to be configured through a railtie as in config.action_dispatch.rescue_responses. + +h5(#actiondispatch_deprecations). Deprecations + +* Deprecated the ability to set a default charset at the controller level, use the new config.action_dispatch.default_charset instead. + +h4. Action View + +* Add +button_tag+ support to ActionView::Helpers::FormBuilder. This support mimics the default behavior of +submit_tag+. + + +<%= form_for @post do |f| %> + <%= f.button %> +<% end %> + + +* Date helpers accept a new option :use_two_digit_numbers => true, that renders select boxes for months and days with a leading zero without changing the respective values. For example, this is useful for displaying ISO 8601-style dates such as '2011-08-01'. + +* You can provide a namespace for your form to ensure uniqueness of id attributes on form elements. The namespace attribute will be prefixed with underscore on the generated HTML id. + + +<%= form_for(@offer, :namespace => 'namespace') do |f| %> + <%= f.label :version, 'Version' %>: + <%= f.text_field :version %> +<% end %> + + +* Limit the number of options for +select_year+ to 1000. Pass +:max_years_allowed+ option to set your own limit. + +* +content_tag_for+ and +div_for+ can now take a collection of records. It will also yield the record as the first argument if you set a receiving argument in your block. So instead of having to do this: + + +@items.each do |item| + content_tag_for(:li, item) do + Title: <%= item.title %> + end +end + + +You can do this: + + +content_tag_for(:li, @items) do |item| + Title: <%= item.title %> +end + + +* Added +font_path+ helper method that computes the path to a font asset in public/fonts. + +h5(#actionview_deprecations). Deprecations + +* Passing formats or handlers to render :template and friends like render :template => "foo.html.erb" is deprecated. Instead, you can provide :handlers and :formats directly as options: render :template => "foo", :formats => [:html, :js], :handlers => :erb. + +h4. Sprockets + +* Adds a configuration option config.assets.logger to control Sprockets logging. Set it to +false+ to turn off logging and to +nil+ to default to +Rails.logger+. + +h3. Active Record + +* Boolean columns with 'on' and 'ON' values are type cast to true. + +* When the +timestamps+ method creates the +created_at+ and +updated_at+ columns, it makes them non-nullable by default. + +* Implemented ActiveRecord::Relation#explain. + +* Implements AR::Base.silence_auto_explain which allows the user to selectively disable automatic EXPLAINs within a block. + +* Implements automatic EXPLAIN logging for slow queries. A new configuration parameter +config.active_record.auto_explain_threshold_in_seconds+ determines what's to be considered a slow query. Setting that to nil disables this feature. Defaults are 0.5 in development mode, and nil in test and production modes. Rails 3.2 supports this feature in SQLite, MySQL (mysql2 adapter), and PostgreSQL. + +* Added ActiveRecord::Base.store for declaring simple single-column key/value stores. + + +class User < ActiveRecord::Base + store :settings, accessors: [ :color, :homepage ] +end + +u = User.new(color: 'black', homepage: '37signals.com') +u.color # Accessor stored attribute +u.settings[:country] = 'Denmark' # Any attribute, even if not specified with an accessor + + +* Added ability to run migrations only for a given scope, which allows to run migrations only from one engine (for example to revert changes from an engine that need to be removed). + + +rake db:migrate SCOPE=blog + + +* Migrations copied from engines are now scoped with engine's name, for example 01_create_posts.blog.rb. + +* Implemented ActiveRecord::Relation#pluck method that returns an array of column values directly from the underlying table. This also works with serialized attributes. + + +Client.where(:active => true).pluck(:id) +# SELECT id from clients where active = 1 + + +* Generated association methods are created within a separate module to allow overriding and composition. For a class named MyModel, the module is named MyModel::GeneratedFeatureMethods. It is included into the model class immediately after the +generated_attributes_methods+ module defined in Active Model, so association methods override attribute methods of the same name. + +* Add ActiveRecord::Relation#uniq for generating unique queries. + + +Client.select('DISTINCT name') + + +..can be written as: + + +Client.select(:name).uniq + + +This also allows you to revert the uniqueness in a relation: + + +Client.select(:name).uniq.uniq(false) + + +* Support index sort order in SQLite, MySQL and PostgreSQL adapters. + +* Allow the +:class_name+ option for associations to take a symbol in addition to a string. This is to avoid confusing newbies, and to be consistent with the fact that other options like :foreign_key already allow a symbol or a string. + + +has_many :clients, :class_name => :Client # Note that the symbol need to be capitalized + + +* In development mode, db:drop also drops the test database in order to be symmetric with db:create. + +* Case-insensitive uniqueness validation avoids calling LOWER in MySQL when the column already uses a case-insensitive collation. + +* Transactional fixtures enlist all active database connections. You can test models on different connections without disabling transactional fixtures. + +* Add +first_or_create+, +first_or_create!+, +first_or_initialize+ methods to Active Record. This is a better approach over the old +find_or_create_by+ dynamic methods because it's clearer which arguments are used to find the record and which are used to create it. + + +User.where(:first_name => "Scarlett").first_or_create!(:last_name => "Johansson") + + +* Added a with_lock method to Active Record objects, which starts a transaction, locks the object (pessimistically) and yields to the block. The method takes one (optional) parameter and passes it to +lock!+. + +This makes it possible to write the following: + + +class Order < ActiveRecord::Base + def cancel! + transaction do + lock! + # ... cancelling logic + end + end +end + + +as: + + +class Order < ActiveRecord::Base + def cancel! + with_lock do + # ... cancelling logic + end + end +end + + +h4(#activerecord_deprecations). Deprecations + +* Automatic closure of connections in threads is deprecated. For example the following code is deprecated: + + +Thread.new { Post.find(1) }.join + + +It should be changed to close the database connection at the end of the thread: + + +Thread.new { + Post.find(1) + Post.connection.close +}.join + + +Only people who spawn threads in their application code need to worry about this change. + +* The +set_table_name+, +set_inheritance_column+, +set_sequence_name+, +set_primary_key+, +set_locking_column+ methods are deprecated. Use an assignment method instead. For example, instead of +set_table_name+, use self.table_name=. + + +class Project < ActiveRecord::Base + self.table_name = "project" +end + + +Or define your own self.table_name method: + + +class Post < ActiveRecord::Base + def self.table_name + "special_" + super + end +end + +Post.table_name # => "special_posts" + + + +h3. Active Model + +* Add ActiveModel::Errors#added? to check if a specific error has been added. + +* Add ability to define strict validations with strict => true that always raises exception when fails. + +* Provide mass_assignment_sanitizer as an easy API to replace the sanitizer behavior. Also support both :logger (default) and :strict sanitizer behavior. + +h4(#activemodel_deprecations). Deprecations + +* Deprecated define_attr_method in ActiveModel::AttributeMethods because this only existed to support methods like +set_table_name+ in Active Record, which are themselves being deprecated. + +* Deprecated Model.model_name.partial_path in favor of model.to_partial_path. + +h3. Active Resource + +* Redirect responses: 303 See Other and 307 Temporary Redirect now behave like 301 Moved Permanently and 302 Found. + +h3. Active Support + +* Added ActiveSupport:TaggedLogging that can wrap any standard +Logger+ class to provide tagging capabilities. + + +Logger = ActiveSupport::TaggedLogging.new(Logger.new(STDOUT)) + +Logger.tagged("BCX") { Logger.info "Stuff" } +# Logs "[BCX] Stuff" + +Logger.tagged("BCX", "Jason") { Logger.info "Stuff" } +# Logs "[BCX] [Jason] Stuff" + +Logger.tagged("BCX") { Logger.tagged("Jason") { Logger.info "Stuff" } } +# Logs "[BCX] [Jason] Stuff" + + +* The +beginning_of_week+ method in +Date+, +Time+ and +DateTime+ accepts an optional argument representing the day in which the week is assumed to start. + +* ActiveSupport::Notifications.subscribed provides subscriptions to events while a block runs. + +* Defined new methods Module#qualified_const_defined?, Module#qualified_const_get and Module#qualified_const_set that are analogous to the corresponding methods in the standard API, but accept qualified constant names. + +* Added +#deconstantize+ which complements +#demodulize+ in inflections. This removes the rightmost segment in a qualified constant name. + +* Added safe_constantize that constantizes a string but returns +nil+ instead of raising an exception if the constant (or part of it) does not exist. + +* ActiveSupport::OrderedHash is now marked as extractable when using Array#extract_options!. + +* Added Array#prepend as an alias for Array#unshift and Array#append as an alias for Array#<<. + +* The definition of a blank string for Ruby 1.9 has been extended to Unicode whitespace. Also, in Ruby 1.8 the ideographic space U+3000 is considered to be whitespace. + +* The inflector understands acronyms. + +* Added Time#all_day, Time#all_week, Time#all_quarter and Time#all_year as a way of generating ranges. + + +Event.where(:created_at => Time.now.all_week) +Event.where(:created_at => Time.now.all_day) + + +* Added instance_accessor: false as an option to Class#cattr_accessor and friends. + +* ActiveSupport::OrderedHash now has different behavior for #each and #each_pair when given a block accepting its parameters with a splat. + +* Added ActiveSupport::Cache::NullStore for use in development and testing. + +* Removed ActiveSupport::SecureRandom in favor of SecureRandom from the standard library. + +h4(#activesupport_deprecations). Deprecations + +* +ActiveSupport::Base64+ is deprecated in favor of ::Base64. + +* Deprecated ActiveSupport::Memoizable in favor of Ruby memoization pattern. + +* Module#synchronize is deprecated with no replacement. Please use monitor from ruby's standard library. + +* Deprecated ActiveSupport::MessageEncryptor#encrypt and ActiveSupport::MessageEncryptor#decrypt. + +* ActiveSupport::BufferedLogger#silence is deprecated. If you want to squelch logs for a certain block, change the log level for that block. + +* ActiveSupport::BufferedLogger#open_log is deprecated. This method should not have been public in the first place. + +* ActiveSupport::BufferedLogger's behavior of automatically creating the directory for your log file is deprecated. Please make sure to create the directory for your log file before instantiating. + +* ActiveSupport::BufferedLogger#auto_flushing is deprecated. Either set the sync level on the underlying file handle like this. Or tune your filesystem. The FS cache is now what controls flushing. + + +f = File.open('foo.log', 'w') +f.sync = true +ActiveSupport::BufferedLogger.new f + + +* ActiveSupport::BufferedLogger#flush is deprecated. Set sync on your filehandle, or tune your filesystem. + +h3. Credits + +See the "full list of contributors to Rails":http://contributors.rubyonrails.org/ for the many people who spent many hours making Rails, the stable and robust framework it is. Kudos to all of them. + +Rails 3.2 Release Notes were compiled by "Vijay Dev":https://github.com/vijaydev. diff --git a/guides/source/3_2_release_notes.textile b/guides/source/3_2_release_notes.textile deleted file mode 100644 index 3524ea6595..0000000000 --- a/guides/source/3_2_release_notes.textile +++ /dev/null @@ -1,552 +0,0 @@ -h2. Ruby on Rails 3.2 Release Notes - -Highlights in Rails 3.2: - -* Faster Development Mode -* New Routing Engine -* Automatic Query Explains -* Tagged Logging - -These release notes cover the major changes, but do not include each bug-fix and changes. If you want to see everything, check out the "list of commits":https://github.com/rails/rails/commits/3-2-stable in the main Rails repository on GitHub. - -endprologue. - -h3. Upgrading to Rails 3.2 - -If you're upgrading an existing application, it's a great idea to have good test coverage before going in. You should also first upgrade to Rails 3.1 in case you haven't and make sure your application still runs as expected before attempting an update to Rails 3.2. Then take heed of the following changes: - -h4. Rails 3.2 requires at least Ruby 1.8.7 - -Rails 3.2 requires Ruby 1.8.7 or higher. Support for all of the previous Ruby versions has been dropped officially and you should upgrade as early as possible. Rails 3.2 is also compatible with Ruby 1.9.2. - -TIP: Note that Ruby 1.8.7 p248 and p249 have marshaling bugs that crash Rails. Ruby Enterprise Edition has these fixed since the release of 1.8.7-2010.02. On the 1.9 front, Ruby 1.9.1 is not usable because it outright segfaults, so if you want to use 1.9.x, jump on to 1.9.2 or 1.9.3 for smooth sailing. - -h4. What to update in your apps - -* Update your Gemfile to depend on -** rails = 3.2.0 -** sass-rails ~> 3.2.3 -** coffee-rails ~> 3.2.1 -** uglifier >= 1.0.3 - -* Rails 3.2 deprecates vendor/plugins and Rails 4.0 will remove them completely. You can start replacing these plugins by extracting them as gems and adding them in your Gemfile. If you choose not to make them gems, you can move them into, say, lib/my_plugin/* and add an appropriate initializer in config/initializers/my_plugin.rb. - -* There are a couple of new configuration changes you'd want to add in config/environments/development.rb: - - -# Raise exception on mass assignment protection for Active Record models -config.active_record.mass_assignment_sanitizer = :strict - -# Log the query plan for queries taking more than this (works -# with SQLite, MySQL, and PostgreSQL) -config.active_record.auto_explain_threshold_in_seconds = 0.5 - - -The mass_assignment_sanitizer config also needs to be added in config/environments/test.rb: - - -# Raise exception on mass assignment protection for Active Record models -config.active_record.mass_assignment_sanitizer = :strict - - -h4. What to update in your engines - -Replace the code beneath the comment in script/rails with the following content: - - -ENGINE_ROOT = File.expand_path('../..', __FILE__) -ENGINE_PATH = File.expand_path('../../lib/your_engine_name/engine', __FILE__) - -require 'rails/all' -require 'rails/engine/commands' - - -h3. Creating a Rails 3.2 application - - -# You should have the 'rails' rubygem installed -$ rails new myapp -$ cd myapp - - -h4. Vendoring Gems - -Rails now uses a +Gemfile+ in the application root to determine the gems you require for your application to start. This +Gemfile+ is processed by the "Bundler":https://github.com/carlhuda/bundler gem, which then installs all your dependencies. It can even install all the dependencies locally to your application so that it doesn't depend on the system gems. - -More information: "Bundler homepage":http://gembundler.com - -h4. Living on the Edge - -+Bundler+ and +Gemfile+ makes freezing your Rails application easy as pie with the new dedicated +bundle+ command. If you want to bundle straight from the Git repository, you can pass the +--edge+ flag: - - -$ rails new myapp --edge - - -If you have a local checkout of the Rails repository and want to generate an application using that, you can pass the +--dev+ flag: - - -$ ruby /path/to/rails/railties/bin/rails new myapp --dev - - -h3. Major Features - -h4. Faster Development Mode & Routing - -Rails 3.2 comes with a development mode that's noticeably faster. Inspired by "Active Reload":https://github.com/paneq/active_reload, Rails reloads classes only when files actually change. The performance gains are dramatic on a larger application. Route recognition also got a bunch faster thanks to the new "Journey":https://github.com/rails/journey engine. - -h4. Automatic Query Explains - -Rails 3.2 comes with a nice feature that explains queries generated by ARel by defining an +explain+ method in ActiveRecord::Relation. For example, you can run something like puts Person.active.limit(5).explain and the query ARel produces is explained. This allows to check for the proper indexes and further optimizations. - -Queries that take more than half a second to run are *automatically* explained in the development mode. This threshold, of course, can be changed. - -h4. Tagged Logging - -When running a multi-user, multi-account application, it's a great help to be able to filter the log by who did what. TaggedLogging in Active Support helps in doing exactly that by stamping log lines with subdomains, request ids, and anything else to aid debugging such applications. - -h3. Documentation - -From Rails 3.2, the Rails guides are available for the Kindle and free Kindle Reading Apps for the iPad, iPhone, Mac, Android, etc. - -h3. Railties - -* Speed up development by only reloading classes if dependencies files changed. This can be turned off by setting config.reload_classes_only_on_change to false. - -* New applications get a flag config.active_record.auto_explain_threshold_in_seconds in the environments configuration files. With a value of 0.5 in development.rb and commented out in production.rb. No mention in test.rb. - -* Added config.exceptions_app to set the exceptions application invoked by the +ShowException+ middleware when an exception happens. Defaults to ActionDispatch::PublicExceptions.new(Rails.public_path). - -* Added a DebugExceptions middleware which contains features extracted from ShowExceptions middleware. - -* Display mounted engines' routes in rake routes. - -* Allow to change the loading order of railties with config.railties_order like: - - -config.railties_order = [Blog::Engine, :main_app, :all] - - -* Scaffold returns 204 No Content for API requests without content. This makes scaffold work with jQuery out of the box. - -* Update Rails::Rack::Logger middleware to apply any tags set in config.log_tags to ActiveSupport::TaggedLogging. This makes it easy to tag log lines with debug information like subdomain and request id -- both very helpful in debugging multi-user production applications. - -* Default options to +rails new+ can be set in ~/.railsrc. You can specify extra command-line arguments to be used every time 'rails new' runs in the .railsrc configuration file in your home directory. - -* Add an alias +d+ for +destroy+. This works for engines too. - -* Attributes on scaffold and model generators default to string. This allows the following: rails g scaffold Post title body:text author - -* Allow scaffold/model/migration generators to accept "index" and "uniq" modifiers. For example, - - -rails g scaffold Post title:string:index author:uniq price:decimal{7,2} - - -will create indexes for +title+ and +author+ with the latter being an unique index. Some types such as decimal accept custom options. In the example, +price+ will be a decimal column with precision and scale set to 7 and 2 respectively. - -* Turn gem has been removed from default Gemfile. - -* Remove old plugin generator +rails generate plugin+ in favor of +rails plugin new+ command. - -* Remove old config.paths.app.controller API in favor of config.paths["app/controller"]. - -h4(#railties_deprecations). Deprecations - -* +Rails::Plugin+ is deprecated and will be removed in Rails 4.0. Instead of adding plugins to +vendor/plugins+ use gems or bundler with path or git dependencies. - -h3. Action Mailer - -* Upgraded mail version to 2.4.0. - -* Removed the old Action Mailer API which was deprecated since Rails 3.0. - -h3. Action Pack - -h4. Action Controller - -* Make ActiveSupport::Benchmarkable a default module for ActionController::Base, so the #benchmark method is once again available in the controller context like it used to be. - -* Added +:gzip+ option to +caches_page+. The default option can be configured globally using page_cache_compression. - -* Rails will now use your default layout (such as "layouts/application") when you specify a layout with :only and :except condition, and those conditions fail. - - -class CarsController - layout 'single_car', :only => :show -end - - -Rails will use 'layouts/single_car' when a request comes in :show action, and use 'layouts/application' (or 'layouts/cars', if exists) when a request comes in for any other actions. - -* form_for is changed to use "#{action}_#{as}" as the css class and id if +:as+ option is provided. Earlier versions used "#{as}_#{action}". - -* ActionController::ParamsWrapper on ActiveRecord models now only wrap attr_accessible attributes if they were set. If not, only the attributes returned by the class method +attribute_names+ will be wrapped. This fixes the wrapping of nested attributes by adding them to +attr_accessible+. - -* Log "Filter chain halted as CALLBACKNAME rendered or redirected" every time a before callback halts. - -* ActionDispatch::ShowExceptions is refactored. The controller is responsible for choosing to show exceptions. It's possible to override +show_detailed_exceptions?+ in controllers to specify which requests should provide debugging information on errors. - -* Responders now return 204 No Content for API requests without a response body (as in the new scaffold). - -* ActionController::TestCase cookies is refactored. Assigning cookies for test cases should now use cookies[] - - -cookies[:email] = 'user@example.com' -get :index -assert_equal 'user@example.com', cookies[:email] - - -To clear the cookies, use +clear+. - - -cookies.clear -get :index -assert_nil cookies[:email] - - -We now no longer write out HTTP_COOKIE and the cookie jar is persistent between requests so if you need to manipulate the environment for your test you need to do it before the cookie jar is created. - -* send_file now guesses the MIME type from the file extension if +:type+ is not provided. - -* MIME type entries for PDF, ZIP and other formats were added. - -* Allow fresh_when/stale? to take a record instead of an options hash. - -* Changed log level of warning for missing CSRF token from :debug to :warn. - -* Assets should use the request protocol by default or default to relative if no request is available. - -h5(#actioncontroller_deprecations). Deprecations - -* Deprecated implied layout lookup in controllers whose parent had a explicit layout set: - - -class ApplicationController - layout "application" -end - -class PostsController < ApplicationController -end - - -In the example above, Posts controller will no longer automatically look up for a posts layout. If you need this functionality you could either remove layout "application" from +ApplicationController+ or explicitly set it to +nil+ in +PostsController+. - -* Deprecated ActionController::UnknownAction in favour of AbstractController::ActionNotFound. - -* Deprecated ActionController::DoubleRenderError in favour of AbstractController::DoubleRenderError. - -* Deprecated method_missing in favour of +action_missing+ for missing actions. - -* Deprecated ActionController#rescue_action, ActionController#initialize_template_class and ActionController#assign_shortcuts. - -h4. Action Dispatch - -* Add config.action_dispatch.default_charset to configure default charset for ActionDispatch::Response. - -* Added ActionDispatch::RequestId middleware that'll make a unique X-Request-Id header available to the response and enables the ActionDispatch::Request#uuid method. This makes it easy to trace requests from end-to-end in the stack and to identify individual requests in mixed logs like Syslog. - -* The ShowExceptions middleware now accepts a exceptions application that is responsible to render an exception when the application fails. The application is invoked with a copy of the exception in +env["action_dispatch.exception"]+ and with the PATH_INFO rewritten to the status code. - -* Allow rescue responses to be configured through a railtie as in config.action_dispatch.rescue_responses. - -h5(#actiondispatch_deprecations). Deprecations - -* Deprecated the ability to set a default charset at the controller level, use the new config.action_dispatch.default_charset instead. - -h4. Action View - -* Add +button_tag+ support to ActionView::Helpers::FormBuilder. This support mimics the default behavior of +submit_tag+. - - -<%= form_for @post do |f| %> - <%= f.button %> -<% end %> - - -* Date helpers accept a new option :use_two_digit_numbers => true, that renders select boxes for months and days with a leading zero without changing the respective values. For example, this is useful for displaying ISO 8601-style dates such as '2011-08-01'. - -* You can provide a namespace for your form to ensure uniqueness of id attributes on form elements. The namespace attribute will be prefixed with underscore on the generated HTML id. - - -<%= form_for(@offer, :namespace => 'namespace') do |f| %> - <%= f.label :version, 'Version' %>: - <%= f.text_field :version %> -<% end %> - - -* Limit the number of options for +select_year+ to 1000. Pass +:max_years_allowed+ option to set your own limit. - -* +content_tag_for+ and +div_for+ can now take a collection of records. It will also yield the record as the first argument if you set a receiving argument in your block. So instead of having to do this: - - -@items.each do |item| - content_tag_for(:li, item) do - Title: <%= item.title %> - end -end - - -You can do this: - - -content_tag_for(:li, @items) do |item| - Title: <%= item.title %> -end - - -* Added +font_path+ helper method that computes the path to a font asset in public/fonts. - -h5(#actionview_deprecations). Deprecations - -* Passing formats or handlers to render :template and friends like render :template => "foo.html.erb" is deprecated. Instead, you can provide :handlers and :formats directly as options: render :template => "foo", :formats => [:html, :js], :handlers => :erb. - -h4. Sprockets - -* Adds a configuration option config.assets.logger to control Sprockets logging. Set it to +false+ to turn off logging and to +nil+ to default to +Rails.logger+. - -h3. Active Record - -* Boolean columns with 'on' and 'ON' values are type cast to true. - -* When the +timestamps+ method creates the +created_at+ and +updated_at+ columns, it makes them non-nullable by default. - -* Implemented ActiveRecord::Relation#explain. - -* Implements AR::Base.silence_auto_explain which allows the user to selectively disable automatic EXPLAINs within a block. - -* Implements automatic EXPLAIN logging for slow queries. A new configuration parameter +config.active_record.auto_explain_threshold_in_seconds+ determines what's to be considered a slow query. Setting that to nil disables this feature. Defaults are 0.5 in development mode, and nil in test and production modes. Rails 3.2 supports this feature in SQLite, MySQL (mysql2 adapter), and PostgreSQL. - -* Added ActiveRecord::Base.store for declaring simple single-column key/value stores. - - -class User < ActiveRecord::Base - store :settings, accessors: [ :color, :homepage ] -end - -u = User.new(color: 'black', homepage: '37signals.com') -u.color # Accessor stored attribute -u.settings[:country] = 'Denmark' # Any attribute, even if not specified with an accessor - - -* Added ability to run migrations only for a given scope, which allows to run migrations only from one engine (for example to revert changes from an engine that need to be removed). - - -rake db:migrate SCOPE=blog - - -* Migrations copied from engines are now scoped with engine's name, for example 01_create_posts.blog.rb. - -* Implemented ActiveRecord::Relation#pluck method that returns an array of column values directly from the underlying table. This also works with serialized attributes. - - -Client.where(:active => true).pluck(:id) -# SELECT id from clients where active = 1 - - -* Generated association methods are created within a separate module to allow overriding and composition. For a class named MyModel, the module is named MyModel::GeneratedFeatureMethods. It is included into the model class immediately after the +generated_attributes_methods+ module defined in Active Model, so association methods override attribute methods of the same name. - -* Add ActiveRecord::Relation#uniq for generating unique queries. - - -Client.select('DISTINCT name') - - -..can be written as: - - -Client.select(:name).uniq - - -This also allows you to revert the uniqueness in a relation: - - -Client.select(:name).uniq.uniq(false) - - -* Support index sort order in SQLite, MySQL and PostgreSQL adapters. - -* Allow the +:class_name+ option for associations to take a symbol in addition to a string. This is to avoid confusing newbies, and to be consistent with the fact that other options like :foreign_key already allow a symbol or a string. - - -has_many :clients, :class_name => :Client # Note that the symbol need to be capitalized - - -* In development mode, db:drop also drops the test database in order to be symmetric with db:create. - -* Case-insensitive uniqueness validation avoids calling LOWER in MySQL when the column already uses a case-insensitive collation. - -* Transactional fixtures enlist all active database connections. You can test models on different connections without disabling transactional fixtures. - -* Add +first_or_create+, +first_or_create!+, +first_or_initialize+ methods to Active Record. This is a better approach over the old +find_or_create_by+ dynamic methods because it's clearer which arguments are used to find the record and which are used to create it. - - -User.where(:first_name => "Scarlett").first_or_create!(:last_name => "Johansson") - - -* Added a with_lock method to Active Record objects, which starts a transaction, locks the object (pessimistically) and yields to the block. The method takes one (optional) parameter and passes it to +lock!+. - -This makes it possible to write the following: - - -class Order < ActiveRecord::Base - def cancel! - transaction do - lock! - # ... cancelling logic - end - end -end - - -as: - - -class Order < ActiveRecord::Base - def cancel! - with_lock do - # ... cancelling logic - end - end -end - - -h4(#activerecord_deprecations). Deprecations - -* Automatic closure of connections in threads is deprecated. For example the following code is deprecated: - - -Thread.new { Post.find(1) }.join - - -It should be changed to close the database connection at the end of the thread: - - -Thread.new { - Post.find(1) - Post.connection.close -}.join - - -Only people who spawn threads in their application code need to worry about this change. - -* The +set_table_name+, +set_inheritance_column+, +set_sequence_name+, +set_primary_key+, +set_locking_column+ methods are deprecated. Use an assignment method instead. For example, instead of +set_table_name+, use self.table_name=. - - -class Project < ActiveRecord::Base - self.table_name = "project" -end - - -Or define your own self.table_name method: - - -class Post < ActiveRecord::Base - def self.table_name - "special_" + super - end -end - -Post.table_name # => "special_posts" - - - -h3. Active Model - -* Add ActiveModel::Errors#added? to check if a specific error has been added. - -* Add ability to define strict validations with strict => true that always raises exception when fails. - -* Provide mass_assignment_sanitizer as an easy API to replace the sanitizer behavior. Also support both :logger (default) and :strict sanitizer behavior. - -h4(#activemodel_deprecations). Deprecations - -* Deprecated define_attr_method in ActiveModel::AttributeMethods because this only existed to support methods like +set_table_name+ in Active Record, which are themselves being deprecated. - -* Deprecated Model.model_name.partial_path in favor of model.to_partial_path. - -h3. Active Resource - -* Redirect responses: 303 See Other and 307 Temporary Redirect now behave like 301 Moved Permanently and 302 Found. - -h3. Active Support - -* Added ActiveSupport:TaggedLogging that can wrap any standard +Logger+ class to provide tagging capabilities. - - -Logger = ActiveSupport::TaggedLogging.new(Logger.new(STDOUT)) - -Logger.tagged("BCX") { Logger.info "Stuff" } -# Logs "[BCX] Stuff" - -Logger.tagged("BCX", "Jason") { Logger.info "Stuff" } -# Logs "[BCX] [Jason] Stuff" - -Logger.tagged("BCX") { Logger.tagged("Jason") { Logger.info "Stuff" } } -# Logs "[BCX] [Jason] Stuff" - - -* The +beginning_of_week+ method in +Date+, +Time+ and +DateTime+ accepts an optional argument representing the day in which the week is assumed to start. - -* ActiveSupport::Notifications.subscribed provides subscriptions to events while a block runs. - -* Defined new methods Module#qualified_const_defined?, Module#qualified_const_get and Module#qualified_const_set that are analogous to the corresponding methods in the standard API, but accept qualified constant names. - -* Added +#deconstantize+ which complements +#demodulize+ in inflections. This removes the rightmost segment in a qualified constant name. - -* Added safe_constantize that constantizes a string but returns +nil+ instead of raising an exception if the constant (or part of it) does not exist. - -* ActiveSupport::OrderedHash is now marked as extractable when using Array#extract_options!. - -* Added Array#prepend as an alias for Array#unshift and Array#append as an alias for Array#<<. - -* The definition of a blank string for Ruby 1.9 has been extended to Unicode whitespace. Also, in Ruby 1.8 the ideographic space U+3000 is considered to be whitespace. - -* The inflector understands acronyms. - -* Added Time#all_day, Time#all_week, Time#all_quarter and Time#all_year as a way of generating ranges. - - -Event.where(:created_at => Time.now.all_week) -Event.where(:created_at => Time.now.all_day) - - -* Added instance_accessor: false as an option to Class#cattr_accessor and friends. - -* ActiveSupport::OrderedHash now has different behavior for #each and #each_pair when given a block accepting its parameters with a splat. - -* Added ActiveSupport::Cache::NullStore for use in development and testing. - -* Removed ActiveSupport::SecureRandom in favor of SecureRandom from the standard library. - -h4(#activesupport_deprecations). Deprecations - -* +ActiveSupport::Base64+ is deprecated in favor of ::Base64. - -* Deprecated ActiveSupport::Memoizable in favor of Ruby memoization pattern. - -* Module#synchronize is deprecated with no replacement. Please use monitor from ruby's standard library. - -* Deprecated ActiveSupport::MessageEncryptor#encrypt and ActiveSupport::MessageEncryptor#decrypt. - -* ActiveSupport::BufferedLogger#silence is deprecated. If you want to squelch logs for a certain block, change the log level for that block. - -* ActiveSupport::BufferedLogger#open_log is deprecated. This method should not have been public in the first place. - -* ActiveSupport::BufferedLogger's behavior of automatically creating the directory for your log file is deprecated. Please make sure to create the directory for your log file before instantiating. - -* ActiveSupport::BufferedLogger#auto_flushing is deprecated. Either set the sync level on the underlying file handle like this. Or tune your filesystem. The FS cache is now what controls flushing. - - -f = File.open('foo.log', 'w') -f.sync = true -ActiveSupport::BufferedLogger.new f - - -* ActiveSupport::BufferedLogger#flush is deprecated. Set sync on your filehandle, or tune your filesystem. - -h3. Credits - -See the "full list of contributors to Rails":http://contributors.rubyonrails.org/ for the many people who spent many hours making Rails, the stable and robust framework it is. Kudos to all of them. - -Rails 3.2 Release Notes were compiled by "Vijay Dev":https://github.com/vijaydev. -- cgit v1.2.3