diff options
Diffstat (limited to 'railties')
48 files changed, 1163 insertions, 288 deletions
diff --git a/railties/README.rdoc b/railties/README.rdoc index 0457227473..eb7ed961e3 100644 --- a/railties/README.rdoc +++ b/railties/README.rdoc @@ -11,7 +11,7 @@ Railties is responsible to glue all frameworks together. Overall, it: == Download -The latest version of Railties can be installed with Rubygems: +The latest version of Railties can be installed with RubyGems: * gem install railties diff --git a/railties/guides/rails_guides/generator.rb b/railties/guides/rails_guides/generator.rb index d304512ff7..4682ead66e 100644 --- a/railties/guides/rails_guides/generator.rb +++ b/railties/guides/rails_guides/generator.rb @@ -199,50 +199,10 @@ module RailsGuides end def textile(body, lite_mode=false) - # If the issue with notextile is fixed just remove the wrapper. - with_workaround_for_notextile(body) do |body| - t = RedCloth.new(body) - t.hard_breaks = false - t.lite_mode = lite_mode - t.to_html(:notestuff, :plusplus, :code) - end - end - - # For some reason the notextile tag does not always turn off textile. See - # LH ticket of the security guide (#7). As a temporary workaround we deal - # with code blocks by hand. - def with_workaround_for_notextile(body) - code_blocks = [] - - body.gsub!(%r{<(yaml|shell|ruby|erb|html|sql|plain)>(.*?)</\1>}m) do |m| - brush = case $1 - when 'ruby', 'sql', 'plain' - $1 - when 'erb' - 'ruby; html-script: true' - when 'html' - 'xml' # html is understood, but there are .xml rules in the CSS - else - 'plain' - end - - code_blocks.push(<<HTML) -<notextile> -<div class="code_container"> -<pre class="brush: #{brush}; gutter: false; toolbar: false"> -#{ERB::Util.h($2).strip} -</pre> -</div> -</notextile> -HTML - "\ndirty_workaround_for_notextile_#{code_blocks.size - 1}\n" - end - - body = yield body - - body.gsub(%r{<p>dirty_workaround_for_notextile_(\d+)</p>}) do |_| - code_blocks[$1.to_i] - end + t = RedCloth.new(body) + t.hard_breaks = false + t.lite_mode = lite_mode + t.to_html(:notestuff, :plusplus, :code) end def warn_about_broken_links(html) diff --git a/railties/guides/rails_guides/textile_extensions.rb b/railties/guides/rails_guides/textile_extensions.rb index b3e0e32357..4677fae504 100644 --- a/railties/guides/rails_guides/textile_extensions.rb +++ b/railties/guides/rails_guides/textile_extensions.rb @@ -33,11 +33,30 @@ module RailsGuides body.gsub!('<plus>', '+') end + def brush_for(code_type) + case code_type + when 'ruby', 'sql', 'plain' + code_type + when 'erb' + 'ruby; html-script: true' + when 'html' + 'xml' # html is understood, but there are .xml rules in the CSS + else + 'plain' + end + end + def code(body) body.gsub!(%r{<(yaml|shell|ruby|erb|html|sql|plain)>(.*?)</\1>}m) do |m| - es = ERB::Util.h($2) - css_class = $1.in?(['erb', 'shell']) ? 'html' : $1 - %{<notextile><div class="code_container"><code class="#{css_class}">#{es}</code></div></notextile>} + <<HTML +<notextile> +<div class="code_container"> +<pre class="brush: #{brush_for($1)}; gutter: false; toolbar: false"> +#{ERB::Util.h($2).strip} +</pre> +</div> +</notextile> +HTML end end end diff --git a/railties/guides/source/3_0_release_notes.textile b/railties/guides/source/3_0_release_notes.textile index fbb684978a..d22c76dd81 100644 --- a/railties/guides/source/3_0_release_notes.textile +++ b/railties/guides/source/3_0_release_notes.textile @@ -59,12 +59,12 @@ The +config.gem+ method is gone and has been replaced by using +bundler+ and a + h4. Upgrade Process -To help with the upgrade process, a plugin named "Rails Upgrade":http://github.com/jm/rails_upgrade has been created to automate part of it. +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: <shell> -$ ruby script/plugin install git://github.com/jm/rails_upgrade.git +$ ruby script/plugin install git://github.com/rails/rails_upgrade.git </shell> 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 diff --git a/railties/guides/source/3_1_release_notes.textile b/railties/guides/source/3_1_release_notes.textile new file mode 100644 index 0000000000..087926f98d --- /dev/null +++ b/railties/guides/source/3_1_release_notes.textile @@ -0,0 +1,429 @@ +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. + +h3. Creating a Rails 3.1 application + +<shell> +# You should have the 'rails' rubygem installed +$ rails new myapp +$ cd myapp +</shell> + +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: + +<shell> +$ rails new myapp --edge +</shell> + +If you have a local checkout of the Rails repository and want to generate an application using that, you can pass the +--dev+ flag: + +<shell> +$ ruby /path/to/rails/bin/rails new myapp --dev +</shell> + +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. + +<shell> +$ rails new myapp -j prototype +</shell> + +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 <tt>Rack::SSL</tt> 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 <tt>Rack::Etag</tt> and <tt>Rack::ConditionalGet</tt> to the default middleware stack. + +* Added <tt>Rack::Cache</tt> 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 <tt>config.filter_parameters</tt> 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 <tt>ActionController::ParamsWrapper</tt> 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 <tt>config/initializers/wrap_parameters.rb</tt>. + +* Added <tt>config.action_controller.include_all_helpers</tt>. By default <tt>helper :all</tt> is done in <tt>ActionController::Base</tt>, 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. + +<ruby> +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 +</ruby> + +..can now be written as + +<ruby> +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 +</ruby> + +* Added streaming support, you can enable it with: + +<ruby> +class PostsController < ActionController::Base + stream +end +</ruby> + +You can restrict it to some actions by using +:only+ or +:except+. Please read the docs at "<tt>ActionController::Streaming</tt>":http://edgeapi.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 + +* <tt>config.action_dispatch.x_sendfile_header</tt> now defaults to +nil+ and <tt>config/environments/production.rb</tt> doesn't set any particular value for it. This allows servers to set it through <tt>X-Sendfile-Type</tt>. + +* <tt>ActionDispatch::MiddlewareStack</tt> now uses composition over inheritance and is no longer an array. + +* Added <tt>ActionDispatch::Request.ignore_accept_header</tt> to ignore accept headers. + +* Added <tt>Rack::Cache</tt> to the default stack. + +* Moved etag responsibility from <tt>ActionDispatch::Response</tt> to the middleware stack. + +* Rely on <tt>Rack::Session</tt> stores API for more compatibility across the Ruby world. This is backwards incompatible since <tt>Rack::Session</tt> expects <tt>#get_session</tt> to accept four arguments and requires <tt>#destroy_session</tt> instead of simply <tt>#destroy</tt>. + +* 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 <tt>:authenticity_token => false</tt>. + +* Created <tt>ActionView::Renderer</tt> and specified an API for <tt>ActionView::Context</tt>. + +* In place +SafeBuffer+ mutation is prohibited in Rails 3.1. + +* Added HTML5 +button_tag+ helper. + +* +file_field+ automatically adds <tt>:multipart => true</tt> to the enclosing form. + +* Added a convenience idiom to generate HTML5 data-* attributes in tag helpers from a +:data+ hash of options: + +<plain> +tag("div", :data => {:name => 'Stephen', :city_state => %w(Chicago IL)}) +# => <div data-name="Stephen" data-city-state="["Chicago","IL"]" /> +</plain> + +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. + +* <tt>config.action_view.cache_template_loading</tt> 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 <tt>FormHelper#form_for</tt> to specify the +:method+ as a direct option instead of through the +:html+ hash. <tt>form_for(==@==post, remote: true, method: :delete)</tt> instead of <tt>form_for(==@==post, remote: true, html: { method: :delete })</tt>. + +* Provided <tt>JavaScriptHelper#j()</tt> as an alias for <tt>JavaScriptHelper#escape_javascript()</tt>. This supersedes the <tt>Object#j()</tt> 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 <tt>pluralize_table_names</tt> to singularize/pluralize table names of individual models. Previously this could only be set globally for all models through <tt>ActiveRecord::Base.pluralize_table_names</tt>. +<ruby> +class User < ActiveRecord::Base + self.pluralize_table_names = false +end +</ruby> + +* Added block setting of attributes to singular associations. The block will get called after the instance is initialized. + +<ruby> +class User < ActiveRecord::Base + has_one :account +end + +user.build_account{ |a| a.credit_limit => 100.0 } +</ruby> + +* Added <tt>ActiveRecord::Base.attribute_names</tt> 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. + +* <tt>ActiveRecord#new</tt>, <tt>ActiveRecord#create</tt> and <tt>ActiveRecord#update_attributes</tt> 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: + +<ruby> +class Post < ActiveRecord::Base + attr_accessible :title + attr_accessible :title, :published_at, :as => :admin +end + +Post.new(params[:post], :as => :admin) +</ruby> + +* +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_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 <tt>ActiveRecord::Base.connection_config</tt>. + +* limits and offsets are removed from COUNT queries unless both are supplied. +<ruby> +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' +</ruby> + +* <tt>ActiveRecord::Associations::AssociationProxy</tt> 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 <tt>:dependent</tt> option on <tt>has_many :through</tt> associations. For historical and practical reasons, +:delete_all+ is the default deletion strategy employed by <tt>association.delete(*records)</tt>, 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 <tt>has_many :through</tt> 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, <tt>has_and_belongs_to_many.destroy(*records)</tt> 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, <tt>has_many_through.destroy(*records)</tt> 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 <tt>records.association.each(&:destroy)</tt>. + +* Add <tt>:bulk => true</tt> option to +change_table+ to make all the schema changes defined in a block using a single ALTER statement. + +<ruby> +change_table(:users, :bulk => true) do |t| + t.string :company_name + t.change :birthdate, :datetime +end +</ruby> + +* Removed support for accessing attributes on a +has_and_belongs_to_many+ join table. <tt>has_many :through</tt> 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. +<ruby> +class MyMigration < ActiveRecord::Migration + def change + create_table(:horses) do + t.column :content, :text + t.column :remind_at, :datetime + end + end +end +</ruby> + +* 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: +<ruby> +class FooMigration < ActiveRecord::Migration + def up # Not self.up + ... + end +end +</ruby> + +* 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. + +<ruby> +has_many :things, :conditions => 'foo = #{bar}' # before +has_many :things, :conditions => proc { "foo = #{bar}" } # after +</ruby> + +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: +<ruby> +has_many :things, :conditions => proc { ["foo = ?", bar] } +</ruby> + +* 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 <tt>ActiveRecord::Base#has_secure_password</tt> (via <tt>ActiveModel::SecurePassword</tt>) to encapsulate dead-simple password usage with BCrypt encryption and salting. +<ruby> +# Schema: User(name:string, password_digest:string, password_salt:string) +class User < ActiveRecord::Base + has_secure_password +end +</ruby> + +* 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. + +* <tt>ActiveRecord::Base#dup</tt> and <tt>ActiveRecord::Base#clone</tt> semantics have changed to closer match normal Ruby dup and clone semantics. + +* Calling <tt>ActiveRecord::Base#clone</tt> will result in a shallow copy of the record, including copying the frozen state. No callbacks will be called. + +* Calling <tt>ActiveRecord::Base#dup</tt> 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 <tt>new_record?</tt>, 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 <tt>ActiveModel::SecurePassword</tt> to encapsulate dead-simple password usage with BCrypt encryption and salting. + +* <tt>ActiveModel::AttributeMethods</tt> allows attributes to be defined on demand. + +* Added support for selectively enabling and disabling observers. + +* Alternate <tt>I18n</tt> 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 <tt>self.format = :xml</tt> in the class. For example, + +<ruby> +class User < ActiveResource::Base + self.format = :xml +end +</ruby> + +h3. Active Support + +* <tt>ActiveSupport::Dependencies</tt> now raises +NameError+ if it finds an existing constant in +load_missing_constant+. + +* Added a new reporting method <tt>Kernel#quietly</tt> which silences both +STDOUT+ and +STDERR+. + +* Added <tt>String#inquiry</tt> as a convenience method for turning a String into a +StringInquirer+ object. + +* Added <tt>Object#in?</tt> to test if an object is included in another object. + +* +LocalCache+ strategy is now a real middleware class and no longer an anonymous class. + +* <tt>ActiveSupport::Dependencies::ClassCache</tt> class has been introduced for holding references to reloadable classes. + +* <tt>ActiveSupport::Dependencies::Reference</tt> has been refactored to take direct advantage of the new +ClassCache+. + +* Backports <tt>Range#cover?</tt> as an alias for <tt>Range#include?</tt> in Ruby 1.8. + +* Added +weeks_ago+ and +prev_week+ to Date/DateTime/Time. + +* Added +before_remove_const+ callback to <tt>ActiveSupport::Dependencies.remove_unloadable_constants!</tt>. + +Deprecations: + +* <tt>ActiveSupport::SecureRandom</tt> 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/railties/guides/source/action_mailer_basics.textile b/railties/guides/source/action_mailer_basics.textile index f05d9dcf1c..142b9dba7e 100644 --- a/railties/guides/source/action_mailer_basics.textile +++ b/railties/guides/source/action_mailer_basics.textile @@ -8,7 +8,7 @@ WARNING. This Guide is based on Rails 3.0. Some of the code shown here will not h3. Introduction -Action Mailer allows you to send emails from your application using a mailer model and views. So, in Rails, emails are used by creating mailers that inherit from +ActionMailer::Base+ and live in +app/mailers+. Those mailers have associated views that appear alongside controller views in +app/views+. +Action Mailer allows you to send emails from your application using a mailer model and views. So, in Rails, emails are used by creating mailers that inherit from +ActionMailer::Base+ and live in +app/mailers+. Those mailers have associated views that appear alongside controller views in +app/views+. h3. Sending Emails @@ -48,10 +48,8 @@ class UserMailer < ActionMailer::Base def welcome_email(user) @user = user @url = "http://example.com/login" - mail(:to => user.email, - :subject => "Welcome to My Awesome Site") + mail(:to => user.email, :subject => "Welcome to My Awesome Site") end - end </ruby> @@ -142,17 +140,17 @@ end This provides a much simpler implementation that does not require the registering of observers and the like. -The method +welcome_email+ returns a Mail::Message object which can then just be told +deliver+ to send itself out. +The method +welcome_email+ returns a <tt>Mail::Message</tt> object which can then just be told +deliver+ to send itself out. NOTE: In previous versions of Rails, you would call +deliver_welcome_email+ or +create_welcome_email+. This has been deprecated in Rails 3.0 in favour of just calling the method name itself. -WARNING: Sending out one email should only take a fraction of a second, if you are planning on sending out many emails, or you have a slow domain resolution service, you might want to investigate using a background process like delayed job. +WARNING: Sending out an email should only take a fraction of a second, but if you are planning on sending out many emails, or you have a slow domain resolution service, you might want to investigate using a background process like Delayed Job. h4. Auto encoding header values Action Mailer now handles the auto encoding of multibyte characters inside of headers and bodies. -If you are using UTF-8 as your character set, you do not have to do anything special, just go ahead and send in UTF-8 data to the address fields, subject, keywords, filenames or body of the email and ActionMailer will auto encode it into quoted printable for you in the case of a header field or Base64 encode any body parts that are non US-ASCII. +If you are using UTF-8 as your character set, you do not have to do anything special, just go ahead and send in UTF-8 data to the address fields, subject, keywords, filenames or body of the email and Action Mailer will auto encode it into quoted printable for you in the case of a header field or Base64 encode any body parts that are non US-ASCII. For more complex examples such as defining alternate character sets or self encoding text first, please refer to the Mail library. @@ -213,7 +211,7 @@ NOTE: If you specify an encoding, Mail will assume that your content is already h5. Making Inline Attachments -ActionMailer 3.0 makes inline attachments, which involved a lot of hacking in pre 3.0 versions, much simpler and trivial as they should be. +Action Mailer 3.0 makes inline attachments, which involved a lot of hacking in pre 3.0 versions, much simpler and trivial as they should be. * Firstly, to tell Mail to turn an attachment into an inline attachment, you just call <tt>#inline</tt> on the attachments method within your Mailer: @@ -242,32 +240,33 @@ end h5. Sending Email To Multiple Recipients -It is possible to send email to one or more recipients in one email (for e.g. informing all admins of a new signup) by setting the list of emails to the <tt>:to</tt> key. The <tt>to:</tt> key however expects a string so you have join the list of recipients using a comma. +It is possible to send email to one or more recipients in one email (for e.g. informing all admins of a new signup) by setting the list of emails to the <tt>:to</tt> key. The list of emails can be an array of email addresses or a single string with the addresses separated by commas. <ruby> - class AdminMailer < ActionMailer::Base - default :to => Admin.all.map(&:email).join(", "), - :from => "notification@example.com" +class AdminMailer < ActionMailer::Base + default :to => Admin.all.map(&:email), + :from => "notification@example.com" - def new_registration(user) - @user = user - mail(:subject => "New User Signup: #{@user.email}") - end + def new_registration(user) + @user = user + mail(:subject => "New User Signup: #{@user.email}") end +end </ruby> +The same format can be used to set carbon copy (Cc:) and blind carbon copy (Bcc:) recipients, by using the <tt>:cc</tt> and <tt>:bcc</tt> keys respectively. + h5. Sending Email With Name Sometimes you wish to show the name of the person instead of just their email address when they receive the email. The trick to doing that is to format the email address in the format <tt>"Name <email>"</tt>. <ruby> - def welcome_email(user) - @user = user - email_with_name = "#{@user.name} <#{@user.email}>" - mail(:to => email_with_name, - :subject => "Welcome to My Awesome Site") - end +def welcome_email(user) + @user = user + email_with_name = "#{@user.name} <#{@user.email}>" + mail(:to => email_with_name, :subject => "Welcome to My Awesome Site") +end </ruby> h4. Mailer Views @@ -287,9 +286,7 @@ class UserMailer < ActionMailer::Base :subject => "Welcome to My Awesome Site", :template_path => 'notifications', :template_name => 'another') - end end - end </ruby> @@ -404,7 +401,7 @@ Will put the HTML part first, and the plain text part second. h4. Sending Emails with Attachments -Attachments can be added by using the +attachment+ method: +Attachments can be added by using the +attachments+ method: <ruby> class UserMailer < ActionMailer::Base @@ -459,14 +456,14 @@ h3. Action Mailer Configuration The following configuration options are best made in one of the environment files (environment.rb, production.rb, etc...) -|template_root|Determines the base from which template references will be made.| -|logger|Generates information on the mailing run if available. Can be set to nil for no logging. Compatible with both Ruby's own Logger and Log4r loggers.| -|smtp_settings|Allows detailed configuration for :smtp delivery method:<ul><li>:address - Allows you to use a remote mail server. Just change it from its default "localhost" setting.</li><li>:port - On the off chance that your mail server doesn't run on port 25, you can change it.</li><li>:domain - If you need to specify a HELO domain, you can do it here.</li><li>:user_name - If your mail server requires authentication, set the username in this setting.</li><li>:password - If your mail server requires authentication, set the password in this setting.</li><li>:authentication - If your mail server requires authentication, you need to specify the authentication type here. This is a symbol and one of :plain, :login, :cram_md5.</li></ul>| -|sendmail_settings|Allows you to override options for the :sendmail delivery method.<ul><li>:location - The location of the sendmail executable. Defaults to /usr/sbin/sendmail.</li><li>:arguments - The command line arguments to be passed to sendmail. Defaults to -i -t.</li></ul>| -|raise_delivery_errors|Whether or not errors should be raised if the email fails to be delivered.| -|delivery_method|Defines a delivery method. Possible values are :smtp (default), :sendmail, :file and :test.| -|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.| +|+template_root+|Determines the base from which template references will be made.| +|+logger+|Generates information on the mailing run if available. Can be set to +nil+ for no logging. Compatible with both Ruby's own +Logger+ and +Log4r+ loggers.| +|+smtp_settings+|Allows detailed configuration for <tt>:smtp</tt> delivery method:<ul><li><tt>:address</tt> - Allows you to use a remote mail server. Just change it from its default "localhost" setting.</li><li><tt>:port</tt> - On the off chance that your mail server doesn't run on port 25, you can change it.</li><li><tt>:domain</tt> - If you need to specify a HELO domain, you can do it here.</li><li><tt>:user_name</tt> - If your mail server requires authentication, set the username in this setting.</li><li><tt>:password</tt> - If your mail server requires authentication, set the password in this setting.</li><li><tt>:authentication</tt> - If your mail server requires authentication, you need to specify the authentication type here. This is a symbol and one of <tt>:plain</tt>, <tt>:login</tt>, <tt>:cram_md5</tt>.</li></ul>| +|+sendmail_settings+|Allows you to override options for the <tt>:sendmail</tt> delivery method.<ul><li><tt>:location</tt> - The location of the sendmail executable. Defaults to <tt>/usr/sbin/sendmail</tt>.</li><li><tt>:arguments</tt> - The command line arguments to be passed to sendmail. Defaults to <tt>-i -t</tt>.</li></ul>| +|+raise_delivery_errors+|Whether or not errors should be raised if the email fails to be delivered.| +|+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.| h4. Example Action Mailer Configuration diff --git a/railties/guides/source/action_view_overview.textile b/railties/guides/source/action_view_overview.textile index d40e0840ce..5a1e8b1247 100644 --- a/railties/guides/source/action_view_overview.textile +++ b/railties/guides/source/action_view_overview.textile @@ -478,7 +478,6 @@ javascript_include_tag :monkey # => <script type="text/javascript" src="/javascripts/tail.js"></script> </ruby> - h5. register_stylesheet_expansion Register one or more stylesheet files to be included when symbol is passed to +stylesheet_link_tag+. This method is typically intended to be called from plugin initialization to register stylesheet files that the plugin installed in +public/stylesheets+. diff --git a/railties/guides/source/active_model_basics.textile b/railties/guides/source/active_model_basics.textile new file mode 100644 index 0000000000..3c19fb5177 --- /dev/null +++ b/railties/guides/source/active_model_basics.textile @@ -0,0 +1,204 @@ +h2. Active Model Basics + +This guide should provide you with all you need to get started using model classes. Active Model allow for Action Pack helpers to interact with non-ActiveRecord models. Active Model also helps building custom ORMs for use outside of the Rails framework. + +endprologue. + +WARNING. This Guide is based on Rails 3.0. Some of the code shown here will not work in earlier versions of Rails. + +h3. Introduction + +Active Model is a library containing various modules used in developing frameworks that need to interact with the Rails Action Pack library. Active Model provides a known set of interfaces for usage in classes. Some of modules are explained below - + +h4. AttributeMethods + +AttributeMethods module can add custom prefixes and suffixes on methods of a class. It is used by defining the prefixes and suffixes, which methods on the object will use them. + +<ruby> +class Person + include ActiveModel::AttributeMethods + + attribute_method_prefix 'reset_' + attribute_method_suffix '_highest?' + define_attribute_methods ['age'] + + attr_accessor :age + +private + def reset_attribute(attribute) + send("#{attribute}=", 0) + end + + def attribute_highest?(attribute) + send(attribute) > 100 ? true : false + end + +end + +person = Person.new +person.age = 110 +person.age_highest? # true +person.reset_age # 0 +person.age_highest? # false + +</ruby> + +h4. Callbacks + +Callbacks gives Active Record style callbacks. This provides the ability to define the callbacks and those will run at appropriate time. After defining a callbacks you can wrap with before, after and around custom methods. + +<ruby> +class Person + extend ActiveModel::Callbacks + + define_model_callbacks :update + + before_update :reset_me + + def update + _run_update_callbacks do + # This will call when we are trying to call update on object. + end + end + + def reset_me + # This method will call when you are calling update on object as a before_update callback as defined. + end +end +</ruby> + +h4. Conversion + +If a class defines persisted? and id methods then you can include Conversion module in that class and you can able to call Rails conversion methods to objects of that class. + +<ruby> +class Person + include ActiveModel::Conversion + + def persisted? + false + end + + def id + nil + end +end + +person = Person.new +person.to_model == person #=> true +person.to_key #=> nil +person.to_param #=> nil +</ruby> + +h4. Dirty + +An object becomes dirty when an object is gone through one or more changes to its attributes and not yet saved. This gives the ability to check whether an object has been changed or not. It also has attribute based accessor methods. Lets consider a Person class with attributes first_name and last_name + +<ruby> +require 'rubygems' +require 'active_model' + +class Person + include ActiveModel::Dirty + define_attribute_methods [:first_name, :last_name] + + def first_name + @first_name + end + + def first_name=(value) + first_name_will_change! + @first_name = value + end + + def last_name + @last_name + end + + def last_name=(value) + last_name_will_change! + @last_name = value + end + + def save + @previously_changed = changes + end + +end +</ruby> + +h5. Querying object directly for its list of all changed attributes. + +<ruby> +person = Person.new +person.first_name = "First Name" + +person.first_name #=> "First Name" +person.first_name = "First Name Changed" + +person.changed? #=> true + +#returns an list of fields arry which all has been changed before saved. +person.changed #=> ["first_name"] + +#returns a hash of the fields that have changed with their original values. +person.changed_attributes #=> {"first_name" => "First Name Changed"} + +#returns a hash of changes, with the attribute names as the keys, and the values will be an array of the old and new value for that field. +person.changes #=> {"first_name" => ["First Name","First Name Changed"]} +</ruby> + +h5. Attribute based accessor methods + +Track whether the particular attribute has been changed or not. + +<ruby> +#attr_name_changed? +person.first_name #=> "First Name" + +#assign some other value to first_name attribute +person.first_name = "First Name 1" + +person.first_name_changed? #=> true +</ruby> + +Track what was the previous value of the attribute. +<ruby> +#attr_name_was accessor +person.first_name_was #=> "First Name" +</ruby> + +Track both previous and current value of the changed attribute. Returns an array if changed else returns nil +<ruby> +#attr_name_change +person.first_name_change #=> ["First Name", "First Name 1"] +person.last_name_change #=> nil +</ruby> + +h4. Validations + +Validations module adds the ability to class objects to validate them in Active Record style. + +<ruby> +class Person + include ActiveModel::Validations + + attr_accessor :name, :email + + validates :name, :presence => true + validates_format_of :email, :with => /^([^\s]+)((?:[-a-z0-9]\.)[a-z]{2,})$/i + +end + +person = Person.new +person.valid? #=> false +person.name = 'vishnu' +person.email = 'me' +person.valid? #=> false +person.email = 'me@vishnuatrai.com' +person.valid? #=> true +</ruby> + +h3. Changelog + +* August 5, 2011: Initial version by "Arun Agrawal":http://github.com/arunagw diff --git a/railties/guides/source/active_record_basics.textile b/railties/guides/source/active_record_basics.textile index 3e46e7df9f..cab8c80866 100644 --- a/railties/guides/source/active_record_basics.textile +++ b/railties/guides/source/active_record_basics.textile @@ -204,7 +204,6 @@ Likewise, once retrieved an Active Record object can be destroyed which removes user.destroy </ruby> - h3. Validations Active Record allows you to validate the state of a model before it gets written into the database. There are several methods that you can use to check your models and validate that an attribute value is not empty, is unique and not already in the database, follows a specific format and many more. You can learn more about validations in the "Active Record Validations and Callbacks guide":active_record_validations_callbacks.html#validations-overview. diff --git a/railties/guides/source/active_record_querying.textile b/railties/guides/source/active_record_querying.textile index 8ea06d28aa..4e77a6e803 100644 --- a/railties/guides/source/active_record_querying.textile +++ b/railties/guides/source/active_record_querying.textile @@ -560,6 +560,7 @@ Client.where("orders_count > 10").order(:name).reverse_order </ruby> The SQL that would be executed: + <sql> SELECT * FROM clients WHERE orders_count > 10 ORDER BY name DESC </sql> @@ -571,6 +572,7 @@ Client.where("orders_count > 10").reverse_order </ruby> The SQL that would be executed: + <sql> SELECT * FROM clients WHERE orders_count > 10 ORDER BY clients.id DESC </sql> @@ -621,8 +623,6 @@ You're then responsible for dealing with the conflict by rescuing the exception NOTE: You must ensure that your database schema defaults the +lock_version+ column to +0+. -<br /> - This behavior can be turned off by setting <tt>ActiveRecord::Base.lock_optimistically = false</tt>. To override the name of the +lock_version+ column, +ActiveRecord::Base+ provides a class method called +set_locking_column+: diff --git a/railties/guides/source/active_record_validations_callbacks.textile b/railties/guides/source/active_record_validations_callbacks.textile index ce0b5416de..aba3224ba7 100644 --- a/railties/guides/source/active_record_validations_callbacks.textile +++ b/railties/guides/source/active_record_validations_callbacks.textile @@ -569,11 +569,50 @@ end All validations inside of +with_options+ block will have automatically passed the condition +:if => :is_admin?+ -h3. Creating Custom Validation Methods +h3. Performing Custom Validations -When the built-in validation helpers are not enough for your needs, you can write your own validation methods. +When the built-in validation helpers are not enough for your needs, you can write your own validators or validation methods as you prefer. -Simply create methods that verify the state of your models and add messages to the +errors+ collection when they are invalid. You must then register these methods by using one or more of the +validate+, +validate_on_create+ or +validate_on_update+ class methods, passing in the symbols for the validation methods' names. +h4. Custom Validators + +Custom validators are classes that extend <tt>ActiveModel::Validator</tt>. These classes must implement a +validate+ method which takes a record as an argument and performs the validation on it. The custom validator is called using the +validates_with+ method. + +<ruby> +class MyValidator < ActiveModel::Validator + def validate(record) + if record.name.starts_with? 'X' + record.errors[:name] << 'Need a name starting with X please!' + end + end +end + +class Person + include ActiveModel::Validations + validates_with MyValidator +end +</ruby> + +The easiest way to add custom validators for validating individual attributes is with the convenient <tt>ActiveModel::EachValidator</tt>. In this case, the custom validator class must implement a +validate_each+ method which takes three arguments: record, attribute and value which correspond to the instance, the attribute to be validated and the value of the attribute in the passed instance. + +<ruby> +class EmailValidator < ActiveModel::EachValidator + def validate_each(record, attribute, value) + unless value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i + record.errors[attribute] << (options[:message] || "is not an email") + end + end +end + +class Person < ActiveRecord::Base + validates :email, :presence => true, :email => true +end +</ruby> + +As shown in the example, you can also combine standard validations with your own custom validators. + +h4. Custom Methods + +You can also create methods that verify the state of your models and add messages to the +errors+ collection when they are invalid. You must then register these methods by using one or more of the +validate+, +validate_on_create+ or +validate_on_update+ class methods, passing in the symbols for the validation methods' names. You can pass more than one symbol for each class method and the respective validations will be run in the same order as they were registered. @@ -583,13 +622,15 @@ class Invoice < ActiveRecord::Base :discount_cannot_be_greater_than_total_value def expiration_date_cannot_be_in_the_past - errors.add(:expiration_date, "can't be in the past") if - !expiration_date.blank? and expiration_date < Date.today + if !expiration_date.blank? and expiration_date < Date.today + errors.add(:expiration_date, "can't be in the past") + end end def discount_cannot_be_greater_than_total_value - errors.add(:discount, "can't be greater than total value") if - discount > total_value + if discount > total_value + errors.add(:discount, "can't be greater than total value") + end end end </ruby> @@ -710,8 +751,6 @@ class Person < ActiveRecord::Base end </ruby> - - h4. +errors.clear+ The +clear+ method is used when you intentionally want to clear all the messages in the +errors+ collection. Of course, calling +errors.clear+ upon an invalid object won't actually make it valid: the +errors+ collection will now be empty, but the next time you call +valid?+ or any method that tries to save this object to the database, the validations will run again. If any of the validations fail, the +errors+ collection will be filled again. @@ -758,6 +797,7 @@ h3. Displaying Validation Errors in the View Rails maintains an official plugin that provides helpers to display the error messages of your models in your view templates. You can install it as a plugin or as a Gem. h4. Installing as a plugin + <shell> $ rails plugin install git://github.com/joelmoss/dynamic_form.git </shell> @@ -765,6 +805,7 @@ $ rails plugin install git://github.com/joelmoss/dynamic_form.git h4. Installing as a Gem Add this line in your Gemfile: + <ruby> gem "dynamic_form" </ruby> @@ -1102,8 +1143,9 @@ Here's an example where we create a class with an +after_destroy+ callback for a <ruby> class PictureFileCallbacks def after_destroy(picture_file) - File.delete(picture_file.filepath) - if File.exists?(picture_file.filepath) + if File.exists?(picture_file.filepath) + File.delete(picture_file.filepath) + end end end </ruby> @@ -1121,8 +1163,9 @@ Note that we needed to instantiate a new +PictureFileCallbacks+ object, since we <ruby> class PictureFileCallbacks def self.after_destroy(picture_file) - File.delete(picture_file.filepath) - if File.exists?(picture_file.filepath) + if File.exists?(picture_file.filepath) + File.delete(picture_file.filepath) + end end end </ruby> diff --git a/railties/guides/source/active_resource_basics.textile b/railties/guides/source/active_resource_basics.textile new file mode 100644 index 0000000000..3294227f7b --- /dev/null +++ b/railties/guides/source/active_resource_basics.textile @@ -0,0 +1,124 @@ +h2. Active Resource Basics + +This guide should provide you with all you need to get started managing the connection between business objects and RESTful web services. It implements a way to map web-based resources to local objects with CRUD semantics. + +endprologue. + +WARNING. This Guide is based on Rails 3.0. Some of the code shown here will not work in earlier versions of Rails. + +h3. Introduction + +Active Resource allows you to connect with RESTful web services. So, in Rails, Resource classes inherited from +ActiveResource::Base+ and live in +app/models+. + +h3. Configuration and Usage + +Putting Active Resource to use is very similar to Active Record. It's as simple as creating a model class +that inherits from ActiveResource::Base and providing a <tt>site</tt> class variable to it: + +<ruby> +class Person < ActiveResource::Base + self.site = "http://api.people.com:3000/" +end +</ruby> + +Now the Person class is REST enabled and can invoke REST services very similarly to how Active Record invokes +life cycle methods that operate against a persistent store. + +h3. Reading and Writing Data + +Active Resource make request over HTTP using a standard JSON format. It mirrors the RESTful routing built into Action Controller but will also work with any other REST service that properly implements the protocol. + +h4. Read + +Read requests use the GET method and expect the JSON form of whatever resource/resources is/are being requested. + +<ruby> +# Find a person with id = 1 +person = Person.find(1) +# Check if a person exists with id = 1 +Person.exists?(1) # => true +# Get all resources of Person class +Person.all +</ruby> + +h4. Create + +Creating a new resource submits the JSON form of the resource as the body of the request with HTTP POST method and parse the response into Active Resource object. + +<ruby> +person = Person.create(:name => 'Vishnu') +person.id # => 1 +</ruby> + +h4. Update + +To update an existing resource, 'save' method is used. This method make a HTTP PUT request in JSON format. + +<ruby> +person = Person.find(1) +person.name = 'Atrai' +person.save +</ruby> + +h4. Delete + +'destroy' method makes a HTTP DELETE request for an existing resource in JSON format to delete that resource. + +<ruby> +person = Person.find(1) +person.destroy +</ruby> + +h3. Validations + +Module to support validation and errors with Active Resource objects. The module overrides Base#save to rescue ActiveResource::ResourceInvalid exceptions and parse the errors returned in the web service response. The module also adds an errors collection that mimics the interface of the errors provided by ActiveRecord::Errors. + +h4. Validating client side resources by overriding validation methods in base class + +<ruby> +class Person < ActiveResource::Base + self.site = "http://api.people.com:3000/" + + protected + + def validate + errors.add("last", "has invalid characters") unless last =~ /[a-zA-Z]*/ + end +end +</ruby> + +h4. Validating client side resources + +Consider a Person resource on the server requiring both a first_name and a last_name with a validates_presence_of :first_name, :last_name declaration in the model: + +<ruby> +person = Person.new(:first_name => "Jim", :last_name => "") +person.save # => false (server returns an HTTP 422 status code and errors) +person.valid? # => false +person.errors.empty? # => false +person.errors.count # => 1 +person.errors.full_messages # => ["Last name can't be empty"] +person.errors[:last_name] # => ["can't be empty"] +person.last_name = "Halpert" +person.save # => true (and person is now saved to the remote service) +</ruby> + +h4. Public instance methods + +ActiveResource::Validations have three public instance methods + +h5. errors() + +This will return errors object that holds all information about attribute error messages + +h5. save_with_validation(options=nil) + +This validates the resource with any local validations written in base class and then it will try to POST if there are no errors. + +h5. valid? + +Runs all the local validations and will return true if no errors. + +h3. Changelog + +* July 30, 2011: Initial version by "Vishnu Atrai":http://github.com/vatrai
\ No newline at end of file diff --git a/railties/guides/source/active_support_core_extensions.textile b/railties/guides/source/active_support_core_extensions.textile index 781d3d08cd..df863935cf 100644 --- a/railties/guides/source/active_support_core_extensions.textile +++ b/railties/guides/source/active_support_core_extensions.textile @@ -452,6 +452,30 @@ Examples of +in?+: NOTE: Defined in +active_support/core_ext/object/inclusion.rb+. +h4. +public_send+ + +This method is available by default in Ruby 1.9, and is backported to Ruby 1.8 by Active Support. Like the regular +send+ method, +public_send+ allows you to call a method when the name is not known until runtime. However, if the method is not public then a +NoMethodError+ exception will be raised. + +<ruby> +class Greeter + def hello(who) + "Hello " + who + end + + private + + def secret + "sauce" + end +end + +greeter = Greeter.new +greeter.public_send(:hello, 'Jim') # => "Hello Jim" +greeter.public_send(:secret) # => NoMethodError +</ruby> + +NOTE: Defined in +active_support/core_ext/object/public_send.rb+. + h3. Extensions to +Module+ h4. +alias_method_chain+ @@ -864,7 +888,9 @@ end It is shorter, and the intention more obvious. -The macro accepts several methods: +The method must be public in the target. + +The +delegate+ macro accepts several methods: <ruby> delegate :name, :age, :address, :twitter, :to => :profile @@ -2069,6 +2095,30 @@ shape_types = [Circle, Square, Triangle].sample(2) NOTE: Defined in +active_support/core_ext/array/random_access.rb+. +h4. Adding Elements + +h5. +prepend+ + +This method is an alias of <tt>Array#unshift</tt>. + +<ruby> +%w(a b c d).prepend('e') # => %w(e a b c d) +[].prepend(10) # => [10] +</ruby> + +NOTE: Defined in +active_support/core_ext/array/prepend_and_append.rb+. + +h5. +append+ + +This method is an alias of <tt>Array#<<</tt>. + +<ruby> +%w(a b c d).append('e') # => %w(a b c d e) +[].append([1,2]) # => [[1,2]] +</ruby> + +NOTE: Defined in +active_support/core_ext/array/prepend_and_append.rb+. + h4. Options Extraction When the last argument in a method call is a hash, except perhaps for a +&block+ argument, Ruby allows you to omit the brackets: @@ -2696,6 +2746,18 @@ hash # => {:a => 1} NOTE: Defined in +active_support/core_ext/hash/slice.rb+. +h4. Extracting + +The method +extract!+ removes and returns the key/value pairs matching the given keys. + +<ruby> +hash = {:a => 1, :b => 2} +rest = hash.extract!(:a) # => {:a => 1} +hash # => {:b => 2} +</ruby> + +NOTE: Defined in +active_support/core_ext/hash/slice.rb+. + h4. Indifferent Access The method +with_indifferent_access+ returns an +ActiveSupport::HashWithIndifferentAccess+ out of its receiver: diff --git a/railties/guides/source/ajax_on_rails.textile b/railties/guides/source/ajax_on_rails.textile index 8b72e20c33..77f7661deb 100644 --- a/railties/guides/source/ajax_on_rails.textile +++ b/railties/guides/source/ajax_on_rails.textile @@ -24,16 +24,12 @@ h4. Standard HTML communication vs AJAX How do 'standard' and AJAX requests differ, why does this matter for understanding AJAX on Rails (tie in for *_remote helpers, the next section) - - - - - h3. Built-in Rails Helpers Rails' JavaScript framework of choice is "Prototype":http://www.prototypejs.org. Prototype is a generic-purpose JavaScript framework that aims to ease the development of dynamic web applications by offering DOM manipulation, AJAX and other JavaScript functionality ranging from utility functions to object oriented constructs. It is not specifically written for any language, so Rails provides a set of helpers to enable seamless integration of Prototype with your Rails views. To get access to these helpers, all you have to do is to include the prototype framework in your pages - typically in your master layout, application.html.erb - like so: + <ruby> javascript_include_tag 'prototype' </ruby> @@ -59,7 +55,6 @@ link_to_remote "Add to cart", </ruby> * The very first parameter, a string, is the text of the link which appears on the page. - * The second parameter, the +options+ hash is the most interesting part as it has the AJAX specific stuff: ** *:url* This is the only parameter that is always required to generate the simplest remote link (technically speaking, it is not required, you can pass an empty +options+ hash to +link_to_remote+ - but in this case the URL used for the POST request will be equal to your current URL which is probably not your intention). This URL points to your AJAX action handler. The URL is typically specified by Rails REST view helpers, but you can use the +url_for+ format too. ** *:update* Specifying a DOM id of the element we would like to update. The above example demonstrates the simplest way of accomplishing this - however, we are in trouble if the server responds with an error message because that will be injected into the page too! However, Rails has a solution for this situation: @@ -193,7 +188,6 @@ end What happens here is that by specifying the Content-Type header variable, we instruct the browser to evaluate the text we are sending over (rather than displaying it as plain text, which is the default behavior). - h3. Testing JavaScript JavaScript testing reminds me the definition of the world 'classic' by Mark Twain: "A classic is something that everybody wants to have read and nobody wants to read." It's similar with JavaScript testing: everyone would like to have it, yet it's not done by too much developers as it is tedious, complicated, there is a proliferation of tools and no consensus/accepted best practices, but we will nevertheless take a stab at it: diff --git a/railties/guides/source/api_documentation_guidelines.textile b/railties/guides/source/api_documentation_guidelines.textile index 9c4df2d6b8..3ebf0e10f1 100644 --- a/railties/guides/source/api_documentation_guidelines.textile +++ b/railties/guides/source/api_documentation_guidelines.textile @@ -106,7 +106,6 @@ routes.rb # NO RAILS_ROOT/config/routes.rb # NO </plain> - h3. Fonts h4. Fixed-width Font @@ -188,4 +187,3 @@ self.class_eval %{ h3. Changelog * July 17, 2010: ported from the docrails wiki and revised by "Xavier Noria":credits.html#fxn - diff --git a/railties/guides/source/asset_pipeline.textile b/railties/guides/source/asset_pipeline.textile index 51cb332e38..012149c40e 100644 --- a/railties/guides/source/asset_pipeline.textile +++ b/railties/guides/source/asset_pipeline.textile @@ -1,6 +1,6 @@ h2. Asset Pipeline -This guide will cover the ideology of the asset pipeline introduced in Rails 3.1. +This guide covers the ideology of the asset pipeline introduced in Rails 3.1. By referring to this guide you will be able to: * Understand what the asset pipeline is and what it does @@ -19,7 +19,7 @@ Prior to Rails 3.1 these features were added through third-party Ruby libraries By having this as a core feature of Rails, all developers can benefit from the power of having their assets pre-processed, compressed and minified by one central library, Sprockets. This is part of Rails' "Fast by default" strategy as outlined by DHH in his 2011 keynote at Railsconf. -In new Rails 3.1 application the asset pipeline is enable by default. It can be disabled in +application.rb+ by putting this line inside the +Application+ class definition: +In new Rails 3.1 application the asset pipeline is enabled by default. It can be disabled in +application.rb+ by putting this line inside the +Application+ class definition: <plain> config.assets.enabled = false @@ -27,20 +27,19 @@ config.assets.enabled = false It is recommended that you use the defaults for all new apps. - h4. Main Features -The first feature of the pipeline is to concatenate assets. This is important in a production environment, as it reduces the number of requests that a browser needs to make to render a web page. While Rails already has a feature to concatenate these types of asset--by placing +:cache => true+ at the end of tags such as +javascript_include_tag+ and +stylesheet_link_tag+--, many people do not use it. +The first feature of the pipeline is to concatenate assets. This is important in a production environment, as it reduces the number of requests that a browser must make to render a web page. While Rails already has a feature to concatenate these types of assetsi -- by placing +:cache => true+ at the end of tags such as +javascript_include_tag+ and +stylesheet_link_tag+ -- many people do not use it. -The default behavior in Rails 3.1 and onward is to concatenate all files into one master file each for JS and CSS. However, you can separate files or groups of files if required (see below). In production an MD5 fingerprint is inserted into each filename so that the file is cached by the web browser but can be invalidated if the fingerprint is altered. +The default behavior in Rails 3.1 and onward is to concatenate all files into one master file each for JS and CSS. However, you can separate files or groups of files if required (see below). In production, an MD5 fingerprint is inserted into each filename so that the file is cached by the web browser but can be invalidated if the fingerprint is altered. -The second feature is to minify or compress. For CSS, this usually involves removing whitespace and comments. For JavaScript, more complex processes can be applied. You can choose from a set of built in options or specify your own. +The second feature is to minify or compress assets. For CSS, this usually involves removing whitespace and comments. For JavaScript, more complex processes can be applied. You can choose from a set of built in options or specify your own. The third feature is the ability to code these assets using another language, or language extension. These include SCSS or Sass for CSS, CoffeeScript for JavaScript, and ERB for both. h4. What is Fingerprinting and Why Should I Care? -Fingerprinting is a technique where the filenames of content that is static or infrequently updated is altered to be unique to the content contained in the file. +Fingerprinting is a technique whereby the filenames of content that is static or infrequently updated is altered to be unique to the content contained in the file. When a filename is unique and based on its content, HTTP headers can be set to encourage caches everywhere (at ISPs, in browsers) to keep their own copy of the content. When the content is updated, the fingerprint will change and the remote clients will request the new file. This is generally known as _cachebusting_. @@ -52,7 +51,7 @@ global.css => global-908e25f4bf641868d8683022a5b62f54.css This is the strategy adopted by the Rails asset pipeline. -Rails old strategy was to append a query string to every asset linked with a built-in helper. In the source the generated code looked like this: +Rails' old strategy was to append a query string to every asset linked with a built-in helper. In the source the generated code looked like this: <plain> /stylesheets/global.css?1309495796 @@ -73,21 +72,20 @@ This has several disadvantages: The other problem is that when static assets are deployed with each new release of code, the mtime of *all* these files changes, forcing all remote clients to fetch them again, even when the content of those assets has not changed. -Fingerprinting avoids all these problems by ensuring filenames are consistent based on the content. +Fingerprinting avoids all these problems by ensuring filenames are consistent based on their content. More reading: * "Optimize caching":http://code.google.com/speed/page-speed/docs/caching.html * "Revving Filenames: don’t use querystring":http://www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/ - h3. How to Use the Asset Pipeline -In previous versions of Rails, all assets were located in subdirectories of +public+ such as +images+, +javascripts+ and +stylesheets+. With the asset pipeline, the preferred location for these assets is now the +app/assets+ directory. Files in this directory will be served by the Sprockets middleware included in the sprockets gem. +In previous versions of Rails, all assets were located in subdirectories of +public+ such as +images+, +javascripts+ and +stylesheets+. With the asset pipeline, the preferred location for these assets is now the +app/assets+ directory. Files in this directory are served by the Sprockets middleware included in the sprockets gem. This is not to say that assets can (or should) no longer be placed in +public+; they still can be and will be served as static files by the application or web server. You would only use +app/assets+ if you wish your files to undergo some pre-processing before they are served. -When a scaffold or controller is generated for the application, Rails will also generate a JavaScript file (or CoffeeScript if the +coffee-script+ gem is in the +Gemfile+) and a Cascading Style Sheet file (or SCSS if +sass-rails+ is in the +Gemfile+) file for that controller. +When a scaffold or controller is generated for the application, Rails also generates a JavaScript file (or CoffeeScript file if the +coffee-script+ gem is in the +Gemfile+) and a Cascading Style Sheet file (or SCSS file if +sass-rails+ is in the +Gemfile+) for that controller. For example, if a +ProjectsController+ is generated, there will be a new file at +app/assets/javascripts/projects.js.coffee+ and another at +app/assets/stylesheets/projects.css.scss+. You should put any JavaScript or CSS unique to a controller inside their respective asset files, as these files can then be loaded just for these controllers with lines such as +<%= javascript_include_tag params[:controller] %>+ or +<%= stylesheet_link_tag params[:controller] %>+. @@ -101,13 +99,13 @@ Assets can be placed inside an application in one of three locations: +app/asset +vendor/assets+ is for assets that are owned by outside entities, such as code for JavaScript plugins. -All subdirectories that exist within these three locations will be added to the search path for Sprockets (visible by calling +Rails.application.config.assets.paths+ in a console). When an asset is requested, these paths will be looked through to see if they contain an asset matching the name specified. Once an asset has been found, it's processed by Sprockets and served. +All subdirectories that exist within these three locations are added to the search path for Sprockets (visible by calling +Rails.application.config.assets.paths+ in a console). When an asset is requested, these paths are looked through to see if they contain an asset matching the name specified. Once an asset has been found, it's processed by Sprockets and served. h4. Coding Links to Assets -To access assets, we can use the same tags that we are generally familiar with: +To access assets, you use the same tags that you are generally familiar with: -Sprockets does not add any new methods to require your assets, we still use the familiar +javascript_include_tag+ and +stylesheet_link_tag+. +Sprockets does not add any new methods to require your assets, you still use the familiar +javascript_include_tag+ and +stylesheet_link_tag+. <erb> <%= stylesheet_link_tag "application" %> @@ -126,29 +124,29 @@ Images can be organized into directories if required, and they can be accessed b <%= image_tag "icons/rails.png" %> </erb> -Providing that assets are enabled within our application (+config.assets.enabled+ in the current environment's file is not set to +false+), this file will be served by Sprockets unless a file at +public/assets/rails.png+ exists, in which case that file will be served. +Providing that assets are enabled within your application (+config.assets.enabled+ in the current environment's file is not set to +false+), this file is served by Sprockets unless a file at +public/assets/rails.png+ exists, in which case that file is served. -Alternatively, a file with an MD5 hash after its name such as +public/assets/rails-af27b6a414e6da00003503148be9b409.png+ will also be picked up by Sprockets. How these hashes are generated is covered in the "Production Assets":#production_assets section later on in this guide. +Alternatively, a file with an MD5 hash after its name such as +public/assets/rails-af27b6a414e6da00003503148be9b409.png+ is also picked up by Sprockets. How these hashes are generated is covered in the "Production Assets":#production_assets section later on in this guide. -Otherwise, Sprockets will look through the available paths until it finds a file that matches the name and then will serve it, first looking in the application's assets directories and then falling back to the various engines of the application. +Otherwise, Sprockets looks through the available paths until it finds a file that matches the name and then serves it, first looking in the application's assets directories and then falling back to the various engines of the application. -If you want to use a "css data URI":http://en.wikipedia.org/wiki/Data_URI_scheme - a method of embedding the image data directly into the CSS file - you can use the +asset_data_uri+ helper. +If you want to use a "css data URI":http://en.wikipedia.org/wiki/Data_URI_scheme -- a method of embedding the image data directly into the CSS file -- you can use the +asset_data_uri+ helper. <plain> #logo { background: url(<%= asset_data_uri 'logo.png' %>) </plain> -This will insert a correctly formatted data URI into the CSS source. +This inserts a correctly-formatted data URI into the CSS source. h5. CSS and ERB -If you add an +erb+ extension to a CSS asset, making it something such as +application.css.erb+ then you can use the +asset_path+ helper in your CSS rules: +If you add an +erb+ extension to a CSS asset, making it something such as +application.css.erb+, then you can use the +asset_path+ helper in your CSS rules: <plain> .class{background-image:<%= asset_path 'image.png' %>} </plain> -This will write the path to the particular asset being referenced. In this example, it would make sense to have an image in one of the asset load paths, such as +app/assets/images/image.png+, which would be referenced here. If this image is already available in +public/assets+ as a fingerprinted file then that path will be referenced. +This writes the path to the particular asset being referenced. In this example, it would make sense to have an image in one of the asset load paths, such as +app/assets/images/image.png+, which would be referenced here. If this image is already available in +public/assets+ as a fingerprinted file, then that path is referenced. Note that the closing tag cannot be of the style +-%>+. @@ -166,7 +164,7 @@ The more generic form can also be used but the asset path and class must both be h4. Manifest Files and Directives -Sprockets uses manifest files to determine which assets to include and serve. These manifest files contain _directives_ - instructions that tell Sprockets which files to require in order to build a single CSS or JavaScript file. With these directives, Sprockets will load the files specified, process them if necessary, concatenate them into one single file and then compress them (if +Rails.application.config.assets.compress+ is set to +true+). By serving one file rather than many, a page's load time is greatly reduced as there is not as many requests to make for each file. +Sprockets uses manifest files to determine which assets to include and serve. These manifest files contain _directives_ -- instructions that tell Sprockets which files to require in order to build a single CSS or JavaScript file. With these directives, Sprockets loads the files specified, processes them if necessary, concatenates them into one single file and then compresses them (if +Rails.application.config.assets.compress+ is set to +true+). By serving one file rather than many, the load time of pages are greatly reduced as there are fewer requests to make. For example, in the default Rails application there's a +app/assets/javascripts/application.js+ file which contains the following lines: @@ -176,9 +174,11 @@ For example, in the default Rails application there's a +app/assets/javascripts/ //= require_tree . </plain> -In JavaScript files, directives begin with +//=+. In this case, the following file is using the +require+ directive and the +require_tree+ directive. The +require+ directive tells Sprockets that we would like to require a file called +jquery.js+ that is available somewhere in the search path for Sprockets. By default, this is located inside the +vendor/assets/javascripts+ directory contained within the +jquery-rails+ gem. An identical event takes place for the +jquery_ujs+ require +In JavaScript files, the directives begin with +//=+. In this case, the file is using the +require+ and the +require_tree+ directives. The +require+ directive is used to tell Sprockets the files that you wish to require. Here, you are requiring the files +jquery.js+ and +jquery_ujs.js+ that are available somewhere in the search path for Sprockets. You need not supply the extensions explicitly. Sprockets assumes you are requiring a +.js+ file when done from within a +.js+ file. -The +require_tree .+ directive tells Sprockets to include _all_ JavaScript files in this directory into the output. Only a path relative to the file can be specified. +NOTE. In Rails 3.1, the +jquery.js+ and +jquery_ujs.js+ files are located inside the +vendor/assets/javascripts+ directory contained within the +jquery-rails+ gem. + +The +require_tree .+ directive tells Sprockets to include _all_ JavaScript files in this directory into the output. Only a path relative to the file can be specified. There is also a +require_directory+ directive which includes all JavaScript files only in the directory specified (no nesting). There's also a default +app/assets/stylesheets/application.css+ file which contains these lines: @@ -189,13 +189,13 @@ There's also a default +app/assets/stylesheets/application.css+ file which conta */ </plain> -The directives that work in the JavaScript files will also work in stylesheets, obviously including stylesheets rather than JavaScript files. The +require_tree+ directive here works the same way as the JavaScript one, requiring all stylesheets from the current directory. +The directives that work in the JavaScript files also work in stylesheets, obviously including stylesheets rather than JavaScript files. The +require_tree+ directive here works the same way as the JavaScript one, requiring all stylesheets from the current directory. -In this example +require_self+ is used. This will put the CSS contained within the file (if any) at the top of any other CSS in this file unless +require_self+ is specified after another +require+ directive. +In this example +require_self+ is used. This puts the CSS contained within the file (if any) at the top of any other CSS in this file unless +require_self+ is specified after another +require+ directive. You can have as many manifest files as you need. For example the +admin.css+ and +admin.js+ manifest could contain the JS and CSS files that are used for the admin section of an application. -For some assets (like CSS) the compiled order is important. You can specify individual files and they will be compiled in the order specified: +For some assets (like CSS) the compiled order is important. You can specify individual files and they are compiled in the order specified: <plain> /* ... @@ -208,36 +208,36 @@ For some assets (like CSS) the compiled order is important. You can specify indi h4. Preprocessing -The file extensions used on an asset will determine what preprocessing will be applied. When a controller or a scaffold is generated with the default Rails gemset, a CoffeeScript file and a SCSS file will be generated in place of a regular JavaScript and CSS file. The example used before was a controller called "projects", which generated an +app/assets/javascripts/projects.js.coffee+ and a +app/assets/stylesheets/projects.css.scss+ file. +The file extensions used on an asset determine what preprocessing is applied. When a controller or a scaffold is generated with the default Rails gemset, a CoffeeScript file and a SCSS file are generated in place of a regular JavaScript and CSS file. The example used before was a controller called "projects", which generated an +app/assets/javascripts/projects.js.coffee+ and a +app/assets/stylesheets/projects.css.scss+ file. -When these files are requested, they will be processed by the processors provided by the +coffee-script+ and +sass-rails+ gems and then sent back to the browser as JavaScript and CSS respectively. +When these files are requested, they are processed by the processors provided by the +coffee-script+ and +sass-rails+ gems and then sent back to the browser as JavaScript and CSS respectively. -Additional layers of pre-processing can be requested by adding other extensions, where each extension will be processed in a right-to-left manner. These should be used in the order the processing should be applied. For example, a stylesheet called +app/assets/stylesheets/projects.css.scss.erb+ would first be processed as ERB, then SCSS and finally served as CSS. The same applies to a JavaScript file - +app/assets/javascripts/projects.js.coffee.erb+ would be process as ERB, CoffeeScript and served as JavaScript. +Additional layers of pre-processing can be requested by adding other extensions, where each extension is processed in a right-to-left manner. These should be used in the order the processing should be applied. For example, a stylesheet called +app/assets/stylesheets/projects.css.scss.erb+ is first processed as ERB, then SCSS and finally served as CSS. The same applies to a JavaScript file -- +app/assets/javascripts/projects.js.coffee.erb+ is processed as ERB, CoffeeScript and served as JavaScript. -Keep in mind that the order of these pre-processors is important. For example, if we called our JavaScript file +app/assets/javascripts/projects.js.erb.coffee+ then it would be processed with the CoffeeScript interpreter first, which wouldn't understand ERB and therefore we would run into problems. +Keep in mind that the order of these pre-processors is important. For example, if you called your JavaScript file +app/assets/javascripts/projects.js.erb.coffee+ then it is processed with the CoffeeScript interpreter first, which wouldn't understand ERB and therefore you would run into problems. h3. In Development In the development environment assets are compiled and cached on the first request after the server is started. Sprockets sets a +must-validate+ Cache-Control HTTP header to reduce request overhead on subsequent requests - on these the browser gets a 304 (not-modified) response. -If any of the files in the manifest have changed between requests, the server will respond with a new compiled file. +If any of the files in the manifest have changed between requests, the server responds with a new compiled file. h4. Debugging Assets -You can put +?debug_assets=true+ or +?debug_assets=1+ at the end of a URL and Sprockets will expand the lines which load the assets. For example, if we had an +app/assets/javascripts/application.js+ file containing these lines: +You can put +?debug_assets=true+ or +?debug_assets=1+ at the end of a URL or set +config.assets.debug+ and Sprockets expands the lines which load the assets. For example, if you had an +app/assets/javascripts/application.js+ file containing these lines: <plain> //= require "projects" //= require "tickets" </plain> -By default, this would only render this line when used with +<%= javascript_include_tag "application" %>+ in a view or layout: +By default, this only renders this line when used with +<%= javascript_include_tag "application" %>+ in a view or layout: <html> <script src='/assets/application.js'></script> </html> -When the +debug_assets+ parameter is set, this line will be expanded out into three separate lines, separating out the combined file into their parts. +When the +debug_assets+ parameter is set, this line is expanded out into three separate lines, separating out the combined file into their parts. <html> <script src='/assets/application.js'></script> @@ -247,11 +247,13 @@ When the +debug_assets+ parameter is set, this line will be expanded out into th This allows the individual parts of an asset to be rendered and debugged separately. +NOTE. Assets debugging is turned on by default in development and test environments. + h3. In Production In the production environment, assets are served slightly differently. -On the first request the assets are compiled and cached as described above, however the manifest names are altered to include an MD5 hash. Files names typically will look like these: +On the first request the assets are compiled and cached as described above, however the manifest names are altered to include an MD5 hash. Files names typically look like these: <plain> /assets/application-908e25f4bf641868d8683022a5b62f54.js @@ -268,7 +270,7 @@ h4. Precompiling Assets Even though assets are served by Rack::Cache with far-future headers, in high traffic sites this may not be fast enough. -Rails comes bundled with a rake task to compile the manifests to files on disc. These are located in the +public/assets+ directory where they will be served by your web server instead of the Rails application. +Rails comes bundled with a rake task to compile the manifests to files on disc. These are located in the +public/assets+ directory where they are served by your web server instead of the Rails application. The rake task is: @@ -276,19 +278,17 @@ The rake task is: rake assets:precompile </plain> -You can run this as part of a Capistrano deployment: +Capistrano (v2.8.0+) has a recipe to handle this in deployment. Add the following line to +Capfile+: <erb> -before 'deploy:symlink' do - run "cd #{release_path}; RAILS_ENV=#{rails_env} rake assets:precompile" -end +load 'deploy/assets' </erb> -If you are not precompiling your assets, and you are using the default cache file store (which is the file system), you will need to symlink +rails_root/tmp/cache/assets+ from the shared folder that is part of the Capistrano deployment structure in order to persist the cached file between deployments. +This links the folder specified in +config.assets.prefix+ to +shared/assets+. If you already use this folder you'll need to write your own deployment task. -TODO: Extend above task to allow for this and add task to set it up (See commits 8f0e0b6 and 704ee0df). Note: Capistrano folks are working on a recipe - update this when it available (see https://github.com/capistrano/capistrano/pull/35). +It is important that this folder is shared between deployments so that remotely cached pages that reference the old compiled assets still work for the life of the cached page. -The default matcher for compiling files will include +application.js+, +application.css+ and all files that do not end in +js+ or +css+: +The default matcher for compiling files includes +application.js+, +application.css+ and all files that do not end in +js+ or +css+: <ruby> [ /\w+\.(?!js|css).+/, /application.(css|js)$/ ] @@ -297,7 +297,7 @@ The default matcher for compiling files will include +application.js+, +applicat If you have other manifests or individual stylesheets and JavaScript files to include, you can append them to the +precompile+ array: <erb> -config.assets.precompile << ['admin.js', 'admin.css', 'swfObject.js'] +config.assets.precompile += ['admin.js', 'admin.css', 'swfObject.js'] </erb> Precompiled assets exist on the filesystem and are served directly by your webserver. They do not have far-future headers by default, so to get the benefit of fingerprinting you'll have to update your server configuration to add them. @@ -320,11 +320,10 @@ For Apache: TODO: NGINX instructions -When files are precompiled Sprockets also creates "Gzip":http://en.wikipedia.org/wiki/Gzip (.gz) version of your assets. This avoids the server having to do this for any requests; it can simply read the compressed files from disc. You must configure your server to use gzip compression and serve the compressed assets that will be stored in the public/assets folder. The following configuration options can be used: +When files are precompiled, Sprockets also creates a "Gzip":http://en.wikipedia.org/wiki/Gzip (.gz) version of your assets. This avoids the server having to do this for any requests; it can simply read the compressed files from disc. You must configure your server to use gzip compression and serve the compressed assets that will be stored in the public/assets folder. The following configuration options can be used: TODO: Apache instructions - h3. Customizing the Pipeline @@ -332,7 +331,7 @@ h4. CSS Compression There is currently one option for compressing CSS - YUI. This Gem extends the CSS syntax and offers minification. -The following line will enable YUI compression, and requires the +yui-compressor+ gem. +The following line enables YUI compression, and requires the +yui-compressor+ gem. <erb> config.assets.css_compressor = :yui @@ -344,19 +343,19 @@ h4. JavaScript Possible options for JavaScript compression are +:closure+, +:uglifier+ and +:yui+. These require the use of the +closure-compiler+, +uglifier+ or +yui-compressor+ gems respectively. -The default Gemfile includes "uglifier":https://github.com/lautis/uglifier. This gem wraps "UglifierJS":https://github.com/mishoo/UglifyJS (written for NodeJS) in Ruby. It compress your code by removing white spaces and other magical things like changing your +if+ and +else+ statements to ternary operators where possible. +The default Gemfile includes "uglifier":https://github.com/lautis/uglifier. This gem wraps "UglifierJS":https://github.com/mishoo/UglifyJS (written for NodeJS) in Ruby. It compresses your code by removing white space and other magical things like changing your +if+ and +else+ statements to ternary operators where possible. -The following line will invoke uglifier for JavaScript compression. +The following line invokes +uglifier+ for JavaScript compression. <erb> -config.assets.js_compressor = :uglifier +config.assets.js_compressor = :uglifier </erb> The +config.assets.compress+ must be set to +true+ to enable JavaScript compression h4. Using Your Own Compressor -The compressor config settings for CSS and JavaScript will also take any Object. This object must have a +compress+ method that takes a string as the sole argument and it must return a string. +The compressor config settings for CSS and JavaScript also take any Object. This object must have a +compress+ method that takes a string as the sole argument and it must return a string. <erb> class Transformer @@ -366,13 +365,12 @@ class Transformer end </erb> -To enable this pass a +new+ Object to the config option in +application.rb+: +To enable this, pass a +new+ Object to the config option in +application.rb+: <erb> config.assets.css_compressor = Transformer.new </erb> - h4. Changing the _assets_ Path The public path that Sprockets uses by default is +/assets+. @@ -387,16 +385,15 @@ This is a handy option if you have any existing project (pre Rails 3.1) that alr h4. X-Sendfile Headers -The X-Sendfile header is a directive to the server to ignore the response from the application, and instead serve the file specified in the headers. In production Rails (via Sprockets) does not send the asset - just the location and a zero-length response - relying on the web server to do the file serving, which is usually faster. Both Apache and nginx support this option. +The X-Sendfile header is a directive to the server to ignore the response from the application, and instead serve the file specified in the headers. This option is off by default, but can be enabled if your server supports it. When enabled, this passes responsibility for serving the file to the web server, which is faster. -The configuration is available in <tt>config/environments/production.rb</tt>. +Apache and nginx support this option which is enabled in <tt>config/environments/production.rb</tt>. <erb> -config.action_dispatch.x_sendfile_header = "X-Sendfile" # Use 'X-Accel-Redirect' for nginx +# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache +# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx </erb> -You should check that your server or hosting service actually supports this, otherwise comment it out. - WARNING: If you are upgrading an existing application and intend to use this option, take care to paste this configuration option only into +production.rb+ (and not +application.rb+) and any other environment you define with production behavior. h3. How Caching Works diff --git a/railties/guides/source/caching_with_rails.textile b/railties/guides/source/caching_with_rails.textile index ae56911441..693303950d 100644 --- a/railties/guides/source/caching_with_rails.textile +++ b/railties/guides/source/caching_with_rails.textile @@ -404,7 +404,6 @@ h3. Further reading * "Scaling Rails Screencasts":http://railslab.newrelic.com/scaling-rails - h3. Changelog * Feb 17, 2011: Document 3.0.0 changes to ActiveSupport::Cache @@ -415,4 +414,3 @@ h3. Changelog * December 27, 2008: Typo fixes * November 23, 2008: Incremental updates with various suggested changes and formatting cleanup * September 15, 2008: Initial version by Aditya Chadha - diff --git a/railties/guides/source/command_line.textile b/railties/guides/source/command_line.textile index b34506d4d8..f6b33d283c 100644 --- a/railties/guides/source/command_line.textile +++ b/railties/guides/source/command_line.textile @@ -325,6 +325,8 @@ h4. +rails destroy+ Think of +destroy+ as the opposite of +generate+. It'll figure out what generate did, and undo it. +You can also use the alias "d" to invoke the destroy command: <tt>rails d</tt>. + <shell> $ rails generate model Oops exists app/models/ @@ -381,19 +383,22 @@ Ruby version 1.8.7 (x86_64-linux) RubyGems version 1.3.6 Rack version 1.1 Rails version 3.1.0 +JavaScript Runtime Node.js (V8) Active Record version 3.1.0 Action Pack version 3.1.0 Active Resource version 3.1.0 Action Mailer version 3.1.0 Active Support version 3.1.0 -Middleware ActionDispatch::Static, Rack::Lock, Rack::Runtime, Rails::Rack::Logger, ActionDispatch::ShowExceptions, ActionDispatch::RemoteIp, Rack::Sendfile, ActionDispatch::Callbacks, ActionDispatch::Cookies, ActionDispatch::Session::CookieStore, ActionDispatch::Flash, ActionDispatch::ParamsParser, Rack::MethodOverride, ActionDispatch::Head +Middleware ActionDispatch::Static, Rack::Lock, Rack::Runtime, Rails::Rack::Logger, ActionDispatch::ShowExceptions, ActionDispatch::RemoteIp, ActionDispatch::Callbacks, ActionDispatch::Cookies, ActionDispatch::Session::CookieStore, ActionDispatch::Flash, ActionDispatch::ParamsParser, Rack::MethodOverride, ActionDispatch::Head Application root /home/foobar/commandsapp Environment development +Database adapter sqlite3 +Database schema version 20110805173523 </shell> h4. +assets+ -You can precompile the assets in <tt>app/assets</tt> using <tt>rake assets:precompile</tt> and remove compiled assets using <tt>rake assets:clean</tt>. +You can precompile the assets in <tt>app/assets</tt> using <tt>rake assets:precompile</tt> and remove those compiled assets using <tt>rake assets:clean</tt>. h4. +db+ @@ -458,13 +463,18 @@ h4. +test+ INFO: A good description of unit testing in Rails is given in "A Guide to Testing Rails Applications":testing.html -Rails comes with a test suite called Test::Unit. It is through the use of tests that Rails itself is so stable, and the slew of people working on Rails can prove that everything works as it should. - -The +test:+ namespace helps in running the different tests you will (hopefully!) write. +Rails comes with a test suite called <tt>Test::Unit</tt>. Rails owes its stability to the use of tests. The tasks available in the +test:+ namespace helps in running the different tests you will hopefully write. h4. +tmp+ -The <tt>Rails.root/tmp</tt> directory is, like the *nix /tmp directory, the holding place for temporary files like sessions (if you're using a file store for files), process id files, and cached actions. The +tmp:+ namespace tasks will help you clear them if you need to if they've become overgrown, or create them in case of deletions gone awry. +The <tt>Rails.root/tmp</tt> directory is, like the *nix /tmp directory, the holding place for temporary files like sessions (if you're using a file store for files), process id files, and cached actions. + +The +tmp:+ namespaced tasks will help you clear the <tt>Rails.root/tmp</tt> directory: + +* +rake tmp:cache:clear+ clears <tt>tmp/cache</tt>. +* +rake tmp:sessions:clear+ clears <tt>tmp/sessions</tt>. +* +rake tmp:sockets:clear+ clears <tt>tmp/sockets</tt>. +* +rake tmp:clear+ clears all the three: cache, sessions and sockets. h4. Miscellaneous diff --git a/railties/guides/source/configuring.textile b/railties/guides/source/configuring.textile index 2ff5de2334..110c04f66e 100644 --- a/railties/guides/source/configuring.textile +++ b/railties/guides/source/configuring.textile @@ -557,7 +557,7 @@ The error occurred while evaluating nil.each *+set_load_path+* This initializer runs before +bootstrap_hook+. Adds the +vendor+, +lib+, all directories of +app+ and any paths specified by +config.load_paths+ to +$LOAD_PATH+. -*+set_autoload_path+* This initializer runs before +bootstrap_hook+. Adds all sub-directories of +app+ and paths specified by +config.autoload_paths+ to +ActiveSupport::Dependencies.autoload_paths+. +*+set_autoload_paths+* This initializer runs before +bootstrap_hook+. Adds all sub-directories of +app+ and paths specified by +config.autoload_paths+ to +ActiveSupport::Dependencies.autoload_paths+. *+add_routing_paths+* Loads (by default) all +config/routes.rb+ files (in the application and railties, including engines) and sets up the routes for the application. diff --git a/railties/guides/source/contributing_to_ruby_on_rails.textile b/railties/guides/source/contributing_to_ruby_on_rails.textile index e6ec061c9a..4706725bb6 100644 --- a/railties/guides/source/contributing_to_ruby_on_rails.textile +++ b/railties/guides/source/contributing_to_ruby_on_rails.textile @@ -104,7 +104,6 @@ $ cd railties $ TEST_DIR=generators rake test </shell> - h4. Warnings The test suite runs with warnings enabled. Ideally Ruby on Rails should issue no warning, but there may be a few, and also some from third-party libraries. Please ignore (or fix!) them if any, and submit patches that do not issue new warnings. diff --git a/railties/guides/source/form_helpers.textile b/railties/guides/source/form_helpers.textile index bf2a7369a7..c277f5723a 100644 --- a/railties/guides/source/form_helpers.textile +++ b/railties/guides/source/form_helpers.textile @@ -342,7 +342,6 @@ output: When parsing POSTed data, Rails will take into account the special +_method+ parameter and acts as if the HTTP method was the one specified inside it ("PUT" in this example). - h3. Making Select Boxes with Ease Select boxes in HTML require a significant amount of markup (one +OPTION+ element for each option to choose from), therefore it makes the most sense for them to be dynamically generated. diff --git a/railties/guides/source/getting_started.textile b/railties/guides/source/getting_started.textile index 0b89021392..d2bfcfdbb4 100644 --- a/railties/guides/source/getting_started.textile +++ b/railties/guides/source/getting_started.textile @@ -116,7 +116,6 @@ need to know anything about them to continue with this guide. * Active Support * Railties - h5. Action Pack Action Pack is a single gem that contains Action Controller, Action View and @@ -197,9 +196,10 @@ For example, the following HTTP request: <tt>DELETE /photos/17</tt> -refers to a photo resource with an ID of 17 and indicates an action to be taken -upon it: deletion. REST is a natural web application architecture which Rails -abstracts, shielding you from RESTful complexities and browser quirks. +would be understood to refer to a photo resource with the ID of 17, and to +indicate a desired action - deleting that resource. REST is a natural style for +the architecture of web applications, and Rails hooks into this shielding you +from many of the RESTful complexities and browser quirks. If you'd like more details on REST as an architectural style, these resources are more approachable than Fielding's thesis: @@ -535,21 +535,8 @@ command in your terminal: $ rails generate scaffold Post name:string title:string content:text </shell> -This will create a new database table called posts (plural of Post). The table -will have three columns, name (type string), title (type string) and content -(type text). It will also hook this new database up to Rails (details below). - -NOTE. While scaffolding will get you up and running quickly, the code it -generates is unlikely to be a perfect fit for your application. You'll most -probably want to customize the generated code. Many experienced Rails developers -avoid scaffolding entirely, preferring to write all or most of their source code -from scratch. Rails, however, makes it really simple to customize templates for -generated models, controllers, views and other source files. You'll find more -information in the "Creating and Customizing Rails Generators & -Templates":generators.html guide. - -The scaffold generator will build 17 files in your application, along with some -folders, and edit one more. Here's a quick overview of what it creates: +The scaffold generator will build several files in your application, along with some +folders, and edit <tt>config/routes.rb</tt>. Here's a quick overview of what it creates: |_.File |_.Purpose| |db/migrate/20100207214725_create_posts.rb |Migration to create the posts table in your database (your name will include a different timestamp)| @@ -570,6 +557,15 @@ folders, and edit one more. Here's a quick overview of what it creates: |test/unit/helpers/posts_helper_test.rb |Unit testing harness for the posts helper| |config/routes.rb |Edited to include routing information for posts| +NOTE. While scaffolding will get you up and running quickly, the code it +generates is unlikely to be a perfect fit for your application. You'll most +probably want to customize the generated code. Many experienced Rails developers +avoid scaffolding entirely, preferring to write all or most of their source code +from scratch. Rails, however, makes it really simple to customize templates for +generated models, controllers, views and other source files. You'll find more +information in the "Creating and Customizing Rails Generators & +Templates":generators.html guide. + h4. Running a Migration One of the products of the +rails generate scaffold+ command is a _database @@ -1636,7 +1632,6 @@ Authentication challenge !images/challenge.png(Basic HTTP Authentication Challenge)! - h3. Building a Multi-Model Form Another feature of your average blog is the ability to tag posts. To implement @@ -1895,7 +1890,7 @@ h3. Changelog * April 26, 2011: Change migration code from +up+, +down+ pair to +change+ method by "Prem Sichanugrist":http://sikachu.com * April 11, 2011: Change scaffold_controller generator to create format block for JSON instead of XML by "Sebastian Martinez":http://www.wyeworks.com -* August 30, 2010: Minor editing after Rails 3 release by "Joost Baaij":http://www.spacebabies.nl +* August 30, 2010: Minor editing after Rails 3 release by Joost Baaij * July 12, 2010: Fixes, editing and updating of code samples by "Jaime Iniesta":http://jaimeiniesta.com * May 16, 2010: Added a section on configuration gotchas to address common encoding problems that people might have by "Yehuda Katz":http://www.yehudakatz.com * April 30, 2010: Fixes, editing and updating of code samples by "Rohit Arondekar":http://rohitarondekar.com diff --git a/railties/guides/source/i18n.textile b/railties/guides/source/i18n.textile index 0c8e4e974d..4b6b08bcec 100644 --- a/railties/guides/source/i18n.textile +++ b/railties/guides/source/i18n.textile @@ -1,4 +1,4 @@ -lh2. Rails Internationalization (I18n) API +h2. Rails Internationalization (I18n) API The Ruby I18n (shorthand for _internationalization_) gem which is shipped with Ruby on Rails (starting from Rails 2.2) provides an easy-to-use and extensible framework for *translating your application to a single custom language* other than English or for *providing multi-language support* in your application. @@ -796,7 +796,6 @@ h5. Active Support Methods * +Array#to_sentence+ uses format settings as given in the "support.array":https://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L30 scope. - h3. Customize your I18n Setup h4. Using Different Backends diff --git a/railties/guides/source/initialization.textile b/railties/guides/source/initialization.textile index 477ee5a3a2..9cc4dd5f04 100644 --- a/railties/guides/source/initialization.textile +++ b/railties/guides/source/initialization.textile @@ -1,6 +1,6 @@ h2. The Rails Initialization Process -This guide explains the internals of the initialization process in Rails works as of Rails 3.1. It is an extremely in-depth guide and recommended for advanced Rails developers. +This guide explains the internals of the initialization process in Rails as of Rails 3.1. It is an extremely in-depth guide and recommended for advanced Rails developers. * Using +rails server+ * Using Passenger @@ -33,7 +33,7 @@ end This file will attempt to load +rails/cli+ and if it cannot find it then add the +railties/lib+ path to the load path (+$:+) and will then try to require it again. -h4. +railites/lib/rails/cli.rb+ +h4. +railties/lib/rails/cli.rb+ This file looks like this: @@ -71,7 +71,7 @@ module Rails end </ruby> -The +rails/script_rails_loader+ file uses +RbConfig::Config+ to gather up the +bin_dir+ and +ruby_install_name+ values for the configuration which will result in a path such as +/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby+, which is the default path on Mac OS X. If you're running Windows the path may be something such as +C:/Ruby192/bin/ruby+. Anyway, the path on your system may be different, but the point of this is that it will point at the known ruby executable location for your install. The +RbConfig::CONFIG["EXEEXT"]+ will suffix this path with ".exe" if the script is running on Windows. This constant is used later on in +exec_script_rails!+. As for the +SCRIPT_RAILS+ console, we'll see that when we get to the +in_rails_application?+ method. +The +rails/script_rails_loader+ file uses +RbConfig::Config+ to gather up the +bin_dir+ and +ruby_install_name+ values for the configuration which will result in a path such as +/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby+, which is the default path on Mac OS X. If you're running Windows the path may be something such as +C:/Ruby192/bin/ruby+. Anyway, the path on your system may be different, but the point of this is that it will point at the known ruby executable location for your install. The +RbConfig::CONFIG["EXEEXT"]+ will suffix this path with ".exe" if the script is running on Windows. This constant is used later on in +exec_script_rails!+. As for the +SCRIPT_RAILS+ constant, we'll see that when we get to the +in_rails_application?+ method. Back in +rails/cli+, the next line is this: @@ -190,7 +190,8 @@ aliases = { "g" => "generate", "c" => "console", "s" => "server", - "db" => "dbconsole" + "db" => "dbconsole", + "r" => "runner" } command = ARGV.shift @@ -348,10 +349,10 @@ The class *is* defined in +Rack::Server+, but is overwritten in +Rails::Server+ def parse!(args) args, options = args.dup, {} - opt_parser = OptionParser.new do |opts| - opts.banner = "Usage: rails server [mongrel, thin, etc] [options]" - opts.on("-p", "--port=port", Integer, - "Runs Rails on the specified port.", "Default: 3000") { |v| options[:Port] = v } + opt_parser = OptionParser.new do |opts| + opts.banner = "Usage: rails server [mongrel, thin, etc] [options]" + opts.on("-p", "--port=port", Integer, + "Runs Rails on the specified port.", "Default: 3000") { |v| options[:Port] = v } ... </ruby> @@ -760,7 +761,6 @@ def subclasses end </ruby> - The +config+ method used at the top of +I18n::Railtie+ is defined on +Rails::Railtie+ and is defined like this: <ruby> @@ -847,7 +847,7 @@ The +Collection+ class in +railties/lib/rails/initializable.rb+ inherits from +A The +initializers_chain+ method referenced in the +initializers_for+ method is defined like this: -<rub> +<ruby> def initializers_chain initializers = Collection.new ancestors.reverse_each do | klass | diff --git a/railties/guides/source/layouts_and_rendering.textile b/railties/guides/source/layouts_and_rendering.textile index 57485e8986..87ba8ab82d 100644 --- a/railties/guides/source/layouts_and_rendering.textile +++ b/railties/guides/source/layouts_and_rendering.textile @@ -1179,14 +1179,14 @@ On pages generated by +NewsController+, you want to hide the top menu and add a <% end %> <% content_for :content do %> <div id="right_menu">Right menu items here</div> - <%= yield(:news_content) or yield %> + <%= content_for?(:news_content) ? yield(:news_content) : yield %> <% end %> <%= render :template => 'layouts/application' %> </erb> That's it. The News views will use the new layout, hiding the top menu and adding a new right menu inside the "content" div. -There are several ways of getting similar results with different sub-templating schemes using this technique. Note that there is no limit in nesting levels. One can use the +ActionView::render+ method via +render :template => 'layouts/news'+ to base a new layout on the News layout. If you are sure you will not subtemplate the +News+ layout, you can replace the +yield(:news_content) or yield+ with simply +yield+. +There are several ways of getting similar results with different sub-templating schemes using this technique. Note that there is no limit in nesting levels. One can use the +ActionView::render+ method via +render :template => 'layouts/news'+ to base a new layout on the News layout. If you are sure you will not subtemplate the +News+ layout, you can replace the +content_for?(:news_content) ? yield(:news_content) : yield+ with simply +yield+. h3. Changelog diff --git a/railties/guides/source/migrations.textile b/railties/guides/source/migrations.textile index e51ee0f535..6fcc3cf4a2 100644 --- a/railties/guides/source/migrations.textile +++ b/railties/guides/source/migrations.textile @@ -300,6 +300,7 @@ change_table :products do |t| t.rename :upccode, :upc_code end </ruby> + removes the +description+ and +name+ columns, creates a +part_number+ column and adds an index on it. Finally it renames the +upccode+ column. This is the same as doing <ruby> @@ -471,13 +472,13 @@ By default migrations tell you exactly what they're doing and how long it took. Several methods are provided that allow you to control all this: -* +suppress_messages+ suppresses any output generated by its block -* +say+ outputs text (the second argument controls whether it is indented or not) +* +suppress_messages+ takes a block as an argument and suppresses any output generated by the block. +* +say+ takes a message argument and outputs it as is. A second boolean argument can be passed to specify whether to indent or not. * +say_with_time+ outputs text along with how long it took to run its block. If the block returns an integer it assumes it is the number of rows affected. For example, this migration -<pre> +<ruby> class CreateProducts < ActiveRecord::Migration def change suppress_messages do @@ -496,7 +497,7 @@ class CreateProducts < ActiveRecord::Migration end end end -</pre> +</ruby> generates the following output @@ -510,7 +511,7 @@ generates the following output 20080906170109 CreateProducts: migrated (10.0097s) </shell> -If you just want Active Record to shut up then running +rake db:migrate VERBOSE=false+ will suppress any output. +If you just want Active Record to shut up then running +rake db:migrate VERBOSE=false+ will suppress all output. h3. Using Models in Your Migrations @@ -525,7 +526,7 @@ Bob goes on vacation. Alice creates a migration for the +products+ table which adds a new column and initializes it. She also adds a validation to the Product model for the new column. -<pre> +<ruby> # db/migrate/20100513121110_add_flag_to_product.rb class AddFlagToProduct < ActiveRecord::Migration @@ -534,19 +535,19 @@ class AddFlagToProduct < ActiveRecord::Migration Product.all.each { |f| f.update_attributes!(:flag => 'false') } end end -</pre> +</ruby> -<pre> +<ruby> # app/model/product.rb class Product < ActiveRecord::Base - validates_presence_of :flag + validates :flag, :presence => true end -</pre> +</ruby> Alice adds a second migration which adds and initializes another column to the +products+ table and also adds a validation to the Product model for the new column. -<pre> +<ruby> # db/migrate/20100515121110_add_fuzz_to_product.rb class AddFuzzToProduct < ActiveRecord::Migration @@ -555,16 +556,15 @@ class AddFuzzToProduct < ActiveRecord::Migration Product.all.each { |f| f.update_attributes! :fuzz => 'fuzzy' } end end -</pre> +</ruby> -<pre> +<ruby> # app/model/product.rb class Product < ActiveRecord::Base - validates_presence_of :flag - validates_presence_of :fuzz + validates :flag, :fuzz, :presence => true end -</pre> +</ruby> Both migrations work for Alice. @@ -575,12 +575,12 @@ Bob comes back from vacation and: The migration crashes because when the model attempts to save, it tries to validate the second added column, which is not in the database when the _first_ migration runs. -<pre> +<plain> rake aborted! An error has occurred, this and all later migrations canceled: undefined method `fuzz' for #<Product:0x000001049b14a0> -</pre> +</plain> A fix for this is to create a local model within the migration. This keeps rails from running the validations, so that the migrations run to completion. @@ -588,21 +588,22 @@ When using a faux model, it's a good idea to call +Product.reset_column_informat If Alice had done this instead, there would have been no problem: -<pre> +<ruby> # db/migrate/20100513121110_add_flag_to_product.rb class AddFlagToProduct < ActiveRecord::Migration class Product < ActiveRecord::Base end + def change add_column :products, :flag, :int - Product.reset_column_information + Product.reset_column_information Product.all.each { |f| f.update_attributes!(:flag => false) } end end -</pre> +</ruby> -<pre> +<ruby> # db/migrate/20100515121110_add_fuzz_to_product.rb class AddFuzzToProduct < ActiveRecord::Migration @@ -614,7 +615,7 @@ class AddFuzzToProduct < ActiveRecord::Migration Product.all.each { |f| f.update_attributes! :fuzz => 'fuzzy' } end end -</pre> +</ruby> h3. Schema Dumping and You diff --git a/railties/guides/source/performance_testing.textile b/railties/guides/source/performance_testing.textile index dbe6f97f5c..75f81cf13d 100644 --- a/railties/guides/source/performance_testing.textile +++ b/railties/guides/source/performance_testing.textile @@ -438,9 +438,9 @@ alias gcrails='~/rubygc/bin/rails' Don't forget to use your aliases from now on. -h6. Install Rubygems (1.8 only!) +h6. Install RubyGems (1.8 only!) -Download "Rubygems":http://rubyforge.org/projects/rubygems and install it from source. Rubygem's README file should have necessary installation instructions. Please note that this step isn't necessary if you've installed Ruby 1.9 and above. +Download "RubyGems":http://rubyforge.org/projects/rubygems and install it from source. Rubygem's README file should have necessary installation instructions. Please note that this step isn't necessary if you've installed Ruby 1.9 and above. h4. Using Ruby-Prof on MRI and REE diff --git a/railties/guides/source/plugins.textile b/railties/guides/source/plugins.textile index 188423861d..d3f9783fa6 100644 --- a/railties/guides/source/plugins.textile +++ b/railties/guides/source/plugins.textile @@ -386,6 +386,7 @@ ActiveRecord::Base.send :include, Yaffle::ActsAsYaffle </ruby> Run +rake+ one final time and you should see: + <shell> 7 tests, 7 assertions, 0 failures, 0 errors, 0 skips </shell> @@ -426,6 +427,7 @@ require 'yaffle' You can test this by changing to the Rails application that you added the plugin to and starting a rails console. Once in the console we can check to see if the String has an instance method of to_squawk. + <shell> $ cd my_app $ rails console diff --git a/railties/guides/source/rails_application_templates.textile b/railties/guides/source/rails_application_templates.textile index 90fc763349..566f8a0bdd 100644 --- a/railties/guides/source/rails_application_templates.textile +++ b/railties/guides/source/rails_application_templates.textile @@ -148,7 +148,7 @@ The above creates +lib/tasks/bootstrap.rake+ with a +boot:strap+ rake task. h4. generate(what, args) -Runs the supplied rails generator with given arguments. For example, I love to scaffold some whenever I’m playing with Rails: +Runs the supplied rails generator with given arguments. <ruby> generate(:scaffold, "person", "name:string", "address:text", "age:number") @@ -176,12 +176,6 @@ You can also run rake tasks with a different Rails environment: rake "db:migrate", :env => 'production' </ruby> -Or even use sudo: - -<ruby> -rake "gems:install", :sudo => true -</ruby> - h4. route(routing_code) This adds a routing entry to the +config/routes.rb+ file. In above steps, we generated a person scaffold and also removed +public/index.html+. Now to make +PeopleController#index+ as the default page for the application: diff --git a/railties/guides/source/rails_on_rack.textile b/railties/guides/source/rails_on_rack.textile index 8d5985dba8..818df0ffaf 100644 --- a/railties/guides/source/rails_on_rack.textile +++ b/railties/guides/source/rails_on_rack.textile @@ -89,23 +89,32 @@ $ rake middleware For a freshly generated Rails application, this might produce something like: <ruby> +use ActionDispatch::Static use Rack::Lock -use ActionController::Failsafe -use ActionController::Session::CookieStore, , {:secret=>"<secret>", :session_key=>"_<app>_session"} -use Rails::Rack::Metal -use ActionDispatch::RewindableInput -use ActionController::ParamsParser -use Rack::MethodOverride -use Rack::Head +use ActiveSupport::Cache::Strategy::LocalCache +use Rack::Runtime +use Rails::Rack::Logger +use ActionDispatch::ShowExceptions +use ActionDispatch::RemoteIp +use Rack::Sendfile +use ActionDispatch::Callbacks +use ActiveRecord::ConnectionAdapters::ConnectionManagement use ActiveRecord::QueryCache -run ActionController::Dispatcher.new +use ActionDispatch::Cookies +use ActionDispatch::Session::CookieStore +use ActionDispatch::Flash +use ActionDispatch::ParamsParser +use Rack::MethodOverride +use ActionDispatch::Head +use ActionDispatch::BestStandardsSupport +run Blog::Application.routes </ruby> Purpose of each of this middlewares is explained in the "Internal Middlewares":#internal-middleware-stack section. h4. Configuring Middleware Stack -Rails provides a simple configuration interface +config.middleware+ for adding, removing and modifying the middlewares in the middleware stack via +environment.rb+ or the environment specific configuration file <tt>environments/<environment>.rb</tt>. +Rails provides a simple configuration interface +config.middleware+ for adding, removing and modifying the middlewares in the middleware stack via +application.rb+ or the environment specific configuration file <tt>environments/<environment>.rb</tt>. h5. Adding a Middleware @@ -118,7 +127,7 @@ You can add a new middleware to the middleware stack using any of the following * <tt>config.middleware.insert_after(existing_middleware, new_middleware, args)</tt> - Adds the new middleware after the specified existing middleware in the middleware stack. <ruby> -# config/environment.rb +# config/application.rb # Push Rack::BounceFavicon at the bottom config.middleware.use Rack::BounceFavicon @@ -133,7 +142,7 @@ h5. Swapping a Middleware You can swap an existing middleware in the middleware stack using +config.middleware.swap+. <ruby> -# config/environment.rb +# config/application.rb # Replace ActionController::Failsafe with Lifo::Failsafe config.middleware.swap ActionController::Failsafe, Lifo::Failsafe @@ -198,7 +207,7 @@ The following shows how to replace use +Rack::Builder+ instead of the Rails supp <strong>Clear the existing Rails middleware stack</strong> <ruby> -# environment.rb +# config/application.rb config.middleware.clear </ruby> diff --git a/railties/guides/source/security.textile b/railties/guides/source/security.textile index 1f6ff88c1f..04d1d0bda8 100644 --- a/railties/guides/source/security.textile +++ b/railties/guides/source/security.textile @@ -80,7 +80,6 @@ This will also be a good idea, if you modify the structure of an object and old * _(highlight)Critical data should not be stored in session_. If the user clears his cookies or closes the browser, they will be lost. And with a client-side session storage, the user can read the data. - h4. Session Storage -- _Rails provides several storage mechanisms for the session hashes. The most important are ActiveRecordStore and CookieStore._ diff --git a/railties/lib/rails/application/configuration.rb b/railties/lib/rails/application/configuration.rb index 975e159999..f1add68890 100644 --- a/railties/lib/rails/application/configuration.rb +++ b/railties/lib/rails/application/configuration.rb @@ -37,6 +37,8 @@ module Rails @assets.paths = [] @assets.precompile = [ /\w+\.(?!js|css).+/, /application.(css|js)$/ ] @assets.prefix = "/assets" + @assets.version = '' + @assets.debug = false @assets.cache_store = [ :file_store, "#{root}/tmp/cache/assets/" ] @assets.js_compressor = nil diff --git a/railties/lib/rails/commands.rb b/railties/lib/rails/commands.rb index a21484e5cb..ada150ceec 100644 --- a/railties/lib/rails/commands.rb +++ b/railties/lib/rails/commands.rb @@ -4,6 +4,7 @@ ARGV << '--help' if ARGV.empty? aliases = { "g" => "generate", + "d" => "destroy", "c" => "console", "s" => "server", "db" => "dbconsole", @@ -87,7 +88,7 @@ The most common rails commands are: In addition to those, there are: application Generate the Rails application code - destroy Undo code generated with "generate" + destroy Undo code generated with "generate" (short-cut alias: "d") benchmarker See how fast a piece of code runs profiler Get profile information from a piece of code plugin Install a plugin diff --git a/railties/lib/rails/engine.rb b/railties/lib/rails/engine.rb index c41f7d7c2e..2c3f61f404 100644 --- a/railties/lib/rails/engine.rb +++ b/railties/lib/rails/engine.rb @@ -542,9 +542,9 @@ module Rails end initializer :append_assets_path do |app| - app.config.assets.paths.unshift(*paths["vendor/assets"].existent) - app.config.assets.paths.unshift(*paths["lib/assets"].existent) - app.config.assets.paths.unshift(*paths["app/assets"].existent) + app.config.assets.paths.unshift(*paths["vendor/assets"].existent_directories) + app.config.assets.paths.unshift(*paths["lib/assets"].existent_directories) + app.config.assets.paths.unshift(*paths["app/assets"].existent_directories) end initializer :prepend_helpers_path do |app| diff --git a/railties/lib/rails/engine/commands.rb b/railties/lib/rails/engine/commands.rb index 3b0920e213..b71119af77 100644 --- a/railties/lib/rails/engine/commands.rb +++ b/railties/lib/rails/engine/commands.rb @@ -3,7 +3,8 @@ require 'active_support/core_ext/object/inclusion' ARGV << '--help' if ARGV.empty? aliases = { - "g" => "generate" + "g" => "generate", + "d" => "destroy" } command = ARGV.shift @@ -30,7 +31,7 @@ Usage: rails COMMAND [ARGS] The common rails commands available for engines are: generate Generate new code (short-cut alias: "g") - destroy Undo code generated with "generate" + destroy Undo code generated with "generate" (short-cut alias: "d") All commands can be run with -h for more information. EOT diff --git a/railties/lib/rails/generators/rails/app/templates/app/assets/stylesheets/application.css b/railties/lib/rails/generators/rails/app/templates/app/assets/stylesheets/application.css index 9e07c7d9a9..3b5cc6648e 100644 --- a/railties/lib/rails/generators/rails/app/templates/app/assets/stylesheets/application.css +++ b/railties/lib/rails/generators/rails/app/templates/app/assets/stylesheets/application.css @@ -4,10 +4,10 @@ * * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets, * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path. - * + * * You're free to add application-wide styles to this file and they'll appear at the top of the * compiled file, but it's generally better to create a new file per style scope. * *= require_self - *= require_tree . -*/
\ No newline at end of file + *= require_tree . +*/ diff --git a/railties/lib/rails/generators/rails/app/templates/config/application.rb b/railties/lib/rails/generators/rails/app/templates/config/application.rb index 7687b1beac..86c9bd2d1d 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/application.rb +++ b/railties/lib/rails/generators/rails/app/templates/config/application.rb @@ -12,10 +12,12 @@ require "active_resource/railtie" <%= comment_if :skip_test_unit %>require "rails/test_unit/railtie" <% end -%> -# If you have a Gemfile, require the default gems, the ones in the -# current environment and also include :assets gems if in development -# or test environments. -Bundler.require *Rails.groups(:assets) if defined?(Bundler) +if defined?(Bundler) + # If you precompile assets before deploying to production, use this line + Bundler.require *Rails.groups(:assets => %w(development test)) + # If you want your assets lazily compiled in production, use this line + # Bundler.require(:default, :assets, Rails.env) +end module <%= app_const_base %> class Application < Rails::Application diff --git a/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt index 3e0c29a587..47078e3af9 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt +++ b/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt @@ -29,4 +29,7 @@ # Do not compress assets config.assets.compress = false + + # Expands the lines which load the assets + config.assets.debug = true end diff --git a/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt index 06ed890e05..de56d47688 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt +++ b/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt @@ -15,8 +15,8 @@ config.assets.compress = true # Specifies the header that your server uses for sending files - # (comment out if your front-end server doesn't support this) - config.action_dispatch.x_sendfile_header = "X-Sendfile" # Use 'X-Accel-Redirect' for nginx + # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache + # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true diff --git a/railties/lib/rails/generators/rails/app/templates/config/initializers/wrap_parameters.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/initializers/wrap_parameters.rb.tt index fa1548db8b..d640f578da 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/initializers/wrap_parameters.rb.tt +++ b/railties/lib/rails/generators/rails/app/templates/config/initializers/wrap_parameters.rb.tt @@ -4,9 +4,13 @@ # is enabled by default. # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. -ActionController::Base.wrap_parameters <%= key_value :format, "[:json]" %> +ActiveSupport.on_load(:action_controller) do + wrap_parameters <%= key_value :format, "[:json]" %> +end +<%- unless options.skip_active_record? -%> # Disable root element in JSON by default. -if defined?(ActiveRecord) - ActiveRecord::Base.include_root_in_json = false +ActiveSupport.on_load(:active_record) do + self.include_root_in_json = false end +<%- end -%> diff --git a/railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb b/railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb index c46422437d..4baa2110e7 100644 --- a/railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb +++ b/railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb @@ -11,8 +11,6 @@ module Rails def app if mountable? directory "app" - template "app/views/layouts/application.html.erb.tt", - "app/views/layouts/#{name}/application.html.erb" empty_directory_with_gitkeep "app/assets/images/#{name}" elsif full? empty_directory_with_gitkeep "app/models" diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/app/views/layouts/application.html.erb.tt b/railties/lib/rails/generators/rails/plugin_new/templates/app/views/layouts/%name%/application.html.erb.tt index 01550dec2f..01550dec2f 100644 --- a/railties/lib/rails/generators/rails/plugin_new/templates/app/views/layouts/application.html.erb.tt +++ b/railties/lib/rails/generators/rails/plugin_new/templates/app/views/layouts/%name%/application.html.erb.tt diff --git a/railties/lib/rails/paths.rb b/railties/lib/rails/paths.rb index de3d0b6fc5..b37421c09c 100644 --- a/railties/lib/rails/paths.rb +++ b/railties/lib/rails/paths.rb @@ -172,6 +172,10 @@ module Rails expanded.select { |f| File.exists?(f) } end + def existent_directories + expanded.select { |d| File.directory?(d) } + end + alias to_a expanded end end diff --git a/railties/lib/rails/railtie.rb b/railties/lib/rails/railtie.rb index 8c88b25617..e8fb1f3d98 100644 --- a/railties/lib/rails/railtie.rb +++ b/railties/lib/rails/railtie.rb @@ -2,6 +2,7 @@ require 'rails/initializable' require 'rails/configuration' require 'active_support/inflector' require 'active_support/core_ext/module/introspection' +require 'active_support/core_ext/module/delegation' module Rails # Railtie is the core of the Rails framework and provides several hooks to extend diff --git a/railties/lib/rails/tasks/documentation.rake b/railties/lib/rails/tasks/documentation.rake index 5d613e0698..ca8875ad9b 100644 --- a/railties/lib/rails/tasks/documentation.rake +++ b/railties/lib/rails/tasks/documentation.rake @@ -8,6 +8,8 @@ end # Monkey-patch to remove redoc'ing and clobber descriptions to cut down on rake -T noise class RDocTaskWithoutDescriptions < RDoc::Task + include ::Rake::DSL + def define task rdoc_task_name diff --git a/railties/test/application/assets_test.rb b/railties/test/application/assets_test.rb index 7fb930bd99..a8d1382e94 100644 --- a/railties/test/application/assets_test.rb +++ b/railties/test/application/assets_test.rb @@ -46,10 +46,11 @@ module ApplicationTests assert defined?(Uglifier) end - test "precompile creates the file and gives it the original asset's content" do + test "precompile creates the file, gives it the original asset's content and run in production as default" do app_file "app/assets/javascripts/application.js", "alert();" app_file "app/assets/javascripts/foo/application.js", "alert();" + ENV["RAILS_ENV"] = nil capture(:stdout) do Dir.chdir(app_path){ `bundle exec rake assets:precompile` } end @@ -57,15 +58,26 @@ module ApplicationTests files << Dir["#{app_path}/public/assets/foo/application-*.js"].first files.each do |file| assert_not_nil file, "Expected application.js asset to be generated, but none found" - assert_equal "alert();\n", File.read(file) + assert_equal "alert()", File.read(file) end end - test "precompile appends the md5 hash to files referenced with asset_path" do + test "precompile appends the md5 hash to files referenced with asset_path and run in the provided RAILS_ENV" do app_file "app/assets/stylesheets/application.css.erb", "<%= asset_path('rails.png') %>" + # capture(:stdout) do + Dir.chdir(app_path){ `bundle exec rake assets:precompile RAILS_ENV=test` } + # end + file = Dir["#{app_path}/public/assets/application-*.css"].first + assert_match /\/assets\/rails-([0-z]+)\.png/, File.read(file) + end + + test "precompile appends the md5 hash to files referenced with asset_path and run in production as default even using RAILS_GROUPS=assets" do + app_file "app/assets/stylesheets/application.css.erb", "<%= asset_path('rails.png') %>" + + ENV["RAILS_ENV"] = nil capture(:stdout) do - Dir.chdir(app_path){ `bundle exec rake assets:precompile` } + Dir.chdir(app_path){ `bundle exec rake assets:precompile RAILS_GROUPS=assets` } end file = Dir["#{app_path}/public/assets/application-*.css"].first assert_match /\/assets\/rails-([0-z]+)\.png/, File.read(file) @@ -80,7 +92,7 @@ module ApplicationTests Dir.chdir(app_path){ `bundle exec rake assets:clean` } end - files = Dir["#{app_path}/public/assets/**/*"] + files = Dir["#{app_path}/public/assets/**/*", "#{app_path}/tmp/cache/*"] assert_equal 0, files.length, "Expected no assets, but found #{files.join(', ')}" end @@ -109,5 +121,19 @@ module ApplicationTests assert_match "alert()", last_response.body assert_equal nil, last_response.headers["Set-Cookie"] end + + test "files in any assets/ directories are not added to Sprockets" do + %w[app lib vendor].each do |dir| + app_file "#{dir}/assets/#{dir}_test.erb", "testing" + end + + app_file "app/assets/javascripts/demo.js", "alert();" + + require "#{app_path}/config/environment" + + get "/assets/demo.js" + assert_match "alert();", last_response.body + assert_equal 200, last_response.status + end end end diff --git a/railties/test/application/middleware/sendfile_test.rb b/railties/test/application/middleware/sendfile_test.rb index c7a1c573f9..d2ad2668bb 100644 --- a/railties/test/application/middleware/sendfile_test.rb +++ b/railties/test/application/middleware/sendfile_test.rb @@ -27,11 +27,12 @@ module ApplicationTests end # x_sendfile_header middleware - test "config.action_dispatch.x_sendfile_header defaults to ''" do + test "config.action_dispatch.x_sendfile_header defaults to nil" do make_basic_app simple_controller get "/" + assert !last_response.headers["X-Sendfile"] assert_equal File.read(__FILE__), last_response.body end diff --git a/railties/test/generators/app_generator_test.rb b/railties/test/generators/app_generator_test.rb index 0db9b99234..1b48c80042 100644 --- a/railties/test/generators/app_generator_test.rb +++ b/railties/test/generators/app_generator_test.rb @@ -189,7 +189,7 @@ class AppGeneratorTest < Rails::Generators::TestCase assert_file "test/performance/browsing_test.rb" end - def test_generator_if_skip_active_record_is_given + def test_generator_if_skip_sprockets_is_given run_generator [destination_root, "--skip-sprockets"] assert_file "config/application.rb" do |content| assert_match(/#\s+require\s+["']sprockets\/railtie["']/, content) |