diff options
Diffstat (limited to 'guides/source')
20 files changed, 295 insertions, 110 deletions
diff --git a/guides/source/4_0_release_notes.textile b/guides/source/4_0_release_notes.textile index d545798f6f..2f21f8cc71 100644 --- a/guides/source/4_0_release_notes.textile +++ b/guides/source/4_0_release_notes.textile @@ -82,8 +82,6 @@ will generate the model with <tt>belongs_to :supplier, polymorphic: true</tt> as * Load all environments available in <tt>config.paths["config/environments"]</tt>. -* The application generator generates <tt>public/humans.txt</tt> with some basic data. - * Add <tt>config.queue_consumer</tt> to allow the default consumer to be configurable. * Add <tt>Rails.queue</tt> as an interface with a default implementation that consumes jobs in a separate thread. @@ -196,6 +194,37 @@ h5(#actioncontroller_deprecations). Deprecations h4. Action Dispatch +* Add Routing Concerns to declare common routes that can be reused inside others resources and routes. + +Code before: + +<ruby> +resources :messages do + resources :comments +end + +resources :posts do + resources :comments + resources :images, only: :index +end +</ruby> + +Code after: + +<ruby> +concern :commentable do + resources :comments +end + +concern :image_attachable do + resources :images, only: :index +end + +resources :messages, concerns: :commentable + +resources :posts, concerns: [:commentable, :image_attachable] +</ruby> + * Show routes in exception page while debugging a <tt>RoutingError</tt> in development. * Include <tt>mounted_helpers</tt> (helpers for accessing mounted engines) in <tt>ActionDispatch::IntegrationTest</tt> by default. @@ -747,6 +776,8 @@ h3. Active Resource h3. Active Support +* Add default values to all <tt>ActiveSupport::NumberHelper</tt> methods, to avoid errors with empty locales or missing values. + * <tt>Time#change</tt> now works with time values with offsets other than UTC or the local time zone. * Add <tt>Time#prev_quarter</tt> and <tt>Time#next_quarter</tt> short-hands for <tt>months_ago(3)</tt> and <tt>months_since(3)</tt>. diff --git a/guides/source/action_controller_overview.textile b/guides/source/action_controller_overview.textile index cc3350819b..3c828735ae 100644 --- a/guides/source/action_controller_overview.textile +++ b/guides/source/action_controller_overview.textile @@ -478,9 +478,9 @@ class ChangesController < ActionController::Base end </ruby> -Note that an around filter wraps also rendering. In particular, if in the example above the view itself reads from the database via a scope or whatever, it will do so within the transaction and thus present the data to preview. +Note that an around filter also wraps rendering. In particular, if in the example above, the view itself reads from the database (e.g. via a scope), it will do so within the transaction and thus present the data to preview. -They can choose not to yield and build the response themselves, in which case the action is not run. +You can choose not to yield and build the response yourself, in which case the action will not be run. h4. Other Ways to Use Filters diff --git a/guides/source/action_mailer_basics.textile b/guides/source/action_mailer_basics.textile index 54e55d7260..abfa68b76d 100644 --- a/guides/source/action_mailer_basics.textile +++ b/guides/source/action_mailer_basics.textile @@ -4,7 +4,7 @@ This guide should provide you with all you need to get started in sending and re endprologue. -WARNING. This Guide is based on Rails 3.2. Some of the code shown here will not work in earlier versions of Rails. +WARNING. This guide is based on Rails 3.2. Some of the code shown here will not work in earlier versions of Rails. h3. Introduction @@ -84,7 +84,7 @@ Create a file called +welcome_email.html.erb+ in +app/views/user_mailer/+. This </html> </erb> -It is also a good idea to make a text part for this email, to do this, create a file called +welcome_email.text.erb+ in +app/views/user_mailer/+: +It is also a good idea to make a text part for this email. To do this, create a file called +welcome_email.text.erb+ in +app/views/user_mailer/+: <erb> Welcome to example.com, <%= @user.name %> @@ -144,7 +144,7 @@ The method +welcome_email+ returns a <tt>Mail::Message</tt> object which can the 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 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. +WARNING: Sending out an 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. h4. Auto encoding header values @@ -152,14 +152,14 @@ Action Mailer now handles the auto encoding of multibyte characters inside of he 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. +For more complex examples such as defining alternate character sets or self-encoding text first, please refer to the Mail library. h4. Complete List of Action Mailer Methods There are just three methods that you need to send pretty much any email message: -* <tt>headers</tt> - Specifies any header on the email you want, you can pass a hash of header field names and value pairs, or you can call <tt>headers[:field_name] = 'value'</tt> -* <tt>attachments</tt> - Allows you to add attachments to your email, for example <tt>attachments['file-name.jpg'] = File.read('file-name.jpg')</tt> +* <tt>headers</tt> - Specifies any header on the email you want. You can pass a hash of header field names and value pairs, or you can call <tt>headers[:field_name] = 'value'</tt>. +* <tt>attachments</tt> - Allows you to add attachments to your email. For example, <tt>attachments['file-name.jpg'] = File.read('file-name.jpg')</tt>. * <tt>mail</tt> - Sends the actual email itself. You can pass in headers as a hash to the mail method as a parameter, mail will then create an email, either plain text, or multipart, depending on what email templates you have defined. h5. Custom Headers @@ -184,7 +184,7 @@ headers["X-Spam"] = value headers {"X-Spam" => value, "X-Special" => another_value} </ruby> -TIP: All <tt>X-Value</tt> headers per the RFC2822 can appear more than one time. If you want to delete an <tt>X-Value</tt> header, you need to assign it a value of <tt>nil</tt>. +TIP: All <tt>X-Value</tt> headers per the RFC2822 can appear more than once. If you want to delete an <tt>X-Value</tt> header, you need to assign it a value of <tt>nil</tt>. h5. Adding Attachments @@ -196,7 +196,7 @@ Adding attachments has been simplified in Action Mailer 3.0. attachments['filename.jpg'] = File.read('/path/to/filename.jpg') </ruby> -NOTE: Mail will automatically Base64 encode an attachment, if you want something different, pre-encode your content and pass in the encoded content and encoding in a +Hash+ to the +attachments+ method. +NOTE: Mail will automatically Base64 encode an attachment. If you want something different, pre-encode your content and pass in the encoded content and encoding in a +Hash+ to the +attachments+ method. * Pass the file name and specify headers and content and Action Mailer and Mail will use the settings you pass in. @@ -229,7 +229,7 @@ end <%= image_tag attachments['image.jpg'].url %> </erb> -* As this is a standard call to +image_tag+ you can pass in an options hash after the attachment url as you could for any other image: +* As this is a standard call to +image_tag+ you can pass in an options hash after the attachment URL as you could for any other image: <erb> <p>Hello there, this is our image</p> @@ -240,7 +240,7 @@ 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 list of emails can be an array of email addresses or a single string with the addresses separated by commas. +It is possible to send email to one or more recipients in one email (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 @@ -458,6 +458,7 @@ The following configuration options are best made in one of the environment file |+perform_deliveries+|Determines whether deliveries are actually carried out when the +deliver+ method is invoked on the Mail message. By default they are, but this can be turned off to help functional testing.| |+deliveries+|Keeps an array of all the emails sent out through the Action Mailer with delivery_method :test. Most useful for unit and functional testing.| |+async+|Setting this flag will turn on asynchronous message sending, message rendering and delivery will be pushed to <tt>Rails.queue</tt> for processing.| +|+default_options+|Allows you to set default values for the <tt>mail</tt> method options (<tt>:from</tt>, <tt>:reply_to</tt>, etc.).| h4. Example Action Mailer Configuration @@ -472,6 +473,7 @@ config.action_mailer.delivery_method = :sendmail # } config.action_mailer.perform_deliveries = true config.action_mailer.raise_delivery_errors = true +config.action_mailer.default_options = {from: "no-replay@example.org"} </ruby> h4. Action Mailer Configuration for GMail diff --git a/guides/source/active_model_basics.textile b/guides/source/active_model_basics.textile index 7cafff2ad8..2c30ddb84c 100644 --- a/guides/source/active_model_basics.textile +++ b/guides/source/active_model_basics.textile @@ -1,18 +1,18 @@ 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. +This guide should provide you with all you need to get started using model classes. Active Model allows 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. +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 - +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. +The 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 @@ -92,7 +92,7 @@ person.to_param #=> nil 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 +An object becomes dirty when it has gone through one or more changes to its attributes and has not been saved. This gives the ability to check whether an object has been changed or not. It also has attribute based accessor methods. Let's consider a Person class with attributes first_name and last_name <ruby> require 'active_model' @@ -168,7 +168,7 @@ Track what was the previous value of the attribute. 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 +Track both previous and current value of the changed attribute. Returns an array if changed, else returns nil. <ruby> #attr_name_change diff --git a/guides/source/active_record_querying.textile b/guides/source/active_record_querying.textile index dff829a4c1..80c9260a0d 100644 --- a/guides/source/active_record_querying.textile +++ b/guides/source/active_record_querying.textile @@ -53,6 +53,7 @@ To retrieve objects from the database, Active Record provides several finder met The methods are: * +bind+ * +create_with+ +* +eager_load+ * +extending+ * +from+ * +group+ @@ -61,9 +62,11 @@ The methods are: * +joins+ * +limit+ * +lock+ +* +none+ * +offset+ * +order+ * +none+ +* +preload+ * +readonly+ * +references+ * +reorder+ diff --git a/guides/source/active_support_core_extensions.textile b/guides/source/active_support_core_extensions.textile index 66de6fd310..109228f8c7 100644 --- a/guides/source/active_support_core_extensions.textile +++ b/guides/source/active_support_core_extensions.textile @@ -1325,6 +1325,41 @@ that amount of leading whitespace. NOTE: Defined in +active_support/core_ext/string/strip.rb+. +h4. +indent+ + +Indents the lines in the receiver: + +<ruby> +<<EOS.indent(2) +def some_method + some_code +end +EOS +# => + def some_method + some_code + end +</ruby> + +The second argument, +indent_string+, specifies which indent string to use. The default is +nil+, which tells the method to make an educated guess peeking at the first indented line, and fallback to a space if there is none. + +<ruby> +" foo".indent(2) # => " foo" +"foo\n\t\tbar".indent(2) # => "\t\tfoo\n\t\t\t\tbar" +"foo".indent(2, "\t") # => "\t\tfoo" +</ruby> + +While +indent_string+ is tipically one space or tab, it may be any string. + +The third argument, +indent_empty_lines+, is a flag that says whether empty lines should be indented. Default is false. + +<ruby> +"foo\n\nbar".indent(2) # => " foo\n\n bar" +"foo\n\nbar".indent(2, nil, true) # => " foo\n \n bar" +</ruby> + +The +indent!+ method performs indentation in-place. + h4. Access h5. +at(position)+ diff --git a/guides/source/api_documentation_guidelines.textile b/guides/source/api_documentation_guidelines.textile index c6aa1f0a2b..3de5b119ee 100644 --- a/guides/source/api_documentation_guidelines.textile +++ b/guides/source/api_documentation_guidelines.textile @@ -127,7 +127,7 @@ class Array end </ruby> -WARNING: Using a pair of ++...++ for fixed-width font only works with *words*; that is: anything matching <tt>\A\w+\z</tt>. For anything else use +<tt>...</tt>+, notably symbols, setters, inline snippets, etc: +WARNING: Using a pair of ++...++ for fixed-width font only works with *words*; that is: anything matching <tt>\A\w+\z</tt>. For anything else use +<tt>...</tt>+, notably symbols, setters, inline snippets, etc. h4. Regular Font diff --git a/guides/source/asset_pipeline.textile b/guides/source/asset_pipeline.textile index 8fec109951..e385ec4f17 100644 --- a/guides/source/asset_pipeline.textile +++ b/guides/source/asset_pipeline.textile @@ -443,6 +443,8 @@ If you have other manifests or individual stylesheets and JavaScript files to in config.assets.precompile += ['admin.js', 'admin.css', 'swfObject.js'] </erb> +NOTE. Always specify an expected compiled filename that ends with js or css, even if you want to add Sass or CoffeeScript files to the precompile array. + The rake task also generates a +manifest.yml+ that contains a list with all your assets and their respective fingerprints. This is used by the Rails helper methods to avoid handing the mapping requests back to Sprockets. A typical manifest file looks like: <plain> diff --git a/guides/source/association_basics.textile b/guides/source/association_basics.textile index 2b8b1bd937..d4c0a1ba74 100644 --- a/guides/source/association_basics.textile +++ b/guides/source/association_basics.textile @@ -967,10 +967,13 @@ end h6(#has_one-dependent). +:dependent+ -If you set the +:dependent+ option to +:destroy+, then deleting this object will call the +destroy+ method on the associated object to delete that object. If you set the +:dependent+ option to +:delete+, then deleting this object will delete the associated object _without_ calling its +destroy+ method. If you set the +:dependent+ option to +:nullify+, then deleting this object will set the foreign key in the association object to +NULL+. -If you set the +:dependent+ option to +:restrict+, then the deletion of the object is restricted if a dependent associated object exist and a +DeleteRestrictionError+ exception is raised. +Controls what happens to the associated object when its owner is destroyed: -NOTE: The default behavior for +:dependent => :restrict+ is to raise a +DeleteRestrictionError+ when associated objects exist. Since Rails 4.0 this behavior is being deprecated in favor of adding an error to the base model. To silence the warning in Rails 4.0, you should fix your code to not expect this Exception and add +config.active_record.dependent_restrict_raises = false+ to your application config. +* +:destroy+ causes the associated object to also be destroyed +* +:delete+ causes the asssociated object to be deleted directly from the database (so callbacks will not execute) +* +:nullify+ causes the foreign key to be set to +NULL+. Callbacks are not executed. +* +:restrict_with_exception+ causes an exception to be raised if there is an associated record +* +:restrict_with_error+ causes an error to be added to the owner if there is an associated object h6(#has_one-foreign_key). +:foreign_key+ @@ -1307,10 +1310,13 @@ end h6(#has_many-dependent). +:dependent+ -If you set the +:dependent+ option to +:destroy+, then deleting this object will call the +destroy+ method on the associated objects to delete those objects. If you set the +:dependent+ option to +:delete_all+, then deleting this object will delete the associated objects _without_ calling their +destroy+ method. If you set the +:dependent+ option to +:nullify+, then deleting this object will set the foreign key in the associated objects to +NULL+. -If you set the +:dependent+ option to +:restrict+, then the deletion of the object is restricted if a dependent associated object exist and a +DeleteRestrictionError+ exception is raised. +Controls what happens to the associated objects when their owner is destroyed: -NOTE: The default behavior for +:dependent => :restrict+ is to raise a +DeleteRestrictionError+ when associated objects exist. Since Rails 4.0 this behavior is being deprecated in favor of adding an error to the base model. To silence the warning in Rails 4.0, you should fix your code to not expect this Exception and add +config.active_record.dependent_restrict_raises = false+ to your application config. +* +:destroy+ causes all the associated objects to also be destroyed +* +:delete_all+ causes all the asssociated objects to be deleted directly from the database (so callbacks will not execute) +* +:nullify+ causes the foreign keys to be set to +NULL+. Callbacks are not executed. +* +:restrict_with_exception+ causes an exception to be raised if there are any associated records +* +:restrict_with_error+ causes an error to be added to the owner if there are any associated objects NOTE: This option is ignored when you use the +:through+ option on the association. diff --git a/guides/source/caching_with_rails.textile b/guides/source/caching_with_rails.textile index 3ee36ae971..815b2ef9c2 100644 --- a/guides/source/caching_with_rails.textile +++ b/guides/source/caching_with_rails.textile @@ -33,7 +33,7 @@ class ProductsController < ActionController caches_page :index def index - @products = Products.all + @products = Product.all end end </ruby> @@ -52,7 +52,7 @@ class ProductsController < ActionController caches_page :index def index - @products = Products.all + @products = Product.all end def create diff --git a/guides/source/configuring.textile b/guides/source/configuring.textile index cc5c352df4..5ed3ad4a6b 100644 --- a/guides/source/configuring.textile +++ b/guides/source/configuring.textile @@ -286,8 +286,6 @@ h4. Configuring Active Record * +config.active_record.auto_explain_threshold_in_seconds+ configures the threshold for automatic EXPLAINs (+nil+ disables this feature). Queries exceeding the threshold get their query plan logged. Default is 0.5 in development mode. -* +config.active_record.dependent_restrict_raises+ will control the behavior when an object with a <tt>:dependent => :restrict</tt> association is deleted. Setting this to false will prevent +DeleteRestrictionError+ from being raised and instead will add an error on the model object. Defaults to false in the development mode. - * +config.active_record.mass_assignment_sanitizer+ will determine the strictness of the mass assignment sanitization within Rails. Defaults to +:strict+. In this mode, mass assigning any non-+attr_accessible+ attribute in a +create+ or +update_attributes+ call will raise an exception. Setting this option to +:logger+ will only print to the log file when an attribute is being assigned and will not raise an exception. The MySQL adapter adds one additional configuration option: @@ -340,6 +338,12 @@ h4. Configuring Action Dispatch * +config.action_dispatch.session_store+ sets the name of the store for session data. The default is +:cookie_store+; other valid options include +:active_record_store+, +:mem_cache_store+ or the name of your own custom class. +* +config.action_dispatch.default_headers+ is a hash with HTTP headers that are set by default in each response. By default, this is defined as: + +<ruby> +config.action_dispatch.default_headers = { 'X-Frame-Options' => 'SAMEORIGIN', 'X-XSS-Protection' => '1; mode=block' } +</ruby> + * +config.action_dispatch.tld_length+ sets the TLD (top-level domain) length for the application. Defaults to +1+. * +ActionDispatch::Callbacks.before+ takes a block of code to run before the request. diff --git a/guides/source/contributing_to_ruby_on_rails.textile b/guides/source/contributing_to_ruby_on_rails.textile index dd43ef795f..4bb4e3b546 100644 --- a/guides/source/contributing_to_ruby_on_rails.textile +++ b/guides/source/contributing_to_ruby_on_rails.textile @@ -36,20 +36,26 @@ Please don't put "feature request" items into GitHub Issues. If there's a new fe If you'd like feedback on an idea for a feature before doing the work for make a patch, please send an email to the "rails-core mailing list":https://groups.google.com/forum/?fromgroups#!forum/rubyonrails-core. You might get no response, which means that everyone is indifferent. You might find someone who's also interested in building that feature. You might get a "This won't be accepted." But it's the proper place to discuss new ideas. GitHub Issues are not a particularly good venue for the sometimes long and involved discussions new features require. -h3. Running the Test Suite +h3. Setting Up a Development Environment To move on from submitting bugs to helping resolve existing issues or contributing your own code to Ruby on Rails, you _must_ be able to run its test suite. In this section of the guide you'll learn how to set up the tests on your own computer. -h4. Install Git +h4. The Easy Way -Ruby on Rails uses git for source code control. The "git homepage":http://git-scm.com/ has installation instructions. There are a variety of resources on the net that will help you get familiar with git: +The easiest way to get a development environment ready to hack is to use the "Rails development box":https://github.com/rails/rails-dev-box. -* "Everyday Git":http://schacon.github.com/git/everyday.html will teach you just enough about git to get by. -* The "PeepCode screencast":https://peepcode.com/products/git on git ($9) is easier to follow. -* "GitHub":http://help.github.com offers links to a variety of git resources. -* "Pro Git":http://progit.org/book/ is an entire book about git with a Creative Commons license. +h4. The Hard Way -h4. Clone the Ruby on Rails Repository +h5. Install Git + +Ruby on Rails uses Git for source code control. The "Git homepage":http://git-scm.com/ has installation instructions. There are a variety of resources on the net that will help you get familiar with Git: + +* "Everyday Git":http://schacon.github.com/git/everyday.html will teach you just enough about Git to get by. +* The "PeepCode screencast":https://peepcode.com/products/git on Git ($9) is easier to follow. +* "GitHub":http://help.github.com offers links to a variety of Git resources. +* "Pro Git":http://git-scm.com/book is an entire book about Git with a Creative Commons license. + +h5. Clone the Ruby on Rails Repository Navigate to the folder where you want the Ruby on Rails source code (it will create its own +rails+ subdirectory) and run: @@ -58,7 +64,7 @@ $ git clone git://github.com/rails/rails.git $ cd rails </shell> -h4. Set up and Run the Tests +h5. Set up and Run the Tests The test suite must pass with any submitted code. No matter whether you are writing a new patch, or evaluating someone else's, you need to be able to run the tests. @@ -74,7 +80,7 @@ If you are on Fedora or CentOS, you can run $ sudo yum install libxml2 libxml2-devel libxslt libxslt-devel </shell> -If you have any problems with these libraries, you should install them manually compiling the source code. Just follow the instructions "here":http://nokogiri.org/tutorials/installing_nokogiri.html#red_hat__centos . +If you have any problems with these libraries, you should install them manually compiling the source code. Just follow the instructions at the "Red Hat/CentOS section of the Nokogiri tutorials":http://nokogiri.org/tutorials/installing_nokogiri.html#red_hat__centos . Also, SQLite3 and its development files for the +sqlite3-ruby+ gem -- in Ubuntu you're done with just @@ -128,36 +134,17 @@ $ cd actionpack $ bundle exec ruby -Itest test/template/form_helper_test.rb </shell> -h4. Warnings - -The test suite runs with warnings enabled. Ideally, Ruby on Rails should issue no warnings, but there may be a few, as well as some from third-party libraries. Please ignore (or fix!) them, if any, and submit patches that do not issue new warnings. - -As of this writing (December, 2010) they are specially noisy with Ruby 1.9. If you are sure about what you are doing and would like to have a more clear output, there's a way to override the flag: - -<shell> -$ RUBYOPT=-W0 bundle exec rake test -</shell> - -h4. Testing Active Record +h5. Active Record Setup The test suite of Active Record attempts to run four times: once for SQLite3, once for each of the two MySQL gems (+mysql+ and +mysql2+), and once for PostgreSQL. We are going to see now how to set up the environment for them. WARNING: If you're working with Active Record code, you _must_ ensure that the tests pass for at least MySQL, PostgreSQL, and SQLite3. Subtle differences between the various adapters have been behind the rejection of many patches that looked OK when tested only against MySQL. -h5. Database Configuration +h6. Database Configuration The Active Record test suite requires a custom config file: +activerecord/test/config.yml+. An example is provided in +activerecord/test/config.example.yml+ which can be copied and used as needed for your environment. -h5. SQLite3 - -The gem +sqlite3-ruby+ does not belong to the "db" group. Indeed, if you followed the instructions above you're ready. This is how you run the Active Record test suite only for SQLite3: - -<shell> -$ cd activerecord -$ bundle exec rake test_sqlite3 -</shell> - -h5. MySQL and PostgreSQL +h6. MySQL and PostgreSQL To be able to run the suite for MySQL and PostgreSQL we need their gems. Install first the servers, their client libraries, and their development files. In Ubuntu just run @@ -217,6 +204,15 @@ NOTE: You'll see the following warning (or localized warning) during activating If you’re using another database, check the file +activerecord/test/config.yml+ or +activerecord/test/config.example.yml+ for default connection information. You can edit +activerecord/test/config.yml+ to provide different credentials on your machine if you must, but obviously you should not push any such changes back to Rails. +h3. Testing Active Record + +This is how you run the Active Record test suite only for SQLite3: + +<shell> +$ cd activerecord +$ bundle exec rake test_sqlite3 +</shell> + You can now run the tests as you did for +sqlite3+. The tasks are respectively <shell> @@ -225,7 +221,7 @@ test_mysql2 test_postgresql </shell> -As we mentioned before +Finally, <shell> $ bundle exec rake test @@ -241,6 +237,16 @@ $ ARCONN=sqlite3 ruby -Itest test/cases/associations/has_many_associations_test. You can invoke +test_jdbcmysql+, +test_jdbcsqlite3+ or +test_jdbcpostgresql+ also. See the file +activerecord/RUNNING_UNIT_TESTS+ for information on running more targeted database tests, or the file +ci/travis.rb+ for the test suite run by the continuous integration server. +h4. Warnings + +The test suite runs with warnings enabled. Ideally, Ruby on Rails should issue no warnings, but there may be a few, as well as some from third-party libraries. Please ignore (or fix!) them, if any, and submit patches that do not issue new warnings. + +As of this writing (December, 2010) they are specially noisy with Ruby 1.9. If you are sure about what you are doing and would like to have a more clear output, there's a way to override the flag: + +<shell> +$ RUBYOPT=-W0 bundle exec rake test +</shell> + h4. Older Versions of Ruby on Rails If you want to add a fix to older versions of Ruby on Rails, you'll need to set up and switch to your own local tracking branch. Here is an example to switch to the 3-0-stable branch: @@ -250,7 +256,7 @@ $ git branch --track 3-0-stable origin/3-0-stable $ git checkout 3-0-stable </shell> -TIP: You may want to "put your git branch name in your shell prompt":http://qugstart.com/blog/git-and-svn/add-colored-git-branch-name-to-your-shell-prompt/ to make it easier to remember which version of the code you're working with. +TIP: You may want to "put your Git branch name in your shell prompt":http://qugstart.com/blog/git-and-svn/add-colored-git-branch-name-to-your-shell-prompt/ to make it easier to remember which version of the code you're working with. h3. Helping to Resolve Existing Issues @@ -331,7 +337,7 @@ $ cd rails $ git checkout -b my_new_branch </shell> -It doesn’t matter much what name you use, because this branch will only exist on your local computer and your personal repository on Github. It won't be part of the Rails git repository. +It doesn’t matter much what name you use, because this branch will only exist on your local computer and your personal repository on Github. It won't be part of the Rails Git repository. h4. Write Your Code @@ -359,6 +365,31 @@ Rails follows a simple set of coding style conventions. The above are guidelines -- please use your best judgment in using them. +h4. Updating the CHANGELOG + +The CHANGELOG is an important part of every release. It keeps the list of changes for every Rails version. + +You should add an entry to the CHANGELOG of the framework that you modified if you're adding or removing a feature, commiting a bug fix or adding deprecation notices. Refactorings and documentation changes generally should not go to the CHANGELOG. + +A CHANGELOG entry should summarize what was changed and should end with author's name. You can use multiple lines if you need more space and you can attach code examples indented with 4 spaces. If a change is related to a specific issue, you should attach issue's number. Here is an example CHANGELOG entry: + +<plain> +* Summary of a change that briefly describes what was changed. You can use multiple + lines and wrap them at around 80 characters. Code examples are ok, too, if needed: + + class Foo + def bar + puts 'baz' + end + end + + You can continue after the code example and you can attach issue number. GH#1234 + + * Your Name * +</plain> + +Your name can be added directly after the last word if you don't provide any code examples or don't need multiple paragraphs. Otherwise, it's best to make as a new paragraph. + h4. Sanity Check You should not be the only person who looks at the code before you submit it. You know at least one other Rails developer, right? Show them what you’re doing and ask for feedback. Doing this in private before you push a patch out publicly is the “smoke test” for a patch: if you can’t convince one other developer of the beauty of your code, you’re unlikely to convince the core team either. @@ -367,7 +398,7 @@ You might want also to check out the "RailsBridge BugMash":http://wiki.railsbrid h4. Commit Your Changes -When you're happy with the code on your computer, you need to commit the changes to git: +When you're happy with the code on your computer, you need to commit the changes to Git: <shell> $ git commit -a @@ -386,7 +417,7 @@ the commit content is obvious, it may not be obvious to others. You should add such description also if it's already present in bug tracker, it should not be necessary to visit a webpage to check the history. -Description can have multiple paragraps and you can use code examples +Description can have multiple paragraphs and you can use code examples inside, just indent it with 4 spaces: class PostsController @@ -495,7 +526,7 @@ It’s entirely possible that the feedback you get will suggest changes. Don’t h4. Backporting -Changes that are merged into master are intended for the next major release of Rails. Sometimes, it might be beneficial for your changes to propagate back to the maintenance releases for older stable branches. Generally, security fixes and bug fixes are good candidates for a backport, while new features and patches that introduce a change in behavior will not be accepted. When in doubt, it is best to consult a rails team member before backporting your changes to avoid wasted effort. +Changes that are merged into master are intended for the next major release of Rails. Sometimes, it might be beneficial for your changes to propagate back to the maintenance releases for older stable branches. Generally, security fixes and bug fixes are good candidates for a backport, while new features and patches that introduce a change in behavior will not be accepted. When in doubt, it is best to consult a Rails team member before backporting your changes to avoid wasted effort. For simple fixes, the easiest way to backport your changes is to "extract a diff from your changes in master and apply them to the target branch":http://ariejan.net/2009/10/26/how-to-create-and-apply-a-patch-with-git. @@ -520,9 +551,9 @@ $ git apply ~/my_changes.patch This works well for simple changes. However, if your changes are complicated or if the code in master has deviated significantly from your target branch, it might require more work on your part. The difficulty of a backport varies greatly from case to case, and sometimes it is simply not worth the effort. -Once you have resolved all conflicts and made sure all the tests are passing, push your changes and open a separate pull request for your backport. It is also worth noting that older branches might have a different set of build targets than master. When possible, it is best to first test your backport locally against the ruby versions listed in +.travis.yml+ before submitting your pull request. +Once you have resolved all conflicts and made sure all the tests are passing, push your changes and open a separate pull request for your backport. It is also worth noting that older branches might have a different set of build targets than master. When possible, it is best to first test your backport locally against the Ruby versions listed in +.travis.yml+ before submitting your pull request. -And then ... think about your next contribution! +And then... think about your next contribution! h3. Rails Contributors diff --git a/guides/source/engines.textile b/guides/source/engines.textile index 11c837be32..de4bbb5656 100644 --- a/guides/source/engines.textile +++ b/guides/source/engines.textile @@ -655,15 +655,17 @@ This tells the application that you still want to perform a +GET+ request to the h3. Improving engine functionality -This section looks at overriding or adding functionality to the views, controllers and models provided by an engine. +This section explains how to add and/or override engine MVC functionality in the main Rails application. -h4. Overriding Models +h4. Overriding Models and Controllers -Engine Models can be extended by (1) implementing decorators, or (2) including modules. +Engine model and controller classes can be extended by open classing them in the main Rails application (since model and controller classes are just Ruby classes that inherit Rails specific functionality). Open classing an Engine class redefines it for use in the main applicaiton. This is usually implemented by using the decorator pattern. -h5. Decorators +For simple class modifications use Class#class_eval, and for complex class modifications, consider using ActiveSupport::Concern. -Decorators extends Engine's model classes in the main application by open classing Engine models at run time execution. +h5. Implementing Decorator Pattern Using Class#class_eval + +**Adding** Post#time_since_created, <ruby> # MyApp/app/decorators/models/blorgh/post_decorator.rb @@ -675,15 +677,48 @@ Blorgh::Post.class_eval do end </ruby> -h5. Modules +<ruby> +# Blorgh/app/models/post.rb + +class Post < ActiveRecord::Base + :has_many :comments +end +</ruby> + + +**Overriding** Post#summary -The other strategy is to create modules within the Engine holding all the models' code and include these in the respective Engine's model classes. Thus the Engine's model classes contain a mere include line referencing the respective module. +<ruby> +# MyApp/app/decorators/models/blorgh/post_decorator.rb -Engine models can be overriden in the main application by creating a file with the Engine's same namespace and including the module originally referenced in the Engine's model class. ["**ActiveSupport::Concern**":http://edgeapi.rubyonrails.org/classes/ActiveSupport/Concern.html] helps manage the correct ordering of module dependencies at run time (it's worth it to reach the linked documentation). +Blorgh::Post.class_eval do + def summary + "#{title} - #{truncate(text)}" + end +end +</ruby> + +<ruby> +# Blorgh/app/models/post.rb + +class Post < ActiveRecord::Base + :has_many :comments + def summary + "#{title}" + end +end +</ruby> + + +h5. Implementing Decorator Pattern Using ActiveSupport::Concern + +Using Class#class_eval is great for simple adjustments, but for more complex class modifications, you might want to consider using ActiveSupport::Concern. ["**ActiveSupport::Concern**":http://edgeapi.rubyonrails.org/classes/ActiveSupport/Concern.html] helps manage load order of interlinked dependencies at run time allowing you to significantly modularize your code. + +**Adding** Post#time_since_created<br/> +**Overriding** Post#summary <ruby> # MyApp/app/models/blorgh/post.rb -# overrides Blorgh's original Post model class Blorgh::Post < ActiveRecord::Base include Blorgh::Concerns::Models::Post @@ -691,24 +726,30 @@ class Blorgh::Post < ActiveRecord::Base def time_since_created Time.current - created_at end -end + def summary + "#{title} - #{truncate(text)}" + end +end +</ruby> +<ruby> # Blorgh/app/models/post.rb -# this class is overriden by the MyApp Post model class Post < ActiveRecord::Base include Blorgh::Concerns::Models::Post end +</ruby> +<ruby> +# Blorgh/lib/concerns/models/post -# Blorgh/app/concerns/models/post - -module Blorg::Concerns::Models::Post +module Blorgh::Concerns::Models::Post extend ActiveSupport::Concern - # 'included do' causes the code within to be evaluated in the conext - # where it is included, rather be executed in the module's context. + # 'included do' causes the included code to be evaluated in the + # conext where it is included (post.rb), rather than be + # executed in the module's context (blorgh/concerns/models/post). included do attr_accessor :author_name belongs_to :author, :class_name => "User" @@ -722,9 +763,8 @@ module Blorg::Concerns::Models::Post end end - # methods defined here will be instance methods by default - def some_method - 'some method string' + def summary + "#{title}" end module ClassMethods diff --git a/guides/source/i18n.textile b/guides/source/i18n.textile index c782539399..67863e590c 100644 --- a/guides/source/i18n.textile +++ b/guides/source/i18n.textile @@ -565,7 +565,7 @@ I18n.translate :thanks, :name => 'Jeremy' # => 'Thanks Jeremy!' </ruby> -If a translation uses +:default+ or +:scope+ as an interpolation variable, an I+18n::ReservedInterpolationKey+ exception is raised. If a translation expects an interpolation variable, but this has not been passed to +#translate+, an +I18n::MissingInterpolationArgument+ exception is raised. +If a translation uses +:default+ or +:scope+ as an interpolation variable, an +I18n::ReservedInterpolationKey+ exception is raised. If a translation expects an interpolation variable, but this has not been passed to +#translate+, an +I18n::MissingInterpolationArgument+ exception is raised. h4. Pluralization diff --git a/guides/source/initialization.textile b/guides/source/initialization.textile index 43d89eac4b..b23f31cb1a 100644 --- a/guides/source/initialization.textile +++ b/guides/source/initialization.textile @@ -17,7 +17,7 @@ NOTE: Paths in this guide are relative to Rails or a Rails application unless ot TIP: If you want to follow along while browsing the Rails "source code":https://github.com/rails/rails, we recommend that you use the +t+ -key binding to open the file finder inside github and find files +key binding to open the file finder inside GitHub and find files quickly. h3. Launch! @@ -359,7 +359,7 @@ set earlier) is required. h4. +config/application+ When +require APP_PATH+ is executed, +config/application.rb+ is loaded. -This is a file exists in your app and it's free for you to change based +This file exists in your app and it's free for you to change based on your needs. h4. +Rails::Server#start+ @@ -453,7 +453,7 @@ end The interesting part for a Rails app is the last line, +server.run+. Here we encounter the +wrapped_app+ method again, which this time we're going to explore more (even though it was executed before, and -thus memoized by now). +thus memorized by now). <ruby> @wrapped_app ||= build_app app @@ -540,12 +540,12 @@ end </ruby> This is where all the Rails frameworks are loaded and thus made -available to the application. We wont go into detail of what happens +available to the application. We won't go into detail of what happens inside each of those frameworks, but you're encouraged to try and explore them on your own. For now, just keep in mind that common functionality like Rails engines, -I18n and Rails configuration is all bein defined here. +I18n and Rails configuration is all being defined here. h4. Back to +config/environment.rb+ @@ -657,10 +657,10 @@ def self.run(app, options={}) end </ruby> -We wont dig into the server configuration itself, but this is +We won't dig into the server configuration itself, but this is the last piece of our journey in the Rails initialization process. -This high level overview will help you understand when you code is +This high level overview will help you understand when your code is executed and how, and overall become a better Rails developer. If you still want to know more, the Rails source code itself is probably the best place to go next. diff --git a/guides/source/kindle/KINDLE.md b/guides/source/kindle/KINDLE.md index a7d9a4e4cf..08937e053e 100644 --- a/guides/source/kindle/KINDLE.md +++ b/guides/source/kindle/KINDLE.md @@ -9,16 +9,16 @@ ## Resources - * [StackOverflow: Kindle Periodical Format](http://stackoverflow.com/questions/5379565/kindle-periodical-format) + * [Stack Overflow: Kindle Periodical Format](http://stackoverflow.com/questions/5379565/kindle-periodical-format) * Example Periodical [.ncx](https://gist.github.com/808c971ed087b839d462) and [.opf](https://gist.github.com/d6349aa8488eca2ee6d0) - * [Kindle Publishing guidelines](http://kindlegen.s3.amazonaws.com/AmazonKindlePublishingGuidelines.pdf) + * [Kindle Publishing Guidelines](http://kindlegen.s3.amazonaws.com/AmazonKindlePublishingGuidelines.pdf) * [KindleGen & Kindle Previewer](http://www.amazon.com/gp/feature.html?ie=UTF8&docId=1000234621) ## TODO ### Post release - * Integrate generated Kindle document in to published HTML guides + * Integrate generated Kindle document into published HTML guides * Tweak heading styles (most docs use h3/h4/h5, which end up being smaller than the text under it) * Tweak table styles (smaller text? Many of the tables are unusable on a Kindle in portrait mode) * Have the HTML/XML TOC 'drill down' into the TOCs of the individual guides diff --git a/guides/source/kindle/welcome.html.erb b/guides/source/kindle/welcome.html.erb index e30704c4e6..610a71570f 100644 --- a/guides/source/kindle/welcome.html.erb +++ b/guides/source/kindle/welcome.html.erb @@ -2,4 +2,4 @@ <h3>Kindle Edition</h3> -The Kindle Edition of the Rails Guides should be considered a work in progress. Feedback is really welcome, please see the "Feedback" section at the end of each guide for instructions. +The Kindle Edition of the Rails Guides should be considered a work in progress. Feedback is really welcome. Please see the "Feedback" section at the end of each guide for instructions. diff --git a/guides/source/performance_testing.textile b/guides/source/performance_testing.textile index b7d4f1ef33..6c5676c346 100644 --- a/guides/source/performance_testing.textile +++ b/guides/source/performance_testing.textile @@ -649,6 +649,7 @@ h4. Rails Plugins and Gems * "Palmist":http://www.flyingmachinestudios.com/programming/announcing-palmist * "Rails Footnotes":https://github.com/josevalim/rails-footnotes/tree/master * "Query Reviewer":https://github.com/dsboulder/query_reviewer/tree/master +* "MiniProfiler":http://www.miniprofiler.com h4. Generic Tools @@ -668,4 +669,4 @@ Rails has been lucky to have a few companies dedicated to Rails-specific performance tools. A couple of those are: * "New Relic":http://www.newrelic.com -* "Scout":http://scoutapp.com
\ No newline at end of file +* "Scout":http://scoutapp.com diff --git a/guides/source/plugins.textile b/guides/source/plugins.textile index 9001857a5f..fbd317f0c2 100644 --- a/guides/source/plugins.textile +++ b/guides/source/plugins.textile @@ -13,7 +13,7 @@ After reading this guide you should be familiar with: This guide describes how to build a test-driven plugin that will: -* Extend core ruby classes like Hash and String +* Extend core Ruby classes like Hash and String * Add methods to ActiveRecord::Base in the tradition of the 'acts_as' plugins * Give you information about where to put generators in your plugin. @@ -28,7 +28,7 @@ h3. Setup _"vendored plugins"_ were available in previous versions of Rails, but they are deprecated in Rails 3.2, and will not be available in the future. -Currently, Rails plugins are built as gems, _gemified plugins_. They can be shared accross +Currently, Rails plugins are built as gems, _gemified plugins_. They can be shared across different rails applications using RubyGems and Bundler if desired. h4. Generate a gemified plugin. @@ -392,7 +392,7 @@ the creation of generators can be found in the "Generators Guide":generators.htm h3. Publishing your Gem Gem plugins currently in development can easily be shared from any Git repository. To share the Yaffle gem with others, simply -commit the code to a Git repository (like Github) and add a line to the Gemfile of the application in question: +commit the code to a Git repository (like GitHub) and add a line to the Gemfile of the application in question: <ruby> gem 'yaffle', :git => 'git://github.com/yaffle_watcher/yaffle.git' @@ -401,7 +401,7 @@ gem 'yaffle', :git => 'git://github.com/yaffle_watcher/yaffle.git' After running +bundle install+, your gem functionality will be available to the application. When the gem is ready to be shared as a formal release, it can be published to "RubyGems":http://www.rubygems.org. -For more information about publishing gems to RubyGems, see: "http://blog.thepete.net/2010/11/creating-and-publishing-your-first-ruby.html":http://blog.thepete.net/2010/11/creating-and-publishing-your-first-ruby.html +For more information about publishing gems to RubyGems, see: "Creating and Publishing Your First Ruby Gem":http://blog.thepete.net/2010/11/creating-and-publishing-your-first-ruby.html h3. RDoc Documentation @@ -414,7 +414,7 @@ The first step is to update the README file with detailed information about how * How to add the functionality to the app (several examples of common use cases) * Warnings, gotchas or tips that might help users and save them time -Once your README is solid, go through and add rdoc comments to all of the methods that developers will use. It's also customary to add '#:nodoc:' comments to those parts of the code that are not included in the public api. +Once your README is solid, go through and add rdoc comments to all of the methods that developers will use. It's also customary to add '#:nodoc:' comments to those parts of the code that are not included in the public API. Once your comments are good to go, navigate to your plugin directory and run: @@ -425,6 +425,6 @@ $ rake rdoc h4. References * "Developing a RubyGem using Bundler":https://github.com/radar/guides/blob/master/gem-development.md -* "Using Gemspecs As Intended":http://yehudakatz.com/2010/04/02/using-gemspecs-as-intended/ +* "Using .gemspecs as Intended":http://yehudakatz.com/2010/04/02/using-gemspecs-as-intended/ * "Gemspec Reference":http://docs.rubygems.org/read/chapter/20 -* "GemPlugins":http://www.intridea.com/blog/2008/6/11/gemplugins-a-brief-introduction-to-the-future-of-rails-plugins +* "GemPlugins: A Brief Introduction to the Future of Rails Plugins":http://www.intridea.com/blog/2008/6/11/gemplugins-a-brief-introduction-to-the-future-of-rails-plugins diff --git a/guides/source/routing.textile b/guides/source/routing.textile index cffbf9bec4..bed7d03e06 100644 --- a/guides/source/routing.textile +++ b/guides/source/routing.textile @@ -273,6 +273,36 @@ The corresponding route helper would be +publisher_magazine_photo_url+, requirin TIP: _Resources should never be nested more than 1 level deep._ +h4. Routing concerns + +Routing Concerns allows you to declare common routes that can be reused inside others resources and routes. + +<ruby> +concern :commentable do + resources :comments +end + +concern :image_attachable do + resources :images, only: :index +end +</ruby> + +These concerns can be used in resources to avoid code duplication and share behavior across routes. + +<ruby> +resources :messages, concerns: :commentable + +resources :posts, concerns: [:commentable, :image_attachable] +</ruby> + +Also you can use them in any place that you want inside the routes, for example in a scope or namespace call: + +<ruby> +namespace :posts do + concerns :commentable +end +</ruby> + h4. Creating Paths and URLs From Objects In addition to using the routing helpers, Rails can also create paths and URLs from an array of parameters. For example, suppose you have this set of routes: |