diff options
Diffstat (limited to 'guides')
-rw-r--r-- | guides/code/getting_started/test/test_helper.rb | 2 | ||||
-rw-r--r-- | guides/source/4_0_release_notes.textile | 260 | ||||
-rw-r--r-- | guides/source/action_mailer_basics.textile | 31 | ||||
-rw-r--r-- | guides/source/configuring.textile | 2 | ||||
-rw-r--r-- | guides/source/debugging_rails_applications.textile | 2 | ||||
-rw-r--r-- | guides/source/getting_started.textile | 16 | ||||
-rw-r--r-- | guides/source/performance_testing.textile | 6 | ||||
-rw-r--r-- | guides/source/routing.textile | 26 |
8 files changed, 293 insertions, 52 deletions
diff --git a/guides/code/getting_started/test/test_helper.rb b/guides/code/getting_started/test/test_helper.rb index 8bf1192ffe..3daca18a71 100644 --- a/guides/code/getting_started/test/test_helper.rb +++ b/guides/code/getting_started/test/test_helper.rb @@ -3,7 +3,7 @@ require File.expand_path('../../config/environment', __FILE__) require 'rails/test_help' class ActiveSupport::TestCase - # Setup all fixtures in test/fixtures/*.(yml|csv) for all tests in alphabetical order. + # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. # # Note: You'll currently still have to declare fixtures explicitly in integration tests # -- they do not yet inherit this setting diff --git a/guides/source/4_0_release_notes.textile b/guides/source/4_0_release_notes.textile index 23c5220c24..b7ac11999a 100644 --- a/guides/source/4_0_release_notes.textile +++ b/guides/source/4_0_release_notes.textile @@ -64,6 +64,16 @@ h3. Documentation h3. Railties +* Allow scaffold/model/migration generators to accept a <tt>polymorphic</tt> modifier for <tt>references</tt>/<tt>belongs_to</tt>, for instance + +<shell> +rails g model Product supplier:references{polymorphic} +</shell> + +will generate the model with <tt>belongs_to :supplier, polymorphic: true</tt> association and appropriate migration. + +* Set <tt>config.active_record.migration_error</tt> to <tt>:page_load</tt> for development. + * Add runner to <tt>Rails::Railtie</tt> as a hook called just after runner starts. * Add <tt>/rails/info/routes</tt> path which displays the same information as +rake routes+. @@ -102,12 +112,32 @@ h4(#railties_deprecations). Deprecations h3. Action Mailer -* No changes. +* Allow to set default Action Mailer options via <tt>config.action_mailer.default_options=</tt>. + +* Raise an <tt>ActionView::MissingTemplate</tt> exception when no implicit template could be found. + +* Asynchronously send messages via the Rails Queue. h3. Action Pack h4. Action Controller +* Remove Active Model dependency from Action Pack. + +* Support unicode characters in routes. Route will be automatically escaped, so instead of manually escaping: + +<ruby> +get Rack::Utils.escape('こんにちは') => 'home#index' +</ruby> + +You just have to write the unicode route: + +<ruby> +get 'こんにちは' => 'home#index' +</ruby> + +* Return proper format on exceptions. + * Extracted redirect logic from <tt>ActionController::ForceSSL::ClassMethods.force_ssl</tt> into <tt>ActionController::ForceSSL#force_ssl_redirect</tt>. * URL path parameters with invalid encoding now raise <tt>ActionController::BadRequest</tt>. @@ -156,6 +186,8 @@ h5(#actioncontroller_deprecations). Deprecations h4. Action Dispatch +* Include <tt>mounted_helpers</tt> (helpers for accessing mounted engines) in <tt>ActionDispatch::IntegrationTest</tt> by default. + * Added <tt>ActionDispatch::SSL</tt> middleware that when included force all the requests to be under HTTPS protocol. * Copy literal route constraints to defaults so that url generation know about them. The copied constraints are <tt>:protocol</tt>, <tt>:subdomain</tt>, <tt>:domain</tt>, <tt>:host</tt> and <tt>:port</tt>. @@ -179,12 +211,14 @@ If <tt>:patch</tt> is the default verb for updates, edits are tunneled as <tt>PA * Turn off verbose mode of <tt>rack-cache</tt>, we still have <tt>X-Rack-Cache</tt> to check that info. -* Include mounted_helpers (helpers for accessing mounted engines) in <tt>ActionDispatch::IntegrationTest</tt> by default. - h5(#actiondispatch_deprecations). Deprecations h4. Action View +* Remove Active Model dependency from Action Pack. + +* Allow to use <tt>mounted_helpers</tt> (helpers for accessing mounted engines) in <tt>ActionView::TestCase</tt>. + * Make current object and counter (when it applies) variables accessible when rendering templates with <tt>:object</tt> or <tt>:collection</tt>. * Allow to lazy load +default_form_builder+ by passing a string instead of a constant. @@ -205,8 +239,6 @@ h4. Action View * Removed old +text_helper+ apis for +highlight+, +excerpt+ and +word_wrap+. -* Allow to use mounted_helpers (helpers for accessing mounted engines) in <tt>ActionView::TestCase</tt>. - * Remove the leading \n added by textarea on +assert_select+. * Changed default value for <tt>config.action_view.embed_authenticity_token_in_remote_forms</tt> to false. This change breaks remote forms that need to work also without JavaScript, so if you need such behavior, you can either set it to true or explicitly pass <tt>:authenticity_token => true</tt> in form options. @@ -299,6 +331,146 @@ Moved into a separate gem <tt>sprockets-rails</tt>. h3. Active Record +* Add <tt>add_reference</tt> and <tt>remove_reference</tt> schema statements. Aliases, <tt>add_belongs_to</tt> and <tt>remove_belongs_to</tt> are acceptable. References are reversible. + +<ruby> +# Create a user_id column +add_reference(:products, :user) + +# Create a supplier_id, supplier_type columns and appropriate index +add_reference(:products, :supplier, polymorphic: true, index: true) + +# Remove polymorphic reference +remove_reference(:products, :supplier, polymorphic: true) +</ruby> + + +* Add <tt>:default</tt> and <tt>:null</tt> options to <tt>column_exists?</tt>. + +<ruby> +column_exists?(:testings, :taggable_id, :integer, null: false) +column_exists?(:testings, :taggable_type, :string, default: 'Photo') +</ruby> + +* <tt>ActiveRecord::Relation#inspect</tt> now makes it clear that you are dealing with a <tt>Relation</tt> object rather than an array: + +<ruby> +User.where(:age => 30).inspect +# => <ActiveRecord::Relation [#<User ...>, #<User ...>]> + +User.where(:age => 30).to_a.inspect +# => [#<User ...>, #<User ...>] +</ruby> + +if more than 10 items are returned by the relation, inspect will only show the first 10 followed by ellipsis. + +* Add <tt>:collation</tt> and <tt>:ctype</tt> support to PostgreSQL. These are available for PostgreSQL 8.4 or later. + +<yaml> +development: + adapter: postgresql + host: localhost + database: rails_development + username: foo + password: bar + encoding: UTF8 + collation: ja_JP.UTF8 + ctype: ja_JP.UTF8 +</yaml> + +* <tt>FinderMethods#exists?</tt> now returns <tt>false</tt> with the <tt>false</tt> argument. + +* Added support for specifying the precision of a timestamp in the postgresql adapter. So, instead of having to incorrectly specify the precision using the <tt>:limit</tt> option, you may use <tt>:precision</tt>, as intended. For example, in a migration: + +<ruby> +def change + create_table :foobars do |t| + t.timestamps :precision => 0 + end +end +</ruby> + +* Allow <tt>ActiveRecord::Relation#pluck</tt> to accept multiple columns. Returns an array of arrays containing the typecasted values: + +<ruby> +Person.pluck(:id, :name) +# SELECT people.id, people.name FROM people +# => [[1, 'David'], [2, 'Jeremy'], [3, 'Jose']] +</ruby> + +* Improve the derivation of HABTM join table name to take account of nesting. It now takes the table names of the two models, sorts them lexically and then joins them, stripping any common prefix from the second table name. Some examples: + +<plain> +Top level models (Category <=> Product) +Old: categories_products +New: categories_products + +Top level models with a global table_name_prefix (Category <=> Product) +Old: site_categories_products +New: site_categories_products + +Nested models in a module without a table_name_prefix method (Admin::Category <=> Admin::Product) +Old: categories_products +New: categories_products + +Nested models in a module with a table_name_prefix method (Admin::Category <=> Admin::Product) +Old: categories_products +New: admin_categories_products + +Nested models in a parent model (Catalog::Category <=> Catalog::Product) +Old: categories_products +New: catalog_categories_products + +Nested models in different parent models (Catalog::Category <=> Content::Page) +Old: categories_pages +New: catalog_categories_content_pages +</plain> + +* Move HABTM validity checks to <tt>ActiveRecord::Reflection</tt>. One side effect of this is to move when the exceptions are raised from the point of declaration to when the association is built. This is consistant with other association validity checks. + +* Added <tt>stored_attributes</tt> hash which contains the attributes stored using <tt>ActiveRecord::Store</tt>. This allows you to retrieve the list of attributes you've defined. + +<ruby> +class User < ActiveRecord::Base + store :settings, accessors: [:color, :homepage] +end + +User.stored_attributes[:settings] # [:color, :homepage] +</ruby> + +* <tt>composed_of</tt> was removed. You'll have to write your own accessor and mutator methods if you'd like to use value objects to represent some portion of your models. So, instead of: + +<ruby> +class Person < ActiveRecord::Base + composed_of :address, :mapping => [ %w(address_street street), %w(address_city city) ] +end +</ruby> + +you could write something like this: + +<ruby> +def address + @address ||= Address.new(address_street, address_city) +end + +def address=(address) + self[:address_street] = @address.street + self[:address_city] = @address.city + + @address = address +end +</ruby> + +* PostgreSQL default log level is now 'warning', to bypass the noisy notice messages. You can change the log level using the <tt>min_messages</tt> option available in your <tt>config/database.yml</tt>. + +* Add uuid datatype support to PostgreSQL adapter. + +* <tt>update_attribute</tt> has been removed. Use <tt>update_column</tt> if you want to bypass mass-assignment protection, validations, callbacks, and touching of updated_at. Otherwise please use <tt>update_attributes</tt>. + +* Added <tt>ActiveRecord::Migration.check_pending!</tt> that raises an error if migrations are pending. + +* Added <tt>#destroy!</tt> which acts like <tt>#destroy</tt> but will raise an <tt>ActiveRecord::RecordNotDestroyed</tt> exception instead of returning <tt>false</tt>. + * Allow blocks for count with <tt>ActiveRecord::Relation</tt>, to work similar as <tt>Array#count</tt>: <tt>Person.where("age > 26").count { |person| person.gender == 'female' }</tt> * Added support to <tt>CollectionAssociation#delete</tt> for passing fixnum or string values as record ids. This finds the records responding to the ids and deletes them. @@ -355,7 +527,7 @@ Post.find_by! name: 'Spartacus' * Added <tt>ActiveRecord::Base#slice</tt> to return a hash of the given methods with their names as keys and returned values as values. -* Remove IdentityMap - IdentityMap has never graduated to be an "enabled-by-default" feature, due to some inconsistencies with associations, as described in this commit: https://github.com/rails/rails/commit/302c912bf6bcd0fa200d964ec2dc4a44abe328a6. Hence the removal from the codebase, until such issues are fixed. +* Remove IdentityMap - IdentityMap has never graduated to be an "enabled-by-default" feature, due to some inconsistencies with associations, as described in this "commit":https://github.com/rails/rails/commit/302c912bf6bcd0fa200d964ec2dc4a44abe328a6. Hence the removal from the codebase, until such issues are fixed. * Added a feature to dump/load internal state of +SchemaCache+ instance because we want to boot more quickly when we have many models. @@ -475,27 +647,37 @@ The code to implement the deprecated features has been moved out to the +active_ Don't use this: - scope :red, where(color: 'red') - default_scope where(color: 'red') +<ruby> +scope :red, where(color: 'red') +default_scope where(color: 'red') +</ruby> Use this: - scope :red, -> { where(color: 'red') } - default_scope { where(color: 'red') } +<ruby> +scope :red, -> { where(color: 'red') } +default_scope { where(color: 'red') } +</ruby> The former has numerous issues. It is a common newbie gotcha to do the following: - scope :recent, where(published_at: Time.now - 2.weeks) +<ruby> +scope :recent, where(published_at: Time.now - 2.weeks) +</ruby> Or a more subtle variant: - scope :recent, -> { where(published_at: Time.now - 2.weeks) } - scope :recent_red, recent.where(color: 'red') +<ruby> +scope :recent, -> { where(published_at: Time.now - 2.weeks) } +scope :recent_red, recent.where(color: 'red') +</ruby> Eager scopes are also very complex to implement within Active Record, and there are still bugs. For example, the following does not do what you expect: - scope :remove_conditions, except(:where) - where(...).remove_conditions # => still has conditions +<ruby> +scope :remove_conditions, except(:where) +where(...).remove_conditions # => still has conditions +</ruby> * Added deprecation for the :dependent => :restrict association option. @@ -507,6 +689,32 @@ The code to implement the deprecated features has been moved out to the +active_ h3. Active Model +* Changed <tt>AM::Serializers::JSON.include_root_in_json</tt> default value to false. Now, AM Serializers and AR objects have the same default behaviour. + +<ruby> +class User < ActiveRecord::Base; end + +class Person + include ActiveModel::Model + include ActiveModel::AttributeMethods + include ActiveModel::Serializers::JSON + + attr_accessor :name, :age + + def attributes + instance_values + end +end + +user.as_json +=> {"id"=>1, "name"=>"Konata Izumi", "age"=>16, "awesome"=>true} +# root is not included + +person.as_json +=> {"name"=>"Francesco", "age"=>22} +# root is not included +</ruby> + * Passing false hash values to +validates+ will no longer enable the corresponding validators. * +ConfirmationValidator+ error messages will attach to <tt>:#{attribute}_confirmation</tt> instead of +attribute+. @@ -521,10 +729,28 @@ h4(#activemodel_deprecations). Deprecations h3. Active Resource -* Active Resource is removed from Rails 4.0 and is now a separate gem. TODO: put a link to the gem here. +* Active Resource is removed from Rails 4.0 and is now a separate "gem":https://github.com/rails/activeresource. h3. Active Support +* <tt>Time#change</tt> now works with time values with offsets other than UTC or the local time zone. + +* Add <tt>Time#prev_quarter</tt> and <tt>Time#next_quarter</tt> short-hands for <tt>months_ago(3)</tt> and <tt>months_since(3)</tt>. + +* Remove obsolete and unused <tt>require_association</tt> method from dependencies. + +* Add <tt>:instance_accessor</tt> option for <tt>config_accessor</tt>. + +<ruby> +class User + include ActiveSupport::Configurable + config_accessor :allowed_access, instance_accessor: false +end + +User.new.allowed_access = true # => NoMethodError +User.new.allowed_access # => NoMethodError +</ruby> + * <tt>ActionView::Helpers::NumberHelper</tt> methods have been moved to <tt>ActiveSupport::NumberHelper</tt> and are now available via <tt>Numeric#to_s</tt>. * <tt>Numeric#to_s</tt> now accepts the formatting options :phone, :currency, :percentage, :delimited, :rounded, :human, and :human_size. @@ -575,6 +801,8 @@ h3. Active Support h4(#activesupport_deprecations). Deprecations +* <tt>ActiveSupport::Callbacks</tt>: deprecate usage of filter object with <tt>#before</tt> and <tt>#after</tt> methods as <tt>around</tt> callback. + * <tt>BufferedLogger</tt> is deprecated. Use <tt>ActiveSupport::Logger</tt> or the +logger+ from Ruby stdlib. * Deprecates the compatibility method <tt>Module#local_constant_names</tt> and use <tt>Module#local_constants</tt> instead (which returns symbols). diff --git a/guides/source/action_mailer_basics.textile b/guides/source/action_mailer_basics.textile index ebe774fbef..7c61cc4a8d 100644 --- a/guides/source/action_mailer_basics.textile +++ b/guides/source/action_mailer_basics.textile @@ -457,6 +457,7 @@ The following configuration options are best made in one of the environment file |+delivery_method+|Defines a delivery method. Possible values are <tt>:smtp</tt> (default), <tt>:sendmail</tt>, <tt>:file</tt> and <tt>:test</tt>.| |+perform_deliveries+|Determines whether deliveries are actually carried out when the +deliver+ method is invoked on the Mail message. By default they are, but this can be turned off to help functional testing.| |+deliveries+|Keeps an array of all the emails sent out through the Action Mailer with delivery_method :test. Most useful for unit and functional testing.| +|+async+|Setting this flag will turn on asynchronous message sending, message rendering and delivery will be pushed to <tt>Rails.queue</tt> for processing.| h4. Example Action Mailer Configuration @@ -514,3 +515,33 @@ end </ruby> In the test we send the email and store the returned object in the +email+ variable. We then ensure that it was sent (the first assert), then, in the second batch of assertions, we ensure that the email does indeed contain what we expect. + +h3. Asynchronous + +You can turn on application-wide asynchronous message sending by adding to your <tt>config/application.rb</tt> file: + +<ruby> +config.action_mailer.async = true +</ruby> + +Alternatively you can turn on async within specific mailers: + +<ruby> +class WelcomeMailer < ActionMailer::Base + self.async = true +end +</ruby> + +h4. Custom Queues + +If you need a different queue than <tt>Rails.queue</tt> for your mailer you can override <tt>ActionMailer::Base#queue</tt>: + +<ruby> +class WelcomeMailer < ActionMailer::Base + def queue + MyQueue.new + end +end +</ruby> + +Your custom queue should expect a job that responds to <tt>#run</tt>. diff --git a/guides/source/configuring.textile b/guides/source/configuring.textile index af46538bf5..cd9aab4892 100644 --- a/guides/source/configuring.textile +++ b/guides/source/configuring.textile @@ -424,7 +424,7 @@ There are a number of settings available on +config.action_mailer+: * +config.action_mailer.perform_deliveries+ specifies whether mail will actually be delivered and is true by default. It can be convenient to set it to false for testing. -* +config.action_mailer.default+ configures Action Mailer defaults. These default to: +* +config.action_mailer.default_options+ configures Action Mailer defaults. Use to set options like `from` or `reply_to` for every mailer. These default to: <ruby> :mime_version => "1.0", :charset => "UTF-8", diff --git a/guides/source/debugging_rails_applications.textile b/guides/source/debugging_rails_applications.textile index 0802a2db26..cc172042e9 100644 --- a/guides/source/debugging_rails_applications.textile +++ b/guides/source/debugging_rails_applications.textile @@ -102,7 +102,7 @@ It can also be useful to save information to log files at runtime. Rails maintai h4. What is the Logger? -Rails makes use of Ruby's standard +logger+ to write log information. You can also substitute another logger such as +Log4r+ if you wish. +Rails makes use of the +ActiveSupport::BufferedLogger+ class to write log information. You can also substitute another logger such as +Log4r+ if you wish. You can specify an alternative logger in your +environment.rb+ or any environment file: diff --git a/guides/source/getting_started.textile b/guides/source/getting_started.textile index f25e0c0200..07419d11b4 100644 --- a/guides/source/getting_started.textile +++ b/guides/source/getting_started.textile @@ -20,13 +20,7 @@ application from scratch. It does not assume that you have any prior experience with Rails. However, to get the most out of it, you need to have some prerequisites installed: -* The "Ruby":http://www.ruby-lang.org/en/downloads language version 1.8.7 or higher - -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 or -1.9.3 for smooth sailing. +* The "Ruby":http://www.ruby-lang.org/en/downloads language version 1.9.3 or higher * The "RubyGems":http://rubyforge.org/frs/?group_id=126 packaging system ** If you want to learn more about RubyGems, please read the "RubyGems User Guide":http://docs.rubygems.org/read/book/1 @@ -216,12 +210,12 @@ You need to do this because Rails will serve any static file in the +public+ dir Next, you have to tell Rails where your actual home page is located. -Open the file +config/routes.rb+ in your editor. +Open the file +config/routes.rb+ in your editor. <ruby> Blog::Application.routes.draw do get "welcome/index" - + # The priority is based upon order of creation: # first created -> highest priority. # ... @@ -906,7 +900,7 @@ end </ruby> The new method, +update_attributes+, is used when you want to update a record -that already exists, and it accepts an hash containing the attributes +that already exists, and it accepts a hash containing the attributes that you want to update. As before, if there was an error updating the post we want to show the form back to the user. @@ -1191,7 +1185,7 @@ delete "posts/:id" => "posts#destroy" That's a lot to type for covering a single *resource*. Fortunately, Rails provides a +resources+ method which can be used to declare a -standard REST resource. Here's how +config/routes/rb+ looks after the +standard REST resource. Here's how +config/routes.rb+ looks after the cleanup: <ruby> diff --git a/guides/source/performance_testing.textile b/guides/source/performance_testing.textile index 958b13cd9e..982fd1b070 100644 --- a/guides/source/performance_testing.textile +++ b/guides/source/performance_testing.textile @@ -524,11 +524,11 @@ Please refer to the "API docs":http://api.rubyonrails.org/classes/ActiveRecord/B h4. Controller -Similarly, you could use this helper method inside "controllers":http://api.rubyonrails.org/classes/ActionController/Benchmarking/ClassMethods.html#M000715 +Similarly, you could use this helper method inside "controllers":http://api.rubyonrails.org/classes/ActiveSupport/Benchmarkable.html <ruby> def process_projects - self.class.benchmark("Processing projects") do + benchmark("Processing projects") do Project.process(params[:project_ids]) Project.update_cached_projects end @@ -539,7 +539,7 @@ NOTE: +benchmark+ is a class method inside controllers h4. View -And in "views":http://api.rubyonrails.org/classes/ActionController/Benchmarking/ClassMethods.html#M000715: +And in "views":http://api.rubyonrails.org/classes/ActiveSupport/Benchmarkable.html: <erb> <% benchmark("Showing projects partial") do %> diff --git a/guides/source/routing.textile b/guides/source/routing.textile index dae25853cd..cffbf9bec4 100644 --- a/guides/source/routing.textile +++ b/guides/source/routing.textile @@ -32,7 +32,13 @@ the request is dispatched to the +patients+ controller's +show+ action with <tt> h4. Generating Paths and URLs from Code -You can also generate paths and URLs. If your application contains this code: +You can also generate paths and URLs. If the route above is modified to be + +<ruby> +get "/patients/:id" => "patients#show", :as => "patient" +</ruby> + +If your application contains this code: <ruby> @patient = Patient.find(17) @@ -845,24 +851,6 @@ end This will create routing helpers such as +magazine_periodical_ads_url+ and +edit_magazine_periodical_ad_path+. -h3. Breaking Up a Large Route File - -If you have a large route file that you would like to break up into multiple files, you can use the +#draw+ method in your router: - -<ruby> -draw :admin -</ruby> - -Then, create a file called +config/routes/admin.rb+. Name the file the same as the symbol passed to the +draw+ method. You can then use the normal routing DSL inside that file: - -<ruby> -# in config/routes/admin.rb - -namespace :admin do - resources :posts -end -</ruby> - h3. Inspecting and Testing Routes Rails offers facilities for inspecting and testing your routes. |