From 14b5c8b98515d9cc13fbdefb02800ad42f1070f5 Mon Sep 17 00:00:00 2001 From: Paul Odeon Date: Sat, 11 Dec 2010 14:30:12 +0000 Subject: Updated generator guide for rails commit 7891de893951c780a1732747d430c33e998dd573 --- railties/guides/source/generators.textile | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/generators.textile b/railties/guides/source/generators.textile index ee3891c43b..6945f6f9bb 100644 --- a/railties/guides/source/generators.textile +++ b/railties/guides/source/generators.textile @@ -208,16 +208,16 @@ end If we generate another resource with the scaffold generator, we can see that neither stylesheets nor fixtures are created anymore. If you want to customize it further, for example to use DataMapper and RSpec instead of Active Record and TestUnit, it's just a matter of adding their gems to your application and configuring your generators. -To demonstrate this, we are going to create a new helper generator that simply adds some instance variable readers. First, we create a generator: +To demonstrate this, we are going to create a new helper generator that simply adds some instance variable readers. First, we create a generator within the rails namespace, as this is where rails searches for generators used as hooks: -$ rails generate generator my_helper +$ rails generate generator rails/my_helper After that, we can delete both the +templates+ directory and the +source_root+ class method from our new generators, because we are not going to need them. So our new generator looks like the following: -class MyHelperGenerator < Rails::Generators::NamedBase +class Rails::MyHelperGenerator < Rails::Generators::NamedBase def create_helper_file create_file "app/helpers/#{file_name}_helper.rb", <<-FILE module #{class_name}Helper @@ -270,7 +270,7 @@ Since Rails 3.0, this is easy to do due to the hooks concept. Our new helper doe To do that, we can change the generator this way: -class MyHelperGenerator < Rails::Generators::NamedBase +class Rails::MyHelperGenerator < Rails::Generators::NamedBase def create_helper_file create_file "app/helpers/#{file_name}_helper.rb", <<-FILE module #{class_name}Helper @@ -283,7 +283,7 @@ end end -Now, when the helper generator is invoked and TestUnit is configured as the test framework, it will try to invoke both +MyHelper::Generators::TestUnitGenerator+ and +TestUnit::Generators::MyHelperGenerator+. Since none of those are defined, we can tell our generator to invoke +TestUnit::Generators::HelperGenerator+ instead, which is defined since it's a Rails generator. To do that, we just need to add: +Now, when the helper generator is invoked and TestUnit is configured as the test framework, it will try to invoke both +Rails::TestUnitGenerator+ and +TestUnit::MyHelperGenerator+. Since none of those are defined, we can tell our generator to invoke +TestUnit::Generators::HelperGenerator+ instead, which is defined since it's a Rails generator. To do that, we just need to add: # Search for :helper instead of :my_helper -- cgit v1.2.3 From 3efe1b738686482730e05ad50e8d0e667686d2e8 Mon Sep 17 00:00:00 2001 From: vijay Date: Sat, 11 Dec 2010 23:06:54 +0530 Subject: fixed typos and rephrased a few sentences; also removed reference to status codes being located in action_controller/status_codes.rb --- .../guides/source/layouts_and_rendering.textile | 24 +++++++++------------- 1 file changed, 10 insertions(+), 14 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/layouts_and_rendering.textile b/railties/guides/source/layouts_and_rendering.textile index 80a1fdd38d..4cdd4f2709 100644 --- a/railties/guides/source/layouts_and_rendering.textile +++ b/railties/guides/source/layouts_and_rendering.textile @@ -106,7 +106,7 @@ Perhaps the simplest thing you can do with +render+ is to render nothing at all: render :nothing => true -If you look at the response for this using Curl you will see the following: +If you look at the response for this using cURL, you will see the following: $ curl -i 127.0.0.1:3000/books @@ -123,7 +123,7 @@ Cache-Control: no-cache $ -We see there is an empty response (no data after the +Cache-Control+ line), but the request was successful because Rails has set the response to 200 OK. You can set the +:status+ options on render to change this response. Rendering nothing can be useful for AJAX requests where all you want to send back to the browser is an acknowledgement that the request was completed. +We see there is an empty response (no data after the +Cache-Control+ line), but the request was successful because Rails has set the response to 200 OK. You can set the +:status+ option on render to change this response. Rendering nothing can be useful for AJAX requests where all you want to send back to the browser is an acknowledgement that the request was completed. TIP: You should probably be using the +head+ method, discussed later in this guide, instead of +render :nothing+. This provides additional flexibility and makes it explicit that you're only generating HTTP headers. @@ -346,7 +346,7 @@ render :status => 500 render :status => :forbidden -Rails understands either numeric status codes or symbols for status codes. You can find its list of status codes in +actionpack/lib/action_controller/status_codes.rb+. You can also see there how Rails maps symbols to status codes. +Rails understands both numeric status codes and symbols for status codes. h6. The +:location+ Option @@ -604,7 +604,7 @@ Which would detect that there are no books, populate the +@books+ instance varia h4. Using +head+ To Build Header-Only Responses -The +head+ method exists to let you send back responses to the browser that have only headers. It provides a more obvious alternative to calling +render :nothing+. The +head+ method takes one response, which is interpreted as a hash of header names and values. For example, you can return only an error header: +The +head+ method can be used to send responses with only headers to the browser. It provides a more obvious alternative to calling +render :nothing+. The +head+ method takes one parameter, which is interpreted as a hash of header names and values. For example, you can return only an error header: head :bad_request @@ -651,11 +651,9 @@ When Rails renders a view as a response, it does so by combining the view with t * +yield+ and +content_for+ * Partials -I'll discuss each of these in turn. - h4. Asset Tags -Asset tags provide methods for generating HTML that links views to assets like images, videos, audio, JavaScript, stylesheets, and feeds. There are six types of include tag: +Asset tags provide methods for generating HTML that links views to feeds, JavaScript, stylesheets, images, videos and audios. These are the six asset tags available in Rails: * +auto_discovery_link_tag+ * +javascript_include_tag+ @@ -680,7 +678,7 @@ The +auto_discovery_link_tag+ helper builds HTML that most browsers and newsread There are three tag options available for +auto_discovery_link_tag+: * +:rel+ specifies the +rel+ value in the link (defaults to "alternate") -* +:type+ specifies an explicit MIME type. Rails will generate an appropriate MIME type automatically +* +:type+ specifies an explicit MIME type. Rails will generate an appropriate MIME type automatically. * +:title+ specifies the title of the link h5. Linking to Javascript Files with +javascript_include_tag+ @@ -829,7 +827,7 @@ You can also supply an alternate image to show on mouseover: <%= image_tag "home.gif", :onmouseover => "menu/home_highlight.gif" %> -Or alternate text if the user has rendering images turned off in their browser, if you do not specify an explicit alt tag, it defaults to the file name of the file, capitalized and with no extension, for example, these two image tags would return the same code: +You can supply alternate text for the image which will be used if the user has images turned off in their browser. If you do not specify an alt text explicitly, it defaults to the file name of the file, capitalized and with no extension. For example, these two image tags would return the same code: <%= image_tag "home.gif" %> @@ -939,7 +937,7 @@ The main body of the view will always render into the unnamed +yield+. To render h4. Using +content_for+ -The +content_for+ method allows you to insert content into a +yield+ block in your layout. You only use +content_for+ to insert content in named yields. For example, this view would work with the layout that you just saw: +The +content_for+ method allows you to insert content into a named +yield+ block in your layout. For example, this view would work with the layout that you just saw: <% content_for :head do %> @@ -966,7 +964,7 @@ The +content_for+ method is very helpful when your layout contains distinct regi h4. Using Partials -Partial templates - usually just called "partials" - are another device for breaking apart the rendering process into more manageable chunks. With a partial, you can move the code for rendering a particular piece of a response to its own file. +Partial templates - usually just called "partials" - are another device for breaking the rendering process into more manageable chunks. With a partial, you can move the code for rendering a particular piece of a response to its own file. h5. Naming Partials @@ -1086,15 +1084,13 @@ Partials are very useful in rendering collections. When you pass a collection to When a partial is called with a pluralized collection, then the individual instances of the partial have access to the member of the collection being rendered via a variable named after the partial. In this case, the partial is +_product+, and within the +_product+ partial, you can refer to +product+ to get the instance that is being rendered. -In Rails 3.0, there is also a shorthand for this. Assuming +@products+ is a collection of +product+ instances, you can simply write this in the +index.html.erb+: +In Rails 3.0, there is also a shorthand for this. Assuming +@products+ is a collection of +product+ instances, you can simply write this in the +index.html.erb+ to produce the same result:

Products

<%= render @products %>
-To produce the same result. - Rails determines the name of the partial to use by looking at the model name in the collection. In fact, you can even create a heterogeneous collection and render it this way, and Rails will choose the proper partial for each member of the collection: * +index.html.erb+ -- cgit v1.2.3 From a6faeffe59ce4160ddd10fd8ec8dca8d88c3a35d Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Sun, 12 Dec 2010 21:10:03 +0530 Subject: fixed typos in mailer --- railties/guides/source/action_mailer_basics.textile | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/action_mailer_basics.textile b/railties/guides/source/action_mailer_basics.textile index b75c528a33..b77a0be37b 100644 --- a/railties/guides/source/action_mailer_basics.textile +++ b/railties/guides/source/action_mailer_basics.textile @@ -144,7 +144,7 @@ This provides a much simpler implementation that does not require the registerin The method +welcome_email+ returns a Mail::Message 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+ however in Rails 3.0 this has been deprecated in favour of just calling the method name itself. +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. @@ -154,7 +154,7 @@ 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 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. -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 @@ -213,9 +213,7 @@ NOTE: If you specify an encoding, Mail will assume that your content is already h5. Making Inline Attachments -Inline attachments are now possible in ActionMailer. While previously in the pre 3.0 version of Rails, you could do inline attachments, it involved a lot of hacking and determination to pull it off. - -ActionMailer now makes inline attachments as trivial as they should be. +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. * Firstly, to tell Mail to turn an attachment into an inline attachment, you just call #inline on the attachments method within your Mailer: @@ -274,7 +272,7 @@ to format the email address in the format "Name <email>". h4. Mailer Views -Mailer views are located in the +app/views/name_of_mailer_class+ directory. The specific mailer view is known to the class because it's name is the same as the mailer method. So for example, in our example from above, our mailer view for the +welcome_email+ method will be in +app/views/user_mailer/welcome_email.html.erb+ for the HTML version and +welcome_email.text.erb+ for the plain text version. +Mailer views are located in the +app/views/name_of_mailer_class+ directory. The specific mailer view is known to the class because its name is the same as the mailer method. In our example from above, our mailer view for the +welcome_email+ method will be in +app/views/user_mailer/welcome_email.html.erb+ for the HTML version and +welcome_email.text.erb+ for the plain text version. To change the default mailer view for your action you do something like: @@ -441,7 +439,7 @@ 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|The logger is used for generating 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.| +|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:
  • :address - Allows you to use a remote mail server. Just change it from its default "localhost" setting.
  • :port - On the off chance that your mail server doesn't run on port 25, you can change it.
  • :domain - If you need to specify a HELO domain, you can do it here.
  • :user_name - If your mail server requires authentication, set the username in this setting.
  • :password - If your mail server requires authentication, set the password in this setting.
  • :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.
| |sendmail_settings|Allows you to override options for the :sendmail delivery method.
  • :location - The location of the sendmail executable. Defaults to /usr/sbin/sendmail.
  • :arguments - The command line arguments to be passed to sendmail. Defaults to -i -t.
| |raise_delivery_errors|Whether or not errors should be raised if the email fails to be delivered.| @@ -504,7 +502,7 @@ class UserMailerTest < ActionMailer::TestCase end
-In the test we send the email and store the returned object in the +email+ variable. We then ensure that it was sent (the first assert), then, in the second batch of assertions, we ensure that the email does indeed contain the what we expect. +In the test we send the email and store the returned object in the +email+ variable. We then ensure that it was sent (the first assert), then, in the second batch of assertions, we ensure that the email does indeed contain what we expect. h3. Changelog -- cgit v1.2.3 From 0b5671ccca4a9f55379c913a211d669e241ad20c Mon Sep 17 00:00:00 2001 From: Umar Sheikh Date: Mon, 13 Dec 2010 11:18:49 +0500 Subject: for the root route to work, we need to delete the public/index.html.erb file as well --- railties/guides/source/routing.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/routing.textile b/railties/guides/source/routing.textile index bc38e4a6e5..74dee60c32 100644 --- a/railties/guides/source/routing.textile +++ b/railties/guides/source/routing.textile @@ -595,7 +595,7 @@ You can specify what Rails should route +"/"+ to with the +root+ method: root :to => 'pages#main' -You should put the +root+ route at the end of the file. +You should put the +root+ route at the end of the file. You also need to delete the public/index.html.erb file for the root route to take effect. h3. Customizing Resourceful Routes -- cgit v1.2.3 From de4f9acad8b7014b29352a747926ee2db6f71643 Mon Sep 17 00:00:00 2001 From: Elben Shira Date: Tue, 14 Dec 2010 20:35:08 -0600 Subject: It should be ActiveModel::Validator, not ActiveRecord::Validator. --- railties/guides/source/active_record_validations_callbacks.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/active_record_validations_callbacks.textile b/railties/guides/source/active_record_validations_callbacks.textile index 0824ba450c..a15571fe58 100644 --- a/railties/guides/source/active_record_validations_callbacks.textile +++ b/railties/guides/source/active_record_validations_callbacks.textile @@ -414,7 +414,7 @@ class Person < ActiveRecord::Base validates_with GoodnessValidator end -class GoodnessValidator < ActiveRecord::Validator +class GoodnessValidator < ActiveModel::Validator def validate if record.first_name == "Evil" record.errors[:base] << "This person is evil" -- cgit v1.2.3 From 003fce430ab3991ef19cba5eef902510968b2ebd Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Wed, 15 Dec 2010 14:08:08 +1000 Subject: WIP: Reviewing the initialization guide for Rails 3.1 --- railties/guides/source/initialization.textile | 514 ++++++++++++++++++++------ 1 file changed, 393 insertions(+), 121 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/initialization.textile b/railties/guides/source/initialization.textile index 4cc5f3843f..72e10191f9 100644 --- a/railties/guides/source/initialization.textile +++ b/railties/guides/source/initialization.textile @@ -1,79 +1,140 @@ h2. The Rails Initialization Process -This guide explains how the initialization process in Rails works as of Rails 3. +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. * Using +rails server+ * Using Passenger endprologue. -This guide first describes the process of +rails server+ then explains the Passenger + Rack method, before delving into the common initialize pattern these two go through. +This guide goes through every single file, class and method call that is required to boot up the Ruby on Rails stack for a default Rails 3.1 application, explaining each part in detail a long the way. For this guide, we will be focusing on how the two most common methods (+rails server+ and Passenger) boot a Rails application. + +NOTE: Paths in this guide are relative to Rails or a Rails application unless otherwise specified. h3. Launch! As of Rails 3, +script/server+ has become +rails server+. This was done to centralize all rails related commands to one common file. -The actual +rails+ command is kept in _railties/bin/rails_ and goes like this: +h4. +bin/rails+ + +The actual +rails+ command is kept in _bin/rails_ at the and goes like this: - require 'rbconfig' + #!/usr/bin/env ruby - module Rails - module ScriptRailsLoader - RUBY = File.join(*RbConfig::CONFIG.values_at("bindir", "ruby_install_name")) + RbConfig::CONFIG["EXEEXT"] - SCRIPT_RAILS = File.join('script', 'rails') - - def self.exec_script_rails! - cwd = Dir.pwd - exec RUBY, SCRIPT_RAILS, *ARGV if File.exists?(SCRIPT_RAILS) - Dir.chdir("..") do - # Recurse in a chdir block: if the search fails we want to be sure - # the application is generated in the original working directory. - exec_script_rails! unless cwd == Dir.pwd - end - rescue SystemCallError - # could not chdir, no problem just return - end - end + begin + require "rails/cli" + rescue LoadError + railties_path = File.expand_path('../../railties/lib', __FILE__) + $:.unshift(railties_path) + require "rails/cli" end + - Rails::ScriptRailsLoader.exec_script_rails! +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. - railties_path = File.expand_path('../../lib', __FILE__) - $:.unshift(railties_path) if File.directory?(railties_path) && !$:.include?(railties_path) +h4. +railites/lib/rails/cli.rb+ + +This file looks like this: + + + require 'rbconfig' + require 'rails/script_rails_loader' + + # If we are inside a Rails application this method performs an exec and thus + # the rest of this script is not run. + Rails::ScriptRailsLoader.exec_script_rails! require 'rails/ruby_version_check' Signal.trap("INT") { puts; exit } - require 'rails/commands/application' + if ARGV.first == 'plugin' + ARGV.shift + require 'rails/commands/plugin_new' + else + require 'rails/commands/application' + end -The +Rails::ScriptRailsLoader+ module here defines two constants: +RUBY+ and +SCRIPT_RAILS+. +RUBY+ is the full path to your ruby executable, on a Snow Leopard system it's _/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby_. +SCRIPT_RAILS+ is simply _script/rails_. When +exec_script_rails+ is invoked, this will attempt to +exec+ the _rails_ file in the _script_ directory using the path to your Ruby executable, +RUBY+. If +exec+ is invoked, the program will stop at this point. If the _script/rails_ file doesn't exist in the current directory, Rails will recurse upwards until it finds it by calling +exec_script_rails+ from inside the +Dir.chdir("..")+. This is handy if you're currently in one of the sub-directories of the rails application and wish to launch a server or a console. +The +rbconfig+ file here is out of Ruby's standard library and provides us with the +RbConfig+ class which contains useful information dependent on how Ruby was compiled. We'll see this in use in +railties/lib/rails/script_rails_loader+. + + +require 'pathname' + +module Rails + module ScriptRailsLoader + RUBY = File.join(*RbConfig::CONFIG.values_at("bindir", "ruby_install_name")) + RbConfig::CONFIG["EXEEXT"] + SCRIPT_RAILS = File.join('script', 'rails') + ... -If Rails cannot execute _script/rails_ then it will fall back to the standard +rails+ command task of generating an application. + end +end + + +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. -In +script/rails+ we see the following: +Back in +rails/cli+, the next line is this: - #!/usr/bin/env ruby - # This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application. + Rails::ScriptRailsLoader.exec_script_rails! + - APP_PATH = File.expand_path('../../config/application', __FILE__) - require File.expand_path('../../config/boot', __FILE__) - require 'rails/commands' +This method is defined in +rails/script_rails_loader+ like this: + + + def self.exec_script_rails! + cwd = Dir.pwd + return unless in_rails_application? || in_rails_application_subdirectory? + exec RUBY, SCRIPT_RAILS, *ARGV if in_rails_application? + Dir.chdir("..") do + # Recurse in a chdir block: if the search fails we want to be sure + # the application is generated in the original working directory. + exec_script_rails! unless cwd == Dir.pwd + end + rescue SystemCallError + # could not chdir, no problem just return + end -This obviously defines a couple of constants to some pretty important files, _config/environment.rb_, _config/boot.rb_ and _config/application.rb_ all within the context of +__FILE__+ which is of course +script/rails+ in the root of your application. Then it goes on to +require BOOT_PATH+ which leads us onto _config/boot.rb_. +This method will first check if the current working directory (+cwd+) is a Rails application or is a subdirectory of one. The way to determine this is defined in the +in_rails_application?+ method like this: -h3. Passenger + + def self.in_rails_application? + File.exists?(SCRIPT_RAILS) + end + -Before we dive into what _config/boot.rb_ encompasses, we'll just glimpse at what Passenger does enough to get an understanding of how it requires a Rails application. +The +SCRIPT_RAILS+ constant defined earlier is used here, with +File.exists?+ checking for its presence in the current directory. If this method returns +false+, then +in_rails_application_subdirectory?+ will be used: + + + def self.in_rails_application_subdirectory?(path = Pathname.new(Dir.pwd)) + File.exists?(File.join(path, SCRIPT_RAILS)) || !path.root? && in_rails_application_subdirectory?(path.parent) + end + + +This climbs the directory tree until it reaches a path which contains a +script/rails+ file. If a directory is reached which contains this file then this line will run: + + + exec RUBY, SCRIPT_RAILS, *ARGV if in_rails_application? + + +This is effectively the same as doing +ruby script/rails [arguments]+. Where +[arguments]+ at this point in time is simply "server". + +h4. +script/rails+ + +This file looks like this: + + + APP_PATH = File.expand_path('../../config/application', __FILE__) + require File.expand_path('../../config/boot', __FILE__) + require 'rails/commands' + -Passenger will require _config/environment.rb_ by way of its +PhusionPassenger::Railz::ApplicationSpawner#preload_application+ method. _config/environment.rb_ requires _config/application.rb_ which requires _config/boot.rb_. That's how the Rails boot process begins with Passenger in a nutshell. +The +APP_PATH+ constant here will be used later in +rails/commands+. The +config/boot+ file that +script/rails+ references is the +config/boot.rb+ file in our application which is responsible for loading Bundler and setting it up. -h3. _config/boot.rb_ +h4. +config/boot.rb+ -_config/boot.rb_ is the first stop for everything for initializing your application. This boot process does quite a bit of work for you and so this section attempts to go in-depth enough to explain what each of the pieces does. ++config/boot.rb+ contains this: require 'rubygems' @@ -91,134 +152,345 @@ _config/boot.rb_ is the first stop for everything for initializing your applicat end if File.exist?(gemfile) -h3. Bundled Rails (3.x) +In a standard Rails application, there's a +Gemfile+ which declares all dependencies of the application. +config/boot.rb+ sets +ENV["BUNDLE_GEMFILE"]+ to the location of this file, then requires Bundler and calls +Bundler.setup+ which adds the dependencies of the application (including all the Rails parts) to the load path, making them available for the application to load. The gems that a Rails 3.1 application depends on are as follows: + +* abstract (1.0.0) +* actionmailer (3.1.0.beta) +* actionpack (3.1.0.beta) +* activemodel (3.1.0.beta) +* activerecord (3.1.0.beta) +* activeresource (3.1.0.beta) +* activesupport (3.1.0.beta) +* arel (2.0.7) +* builder (3.0.0) +* bundler (1.0.6) +* erubis (2.6.6) +* i18n (0.5.0) +* mail (2.2.12) +* mime-types (1.16) +* polyglot (0.3.1) +* rack (1.2.1) +* rack-cache (0.5.3) +* rack-mount (0.6.13) +* rack-test (0.5.6) +* rails (3.1.0.beta) +* railties (3.1.0.beta) +* rake (0.8.7) +* sqlite3-ruby (1.3.2) +* thor (0.14.6) +* treetop (1.4.9) +* tzinfo (0.3.23) + +h4. +rails/commands.rb+ + +Once +config/boot.rb+ has finished, the next file that is required is +rails/commands+ which will execute a command based on the arguments passed in. In this case, the +ARGV+ array simply contains +server+ which is extracted into the +command+ variable using these lines: + + + aliases = { + "g" => "generate", + "c" => "console", + "s" => "server", + "db" => "dbconsole" + } + + command = ARGV.shift + command = aliases[command] || command + + +If we used s rather than +server+, Rails will use the +aliases+ defined in the file and match them to their respective commands. With the +server+ command, Rails will run this code: + + + when 'server' + # Change to the application's path if there is no config.ru file in current dir. + # This allows us to run script/rails server from other directories, but still get + # the main config.ru and properly set the tmp directory. + Dir.chdir(File.expand_path('../../', APP_PATH)) unless File.exists?(File.expand_path("config.ru")) + + require 'rails/commands/server' + Rails::Server.new.tap { |server| + # We need to require application after the server sets environment, + # otherwise the --environment option given to the server won't propagate. + require APP_PATH + Dir.chdir(Rails.application.root) + server.start + } + + +This file will change into the root of the directory (a path two directories back from +APP_PATH+ which points at +config/application.rb+), but only if the +config.ru+ file isn't found. This then requires +rails/commands/server+ which requires +action_dispatch+ and sets up the +Rails::Server+ class. + +h4. +actionpack/lib/action_dispatch.rb+ + +Action Dispatch is the routing component of the Rails framework. It depends on Active Support, +actionpack/lib/action_pack.rb+ and +Rack+ being available. The first thing required here is +active_support+. + +h4. +active_support/lib/active_support.rb+ + +This file begins with requiring +active_support/lib/active_support/dependencies/autoload.rb+ which redefines Ruby's +autoload+ method to have a little more extra behaviour especially in regards to eager autoloading. Eager autoloading is the loading of all required classes and will happen when the +config.cache_classes+ setting is +true+. +The +active_support/lib/active_support/version.rb+ that is also required here simply defines an +ActiveSupport::VERSION+ constant which defines a couple of constants inside this module, the main constant of this is +ActiveSupport::VERSION::STRING+ which returns the current version of ActiveSupport. -Rails 3 now uses Bundler and the README for the project explains it better than I could: +The +active_support/lib/active_support.rb+ file simply defines the +ActiveSupport+ module and some autoloads (eager and of the normal variety) for it. -> "Bundler is a tool that manages gem dependencies for your ruby application. It takes a gem manifest file and is able to fetch, download, and install the gems and all child dependencies specified in this manifest. It can manage any update to the gem manifest file and update the bundle's gems accordingly. It also lets you run any ruby code in context of the bundle's gem environment." +h4. +actionpack/lib/action_dispatch.rb+ cont'd. -Now with Rails 3 we have a Gemfile which defines the basics our application needs to get going: +Now back to +action_pack/lib/action_dispatch.rb+. The next +require+ in this file is one for +action_pack+, which simply calls +action_pack/version.rb+ which defines +ActionPack::VERSION+ and the constants, much like +ActiveSpport+ does. + +After this line, there's a require to +active_model+ which simply defines autoloads for the +ActiveModel+ part of Rails and sets up the +ActiveModel+ module which is used later on. + +The last of the requires is to +rack+, which like the +active_model+ and +active_support+ requires before it, sets up the +Rack+ module as well as the autoloads for constants within it. + +Finally in +action_dispatch.rb+ the +ActionDispatch+ module and *its* autoloads are declared. + +h4. +rails/commands/server.rb+ + +The +Rails::Server+ class is defined in this file as inheriting from +Rack::Server+. When +Rails::Server.new+ is called, this calls the +initialize+ method in +rails/commands/server.rb+: - source 'http://rubygems.org' + def initialize(*) + super + set_environment + end + - gem 'rails', '3.0.0' +Firstly, +super+ is called which calls the +initialize+ method on +Rack::Server+. - # Bundle edge Rails instead: - # gem 'rails', :git => 'git://github.com/rails/rails.git' +h4. Rack: +lib/rack/server.rb+ - gem 'sqlite3-ruby', :require => 'sqlite3' ++Rack::Server+ is responsible for providing a common server interface for all Rack-based applications, which Rails is now a part of. - # Use unicorn as the web server - # gem 'unicorn' +The +initialize+ method in +Rack::Server+ simply sets a couple of variables: - # Deploy with Capistrano - # gem 'capistrano' + + def initialize(options = nil) + @options = options + @app = options[:app] if options && options[:app] + end + - # Bundle the extra gems: - # gem 'bj' - # gem 'nokogiri' - # gem 'sqlite3-ruby', :require => 'sqlite3' - # gem 'aws-s3', :require => 'aws/s3' +In this case, +options+ will be +nil+ so nothing happens in this method. - # Bundle gems for certain environments: - # gem 'rspec', :group => :test - # group :test do - # gem 'webrat' - # end +After +super+ has finished in +Rack::Server+, we jump back to +rails/commands/server.rb+. At this point, +set_environment+ is called within the context of the +Rails::Server+ object and this method doesn't appear to do much at first glance: + + def set_environment + ENV["RAILS_ENV"] ||= options[:environment] + end -Here the only two gems we need are +rails+ and +sqlite3-ruby+, so it seems. This is until you run +bundle pack+. This command freezes all the gems required by your application into _vendor/cache_. The gems installed by default are: +In fact, the +options+ method here does quite a lot. This method is defined in +Rack::Server+ like this: -* abstract-1.0.0.gem -* actionmailer-3.0.0.gem -* actionpack-3.0.0.gem -* activemodel-3.0.0.gem -* activerecord-3.0.0.gem -* activeresource-3.0.0.gem -* activesupport-3.0.0.gem -* arel-0.4.0.gem -* builder-2.1.2.gem -* bundler-1.0.3.gem -* erubis-2.6.6.gem -* i18n-0.4.1.gem -* mail-2.2.5.gem -* memcache-client-1.8.5.gem -* mime-types-1.16.gem -* nokogiri-1.4.3.1.gem -* polyglot-0.3.1.gem -* rack-1.2.1.gem -* rack-mount-0.6.12.gem -* rack-test-0.5.4.gem -* rails-3.0.0.gem -* railties-3.0.0.gem -* rake-0.8.7.gem -* sqlite3-ruby-1.3.1.gem -* text-format-1.0.0.gem -* text-hyphen-1.0.0.gem -* thor-0.13.7.gem -* treetop-1.4.8.gem -* tzinfo-0.3.23.gem + + def options + @options ||= parse_options(ARGV) + end + -TODO: Prettify when it becomes more stable. +Then +parse_options+ is defined like this: -I won't go into what each of these gems are, as that is really something that needs covering on a case-by-case basis. We will however just dig a little under the surface of Bundler. + + def parse_options(args) + options = default_options -Back in _config/boot.rb_, we call +Bundler.setup+ which will load and parse the +Gemfile+ and add the _lib_ directory of the gems mentioned **and** their dependencies (**and** their dependencies' dependencies, and so on) to the +$LOAD_PATH+. + # Don't evaluate CGI ISINDEX parameters. + # http://hoohoo.ncsa.uiuc.edu/cgi/cl.html + args.clear if ENV.include?("REQUEST_METHOD") -h3. Requiring Rails + options.merge! opt_parser.parse! args + options[:config] = ::File.expand_path(options[:config]) + ENV["RACK_ENV"] = options[:environment] + options + end + -After _config/boot.rb_ is loaded, there's this +require+: +With the +default_options+ set to this: - require 'rails/commands' + def default_options + { + :environment => ENV['RACK_ENV'] || "development", + :pid => nil, + :Port => 9292, + :Host => "0.0.0.0", + :AccessLog => [], + :config => "config.ru" + } + end -In this file, _railties/lib/rails/commands.rb_, there is a case statement for +ARGV.shift+: +There is no +REQUEST_METHOD+ key in +ENV+ so we can skip over that line. The next line merges in the options from +opt_parser+ which is defined plainly in +Rack::Server+ - case ARGV.shift - ... - when 's', 'server' - require 'rails/commands/server' - # Initialize the server first, so environment options are set - server = Rails::Server.new - require APP_PATH + def opt_parser + Options.new + end + + +The class *is* defined in +Rack::Server+, but is overwritten in +Rails::Server+ to take different arguments. Its +parse!+ method begins like this: + + + 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 } ... + + +This method will set up keys for the +options+ which Rails will then be able to use to determine how its server should run. After +initialize+ has finished, then the +start+ method will launch the server. + +h4. +Rails::Server#start+ + +This method is defined like this: + + + def start + puts "=> Booting #{ActiveSupport::Inflector.demodulize(server)}" + puts "=> Rails #{Rails.version} application starting in #{Rails.env} on http://#{options[:Host]}:#{options[:Port]}" + puts "=> Call with -d to detach" unless options[:daemonize] + trap(:INT) { exit } + puts "=> Ctrl-C to shutdown server" unless options[:daemonize] + + #Create required tmp directories if not found + %w(cache pids sessions sockets).each do |dir_to_make| + FileUtils.mkdir_p(Rails.root.join('tmp', dir_to_make)) + end + + super + ensure + # The '-h' option calls exit before @options is set. + # If we call 'options' with it unset, we get double help banners. + puts 'Exiting' unless @options && options[:daemonize] end -We're running +rails server+ and this means it will make a require out to _rails/commands/server_ (_railties/lib/rails/commands/server.rb_). Firstly, this file makes a couple of requires of its own: +This is where the first output of the Rails initialization happens. This method creates a trap for +INT+ signals, so if you +CTRL+C+ the server, it will exit the process. As we can see from the code here, it will create the +tmp/cache+, +tmp/pids+, +tmp/sessions+ and +tmp/sockets+ directories if they don't already exist prior to calling +super+. The +super+ method will call +Rack::Server.start+ which begins its definition like this: + + + def start + if options[:warn] + $-w = true + end + + if includes = options[:include] + $LOAD_PATH.unshift(*includes) + end + + if library = options[:require] + require library + end + + if options[:debug] + $DEBUG = true + require 'pp' + p options[:server] + pp wrapped_app + pp app + end + + +In a Rails application, these options are not set at all and therefore aren't used at all. The first line of code that's executed in this method is a call to this method: - require 'fileutils' - require 'optparse' - require 'action_dispatch' + wrapped_app -The first two are Ruby core and this guide does not cover what they do, but _action_dispatch_ (_actionpack/lib/action_dispatch.rb_) is important. This file firstly make a require to _active_support_ (_activesupport/lib/active_support.rb_) which defines the +ActiveSupport+ module. +This method calls another method: -h4. +require 'active_support'+ + + @wrapped_app ||= build_app app + -_activesupport/lib/active_support.rb_ sets up +module ActiveSupport+: +Then the +app+ method here is defined like so: - module ActiveSupport - class << self - attr_accessor :load_all_hooks - def on_load_all(&hook) load_all_hooks << hook end - def load_all!; load_all_hooks.each { |hook| hook.call } end + def app + @app ||= begin + if !::File.exist? options[:config] + abort "configuration #{options[:config]} not found" + end + + app, options = Rack::Builder.parse_file(self.options[:config], opt_parser) + self.options.merge! options + app end - self.load_all_hooks = [] + end + + +The +options[:config]+ value defaults to +config.ru+ which contains this: + + + # This file is used by Rack-based servers to start the application. + + require ::File.expand_path('../config/environment', __FILE__) + run YourApp::Application + + + +The +Rack::Builder.parse_file+ method here takes the content from this +config.ru+ file and parses it using this code: + + + app = eval "Rack::Builder.new {( " + cfgfile + "\n )}.to_app", + TOPLEVEL_BINDING, config + + +The initialize method will take the block here and execute it within an instance of +Rack::Builder+. This is where the majority of the initialization process of Rails happens. The chain of events that this simple line sets off will be the focus of a large majority of this guide. The +require+ line for +config/environment.rb+ in +config.ru+ is the first to run: + + + require ::File.expand_path('../config/environment', __FILE__) + + +h4. +config/environment.rb+ + +This file is the common file required by +config.ru+ (+rails server+) and Passenger. This is where these two ways to run the server meet; everything before this point has been Rack and Rails setup. + +This file begins with requiring +config/application.rb+. + +h4. +config/application.rb+ + +This file requires +config/boot.rb+, but only if it hasn't been required before, which would be the case in +rails server+ but *wouldn't* be the case with Passenger. + +Then the fun begins! The next line is: - on_load_all do - [Dependencies, Deprecation, Gzip, MessageVerifier, Multibyte, SecureRandom] + + require 'rails/all' + + +h4 +railties/lib/rails/all.rb+ + + +This file is responsible for requiring all the individual parts of Rails like so: + + + require "rails" + + %w( + active_record + action_controller + action_mailer + active_resource + rails/test_unit + ).each do |framework| + begin + require "#{framework}/railtie" + rescue LoadError end end +First off the line is the +rails+ require itself. + +h4. +railties/lib/rails.rb+ + +This file is responsible for the initial definition of the +Rails+ module and, rather than defining the autoloads like +ActiveSupport+, +ActionDispatch+ and so on, it actually defines other functionality. Such as the +root+, +env+ and +application+ methods which are extremely useful in Rails 3 applications. + +However, before all that takes place the +rails/ruby_version_check+ file is required first. + + + + +**** REVIEW IS HERE **** + This defines two methods on the module itself by using the familiar +class << self+ syntax. This allows you to call them as if they were class methods: +ActiveSupport.on_load_all+ and +ActiveSupport.load_all!+ respectively. The first method simply adds loading hooks to save them up for loading later on when +load_all!+ is called. By +call+'ing the block, the classes will be loaded. (NOTE: kind of guessing, I feel 55% about this). The +on_load_all+ method is called later with the +Dependencies+, +Deprecation+, +Gzip+, +MessageVerifier+, +Multibyte+ and +SecureRandom+. What each of these modules do will be covered later. -- cgit v1.2.3 From a7791c375228472f2d51705bcee01eced982df3a Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Wed, 15 Dec 2010 16:17:55 +1000 Subject: Active Support coreext guide: Logger core extension documentation --- .../source/active_support_core_extensions.textile | 43 ++++++++++++++++++++++ 1 file changed, 43 insertions(+) (limited to 'railties/guides') diff --git a/railties/guides/source/active_support_core_extensions.textile b/railties/guides/source/active_support_core_extensions.textile index 7333a81cf9..2e295aec3d 100644 --- a/railties/guides/source/active_support_core_extensions.textile +++ b/railties/guides/source/active_support_core_extensions.textile @@ -3359,6 +3359,49 @@ The auxiliary file is written in a standard directory for temporary files, but y NOTE: Defined in +active_support/core_ext/file/atomic.rb+. +h3. Extensions to +Logger+ + +h4. +around_[level]+ + +Takes two arguments, a +before_message+ and +after_message+ and calls the current level method on the +Logger+ instance, passing in the +before_message+, then the specified message, then the +after_message+: + + + logger = Logger.new("log/development.log") + logger.around_info("before", "after") { |logger| logger.info("during") } + + +h4. +silence+ + +Silences every log level lesser to the specified one for the duration of the given block. Log level orders are: debug, info, error and fatal. + + + logger = Logger.new("log/development.log") + logger.silence(Logger::INFO) do + logger.debug("In space, no one can hear you scream.") + logger.info("Scream all you want, small mailman!") + end + + +h4. +datetime_format=+ + +Modifies the datetime format output by the formatter class associated with this logger. If the formatter class does not have a +datetime_format+ method then this is ignored. + + + class Logger::FormatWithTime < Logger::Formatter + cattr_accessor(:datetime_format) { "%Y%m%d%H%m%S" } + + def self.call(severity, timestamp, progname, msg) + "#{timestamp.strftime(datetime_format)} -- #{String === msg ? msg : msg.inspect}\n" + end + end + + logger = Logger.new("log/development.log") + logger.formatter = Logger::FormatWithTime + logger.info("<- is the current time") + + +NOTE: Defined in +active_support/core_ext/logger.rb+. + h3. Extensions to +NameError+ Active Support adds +missing_name?+ to +NameError+, which tests whether the exception was raised because of the name passed as argument. -- cgit v1.2.3 From e15a55c862c98d05ff95e7fa3162ed1298ba8be7 Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Wed, 15 Dec 2010 22:35:09 +0530 Subject: filter_parameter_logging is deprecated in Rails 3. Changed it to config.filter_parameters --- railties/guides/source/security.textile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/security.textile b/railties/guides/source/security.textile index 528c8861d4..9963106ff3 100644 --- a/railties/guides/source/security.textile +++ b/railties/guides/source/security.textile @@ -524,10 +524,10 @@ h4. Logging -- _Tell Rails not to put passwords in the log files._ -By default, Rails logs all requests being made to the web application. But log files can be a huge security issue, as they may contain login credentials, credit card numbers et cetera. When designing a web application security concept, you should also think about what will happen if an attacker got (full) access to the web server. Encrypting secrets and passwords in the database will be quite useless, if the log files list them in clear text. You can _(highlight)filter certain request parameters from your log files_ by the filter_parameter_logging method in a controller. These parameters will be marked [FILTERED] in the log. +By default, Rails logs all requests being made to the web application. But log files can be a huge security issue, as they may contain login credentials, credit card numbers et cetera. When designing a web application security concept, you should also think about what will happen if an attacker got (full) access to the web server. Encrypting secrets and passwords in the database will be quite useless, if the log files list them in clear text. You can _(highlight)filter certain request parameters from your log files_ by appending them to config.filter_parameters in the application configuration. These parameters will be marked [FILTERED] in the log. -filter_parameter_logging :password +config.filter_parameters << :password h4. Good Passwords -- cgit v1.2.3 From 7a028eae7914f8099b4369b51c2d06a47ecdab9e Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Wed, 15 Dec 2010 23:13:22 +0530 Subject: fixed font --- railties/guides/source/security.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/security.textile b/railties/guides/source/security.textile index 9963106ff3..fbafc40d93 100644 --- a/railties/guides/source/security.textile +++ b/railties/guides/source/security.textile @@ -524,7 +524,7 @@ h4. Logging -- _Tell Rails not to put passwords in the log files._ -By default, Rails logs all requests being made to the web application. But log files can be a huge security issue, as they may contain login credentials, credit card numbers et cetera. When designing a web application security concept, you should also think about what will happen if an attacker got (full) access to the web server. Encrypting secrets and passwords in the database will be quite useless, if the log files list them in clear text. You can _(highlight)filter certain request parameters from your log files_ by appending them to config.filter_parameters in the application configuration. These parameters will be marked [FILTERED] in the log. +By default, Rails logs all requests being made to the web application. But log files can be a huge security issue, as they may contain login credentials, credit card numbers et cetera. When designing a web application security concept, you should also think about what will happen if an attacker got (full) access to the web server. Encrypting secrets and passwords in the database will be quite useless, if the log files list them in clear text. You can _(highlight)filter certain request parameters from your log files_ by appending them to config.filter_parameters in the application configuration. These parameters will be marked [FILTERED] in the log. config.filter_parameters << :password -- cgit v1.2.3 From 80382c7465af27194dc9644b8ba4c4ad458b7ef7 Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Thu, 16 Dec 2010 00:16:28 +0530 Subject: fixed link to ruby-prof --- railties/guides/source/performance_testing.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/performance_testing.textile b/railties/guides/source/performance_testing.textile index 41bdd27e9b..b9401f3559 100644 --- a/railties/guides/source/performance_testing.textile +++ b/railties/guides/source/performance_testing.textile @@ -398,7 +398,7 @@ $ rails benchmarker 'Item.first' 'Item.last' h4. +profiler+ -+profiler+ is a wrapper around http://ruby-prof.rubyforge.org/[ruby-prof] gem. ++profiler+ is a wrapper around the "ruby-prof":http://ruby-prof.rubyforge.org gem. Usage: -- cgit v1.2.3 From ae7910fad44ff05cc9db6e1d13cd57c844e53e13 Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Thu, 16 Dec 2010 00:54:15 +0530 Subject: minor formatting fixes --- railties/guides/source/configuring.textile | 38 +++++++++++++++--------------- 1 file changed, 19 insertions(+), 19 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/configuring.textile b/railties/guides/source/configuring.textile index 44f7a61a77..33319fa40a 100644 --- a/railties/guides/source/configuring.textile +++ b/railties/guides/source/configuring.textile @@ -42,9 +42,9 @@ h4. Rails General Configuration * +config.after_initialize+ takes a block which will be ran _after_ Rails has finished initializing. Useful for configuring values set up by other initializers: - config.after_initialize do - ActionView::Base.sanitized_allowed_tags.delete 'div' - end +config.after_initialize do + ActionView::Base.sanitized_allowed_tags.delete 'div' +end * +config.allow_concurrency+ should be set to +true+ to allow concurrent (threadsafe) action processing. Set to +false+ by default. You probably don't want to call this one directly, though, because a series of other adjustments need to be made for threadsafe mode to work properly. Can also be enabled with +threadsafe!+. @@ -115,7 +115,7 @@ WARNING: Threadsafe operation is incompatible with the normal workings of develo * +config.time_zone+ sets the default time zone for the application and enables time zone awareness for Active Record. -* +config.whiny_nils+ enables or disabled warnings when an methods of nil are invoked. Defaults to _false_. +* +config.whiny_nils+ enables or disables warnings when any methods of nil are invoked. Defaults to _true_ in development and test environments. h4. Configuring Generators @@ -131,12 +131,12 @@ Rails 3 allows you to alter what generators are used with the +config.generators The full set of methods that can be used in this block are as follows: * +force_plural+ allows pluralized model names. Defaults to _false_. -* +helper+ defines whether or not to generate helpers. Defaults to _true_ +* +helper+ defines whether or not to generate helpers. Defaults to _true_. * +orm+ defines which orm to use. Defaults to _nil_, so will use Active Record by default. -* +integration_tool+ defines which integration tool to use. Defaults to _nil_ -* +performance_tool+ defines which performance tool to use. Defaults to _nil_ +* +integration_tool+ defines which integration tool to use. Defaults to _nil_. +* +performance_tool+ defines which performance tool to use. Defaults to _nil_. * +resource_controller+ defines which generator to use for generating a controller when using +rails generate resource+. Defaults to +:controller+. -* +scaffold_controller+ different from +resource_controller+, defines which generator to use for generating a _scaffolded_ controller when using +rails generate scaffold+. Defaults to +:scaffold_controller+ +* +scaffold_controller+ different from +resource_controller+, defines which generator to use for generating a _scaffolded_ controller when using +rails generate scaffold+. Defaults to +:scaffold_controller+. * +stylesheets+ turns on the hook for stylesheets in generators. Used in Rails for when the +scaffold+ generator is ran, but this hook can be used in other generates as well. * +test_framework+ defines which test framework to use. Defaults to _nil_, so will use Test::Unit by default. * +template_engine+ defines which template engine to use, such as ERB or Haml. Defaults to +:erb+. @@ -234,7 +234,7 @@ h4. Configuring Action Controller * +config.action_controller.asset_path+ takes a block which configures where assets can be found. Shorter version of +config.action_controller.asset_path+. -* +config.action_controller.page_cache_directory+ should be the document root for the web server and is set using Base.page_cache_directory = "/document/root". For Rails, this directory has already been set to Rails.public_path (which is usually set to Rails.root + "/public"). Changing this setting can be useful to avoid naming conflicts with files in public/, but doing so will likely require configuring your web server to look in the new location for cached files. +* +config.action_controller.page_cache_directory+ should be the document root for the web server and is set using Base.page_cache_directory = "/document/root". For Rails, this directory has already been set to +Rails.public_path+ (which is usually set to Rails.root + "/public"). Changing this setting can be useful to avoid naming conflicts with files in public/, but doing so will likely require configuring your web server to look in the new location for cached files. * +config.action_controller.page_cache_extension+ configures the extension used for cached pages saved to +page_cache_directory+. Defaults to +.html+ @@ -252,7 +252,7 @@ h4. Configuring Action Controller The caching code adds two additional settings: -* +ActionController::Base.page_cache_directory+ sets the directory where Rails will create cached pages for your web server. The default is +Rails.public_path+ (which is usually set to +Rails.root + "/public"+). +* +ActionController::Base.page_cache_directory+ sets the directory where Rails will create cached pages for your web server. The default is +Rails.public_path+ (which is usually set to Rails.root + "/public"). * +ActionController::Base.page_cache_extension+ sets the extension to be used when generating pages for the cache (this is ignored if the incoming request already has an extension). The default is +.html+. @@ -280,7 +280,7 @@ h4. Configuring Action View There are only a few configuration options for Action View, starting with four on +ActionView::Base+: -* +config.action_view.debug_rjs+ specifies whether RJS responses should be wrapped in a try/catch block that alert()s the caught exception (and then re-raises it). The default is +false+. +* +config.action_view.debug_rjs+ specifies whether RJS responses should be wrapped in a try/catch block that alerts the caught exception (and then re-raises it). The default is +false+. * +config.action_view.field_error_proc+ provides an HTML generator for displaying errors that come from Active Record. The default is Proc.new{ |html_tag, instance| %Q(%<div class="field_with_errors">#{html_tag}</div>).html_safe } @@ -290,7 +290,7 @@ There are only a few configuration options for Action View, starting with four o * +config.action_view.erb_trim_mode+ gives the trim mode to be used by ERB. It defaults to +'-'+. See the "ERB documentation":http://www.ruby-doc.org/stdlib/libdoc/erb/rdoc/ for more information. -* +config.action_view.javascript_expansions+ a hash containining expansions that can be used for javascript include tag. By default, this is defined as: +* +config.action_view.javascript_expansions+ is a hash containing expansions that can be used for the JavaScript include tag. By default, this is defined as: config.action_view.javascript_expansions = { :defaults => ['prototype', 'effects', 'dragdrop', 'controls', 'rails'] } @@ -302,7 +302,7 @@ However, you may add to this by defining others: config.action_view.javascript_expansions[:jquery] = ["jquery", "jquery-ui"] -Then this can be referenced in the view with the following code: +And can reference in the view with the following code: <%= javascript_include_tag :jquery %> @@ -374,9 +374,9 @@ h3. Rails Environment Settings Some parts of Rails can also be configured externally by supplying environment variables. The following environment variables are recognized by various parts of Rails: -* +ENV['RAILS_ENV']+ defines the Rails environment (production, development, test, and so on) that Rails will run under. +* +ENV["RAILS_ENV"]+ defines the Rails environment (production, development, test, and so on) that Rails will run under. -* +ENV['RAILS_RELATIVE_URL_ROOT']+ is used by the routing code to recognize URLs when you deploy your application to a subdirectory. +* +ENV["RAILS_RELATIVE_URL_ROOT"]+ is used by the routing code to recognize URLs when you deploy your application to a subdirectory. * +ENV["RAILS_ASSET_ID"]+ will override the default cache-busting timestamps that Rails generates for downloadable assets. @@ -404,9 +404,9 @@ h4. +Rails::Railtie#initializer+ Rails has several initializers that run on startup that are all defined by using the +initializer+ method from +Rails::Railtie+. Here's an example of the +initialize_whiny_nils+ initializer from Active Support: - initializer "active_support.initialize_whiny_nils" do |app| - require 'active_support/whiny_nil' if app.config.whiny_nils - end +initializer "active_support.initialize_whiny_nils" do |app| + require 'active_support/whiny_nil' if app.config.whiny_nils +end The +initializer+ method takes three arguments with the first being the name for the initializer and the second being an options hash (not shown here) and the third being a block. The +:before+ key in the options hash can be specified to specify which initializer this new initializer must run before, and the +:after+ key will specify which initializer to run this initializer _after_. @@ -442,7 +442,7 @@ Serves as a placeholder so that +:load_environment_config+ can be defined to run *+i18n.callbacks+* In the development environment, sets up a +to_prepare+ callback which will call +I18n.reload!+ if any of the locales have changed since the last request. In production mode this callback will only run on the first request. -*+active_support.initialize_whiny_nils+* Will require +active_support/whiny_nil+ if +config.whiny_nil+ is set to +true+. This file will output errors such as: +*+active_support.initialize_whiny_nils+* Will require +active_support/whiny_nil+ if +config.whiny_nils+ is set to +true+. This file will output errors such as: Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id -- cgit v1.2.3 From e9732c75a819bd36ae6a47dd2b19f6cb0db4d238 Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Thu, 16 Dec 2010 00:56:02 +0530 Subject: fixed typos --- railties/guides/source/debugging_rails_applications.textile | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/debugging_rails_applications.textile b/railties/guides/source/debugging_rails_applications.textile index 6613fad406..2c8a6619c2 100644 --- a/railties/guides/source/debugging_rails_applications.textile +++ b/railties/guides/source/debugging_rails_applications.textile @@ -48,7 +48,7 @@ Title: Rails debugging guide h4. +to_yaml+ -Displaying an instance variable, or any other object or method, in yaml format can be achieved this way: +Displaying an instance variable, or any other object or method, in YAML format can be achieved this way: <%= simple_format @post.to_yaml %> @@ -122,7 +122,7 @@ It can also be useful to save information to log files at runtime. Rails maintai h4. What is the Logger? -Rails makes use of Ruby's standard +logger+ to write log information. You can also substitute another logger such as +Log4R+ if you wish. +Rails makes use of Ruby's standard +logger+ to write log information. You can also substitute another logger such as +Log4r+ if you wish. You can specify an alternative logger in your +environment.rb+ or any environment file: @@ -178,7 +178,7 @@ class PostsController < ApplicationController if @post.save flash[:notice] = 'Post was successfully created.' - logger.debug "The post was saved and now is the user is going to be redirected..." + logger.debug "The post was saved and now the user is going to be redirected..." redirect_to(@post) else render :action => "new" @@ -204,7 +204,7 @@ Post should be valid: true Post Create (0.000443) INSERT INTO "posts" ("updated_at", "title", "body", "published", "created_at") VALUES('2008-09-08 14:52:54', 'Debugging Rails', 'I''m learning how to print in logs!!!', 'f', '2008-09-08 14:52:54') -The post was saved and now is the user is going to be redirected... +The post was saved and now the user is going to be redirected... Redirected to # Completed in 0.01224 (81 reqs/sec) | DB: 0.00044 (3%) | 302 Found [http://localhost/posts] @@ -601,7 +601,7 @@ There are some settings that can be configured in ruby-debug to make it easier t You can see the full list by using +help set+. Use +help set _subcommand_+ to learn about a particular +set+ command. -TIP: You can include any number of these configuration lines inside a +.rdebugrc+ file in your HOME directory. ruby-debug will read this file every time it is loaded. and configure itself accordingly. +TIP: You can include any number of these configuration lines inside a +.rdebugrc+ file in your HOME directory. ruby-debug will read this file every time it is loaded and configure itself accordingly. Here's a good start for an +.rdebugrc+: @@ -615,7 +615,7 @@ h3. Debugging Memory Leaks A Ruby application (on Rails or not), can leak memory - either in the Ruby code or at the C code level. -In this section, you will learn how to find and fix such leaks by using Bleak House and Valgrind debugging tools. +In this section, you will learn how to find and fix such leaks by using tools such as BleakHouse and Valgrind. h4. BleakHouse -- cgit v1.2.3 From edf5b57451796ba40a330748aa7f4c77048b564f Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Sat, 11 Dec 2010 01:50:21 -0200 Subject: Add named helper output to translated paths example --- railties/guides/source/routing.textile | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/routing.textile b/railties/guides/source/routing.textile index 74dee60c32..a51f7475ea 100644 --- a/railties/guides/source/routing.textile +++ b/railties/guides/source/routing.textile @@ -745,14 +745,14 @@ end Rails now creates routes to the +CategoriesController+. -|_.HTTP verb|_.Path |_.action | -|GET |/kategorien |index | -|GET |/kategorien/neu |new | -|POST |/kategorien |create | -|GET |/kategorien/1 |show | -|GET |/kategorien/:id/bearbeiten |edit | -|PUT |/kategorien/1 |update | -|DELETE |/kategorien/1 |destroy | +|_.HTTP verb|_.Path |_.action | .named helper | +|GET |/kategorien |index | categories_path | +|GET |/kategorien/neu |new | new_category_path | +|POST |/kategorien |create | categories_path | +|GET |/kategorien/1 |show | category_path | +|GET |/kategorien/:id/bearbeiten |edit | edit_category_path | +|PUT |/kategorien/1 |update | category_path | +|DELETE |/kategorien/1 |destroy | category_path | h4. Overriding the Singular Form -- cgit v1.2.3 From 6f8cc0776bfabac12208a5134c6feb26813754dc Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Sat, 11 Dec 2010 01:54:59 -0200 Subject: Add underline to header --- railties/guides/source/routing.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/routing.textile b/railties/guides/source/routing.textile index a51f7475ea..759aa7bb90 100644 --- a/railties/guides/source/routing.textile +++ b/railties/guides/source/routing.textile @@ -745,7 +745,7 @@ end Rails now creates routes to the +CategoriesController+. -|_.HTTP verb|_.Path |_.action | .named helper | +|_.HTTP verb|_.Path |_.action |_.named helper | |GET |/kategorien |index | categories_path | |GET |/kategorien/neu |new | new_category_path | |POST |/kategorien |create | categories_path | -- cgit v1.2.3 From 4c5805dfabad7de5bc10c9e4a76c260d6e47ba92 Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Sat, 11 Dec 2010 02:02:09 -0200 Subject: Add named helper to photo controller example --- railties/guides/source/routing.textile | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/routing.textile b/railties/guides/source/routing.textile index 759aa7bb90..9c1ed74804 100644 --- a/railties/guides/source/routing.textile +++ b/railties/guides/source/routing.textile @@ -611,14 +611,14 @@ resources :photos, :controller => "images" will recognize incoming paths beginning with +/photos+ but route to the +Images+ controller: -|_. Verb |_.Path |_.action | -|GET |/photos |index | -|GET |/photos/new |new | -|POST |/photos |create | -|GET |/photos/1 |show | -|GET |/photos/1/edit |edit | -|PUT |/photos/1 |update | -|DELETE |/photos/1 |destroy | +|_. Verb |_.Path |_.action |_.named helper | +|GET |/photos |index | photos_path | +|GET |/photos/new |new | new_photo_path | +|POST |/photos |create | photos_path | +|GET |/photos/1 |show | photo_path | +|GET |/photos/1/edit |edit | edit_photo_path | +|PUT |/photos/1 |update | photo_path | +|DELETE |/photos/1 |destroy | photo_path | NOTE: Use +photos_path+, +new_photos_path+, etc. to generate paths for this resource. -- cgit v1.2.3 From 692b621d2a134ac784719abcb4fd24f1710cd786 Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Sat, 11 Dec 2010 02:24:07 -0200 Subject: Tables style unification --- railties/guides/source/routing.textile | 126 ++++++++++++++++----------------- 1 file changed, 63 insertions(+), 63 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/routing.textile b/railties/guides/source/routing.textile index 9c1ed74804..32346e8f2b 100644 --- a/railties/guides/source/routing.textile +++ b/railties/guides/source/routing.textile @@ -76,14 +76,14 @@ resources :photos creates seven different routes in your application, all mapping to the +Photos+ controller: -|_. Verb |_.Path |_.action |_.used for| -|GET |/photos |index |display a list of all photos| -|GET |/photos/new |new |return an HTML form for creating a new photo| -|POST |/photos |create |create a new photo| -|GET |/photos/:id |show |display a specific photo| -|GET |/photos/:id/edit |edit |return an HTML form for editing a photo| -|PUT |/photos/:id |update |update a specific photo| -|DELETE |/photos/:id |destroy |delete a specific photo| +|_. HTTP Verb |_.Path |_.action |_.used for | +|GET |/photos |index |display a list of all photos | +|GET |/photos/new |new |return an HTML form for creating a new photo | +|POST |/photos |create |create a new photo | +|GET |/photos/:id |show |display a specific photo | +|GET |/photos/:id/edit |edit |return an HTML form for editing a photo | +|PUT |/photos/:id |update |update a specific photo | +|DELETE |/photos/:id |destroy |delete a specific photo | h4. Paths and URLs @@ -130,13 +130,13 @@ resource :geocoder creates six different routes in your application, all mapping to the +Geocoders+ controller: -|_. Verb |_.Path |_.action |_.used for| -|GET |/geocoder/new |new |return an HTML form for creating the geocoder| -|POST |/geocoder |create |create the new geocoder| -|GET |/geocoder |show |display the one and only geocoder resource| -|GET |/geocoder/edit |edit |return an HTML form for editing the geocoder| -|PUT |/geocoder |update |update the one and only geocoder resource| -|DELETE |/geocoder |destroy |delete the geocoder resource| +|_.HTTP Verb |_.Path |_.action |_.used for | +|GET |/geocoder/new |new |return an HTML form for creating the geocoder | +|POST |/geocoder |create |create the new geocoder | +|GET |/geocoder |show |display the one and only geocoder resource | +|GET |/geocoder/edit |edit |return an HTML form for editing the geocoder | +|PUT |/geocoder |update |update the one and only geocoder resource | +|DELETE |/geocoder |destroy |delete the geocoder resource | NOTE: Because you might want to use the same controller for a singular route (+/account+) and a plural route (+/accounts/45+), singular resources map to plural controllers. @@ -160,14 +160,14 @@ end This will create a number of routes for each of the +posts+ and +comments+ controller. For +Admin::PostsController+, Rails will create: -|_. Verb |_.Path |_.action |_. helper | -|GET |/admin/posts |index | admin_posts_path | -|GET |/admin/posts/new |new | new_admin_posts_path | -|POST |/admin/posts |create | admin_posts_path | -|GET |/admin/posts/1 |show | admin_post_path(id) | -|GET |/admin/posts/1/edit |edit | edit_admin_post_path(id) | -|PUT |/admin/posts/1 |update | admin_post_path(id) | -|DELETE |/admin/posts/1 |destroy | admin_post_path(id) | +|_.HTTP Verb |_.Path |_.action |_.named helper | +|GET |/admin/posts |index | admin_posts_path | +|GET |/admin/posts/new |new | new_admin_posts_path | +|POST |/admin/posts |create | admin_posts_path | +|GET |/admin/posts/1 |show | admin_post_path(id) | +|GET |/admin/posts/1/edit |edit | edit_admin_post_path(id) | +|PUT |/admin/posts/1 |update | admin_post_path(id) | +|DELETE |/admin/posts/1 |destroy | admin_post_path(id) | If you want to route +/posts+ (without the prefix +/admin+) to +Admin::PostsController+, you could use @@ -199,14 +199,14 @@ resources :posts, :path => "/admin/posts" In each of these cases, the named routes remain the same as if you did not use +scope+. In the last case, the following paths map to +PostsController+: -|_. Verb |_.Path |_.action |_. helper | -|GET |/admin/posts |index | posts_path | -|GET |/admin/posts/new |new | posts_path | -|POST |/admin/posts |create | posts_path | -|GET |/admin/posts/1 |show | post_path(id) | -|GET |/admin/posts/1/edit |edit | edit_post_path(id) | -|PUT |/admin/posts/1 |update | post_path(id) | -|DELETE |/admin/posts/1 |destroy | post_path(id) | +|_.HTTP Verb |_.Path |_.action |_.named helper | +|GET |/admin/posts |index | posts_path | +|GET |/admin/posts/new |new | posts_path | +|POST |/admin/posts |create | posts_path | +|GET |/admin/posts/1 |show | post_path(id) | +|GET |/admin/posts/1/edit |edit | edit_post_path(id) | +|PUT |/admin/posts/1 |update | post_path(id) | +|DELETE |/admin/posts/1 |destroy | post_path(id) | h4. Nested Resources @@ -232,14 +232,14 @@ end In addition to the routes for magazines, this declaration will also route ads to an +AdsController+. The ad URLs require a magazine: -|_.Verb |_.Path |_.action |_.used for| -|GET |/magazines/1/ads |index |display a list of all ads for a specific magazine| -|GET |/magazines/1/ads/new |new |return an HTML form for creating a new ad belonging to a specific magazine| -|POST |/magazines/1/ads |create |create a new ad belonging to a specific magazine| -|GET |/magazines/1/ads/1 |show |display a specific ad belonging to a specific magazine| -|GET |/magazines/1/ads/1/edit |edit |return an HTML form for editing an ad belonging to a specific magazine| -|PUT |/magazines/1/ads/1 |update |update a specific ad belonging to a specific magazine| -|DELETE |/magazines/1/ads/1 |destroy |delete a specific ad belonging to a specific magazine| +|_.HTTP Verb |_.Path |_.action |_.used for | +|GET |/magazines/1/ads |index |display a list of all ads for a specific magazine | +|GET |/magazines/1/ads/new |new |return an HTML form for creating a new ad belonging to a specific magazine | +|POST |/magazines/1/ads |create |create a new ad belonging to a specific magazine | +|GET |/magazines/1/ads/1 |show |display a specific ad belonging to a specific magazine | +|GET |/magazines/1/ads/1/edit |edit |return an HTML form for editing an ad belonging to a specific magazine | +|PUT |/magazines/1/ads/1 |update |update a specific ad belonging to a specific magazine | +|DELETE |/magazines/1/ads/1 |destroy |delete a specific ad belonging to a specific magazine | This will also create routing helpers such as +magazine_ads_url+ and +edit_magazine_ad_path+. These helpers take an instance of Magazine as the first parameter (+magazine_ads_url(@magazine)+). @@ -611,14 +611,14 @@ resources :photos, :controller => "images" will recognize incoming paths beginning with +/photos+ but route to the +Images+ controller: -|_. Verb |_.Path |_.action |_.named helper | -|GET |/photos |index | photos_path | -|GET |/photos/new |new | new_photo_path | -|POST |/photos |create | photos_path | -|GET |/photos/1 |show | photo_path | -|GET |/photos/1/edit |edit | edit_photo_path | -|PUT |/photos/1 |update | photo_path | -|DELETE |/photos/1 |destroy | photo_path | +|_.HTTP Verb |_.Path |_.action |_.named helper | +|GET |/photos |index | photos_path | +|GET |/photos/new |new | new_photo_path | +|POST |/photos |create | photos_path | +|GET |/photos/1 |show | photo_path(id) | +|GET |/photos/1/edit |edit | edit_photo_path(id) | +|PUT |/photos/1 |update | photo_path(id) | +|DELETE |/photos/1 |destroy | photo_path(id) | NOTE: Use +photos_path+, +new_photos_path+, etc. to generate paths for this resource. @@ -653,14 +653,14 @@ resources :photos, :as => "images" will recognize incoming paths beginning with +/photos+ and route the requests to +PhotosController+, but use the value of the :as option to name the helpers. -|_.HTTP verb|_.Path |_.action |_.named helper | -|GET |/photos |index | images_path | -|GET |/photos/new |new | new_image_path | -|POST |/photos |create | images_path | -|GET |/photos/1 |show | image_path | -|GET |/photos/1/edit |edit | edit_image_path | -|PUT |/photos/1 |update | image_path | -|DELETE |/photos/1 |destroy | image_path | +|_.HTTP verb|_.Path |_.action |_.named helper | +|GET |/photos |index | images_path | +|GET |/photos/new |new | new_image_path | +|POST |/photos |create | images_path | +|GET |/photos/1 |show | image_path(id) | +|GET |/photos/1/edit |edit | edit_image_path(id) | +|PUT |/photos/1 |update | image_path(id) | +|DELETE |/photos/1 |destroy | image_path(id) | h4. Overriding the +new+ and +edit+ Segments @@ -745,14 +745,14 @@ end Rails now creates routes to the +CategoriesController+. -|_.HTTP verb|_.Path |_.action |_.named helper | -|GET |/kategorien |index | categories_path | -|GET |/kategorien/neu |new | new_category_path | -|POST |/kategorien |create | categories_path | -|GET |/kategorien/1 |show | category_path | -|GET |/kategorien/:id/bearbeiten |edit | edit_category_path | -|PUT |/kategorien/1 |update | category_path | -|DELETE |/kategorien/1 |destroy | category_path | +|_.HTTP verb|_.Path |_.action |_.named helper | +|GET |/kategorien |index | categories_path | +|GET |/kategorien/neu |new | new_category_path | +|POST |/kategorien |create | categories_path | +|GET |/kategorien/1 |show | category_path(id) | +|GET |/kategorien/1/bearbeiten |edit | edit_category_path(id) | +|PUT |/kategorien/1 |update | category_path(id) | +|DELETE |/kategorien/1 |destroy | category_path(id) | h4. Overriding the Singular Form -- cgit v1.2.3 From f96fb78e57a9eda13edcba8716b4c7d7d5cbb375 Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Thu, 16 Dec 2010 01:48:11 +0530 Subject: removed info about deprecated rake tasks, documented the sandbox option for the rails console and minor corrections --- railties/guides/source/command_line.textile | 42 +++++++++++++---------------- 1 file changed, 18 insertions(+), 24 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/command_line.textile b/railties/guides/source/command_line.textile index 11ce3a5003..1e570c9992 100644 --- a/railties/guides/source/command_line.textile +++ b/railties/guides/source/command_line.textile @@ -31,7 +31,7 @@ h4. +rails new+ The first thing we'll want to do is create a new Rails application by running the +rails new+ command after installing Rails. -WARNING: You know you need the rails gem installed by typing +gem install rails+ first, if you don't have this installed, follow the instructions in the "Rails 3 Release Notes":/3_0_release_notes.html +WARNING: You can install the rails gem by typing +gem install rails+, if you don't have it already. Follow the instructions in the "Rails 3 Release Notes":/3_0_release_notes.html $ rails new commandsapp @@ -73,7 +73,7 @@ $ rails server [2010-04-18 03:20:33] INFO WEBrick::HTTPServer#start: pid=26086 port=3000 -With just three commands we whipped up a Rails server listening on port 3000. Go to your browser and open "http://localhost:3000":http://localhost:3000, you will see a basic rails app running. +With just three commands we whipped up a Rails server listening on port 3000. Go to your browser and open "http://localhost:3000":http://localhost:3000, you will see a basic Rails app running. h4. +rails generate+ @@ -101,7 +101,7 @@ Using generators will save you a large amount of time by writing *boilerplate co Let's make our own controller with the controller generator. But what command should we use? Let's ask the generator: -INFO: All Rails console utilities have help text. As with most *NIX utilities, you can try adding +--help+ or +-h+ to the end, for example +rails server --help+. +INFO: All Rails console utilities have help text. As with most *nix utilities, you can try adding +--help+ or +-h+ to the end, for example +rails server --help+. $ rails generate controller @@ -134,6 +134,7 @@ The controller generator is expecting parameters in the form of +generate contro $ rails generate controller Greetings hello create app/controllers/greetings_controller.rb + route get "greetings/hello" invoke erb create app/views/greetings create app/views/greetings/hello.html.erb @@ -261,6 +262,15 @@ h4. +rails console+ The +console+ command lets you interact with your Rails application from the command line. On the underside, +rails console+ uses IRB, so if you've ever used it, you'll be right at home. This is useful for testing out quick ideas with code and changing data server-side without touching the website. +If you wish to test out some code without changing any data, you can do that by invoking +rails console --sandbox+. + + +$ rails console --sandbox +Loading development environment in sandbox (Rails 3.0.0) +Any modifications you make will be rolled back on exit +irb(main):001:0> + + h4. +rails dbconsole+ +rails dbconsole+ figures out which database you're using and drops you into whichever command line interface you would use with it (and figures out the command line parameters to give to it, too!). It supports MySQL, PostgreSQL, SQLite and SQLite3. @@ -281,7 +291,7 @@ $ rails plugin install http://svn.techno-weenie.net/projects/plugins/acts_as_par ... -h4. +runner+ +h4. +rails runner+ runner runs Ruby code in the context of Rails non-interactively. For instance: @@ -289,7 +299,7 @@ h4. +runner+ $ rails runner "Model.long_running_method" -h4. +destroy+ +h4. +rails destroy+ Think of +destroy+ as the opposite of +generate+. It'll figure out what generate did, and undo it. Believe you-me, the creation of this tutorial used this command many times! @@ -318,7 +328,7 @@ $ rails destroy model Oops notempty app -h4. +about+ +h4. +rake about+ Check it: Version numbers for Ruby, RubyGems, Rails, the Rails subcomponents, your application's folder, the current Rails environment name, your app's database adapter, and schema version! +about+ is useful when you need to ask for help, check if a security patch might affect you, or when you need some stats for an existing Rails installation. @@ -341,7 +351,7 @@ Environment development h3. The Rails Advanced Command Line -The more advanced uses of the command line are focused around finding useful (even surprising at times) options in the utilities, and fitting utilities to your needs and specific work flow. Listed here are some tricks up Rails' sleeve. +More advanced use of the command line is focused around finding useful (even surprising at times) options in the utilities, and fitting those to your needs and specific work flow. Listed here are some tricks up Rails' sleeve. h4. Rails with Databases and SCM @@ -474,7 +484,7 @@ We take whatever args are supplied, save them to an instance variable, and liter * Check there's a *public* directory. You bet there is. * Run the ERb template called "tutorial.erb". * Save it into "Rails.root/public/tutorial.txt". -* Pass in the arguments we saved through the +:assign+ parameter. +* Pass in the arguments we saved through the +:assigns+ parameter. Next we'll build the template: @@ -540,8 +550,6 @@ rake tmp:sessions:clear # Clears all files in tmp/sessions rake tmp:sockets:clear # Clears all files in tmp/sockets -Let's take a look at some of these 80 or so rake tasks. - h5. +db:+ Database The most common tasks of the +db:+ Rake namespace are +migrate+ and +create+, and it will pay off to try out all of the migration rake tasks (+up+, +down+, +redo+, +reset+). +rake db:version+ is useful when troubleshooting, telling you the current version of the database. @@ -550,24 +558,10 @@ h5. +doc:+ Documentation If you want to strip out or rebuild any of the Rails documentation (including this guide!), the +doc:+ namespace has the tools. Stripping documentation is mainly useful for slimming your codebase, like if you're writing a Rails application for an embedded platform. -h5. +gems:+ Ruby gems - -You can specify which gems your application uses, and +rake gems:install+ will install them for you. Look at your environment.rb to learn how with the *config.gem* directive. - -NOTE: +gems:unpack+ will unpack, that is internalize your application's Gem dependencies by copying the Gem code into your vendor/gems directory. By doing this you increase your codebase size, but simplify installation on new hosts by eliminating the need to run +rake gems:install+, or finding and installing the gems your application uses. - h5. +notes:+ Code note enumeration These tasks will search through your code for commented lines beginning with "FIXME", "OPTIMIZE", "TODO", or any custom annotation (like XXX) and show you them. -h5. +rails:+ Rails-specific tasks - -In addition to the +gems:unpack+ task above, you can also unpack the Rails backend specific gems into vendor/rails by calling +rake rails:freeze:gems+, to unpack the version of Rails you are currently using, or +rake rails:freeze:edge+ to unpack the most recent (cutting, bleeding edge) version. - -When you have frozen the Rails gems, Rails will prefer to use the code in vendor/rails instead of the system Rails gems. You can "thaw" by running +rake rails:unfreeze+. - -After upgrading Rails, it is useful to run +rails:update+, which will update your config and scripts directories, and upgrade your Rails-specific javascript (like Scriptaculous). - h5. +test:+ Rails tests INFO: A good description of unit testing in Rails is given in "A Guide to Testing Rails Applications":testing.html -- cgit v1.2.3 From e00afadfdd998f22905c2a0d59e8d76602b3592c Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Thu, 16 Dec 2010 01:48:11 +0530 Subject: removed info about deprecated rake tasks, documented the sandbox option for the rails console and minor corrections --- railties/guides/source/command_line.textile | 42 +++++++++++++---------------- 1 file changed, 18 insertions(+), 24 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/command_line.textile b/railties/guides/source/command_line.textile index 11ce3a5003..1e570c9992 100644 --- a/railties/guides/source/command_line.textile +++ b/railties/guides/source/command_line.textile @@ -31,7 +31,7 @@ h4. +rails new+ The first thing we'll want to do is create a new Rails application by running the +rails new+ command after installing Rails. -WARNING: You know you need the rails gem installed by typing +gem install rails+ first, if you don't have this installed, follow the instructions in the "Rails 3 Release Notes":/3_0_release_notes.html +WARNING: You can install the rails gem by typing +gem install rails+, if you don't have it already. Follow the instructions in the "Rails 3 Release Notes":/3_0_release_notes.html $ rails new commandsapp @@ -73,7 +73,7 @@ $ rails server [2010-04-18 03:20:33] INFO WEBrick::HTTPServer#start: pid=26086 port=3000 -With just three commands we whipped up a Rails server listening on port 3000. Go to your browser and open "http://localhost:3000":http://localhost:3000, you will see a basic rails app running. +With just three commands we whipped up a Rails server listening on port 3000. Go to your browser and open "http://localhost:3000":http://localhost:3000, you will see a basic Rails app running. h4. +rails generate+ @@ -101,7 +101,7 @@ Using generators will save you a large amount of time by writing *boilerplate co Let's make our own controller with the controller generator. But what command should we use? Let's ask the generator: -INFO: All Rails console utilities have help text. As with most *NIX utilities, you can try adding +--help+ or +-h+ to the end, for example +rails server --help+. +INFO: All Rails console utilities have help text. As with most *nix utilities, you can try adding +--help+ or +-h+ to the end, for example +rails server --help+. $ rails generate controller @@ -134,6 +134,7 @@ The controller generator is expecting parameters in the form of +generate contro $ rails generate controller Greetings hello create app/controllers/greetings_controller.rb + route get "greetings/hello" invoke erb create app/views/greetings create app/views/greetings/hello.html.erb @@ -261,6 +262,15 @@ h4. +rails console+ The +console+ command lets you interact with your Rails application from the command line. On the underside, +rails console+ uses IRB, so if you've ever used it, you'll be right at home. This is useful for testing out quick ideas with code and changing data server-side without touching the website. +If you wish to test out some code without changing any data, you can do that by invoking +rails console --sandbox+. + + +$ rails console --sandbox +Loading development environment in sandbox (Rails 3.0.0) +Any modifications you make will be rolled back on exit +irb(main):001:0> + + h4. +rails dbconsole+ +rails dbconsole+ figures out which database you're using and drops you into whichever command line interface you would use with it (and figures out the command line parameters to give to it, too!). It supports MySQL, PostgreSQL, SQLite and SQLite3. @@ -281,7 +291,7 @@ $ rails plugin install http://svn.techno-weenie.net/projects/plugins/acts_as_par ... -h4. +runner+ +h4. +rails runner+ runner runs Ruby code in the context of Rails non-interactively. For instance: @@ -289,7 +299,7 @@ h4. +runner+ $ rails runner "Model.long_running_method" -h4. +destroy+ +h4. +rails destroy+ Think of +destroy+ as the opposite of +generate+. It'll figure out what generate did, and undo it. Believe you-me, the creation of this tutorial used this command many times! @@ -318,7 +328,7 @@ $ rails destroy model Oops notempty app -h4. +about+ +h4. +rake about+ Check it: Version numbers for Ruby, RubyGems, Rails, the Rails subcomponents, your application's folder, the current Rails environment name, your app's database adapter, and schema version! +about+ is useful when you need to ask for help, check if a security patch might affect you, or when you need some stats for an existing Rails installation. @@ -341,7 +351,7 @@ Environment development h3. The Rails Advanced Command Line -The more advanced uses of the command line are focused around finding useful (even surprising at times) options in the utilities, and fitting utilities to your needs and specific work flow. Listed here are some tricks up Rails' sleeve. +More advanced use of the command line is focused around finding useful (even surprising at times) options in the utilities, and fitting those to your needs and specific work flow. Listed here are some tricks up Rails' sleeve. h4. Rails with Databases and SCM @@ -474,7 +484,7 @@ We take whatever args are supplied, save them to an instance variable, and liter * Check there's a *public* directory. You bet there is. * Run the ERb template called "tutorial.erb". * Save it into "Rails.root/public/tutorial.txt". -* Pass in the arguments we saved through the +:assign+ parameter. +* Pass in the arguments we saved through the +:assigns+ parameter. Next we'll build the template: @@ -540,8 +550,6 @@ rake tmp:sessions:clear # Clears all files in tmp/sessions rake tmp:sockets:clear # Clears all files in tmp/sockets -Let's take a look at some of these 80 or so rake tasks. - h5. +db:+ Database The most common tasks of the +db:+ Rake namespace are +migrate+ and +create+, and it will pay off to try out all of the migration rake tasks (+up+, +down+, +redo+, +reset+). +rake db:version+ is useful when troubleshooting, telling you the current version of the database. @@ -550,24 +558,10 @@ h5. +doc:+ Documentation If you want to strip out or rebuild any of the Rails documentation (including this guide!), the +doc:+ namespace has the tools. Stripping documentation is mainly useful for slimming your codebase, like if you're writing a Rails application for an embedded platform. -h5. +gems:+ Ruby gems - -You can specify which gems your application uses, and +rake gems:install+ will install them for you. Look at your environment.rb to learn how with the *config.gem* directive. - -NOTE: +gems:unpack+ will unpack, that is internalize your application's Gem dependencies by copying the Gem code into your vendor/gems directory. By doing this you increase your codebase size, but simplify installation on new hosts by eliminating the need to run +rake gems:install+, or finding and installing the gems your application uses. - h5. +notes:+ Code note enumeration These tasks will search through your code for commented lines beginning with "FIXME", "OPTIMIZE", "TODO", or any custom annotation (like XXX) and show you them. -h5. +rails:+ Rails-specific tasks - -In addition to the +gems:unpack+ task above, you can also unpack the Rails backend specific gems into vendor/rails by calling +rake rails:freeze:gems+, to unpack the version of Rails you are currently using, or +rake rails:freeze:edge+ to unpack the most recent (cutting, bleeding edge) version. - -When you have frozen the Rails gems, Rails will prefer to use the code in vendor/rails instead of the system Rails gems. You can "thaw" by running +rake rails:unfreeze+. - -After upgrading Rails, it is useful to run +rails:update+, which will update your config and scripts directories, and upgrade your Rails-specific javascript (like Scriptaculous). - h5. +test:+ Rails tests INFO: A good description of unit testing in Rails is given in "A Guide to Testing Rails Applications":testing.html -- cgit v1.2.3 From f176b2552ecc06634dae53b82a4562d8e80aeed6 Mon Sep 17 00:00:00 2001 From: Piotr Sarnacki Date: Thu, 16 Dec 2010 22:53:19 +0100 Subject: Changelog and guide entries for config.action_view.cache_template_loading --- railties/guides/source/configuring.textile | 2 ++ 1 file changed, 2 insertions(+) (limited to 'railties/guides') diff --git a/railties/guides/source/configuring.textile b/railties/guides/source/configuring.textile index 33319fa40a..d5faf3da2c 100644 --- a/railties/guides/source/configuring.textile +++ b/railties/guides/source/configuring.textile @@ -63,6 +63,8 @@ end * +config.cache_classes+ controls whether or not application classes should be reloaded on each request. Defaults to _true_ in development, _false_ in test and production. Can also be enabled with +threadsafe!+. +* +config.action_view.cache_template_loading+ controls whether or not templates should be reloaded on each request. Defaults to whatever is set for config.cache_classes. + * +config.cache_store+ configures which cache store to use for Rails caching. Options include +:memory_store+, +:file_store+, +:mem_cache_store+ or the name of your own custom class. Defaults to +:file_store+. * +config.colorize_logging+ specifies whether or not to use ANSI color codes when logging information. Defaults to _true_. -- cgit v1.2.3 From 3b9120fa52b76fb8591fe1d0db85d1a940e867d0 Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Thu, 16 Dec 2010 20:10:30 -0200 Subject: Generate add_index by default when giving type belongs_to or references --- railties/guides/source/getting_started.textile | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/getting_started.textile b/railties/guides/source/getting_started.textile index 902b7353c0..e371632d87 100644 --- a/railties/guides/source/getting_started.textile +++ b/railties/guides/source/getting_started.textile @@ -811,6 +811,8 @@ class CreateComments < ActiveRecord::Migration t.timestamps end + + add_index :comments, :post_id end def self.down @@ -819,7 +821,7 @@ class CreateComments < ActiveRecord::Migration end -The +t.references+ line sets up a foreign key column for the association between the two models. Go ahead and run the migration: +The +t.references+ line sets up a foreign key column for the association between the two models. And the +add_index+ line sets up an index for this association column. Go ahead and run the migration: $ rake db:migrate -- cgit v1.2.3 From 5e0daa0bce83cb01c3db43f2fbcd3d16b14f6eb3 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Wed, 15 Dec 2010 16:39:04 +1000 Subject: init guide: Cover ruby version checker and kernel reporting and logger coreext --- railties/guides/source/initialization.textile | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) (limited to 'railties/guides') diff --git a/railties/guides/source/initialization.textile b/railties/guides/source/initialization.textile index 72e10191f9..f42a40e593 100644 --- a/railties/guides/source/initialization.textile +++ b/railties/guides/source/initialization.textile @@ -486,6 +486,31 @@ This file is responsible for the initial definition of the +Rails+ module and, r However, before all that takes place the +rails/ruby_version_check+ file is required first. +h4. +railties/lib/rails/ruby_version_check.rb+ + +This file simply checks if the Ruby version is less than 1.8.7 or is 1.9.1 and raises an error if that is the case. Rails 3 simply will not run on earlier versions of Ruby than 1.8.7 or 1.9.1. + +NOTE: You should always endeavour to run the latest version of Ruby with your Rails applications. The benefits are many, including security fixes and the like, and very often there is a speed increase associated with it. The caveat is that you could have code that potentially breaks on the latest version, which should be fixed to work on the latest version rather than kept around as an excuse not to upgrade. + +h4. +active_support/core_ext/kernel/reporting.rb+ + +This is the first of the many Active Support core extensions that come with Rails. This one in particular defines methods in the +Kernel+ module which is mixed in to the +Object+ class so the methods are available on +main+ and can therefore be called like this: + + + silence_warnings do + # some code + end + + +These methods can be used to silence STDERR responses and the +silence_stream+ allows you to also silence other streams. Additionally, this mixin allows you to suppress exceptions and capture streams. For more information see the "Silencing Warnings, Streams, and Exceptions":http://guides.rubyonrails.org/active_support_core_extensions.html#silencing-warnings-streams-and-exceptions section from the Active Support Core Extensions Guide. + +h4. +active_support/core_ext/logger.rb+ + +The next file that is required is another Active Support core extension, this time to the +Logger+ class. This begins by defining the +around_[level]+ helpers for the +Logger+ class as well as other methods such as a +datetime_format+ getter and setter for the +formatter+ object tied to a +Logger+ object. + +For more information see the "Extensions to Logger":http://guides.rubyonrails.org/active_support_core_extensions.html#extensions-to-logger section from the Active Support Core Extensions Guide. + + -- cgit v1.2.3 From 225f95237be713b50bce790eae8b6e511080b744 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Wed, 15 Dec 2010 16:59:49 +1000 Subject: init guide: Cover beginnings of rails/application.rb --- railties/guides/source/initialization.textile | 11 +++++++++++ 1 file changed, 11 insertions(+) (limited to 'railties/guides') diff --git a/railties/guides/source/initialization.textile b/railties/guides/source/initialization.textile index f42a40e593..9b879fe67e 100644 --- a/railties/guides/source/initialization.textile +++ b/railties/guides/source/initialization.textile @@ -510,6 +510,17 @@ The next file that is required is another Active Support core extension, this ti For more information see the "Extensions to Logger":http://guides.rubyonrails.org/active_support_core_extensions.html#extensions-to-logger section from the Active Support Core Extensions Guide. +h4. +railties/lib/rails/application.rb+ + +The next file required by +railties/lib/rails.rb+ is +application.rb+. This file defines the +Rails::Application+ constant which the application's class defined in +config/application.rb+ in a standard Rails application depends on. Before the +Rails::Application+ class is defined however, there's some other files that get required first. + +The first of these is +active_support/core_ext/hash/reverse_merge+ which can be "read about in the Active Support Core Extensions guide":http://guides.rubyonrails.org/active_support_core_extensions.html#merging under the "Merging" section. + +h4. +active_support/file_update_checker.rb+ + +The +ActiveSupport::FileUpdateChecker+ class defined within this file is responsible for checking if a file has been updated since it was last checked. This is used for monitoring the routes file for changes during development environment runs. + + -- cgit v1.2.3 From d421b16edcd505a0b725506777c5ba71d6db6331 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Fri, 17 Dec 2010 15:38:41 +1000 Subject: Config guide: middlewares can also be removed from the stack --- railties/guides/source/configuring.textile | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'railties/guides') diff --git a/railties/guides/source/configuring.textile b/railties/guides/source/configuring.textile index 33319fa40a..96b279ed8d 100644 --- a/railties/guides/source/configuring.textile +++ b/railties/guides/source/configuring.textile @@ -188,6 +188,12 @@ Middlewares can also be completely swapped out and replaced with others: config.middleware.swap ActionDispatch::BestStandardsSupport, Magical::Unicorns +They can also be removed from the stack completely: + + + config.middleware.delete ActionDispatch::BestStandardsSupport + + h4. Configuring i18n * +config.i18n.default_locale+ sets the default locale of an application used for i18n. Defaults to +:en+. -- cgit v1.2.3 From 6b65cd57ca20381e7d0f169d7b8cfd7db10e6efb Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Sun, 19 Dec 2010 17:57:20 +0530 Subject: deleting trailing whitespaces --- railties/guides/source/action_mailer_basics.textile | 2 +- .../guides/source/active_support_core_extensions.textile | 4 ++-- railties/guides/source/configuring.textile | 8 ++++---- railties/guides/source/form_helpers.textile | 2 +- railties/guides/source/generators.textile | 4 ++-- railties/guides/source/index.html.erb | 2 +- railties/guides/source/initialization.textile | 12 ++++++------ railties/guides/source/layout.html.erb | 2 +- .../guides/source/ruby_on_rails_guides_guidelines.textile | 2 +- 9 files changed, 19 insertions(+), 19 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/action_mailer_basics.textile b/railties/guides/source/action_mailer_basics.textile index b77a0be37b..6ee17ee5b8 100644 --- a/railties/guides/source/action_mailer_basics.textile +++ b/railties/guides/source/action_mailer_basics.textile @@ -248,7 +248,7 @@ It is possible to send email to one or more recipients in one email (for e.g. in class AdminMailer < ActionMailer::Base default :to => Admin.all.map(&:email).join(", "), :from => "notification@example.com" - + def new_registration(user) @user = user mail(:subject => "New User Signup: #{@user.email}") diff --git a/railties/guides/source/active_support_core_extensions.textile b/railties/guides/source/active_support_core_extensions.textile index 2e295aec3d..bddff1c987 100644 --- a/railties/guides/source/active_support_core_extensions.textile +++ b/railties/guides/source/active_support_core_extensions.textile @@ -3389,12 +3389,12 @@ Modifies the datetime format output by the formatter class associated with this class Logger::FormatWithTime < Logger::Formatter cattr_accessor(:datetime_format) { "%Y%m%d%H%m%S" } - + def self.call(severity, timestamp, progname, msg) "#{timestamp.strftime(datetime_format)} -- #{String === msg ? msg : msg.inspect}\n" end end - + logger = Logger.new("log/development.log") logger.formatter = Logger::FormatWithTime logger.info("<- is the current time") diff --git a/railties/guides/source/configuring.textile b/railties/guides/source/configuring.textile index 96b279ed8d..7b1ac5ece5 100644 --- a/railties/guides/source/configuring.textile +++ b/railties/guides/source/configuring.textile @@ -276,11 +276,11 @@ h4. Configuring Action Dispatch * +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. +* +ActionDispatch::Callbacks.before+ takes a block of code to run before the request. * +ActionDispatch::Callbacks.to_prepare+ takes a block to run after +ActionDispatch::Callbacks.before+, but before the request. Runs for every request in +development+ mode, but only once for +production+ or environments with +cache_classes+ set to +true+. -* +ActionDispatch::Callbacks.after+ takes a block of code to run after the request. +* +ActionDispatch::Callbacks.after+ takes a block of code to run after the request. h4. Configuring Action View @@ -396,7 +396,7 @@ Rails has 5 initialization events which can be hooked into (listed in order that * +before_initialize+: This is run directly before the initialization process of the application occurs with the +:bootstrap_hook+ initializer near the beginning of the Rails initialization process. -* +to_prepare+: Run after the initializers are ran for all Railties (including the application itself), but before eager loading and the middleware stack is built. +* +to_prepare+: Run after the initializers are ran for all Railties (including the application itself), but before eager loading and the middleware stack is built. * +before_eager_load+: This is run directly before eager loading occurs, which is the default behaviour for the _production_ environment and not for the +development+ enviroment. @@ -415,7 +415,7 @@ initializer "active_support.initialize_whiny_nils" do |app| end -The +initializer+ method takes three arguments with the first being the name for the initializer and the second being an options hash (not shown here) and the third being a block. The +:before+ key in the options hash can be specified to specify which initializer this new initializer must run before, and the +:after+ key will specify which initializer to run this initializer _after_. +The +initializer+ method takes three arguments with the first being the name for the initializer and the second being an options hash (not shown here) and the third being a block. The +:before+ key in the options hash can be specified to specify which initializer this new initializer must run before, and the +:after+ key will specify which initializer to run this initializer _after_. Initializers defined using the +initializer+ method will be ran in the order they are defined in, with the exception of ones that use the +:before+ or +:after+ methods. diff --git a/railties/guides/source/form_helpers.textile b/railties/guides/source/form_helpers.textile index e178a60307..7b4426b335 100644 --- a/railties/guides/source/form_helpers.textile +++ b/railties/guides/source/form_helpers.textile @@ -644,7 +644,7 @@ Fundamentally HTML forms don't know about any sort of structured data, all they TIP: You may find you can try out examples in this section faster by using the console to directly invoke Rails' parameter parser. For example, -ActionController::UrlEncodedPairParser.parse_query_parameters "name=fred&phone=0123456789" +ActionController::UrlEncodedPairParser.parse_query_parameters "name=fred&phone=0123456789" # => {"name"=>"fred", "phone"=>"0123456789"} diff --git a/railties/guides/source/generators.textile b/railties/guides/source/generators.textile index 6945f6f9bb..f21984e754 100644 --- a/railties/guides/source/generators.textile +++ b/railties/guides/source/generators.textile @@ -403,7 +403,7 @@ Whilst the final section of this guide doesn't cover how to generate the most aw h3. Generator methods -The following are methods available for both generators and templates for Rails. +The following are methods available for both generators and templates for Rails. NOTE: Methods provided by Thor are not covered this guide and can be found in "Thor's documentation":http://rdoc.info/github/wycats/thor/master/Thor/Actions.html @@ -546,7 +546,7 @@ This method also takes a block: %Q{ task :rock => :environment do puts "Rockin'" - end + end } end diff --git a/railties/guides/source/index.html.erb b/railties/guides/source/index.html.erb index 84fbc53a69..771cfbb794 100644 --- a/railties/guides/source/index.html.erb +++ b/railties/guides/source/index.html.erb @@ -161,7 +161,7 @@ Ruby on Rails Guides <%= guide('API Documentation Guidelines', 'api_documentation_guidelines.html') do %>

This guide documents the Ruby on Rails API documentation guidelines.

<% end %> - + <%= guide('Ruby on Rails Guides Guidelines', 'ruby_on_rails_guides_guidelines.html') do %>

This guide documents the Ruby on Rails guides guidelines.

<% end %> diff --git a/railties/guides/source/initialization.textile b/railties/guides/source/initialization.textile index 9b879fe67e..6dc13930f0 100644 --- a/railties/guides/source/initialization.textile +++ b/railties/guides/source/initialization.textile @@ -31,7 +31,7 @@ The actual +rails+ command is kept in _bin/rails_ at the and goes like this: 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. +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+ @@ -120,7 +120,7 @@ This climbs the directory tree until it reaches a path which contains a +script/ This is effectively the same as doing +ruby script/rails [arguments]+. Where +[arguments]+ at this point in time is simply "server". -h4. +script/rails+ +h4. +script/rails+ This file looks like this: @@ -236,7 +236,7 @@ Now back to +action_pack/lib/action_dispatch.rb+. The next +require+ in this fil After this line, there's a require to +active_model+ which simply defines autoloads for the +ActiveModel+ part of Rails and sets up the +ActiveModel+ module which is used later on. -The last of the requires is to +rack+, which like the +active_model+ and +active_support+ requires before it, sets up the +Rack+ module as well as the autoloads for constants within it. +The last of the requires is to +rack+, which like the +active_model+ and +active_support+ requires before it, sets up the +Rack+ module as well as the autoloads for constants within it. Finally in +action_dispatch.rb+ the +ActionDispatch+ module and *its* autoloads are declared. @@ -337,7 +337,7 @@ The class *is* defined in +Rack::Server+, but is overwritten in +Rails::Server+ ... -This method will set up keys for the +options+ which Rails will then be able to use to determine how its server should run. After +initialize+ has finished, then the +start+ method will launch the server. +This method will set up keys for the +options+ which Rails will then be able to use to determine how its server should run. After +initialize+ has finished, then the +start+ method will launch the server. h4. +Rails::Server#start+ @@ -448,7 +448,7 @@ This file begins with requiring +config/application.rb+. h4. +config/application.rb+ -This file requires +config/boot.rb+, but only if it hasn't been required before, which would be the case in +rails server+ but *wouldn't* be the case with Passenger. +This file requires +config/boot.rb+, but only if it hasn't been required before, which would be the case in +rails server+ but *wouldn't* be the case with Passenger. Then the fun begins! The next line is: @@ -512,7 +512,7 @@ For more information see the "Extensions to Logger":http://guides.rubyonrails.or h4. +railties/lib/rails/application.rb+ -The next file required by +railties/lib/rails.rb+ is +application.rb+. This file defines the +Rails::Application+ constant which the application's class defined in +config/application.rb+ in a standard Rails application depends on. Before the +Rails::Application+ class is defined however, there's some other files that get required first. +The next file required by +railties/lib/rails.rb+ is +application.rb+. This file defines the +Rails::Application+ constant which the application's class defined in +config/application.rb+ in a standard Rails application depends on. Before the +Rails::Application+ class is defined however, there's some other files that get required first. The first of these is +active_support/core_ext/hash/reverse_merge+ which can be "read about in the Active Support Core Extensions guide":http://guides.rubyonrails.org/active_support_core_extensions.html#merging under the "Merging" section. diff --git a/railties/guides/source/layout.html.erb b/railties/guides/source/layout.html.erb index bb62506f04..09b7d72514 100644 --- a/railties/guides/source/layout.html.erb +++ b/railties/guides/source/layout.html.erb @@ -106,7 +106,7 @@
<%= yield.html_safe %> - +

Feedback

You're encouraged to help in keeping the quality of this guide. diff --git a/railties/guides/source/ruby_on_rails_guides_guidelines.textile b/railties/guides/source/ruby_on_rails_guides_guidelines.textile index 0bc409cbda..8a6e87e155 100644 --- a/railties/guides/source/ruby_on_rails_guides_guidelines.textile +++ b/railties/guides/source/ruby_on_rails_guides_guidelines.textile @@ -48,7 +48,7 @@ To generate all the guides just cd into the +railties+ directory and execute rake generate_guides -You'll need the gems erubis, i18n, and RedCloth. +You'll need the gems erubis, i18n, and RedCloth. To process +my_guide.textile+ and nothing else use the +ONLY+ environment variable: -- cgit v1.2.3 From cc3d6a85715e23393ac2e89e4ed19bb10f5ee1fe Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Sun, 19 Dec 2010 21:28:33 +0530 Subject: minor corrections --- railties/guides/source/i18n.textile | 8 ++++---- railties/guides/source/layout.html.erb | 6 +++--- 2 files changed, 7 insertions(+), 7 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/i18n.textile b/railties/guides/source/i18n.textile index 8a39bdf3c1..46e3b80a76 100644 --- a/railties/guides/source/i18n.textile +++ b/railties/guides/source/i18n.textile @@ -852,7 +852,7 @@ h3. Conclusion At this point you should have a good overview about how I18n support in Ruby on Rails works and are ready to start translating your project. -If you find anything missing or wrong in this guide please file a ticket on "our issue tracker":http://i18n.lighthouseapp.com/projects/14948-rails-i18n/overview. If you want to discuss certain portions or have questions please sign up to our "mailinglist":http://groups.google.com/group/rails-i18n. +If you find anything missing or wrong in this guide, please file a ticket on our "issue tracker":http://i18n.lighthouseapp.com/projects/14948-rails-i18n/overview. If you want to discuss certain portions or have questions, please sign up to our "mailing list":http://groups.google.com/group/rails-i18n. h3. Contributing to Rails I18n @@ -867,10 +867,10 @@ If you find your own locale (language) missing from our "example translations da h3. Resources * "rails-i18n.org":http://rails-i18n.org - Homepage of the rails-i18n project. You can find lots of useful resources on the "wiki":http://rails-i18n.org/wiki. -* "rails-i18n Google group":http://groups.google.com/group/rails-i18n - The project's mailing list. +* "Google group: rails-i18n":http://groups.google.com/group/rails-i18n - The project's mailing list. * "Github: rails-i18n":http://github.com/svenfuchs/rails-i18n/tree/master - Code repository for the rails-i18n project. Most importantly you can find lots of "example translations":http://github.com/svenfuchs/rails-i18n/tree/master/rails/locale for Rails that should work for your application in most cases. -* "Lighthouse: rails-i18n":http://i18n.lighthouseapp.com/projects/14948-rails-i18n/overview - Issue tracker for the rails-i18n project. * "Github: i18n":http://github.com/svenfuchs/i18n/tree/master - Code repository for the i18n gem. +* "Lighthouse: rails-i18n":http://i18n.lighthouseapp.com/projects/14948-rails-i18n/overview - Issue tracker for the rails-i18n project. * "Lighthouse: i18n":http://i18n.lighthouseapp.com/projects/14947-ruby-i18n/overview - Issue tracker for the i18n gem. @@ -879,7 +879,7 @@ h3. Authors * "Sven Fuchs":http://www.workingwithrails.com/person/9963-sven-fuchs (initial author) * "Karel Minařík":http://www.workingwithrails.com/person/7476-karel-mina-k -If you found this guide useful please consider recommending its authors on "workingwithrails":http://www.workingwithrails.com. +If you found this guide useful, please consider recommending its authors on "workingwithrails":http://www.workingwithrails.com. h3. Footnotes diff --git a/railties/guides/source/layout.html.erb b/railties/guides/source/layout.html.erb index 09b7d72514..dbb48124d0 100644 --- a/railties/guides/source/layout.html.erb +++ b/railties/guides/source/layout.html.erb @@ -113,7 +113,7 @@

If you see any typos or factual errors you are confident to - patch please clone <%= link_to 'docrails', 'https://github.com/lifo/docrails' %> + patch, please clone <%= link_to 'docrails', 'https://github.com/lifo/docrails' %> and push the change yourself. That branch of Rails has public write access. Commits are still reviewed, but that happens after you've submitted your contribution. <%= link_to 'docrails', 'https://github.com/lifo/docrails' %> is @@ -123,10 +123,10 @@ You may also find incomplete content, or stuff that is not up to date. Please do add any missing documentation for master. Check the <%= link_to 'Ruby on Rails Guides Guidelines', 'ruby_on_rails_guides_guidelines.html' %> - guide for style and conventions. + for style and conventions.

- Issues may also be reported <%= link_to 'in Github', 'https://github.com/lifo/docrails/issues' %>. + Issues may also be reported in <%= link_to 'Github', 'https://github.com/lifo/docrails/issues' %>.

And last but not least, any kind of discussion regarding Ruby on Rails documentation is very welcome in the <%= link_to 'rubyonrails-docs mailing list', 'http://groups.google.com/group/rubyonrails-docs' %>. -- cgit v1.2.3 From eaad8610eea6efdd19124e965e43599811e665eb Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Sun, 19 Dec 2010 23:37:22 +0530 Subject: minor example fix for Rails 3 --- railties/guides/source/api_documentation_guidelines.textile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/api_documentation_guidelines.textile b/railties/guides/source/api_documentation_guidelines.textile index e3ccd6396c..b977d9373e 100644 --- a/railties/guides/source/api_documentation_guidelines.textile +++ b/railties/guides/source/api_documentation_guidelines.textile @@ -46,10 +46,10 @@ Short docs do not need an explicit "Examples" label to introduce snippets, they # Converts a collection of elements into a formatted string by calling # to_s on all elements and joining them. # -# Blog.find(:all).to_formatted_s # => "First PostSecond PostThird Post" +# Blog.all.to_formatted_s # => "First PostSecond PostThird Post" -On the other hand big chunks of structured documentation may have a separate "Examples" section: +On the other hand, big chunks of structured documentation may have a separate "Examples" section: # ==== Examples -- cgit v1.2.3 From 4197fad8413e4b599c1c7f2382f4dcaeccf9473d Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Mon, 20 Dec 2010 00:07:43 +0530 Subject: fix typos --- railties/guides/source/ruby_on_rails_guides_guidelines.textile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/ruby_on_rails_guides_guidelines.textile b/railties/guides/source/ruby_on_rails_guides_guidelines.textile index 8a6e87e155..a2e830b574 100644 --- a/railties/guides/source/ruby_on_rails_guides_guidelines.textile +++ b/railties/guides/source/ruby_on_rails_guides_guidelines.textile @@ -16,7 +16,7 @@ h3. Titles The title of every guide uses +h2+, guide sections use +h3+, subsections +h4+, etc. -Capitalize all words except for internal articles, prepositions, conjuctions, and forms of the verb to be: +Capitalize all words except for internal articles, prepositions, conjunctions, and forms of the verb to be: h5. Middleware Stack is an Array @@ -58,7 +58,7 @@ rake generate_guides ONLY=my_guide Although by default guides that have not been modified are not processed, so +ONLY+ is rarely needed in practice. -To force process of al the guides pass +ALL=1+. +To force process of all the guides, pass +ALL=1+. It is also recommended that you work with +WARNINGS=1+, this detects duplicate IDs and warns about broken internal links. -- cgit v1.2.3 From 6909fb6cff49e11574909b55864af8673d044eb7 Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Mon, 20 Dec 2010 02:34:08 +0530 Subject: indentation fixes --- railties/guides/source/generators.textile | 63 +++++++++++++++---------------- 1 file changed, 31 insertions(+), 32 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/generators.textile b/railties/guides/source/generators.textile index f21984e754..4fec1760c4 100644 --- a/railties/guides/source/generators.textile +++ b/railties/guides/source/generators.textile @@ -371,16 +371,16 @@ h3. Application templates Now that you've seen how generators can be used _inside_ an application, did you know they can also be used to _generate_ applications too? This kind of generator is referred as a "template". - gem("rspec-rails", :group => "test") - gem("cucumber-rails", :group => "test") - - if yes?("Would you like to install Devise?") - gem("devise") - generate("devise:install") - model_name = ask("What would you like the user model to be called? [user]") - model_name = "user" if model_name.blank? - generate("devise", model_name) - end +gem("rspec-rails", :group => "test") +gem("cucumber-rails", :group => "test") + +if yes?("Would you like to install Devise?") + gem("devise") + generate("devise:install") + model_name = ask("What would you like the user model to be called? [user]") + model_name = "user" if model_name.blank? + generate("devise", model_name) +end In the above template we specify that the application relies on the +rspec-rails+ and +cucumber-rails+ gem so these two will be added to the +test+ group in the +Gemfile+. Then we pose a question to the user about whether or not they would like to install Devise. If the user replies "y" or "yes" to this question, then the template will add Devise to the +Gemfile+ outside of any group and then runs the +devise:install+ generator. This template then takes the users input and runs the +devise+ generator, with the user's answer from the last question being passed to this generator. @@ -428,8 +428,8 @@ h4. +gem+ Specifies a gem dependency of the application. - gem("rspec", :group => "test", :version => "2.1.0") - gem("devise", "1.1.5") +gem("rspec", :group => "test", :version => "2.1.0") +gem("devise", "1.1.5") Available options are: @@ -470,10 +470,9 @@ Adds a line to +config/application.rb+ directly after the application class defi This method can also take a block: - application do - "config.asset_host = 'http://example.com'" - end - end +application do + "config.asset_host = 'http://example.com'" +end Available options are: @@ -481,9 +480,9 @@ Available options are: * +:env+ - Specify an environment for this configuration option. If you wish to use this option with the block syntax the recommended syntax is as follows: - application(nil, :env => "development") do - "config.asset_host = 'http://localhost:3000'" - end +application(nil, :env => "development") do + "config.asset_host = 'http://localhost:3000'" +end h4. +git+ @@ -526,9 +525,9 @@ Places a file into +lib+ which contains the specified code. This method also takes a block: - lib("super_special.rb") do - puts "Super special!" - end +lib("super_special.rb") do + puts "Super special!" +end h4. +rakefile+ @@ -542,13 +541,13 @@ Creates a Rake file in the +lib/tasks+ directory of the application. This method also takes a block: - rakefile("test.rake") do - %Q{ - task :rock => :environment do - puts "Rockin'" - end - } - end +rakefile("test.rake") do + %Q{ + task :rock => :environment do + puts "Rockin'" + end + } +end h4. +initializer+ @@ -562,9 +561,9 @@ Creates an initializer in the +config/initializers+ directory of the application This method also takes a block: - initializer("begin.rb") do - puts "Almost done!" - end +initializer("begin.rb") do + puts "Almost done!" +end h4. +generate+ -- cgit v1.2.3 From 8373c735c7dc8adeffffbf85176676fecb6221fc Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Mon, 20 Dec 2010 11:32:37 +1000 Subject: config guide: mention ActiveSupport::Deprecation configuration options. --- railties/guides/source/configuring.textile | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'railties/guides') diff --git a/railties/guides/source/configuring.textile b/railties/guides/source/configuring.textile index 497c8318f0..fa86e0f039 100644 --- a/railties/guides/source/configuring.textile +++ b/railties/guides/source/configuring.textile @@ -376,8 +376,15 @@ There are a few configuration options available in Active Support: * +ActiveSupport::Cache::Store.logger+ specifies the logger to use within cache store operations. +* +ActiveSupport::Deprecation.behavior+ alternative setter to +config.active_support.deprecation+ which configures the behavior of deprecation warnings for Rails. + +* +ActiveSupport::Deprecation.silence+ takes a block in which all deprecation warnings are silenced. + +* +ActiveSupport::Deprecation.silenced+ sets whether or not to display deprecation warnings. + * +ActiveSupport::Logger.silencer+ is set to +false+ to disable the ability to silence logging in a block. The default is +true+. + h3. Rails Environment Settings Some parts of Rails can also be configured externally by supplying environment variables. The following environment variables are recognized by various parts of Rails: -- cgit v1.2.3 From 1cacb08b213e9d0f92cf1fad89ff10141211bce8 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Mon, 20 Dec 2010 11:50:47 +1000 Subject: Improve documentation on ActiveSupport::Deprecation. --- railties/guides/source/configuring.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/configuring.textile b/railties/guides/source/configuring.textile index fa86e0f039..73147efd3a 100644 --- a/railties/guides/source/configuring.textile +++ b/railties/guides/source/configuring.textile @@ -471,7 +471,7 @@ You might have expected an instance of Array. The error occurred while evaluating nil.each -*+active_support.deprecation_behavior+* Sets up deprecation reporting for environments, defaulting to +log+ for development, +notify+ for production and +stderr+ for test. If a value isn't set for +config.active_support.deprecation+ then this initializer will prompt the user to configure this line in the current environment's +config/environments+ file. +*+active_support.deprecation_behavior+* Sets up deprecation reporting for environments, defaulting to +:log+ for development, +:notify+ for production and +:stderr+ for test. If a value isn't set for +config.active_support.deprecation+ then this initializer will prompt the user to configure this line in the current environment's +config/environments+ file. Can be set to an array of values. *+active_support.initialize_time_zone+* Sets the default time zone for the application based off the +config.time_zone+ setting, which defaults to "UTC". -- cgit v1.2.3 From 4da4087fd81f60b615d67cb3b177a3cc3477cc4e Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Tue, 21 Dec 2010 10:39:41 +1000 Subject: Further re-working of the initialization guide --- railties/guides/source/initialization.textile | 81 +++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) (limited to 'railties/guides') diff --git a/railties/guides/source/initialization.textile b/railties/guides/source/initialization.textile index 6dc13930f0..7c6b3b7912 100644 --- a/railties/guides/source/initialization.textile +++ b/railties/guides/source/initialization.textile @@ -520,7 +520,88 @@ h4. +active_support/file_update_checker.rb+ The +ActiveSupport::FileUpdateChecker+ class defined within this file is responsible for checking if a file has been updated since it was last checked. This is used for monitoring the routes file for changes during development environment runs. +h4. +railties/lib/rails/plugin.rb+ +This file defines +Rails::Plugin+ which inherits from +Rails::Engine+. Unlike +Rails::Engine+ and +Rails::Railtie+ however, this class is not designed to be inherited from. Instead, this is used simply for loading plugins from within an application and an engine. + +This file begins by requiring +rails/engine.rb+ + +h4. +railties/lib/rails/engine.rb+ + +The +rails/engine.rb+ file defines the +Rails::Engine+ class which inherits from +Rails::Railtie+. The +Rails::Engine+ class defines much of the functionality found within a standard application class such as the +routes+ and +config+ methods. + +The "API documentation":http://api.rubyonrails.org/classes/Rails/Engine.html for +Rails::Engine+ explains the function of this class pretty well. + +This file's first line requires +rails/railtie.rb+. + +h4. +railties/lib/rails/railtie.rb+ + +The +rails/railtie.rb+ file is responsible for defining +Rails::Railtie+, the underlying class for all ties to Rails now. Gems that want to have their own initializers or rake tasks and hook into Rails should have a +GemName::Railtie+ class that inherits from +Rails::Railtie+. + +The "API documentation":http://api.rubyonrails.org/classes/Rails/Railtie.html for +Rails::Railtie+, much like +Rails::Engine+, explains this class exceptionally well. + +The first require in this file is +rails/initializable.rb+. + +h4. +railties/lib/rails/initializable.rb+ + +Now we reach the end of this particular rabbit hole as +rails/initializable.rb+ doesn't require any more Rails files, only +tsort+ from the Ruby standard library. + +This file defines the +Rails::Initializable+ module which contains the +Initializer+ class, the basis for all initializers in Rails. This module also contains a +ClassMethods+ class which will be included into the +Rails::Railtie+ class when these requires have finished. + +Now that +rails/initializable.rb+ has finished being required from +rails/railtie.rb+, the next require is for +rails/configuration+. + +h4. +railties/lib/rails/configuration.rb+ + +This file defines the +Rails::Configuration+ module, containing the +MiddlewareStackProxy+ class as well as the +Generators+ class. The +MiddlewareStackProxy+ class is used for managing the middleware stack for an application, which we'll see later on. The +Generators+ class provides the functionality used for configuring what generators an application uses through the "+config.generators+ option":http://guides.rubyonrails.org/configuring.html#configuring-generators. + +The first file required in this file is +activesupport/deprecation+. + +h4. +activesupport/lib/active_support/deprecation.rb+ + +This file, and the files it requires, define the basic deprecation warning features found in Rails. This file is responsible for setting defaults in the +ActiveSupport::Deprecation+ module for the +deprecation_horizon+, +silenced+ and +debug+ values. The files that are required before this happens are: + +* +active_support/deprecation/behaviors+ +* +active_support/deprecation/reporting+ +* +active_support/deprecation/method_wrappers+ +* +active_support/deprecation/proxy_wrappers+ + +h4. +activesupport/lib/active_support/deprecation/behaviors.rb+ + +This file defines the behavior of the +ActiveSupport::Deprecation+ module, setting up the +DEFAULT_BEHAVIORS+ hash constant which contains the three defaults to outputting deprecation warnings: +:stderr+, +:log+ and +:notify+. This file begins by requiring +activesupport/notifications+ and +activesupport/core_ext/array/wrap+. + +h4 +activesupport/lib/active_support/notifications.rb+ + +TODO: document +ActiveSupport::Notifications+. + +h4. +activesupport/core_ext/array/wrap+ + +As this file comprises of a core extension, it is covered exclusively in "the Active Support Core Extensions guide":http://guides.rubyonrails.org/active_support_core_extensions.html#wrapping + +h4. +activesupport/lib/active_support/deprecation/reporting.rb+ + +This file is responsible for defining the +warn+ and +silence+ methods for +ActiveSupport::Deprecation+ as well as additional private methods for this module. + +h4. +activesupport/lib/active_support/deprecation/method_wrappers.rb+ + +This file defines a +deprecate_methods+ which is primarily used by the +module/deprecation+ core extension required by the first line of this file. Other core extensions required by this file are the +module/aliasing+ and +array/extract_options+ files. + +h4. +activesupport/lib/active_support/deprecation/proxy_wrappers.rb+ + ++proxy_wrappers.rb+ defines deprecation wrappers for methods, instance variables and constants. Previously, this was used for the +RAILS_ENV+ and +RAILS_ROOT+ constants for 3.0 but since then these constants have been removed. The deprecation message that would be raised from these would be something like: + + + BadConstant is deprecated! Use GoodConstant instead. + + +h4. +active_support/ordered_options+ + +This file is the next file required from +rails/configuration.rb+ is the file that defines +ActiveSupport::OrderedOptions+ which is used for configuration options such as +config.active_support+ and the like. + +The next file required is +active_support/core_ext/hash/deep_dup+ which is covered in "Active Support Core Extensions guide":http://guides.rubyonrails.org/active_support_core_extensions.html#deep_dup + +The file after that is +rails/paths+ + +h4. +railties/lib/rails/paths.rb+ -- cgit v1.2.3 From 68ebd332d0588f6d1299a06f726f9f508e418c76 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Tue, 21 Dec 2010 13:45:38 +1000 Subject: Config guide: Complete sentence about the Rack::SendFile middleware. --- railties/guides/source/configuring.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/configuring.textile b/railties/guides/source/configuring.textile index 73147efd3a..6e72ae6ead 100644 --- a/railties/guides/source/configuring.textile +++ b/railties/guides/source/configuring.textile @@ -154,7 +154,7 @@ Every Rails application comes with a standard set of middleware which it uses in * +Rails::Rack::Logger+ Will notify the logs that the request has began. After request is complete, flushes all the logs. * +ActionDispatch::ShowExceptions+ rescues any exception returned by the application and renders nice exception pages if the request is local or if +config.consider_all_requests_local+ is set to _true_. If +config.action_dispatch.show_exceptions+ is set to _false_, exceptions will be raised regardless. * +ActionDispatch::RemoteIp+ checks for IP spoofing attacks. Configurable with the +config.action_dispatch.ip_spoofing_check+ and +config.action_dispatch.trusted_proxies+ settings. -* +Rack::Sendfile+ The Sendfile middleware intercepts responses whose body is being served from a file and replaces it with a server specific X-Sendfile header. Configurable with +config.action_dispatch_ +* +Rack::Sendfile+ The Sendfile middleware intercepts responses whose body is being served from a file and replaces it with a server specific X-Sendfile header. Configurable with +config.action_dispatch.x_sendfile_header+ * +ActionDispatch::Callbacks+ Runs the prepare callbacks before serving the request. * +ActiveRecord::ConnectionAdapters::ConnectionManagement+ cleans active connections after each request, unless the +rack.test+ key in the request environment is set to _true_. * +ActiveRecord::QueryCache+ caches all +SELECT+ queries generated in a request. If an +INSERT+ or +UPDATE+ takes place then the cache is cleaned. -- cgit v1.2.3 From 55b01e65e21203d87d60bc0fad54702384ffaa2b Mon Sep 17 00:00:00 2001 From: Lee Reilly Date: Tue, 21 Dec 2010 19:49:42 -0800 Subject: No example given on how to render JSON data despite the heading 'Rendering XML and JSON data'; added relevant code. --- railties/guides/source/action_controller_overview.textile | 1 + 1 file changed, 1 insertion(+) (limited to 'railties/guides') diff --git a/railties/guides/source/action_controller_overview.textile b/railties/guides/source/action_controller_overview.textile index 0d6919a205..8f9afb9c6d 100644 --- a/railties/guides/source/action_controller_overview.textile +++ b/railties/guides/source/action_controller_overview.textile @@ -368,6 +368,7 @@ class UsersController < ApplicationController respond_to do |format| format.html # index.html.erb format.xml { render :xml => @users} + format.json { render :json => @users} end end end -- cgit v1.2.3 From 90ef676c7f5d17c6ca707c633dc41285473e4648 Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Wed, 22 Dec 2010 23:47:09 +0530 Subject: remove duplication of links --- railties/guides/source/rails_on_rack.textile | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/rails_on_rack.textile b/railties/guides/source/rails_on_rack.textile index f17e9b4798..8338777480 100644 --- a/railties/guides/source/rails_on_rack.textile +++ b/railties/guides/source/rails_on_rack.textile @@ -17,12 +17,7 @@ bq. Rack provides a minimal, modular and adaptable interface for developing web - "Rack API Documentation":http://rack.rubyforge.org/doc/ -Explaining Rack is not really in the scope of this guide. In case you are not familiar with Rack's basics, you should check out the following links: - -* "Official Rack Website":http://rack.github.com -* "Introducing Rack":http://chneukirchen.org/blog/archive/2007/02/introducing-rack.html -* "Ruby on Rack #1 - Hello Rack!":http://m.onkey.org/2008/11/17/ruby-on-rack-1 -* "Ruby on Rack #2 - The Builder":http://m.onkey.org/2008/11/18/ruby-on-rack-2-rack-builder +Explaining Rack is not really in the scope of this guide. In case you are not familiar with Rack's basics, you should check out the "Resources":#resources section below. h3. Rails on Rack @@ -165,7 +160,7 @@ Much of Action Controller's functionality is implemented as Middlewares. The fol |_.Middleware|_.Purpose| |+Rack::Lock+|Sets +env["rack.multithread"]+ flag to +true+ and wraps the application within a Mutex.| |+ActionController::Failsafe+|Returns HTTP Status +500+ to the client if an exception gets raised while dispatching.| -|+ActiveRecord::QueryCache+|Enable the Active Record query cache.| +|+ActiveRecord::QueryCache+|Enables the Active Record query cache.| |+ActionController::Session::CookieStore+|Uses the cookie based session store.| |+ActionController::Session::MemCacheStore+|Uses the memcached based session store.| |+ActiveRecord::SessionStore+|Uses the database based session store.| -- cgit v1.2.3 From 15ce225ab035bf92e2cb9994db80e60e1cd609bd Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Wed, 22 Dec 2010 23:47:23 +0530 Subject: fix typo --- railties/guides/source/nested_model_forms.textile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/nested_model_forms.textile b/railties/guides/source/nested_model_forms.textile index 1d44da4df1..55694c0eb4 100644 --- a/railties/guides/source/nested_model_forms.textile +++ b/railties/guides/source/nested_model_forms.textile @@ -1,6 +1,6 @@ h2. Rails nested model forms -Creating a form for a model _and_ its associations can become quite tedious. Therefor Rails provides helpers to assist in dealing with the complexities of generating these forms _and_ the required CRUD operations to create, update, and destroy associations. +Creating a form for a model _and_ its associations can become quite tedious. Therefore Rails provides helpers to assist in dealing with the complexities of generating these forms _and_ the required CRUD operations to create, update, and destroy associations. In this guide you will: @@ -219,4 +219,4 @@ You can basically see the +projects_attributes+ hash as an array of attribute ha NOTE: The reason that +fields_for+ constructed a form which would result in a hash instead of an array is that it won't work for any forms nested deeper than one level deep. -TIP: You _can_ however pass an array to the writer method generated by +accepts_nested_attributes_for+ if you're using plain Ruby or some other API access. See (TODO) for more info and example. \ No newline at end of file +TIP: You _can_ however pass an array to the writer method generated by +accepts_nested_attributes_for+ if you're using plain Ruby or some other API access. See (TODO) for more info and example. -- cgit v1.2.3 From 0b5222fa45ff8da340ca4f086d735e97b7fb7326 Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Thu, 23 Dec 2010 00:23:22 +0100 Subject: API guidelines: RDoc markup documentation has been moved in RDoc 3 --- railties/guides/source/api_documentation_guidelines.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/api_documentation_guidelines.textile b/railties/guides/source/api_documentation_guidelines.textile index b977d9373e..2bbb1b5919 100644 --- a/railties/guides/source/api_documentation_guidelines.textile +++ b/railties/guides/source/api_documentation_guidelines.textile @@ -6,7 +6,7 @@ endprologue. h3. RDoc -The Rails API documentation is generated with RDoc 2.5. Please consult the documentation for help with the "markup":http://rdoc.rubyforge.org/RDoc.html, and take into account also these "additional directives":http://rdoc.rubyforge.org/RDoc/Parser/Ruby.html. +The Rails API documentation is generated with RDoc 2.5. Please consult the documentation for help with the "markup":http://rdoc.rubyforge.org/RDoc/Markup.html, and take into account also these "additional directives":http://rdoc.rubyforge.org/RDoc/Parser/Ruby.html. h3. Wording -- cgit v1.2.3 From f183668ff92f220183f58d6779126a11feaf4d04 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Thu, 23 Dec 2010 14:35:17 +1000 Subject: Querying guide: Add mention of the scope method --- .../guides/source/active_record_querying.textile | 42 ++++++++++++++++++++++ 1 file changed, 42 insertions(+) (limited to 'railties/guides') diff --git a/railties/guides/source/active_record_querying.textile b/railties/guides/source/active_record_querying.textile index b9ad7ccbd2..fe6d284239 100644 --- a/railties/guides/source/active_record_querying.textile +++ b/railties/guides/source/active_record_querying.textile @@ -721,6 +721,48 @@ h4. Specifying Conditions on Eager Loaded Associations Even though Active Record lets you specify conditions on the eager loaded associations just like +joins+, the recommended way is to use "joins":#joining-tables instead. +h3. Scopes + +Scoping allows you to specify commonly-used ARel queries which can be referenced as method calls on the association objects or models. With these scopes, you can use every method previously covered such as +where+, +joins+ and +includes+. + +To define a simple scope, we use the +scope+ method inside the class, passing the ARel query that we'd like run when this scope is called: + + + class Post < ActiveRecord::Base + scope :published, where(:published => true) + end + + +Just like before, these methods are also chainable: + + + class Post < ActiveRecord::Base + scope :published, where(:published => true).joins(:category) + end + + +Scopes are also chainable within scopes: + + + class Post < ActiveRecord::Base + scope :published, where(:published => true) + scope :published_and_commented, published.and(self.arel_table[:comments_count].gt(0)) + end + + +To call this +published+ scope we can call it on either the class: + + + Post.published => [published posts] + + +Or on an association consisting of +Post+ objects: + + + category = Category.first + category.posts.published => [published posts, belonging to this category] + + h3. Dynamic Finders For every field (also known as an attribute) you define in your table, Active Record provides a finder method. If you have a field called +first_name+ on your +Client+ model for example, you get +find_by_first_name+ and +find_all_by_first_name+ for free from Active Record. If you have a +locked+ field on the +Client+ model, you also get +find_by_locked+ and +find_all_by_locked+ methods. -- cgit v1.2.3 From 5b19579ab3a2ea95f8354cc6aa407bf2e5264d26 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Thu, 23 Dec 2010 14:35:59 +1000 Subject: Init guide: further revision, covering rails/plugin.rb and friends --- railties/guides/source/initialization.textile | 120 +++++++++++++++++++++++++- 1 file changed, 116 insertions(+), 4 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/initialization.textile b/railties/guides/source/initialization.textile index 7c6b3b7912..1504b973a5 100644 --- a/railties/guides/source/initialization.textile +++ b/railties/guides/source/initialization.textile @@ -222,9 +222,17 @@ h4. +actionpack/lib/action_dispatch.rb+ Action Dispatch is the routing component of the Rails framework. It depends on Active Support, +actionpack/lib/action_pack.rb+ and +Rack+ being available. The first thing required here is +active_support+. -h4. +active_support/lib/active_support.rb+ +h4. +activesupport/lib/active_support.rb+ -This file begins with requiring +active_support/lib/active_support/dependencies/autoload.rb+ which redefines Ruby's +autoload+ method to have a little more extra behaviour especially in regards to eager autoloading. Eager autoloading is the loading of all required classes and will happen when the +config.cache_classes+ setting is +true+. +This file begins with requiring +active_support/lib/active_support/dependencies/autoload.rb+ which redefines Ruby's +autoload+ method to have a little more extra behaviour especially in regards to eager autoloading. Eager autoloading is the loading of all required classes and will happen when the +config.cache_classes+ setting is +true+. + +In this file there are a lot of lines such as this inside the +ActiveSupport+ module: + + + autoload :Inflector + + +Due to the overriding of the +autoload+ method, Ruby will know to look for this file at +activesupport/lib/active_support/inflector.rb+ when the +Inflector+ class is first referenced. The +active_support/lib/active_support/version.rb+ that is also required here simply defines an +ActiveSupport::VERSION+ constant which defines a couple of constants inside this module, the main constant of this is +ActiveSupport::VERSION::STRING+ which returns the current version of ActiveSupport. @@ -450,7 +458,11 @@ h4. +config/application.rb+ This file requires +config/boot.rb+, but only if it hasn't been required before, which would be the case in +rails server+ but *wouldn't* be the case with Passenger. -Then the fun begins! The next line is: +Then the fun begins! + +h3. Loading Rails + +The next line in +config/application.rb+ is: require 'rails/all' @@ -599,10 +611,110 @@ This file is the next file required from +rails/configuration.rb+ is the file th The next file required is +active_support/core_ext/hash/deep_dup+ which is covered in "Active Support Core Extensions guide":http://guides.rubyonrails.org/active_support_core_extensions.html#deep_dup -The file after that is +rails/paths+ +The file that is required next from is +rails/paths+ h4. +railties/lib/rails/paths.rb+ +This file defines the +Rails::Paths+ module which allows paths to be configured for a Rails application or engine. Later on in this guide when we cover Rails configuration during the initialization process we'll see this used to set up some default paths for Rails and some of them will be configured to be eager loaded. + +h4. +railties/lib/rails/rack.rb+ + +The final file to be loaded by +railties/lib/rails/configuration.rb+ is +rails/rack+ which defines some simple autoloads: + + + module Rails + module Rack + autoload :Debugger, "rails/rack/debugger" + autoload :Logger, "rails/rack/logger" + autoload :LogTailer, "rails/rack/log_tailer" + autoload :Static, "rails/rack/static" + end + end + + +Once this file is finished loading, then the +Rails::Configuration+ class is initialized. This completes the loading of +railties/lib/rails/configuration.rb+ and now we jump back to the loading of +railties/lib/rails/railtie.rb+, where the next file loaded is +active_support/inflector+. + +h4. +activesupport/lib/active_support/inflector.rb+ + ++active_support/inflector.rb+ requires a series of file which are responsible for setting up the basics for knowing how to pluralize and singularize words. These files are: + + + require 'active_support/inflector/inflections' + require 'active_support/inflector/transliterate' + require 'active_support/inflector/methods' + + require 'active_support/inflections' + require 'active_support/core_ext/string/inflections' + + +h4. +activesupport/lib/active_support/inflector/inflections.rb+ + +This file references the +ActiveSupport::Inflector+ constant which isn't loaded by this point. But there were autoloads set up in +activesupport/lib/active_support.rb+ which will load the file which loads this constant and so then it will be defined. Then this file defines pluralization and singularization rules for words in Rails. This is how Rails knows how to pluralize "tomato" to "tomatoes". + +h4. +activesupport/lib/active_support/inflector/transliterate.rb+ + +In this file is where the "+transliterate+":http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-transliterate and +parameterize+:http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-parameterize methods are defined. The documentation for both of these methods is very much worth reading. + +h4. +activesupport/lib/active_support/inflector/methods.rb+ + +The +methods.rb+ file is responsible for defining methods such as +camelize+, +underscore+ and +dasherize+ as well as a slew of others. The "+ActiveSupport::Inflector+ documentation":http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html covers them all pretty decently. + +h4. Back to +railties/lib/rails/railtie.rb+ + +Once the inflector files have been loaded, the +Rails::Railtie+ class is defined. This class includes a module called +Initializable+, which is actually +Rails::Initializable+ and is automatically loaded at this point. + +h4. +railties/lib/rails/initializable.rb+ + +When the module from this file (+Rails::Initializable+) is included, it extends the class it's included into with the +ClassMethods+ module inside of it. This module defines the +initializer+ method which is used to define initializers throughout all of the railties. This file completes the loading of +railties/lib/rails/railtie.rb+. Now we go back to +rails/engine.rb+. + +h4. +railties/lib/rails/engine.rb+ + +The next file required in +rails/engine.rb+ is +active_support/core_ext/module/delegation+ which is documented in the "Active Support Core Extensions Guide":http://guides.rubyonrails.org/active_support_core_extensions.html#method-delegation. + +The next two files after this are Ruby standard library files: +pathname+ and +rbconfig+. The file after these is +rails/engine/railties+. + +h4. +railties/lib/rails/engine/railties.rb+ + +This file defines the +Rails::Engine::Railties+ class which provides the +engines+ and +railties+ methods which are used later on for defining rake tasks and other functionality for engines and railties. + +h4. Back to +railties/lib/rails/engine.rb+ + +Once +rails/engine/railties.rb+ has finished loading the +Rails::Engine+ class gets its basic functionality defined, such as the +inherited+ method which will be called when this class is inherited from. + +Once this file has finished loading we jump back to +railties/lib/rails/plugin.rb+ + +h4. Back to +railties/lib/rails/plugin.rb+ + +The next file required in this is a core extension from Active Support called +array/conversions+ which is covered in "this section":http://guides.rubyonrails.org/active_support_core_extensions.html#array-conversions of the Active Support Core Extensions Guide. + +Once that file has finished loading, the +Rails::Plugin+ class is defined. + +h4. Back to +railties/lib/rails/application.rb+ + +Jumping back to +rails/application.rb+ now. This file defines the +Rails::Application+ class where the application's class inherits from. This class (and its superclasses) define the basic behaviour on the application's constant such as the +config+ method used for configuring the application. + +Once this file's done then we go back to the +railties/lib/rails.rb+ file, which next requires +rails/version+. + +h4. +railties/lib/rails/version.rb+ + +Much like +active_support/version+, this file defines the +VERSION+ constant which has a +STRING+ constant on it which returns the current version of Rails. + +h4. +activesupport/lib/active_support/railtie.rb+ + +This file requires +active_support+ and +rails+ which have already been required so these two lines are effectively ignored. The third require in this file is to +active_support/railtie+. + +h4. +activesupport/lib/active_support/i18n_railtie.rb+ + +This file is the first file that sets up configuration with these lines inside the class: + + + class Railtie < Rails::Railtie + config.i18n = ActiveSupport::OrderedOptions.new + config.i18n.railties_load_path = [] + config.i18n.load_path = [] + config.i18n.fallbacks = ActiveSupport::OrderedOptions.new + + -- cgit v1.2.3 From 28b1642561cddc1f8650f7a8c740ece259db913b Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Thu, 23 Dec 2010 14:50:40 +1000 Subject: Query guide: lambdas must be used when working with scopes --- railties/guides/source/active_record_querying.textile | 12 ++++++++++++ 1 file changed, 12 insertions(+) (limited to 'railties/guides') diff --git a/railties/guides/source/active_record_querying.textile b/railties/guides/source/active_record_querying.textile index fe6d284239..25f3723b93 100644 --- a/railties/guides/source/active_record_querying.textile +++ b/railties/guides/source/active_record_querying.textile @@ -763,6 +763,18 @@ Or on an association consisting of +Post+ objects: category.posts.published => [published posts, belonging to this category] +h4. Working with times + +If you're working with dates or times within scopes, due to how they are evaluated, you will need to use a lambda so that the scope is evaluated every time. + + + class Post < ActiveRecord::Base + scope :last_week, lambda { where("created_at < ?", Time.zone.now ) } + end + + +Without the +lambda+, this +Time.zone.now+ will only be called once. + h3. Dynamic Finders For every field (also known as an attribute) you define in your table, Active Record provides a finder method. If you have a field called +first_name+ on your +Client+ model for example, you get +find_by_first_name+ and +find_all_by_first_name+ for free from Active Record. If you have a +locked+ field on the +Client+ model, you also get +find_by_locked+ and +find_all_by_locked+ methods. -- cgit v1.2.3 From f411451ed513d982a2a14e62c38f030a3560ea42 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Thu, 23 Dec 2010 14:53:26 +1000 Subject: Remove comma [samuelkadoph] --- railties/guides/source/active_record_querying.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/active_record_querying.textile b/railties/guides/source/active_record_querying.textile index 25f3723b93..6c1042e70e 100644 --- a/railties/guides/source/active_record_querying.textile +++ b/railties/guides/source/active_record_querying.textile @@ -760,7 +760,7 @@ Or on an association consisting of +Post+ objects: category = Category.first - category.posts.published => [published posts, belonging to this category] + category.posts.published => [published posts belonging to this category] h4. Working with times -- cgit v1.2.3 From b4b2574a12f7a3b6db97d28eda894ad872445190 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Thu, 23 Dec 2010 14:55:42 +1000 Subject: Query guide: fix indentation --- .../guides/source/active_record_querying.textile | 26 +++++++++++----------- 1 file changed, 13 insertions(+), 13 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/active_record_querying.textile b/railties/guides/source/active_record_querying.textile index 6c1042e70e..5cd302f356 100644 --- a/railties/guides/source/active_record_querying.textile +++ b/railties/guides/source/active_record_querying.textile @@ -728,39 +728,39 @@ Scoping allows you to specify commonly-used ARel queries which can be referenced To define a simple scope, we use the +scope+ method inside the class, passing the ARel query that we'd like run when this scope is called: - class Post < ActiveRecord::Base - scope :published, where(:published => true) - end +class Post < ActiveRecord::Base + scope :published, where(:published => true) +end Just like before, these methods are also chainable: - class Post < ActiveRecord::Base - scope :published, where(:published => true).joins(:category) - end +class Post < ActiveRecord::Base + scope :published, where(:published => true).joins(:category) +end Scopes are also chainable within scopes: - class Post < ActiveRecord::Base - scope :published, where(:published => true) - scope :published_and_commented, published.and(self.arel_table[:comments_count].gt(0)) - end +class Post < ActiveRecord::Base + scope :published, where(:published => true) + scope :published_and_commented, published.and(self.arel_table[:comments_count].gt(0)) +end To call this +published+ scope we can call it on either the class: - Post.published => [published posts] +Post.published => [published posts] Or on an association consisting of +Post+ objects: - category = Category.first - category.posts.published => [published posts belonging to this category] +category = Category.first +category.posts.published => [published posts belonging to this category] h4. Working with times -- cgit v1.2.3 From 0644e38c4269c06968cacd60ac677011af82671c Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Thu, 23 Dec 2010 14:57:53 +1000 Subject: Query guide: scopes with arguments should be instead defined as class methods. --- .../guides/source/active_record_querying.textile | 34 ++++++++++++++++++++-- 1 file changed, 31 insertions(+), 3 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/active_record_querying.textile b/railties/guides/source/active_record_querying.textile index 5cd302f356..eb77a35739 100644 --- a/railties/guides/source/active_record_querying.textile +++ b/railties/guides/source/active_record_querying.textile @@ -768,13 +768,41 @@ h4. Working with times If you're working with dates or times within scopes, due to how they are evaluated, you will need to use a lambda so that the scope is evaluated every time. - class Post < ActiveRecord::Base - scope :last_week, lambda { where("created_at < ?", Time.zone.now ) } - end +class Post < ActiveRecord::Base + scope :last_week, lambda { where("created_at < ?", Time.zone.now ) } +end Without the +lambda+, this +Time.zone.now+ will only be called once. +h4. Passing in arguments + +When a +lambda+ is used for a +scope+, it can take arguments: + + +class Post < ActiveRecord::Base + scope :1_week_before, lambda { |time| where("created_at < ?", time) +end + + +This may then be called using this: + + +Post.1_week_before(Time.zone.now) + + +However, this is just duplicating the functionality that would be provided to you by a class method. + + +class Post < ActiveRecord::Base + def self.1_week_before(time) + where("created_at < ?", time) + end +end + + +Using a class method is the preferred way to accept arguments for scopes. + h3. Dynamic Finders For every field (also known as an attribute) you define in your table, Active Record provides a finder method. If you have a field called +first_name+ on your +Client+ model for example, you get +find_by_first_name+ and +find_all_by_first_name+ for free from Active Record. If you have a +locked+ field on the +Client+ model, you also get +find_by_locked+ and +find_all_by_locked+ methods. -- cgit v1.2.3 From 226a2a90edeaaa31948c05a6633c9edbe71fb636 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Thu, 23 Dec 2010 14:58:33 +1000 Subject: Query guide: class methods are still available on associations --- railties/guides/source/active_record_querying.textile | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/active_record_querying.textile b/railties/guides/source/active_record_querying.textile index eb77a35739..bdc4d7c50d 100644 --- a/railties/guides/source/active_record_querying.textile +++ b/railties/guides/source/active_record_querying.textile @@ -801,7 +801,11 @@ class Post < ActiveRecord::Base end -Using a class method is the preferred way to accept arguments for scopes. +Using a class method is the preferred way to accept arguments for scopes. These methods will still be accessible on the association objects: + + +category.posts.1_week_before(time) + h3. Dynamic Finders -- cgit v1.2.3 From c3748190f45a7a48c68606cb2c44a246f978c6ac Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Thu, 23 Dec 2010 14:59:22 +1000 Subject: Query Guide: update Changelog --- railties/guides/source/active_record_querying.textile | 1 + 1 file changed, 1 insertion(+) (limited to 'railties/guides') diff --git a/railties/guides/source/active_record_querying.textile b/railties/guides/source/active_record_querying.textile index bdc4d7c50d..c9c884cd7c 100644 --- a/railties/guides/source/active_record_querying.textile +++ b/railties/guides/source/active_record_querying.textile @@ -968,6 +968,7 @@ For options, please see the parent section, "Calculations":#calculations. h3. Changelog +* December 23 2010: Add documentation for the +scope+ method. "Ryan Bigg":http://ryanbigg.com * April 7, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com * February 3, 2010: Update to Rails 3 by "James Miller":credits.html#bensie * February 7, 2009: Second version by "Pratik":credits.html#lifo -- cgit v1.2.3 From 0795c3a15eccf5406220134fae3f4b44be030655 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Thu, 23 Dec 2010 15:05:17 +1000 Subject: Query guide: Ordering, selecting and so on shouldn't be nested in conditions as they are modifiers, not conditions in the prime sense of the word. --- railties/guides/source/active_record_querying.textile | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/active_record_querying.textile b/railties/guides/source/active_record_querying.textile index c9c884cd7c..b315a2b107 100644 --- a/railties/guides/source/active_record_querying.textile +++ b/railties/guides/source/active_record_querying.textile @@ -337,7 +337,7 @@ This code will generate SQL like this: SELECT * FROM clients WHERE (clients.orders_count IN (1,3,5)) -h4. Ordering +h3. Ordering To retrieve records from the database in a specific order, you can use the +order+ method. @@ -361,7 +361,7 @@ Or ordering by multiple fields: Client.order("orders_count ASC, created_at DESC") -h4. Selecting Specific Fields +h3. Selecting Specific Fields By default, Model.find selects all the fields from the result set using +select *+. @@ -397,7 +397,7 @@ You can also call SQL functions within the select option. For example, if you wo Client.select("DISTINCT(name)") -h4. Limit and Offset +h3. Limit and Offset To apply +LIMIT+ to the SQL fired by the +Model.find+, you can specify the +LIMIT+ using +limit+ and +offset+ methods on the relation. @@ -425,7 +425,7 @@ will return instead a maximum of 5 clients beginning with the 31st. The SQL look SELECT * FROM clients LIMIT 5, 30 -h4. Group +h3. Group To apply a +GROUP BY+ clause to the SQL fired by the finder, you can specify the +group+ method on the find. @@ -443,7 +443,7 @@ The SQL that would be executed would be something like this: SELECT * FROM orders GROUP BY date(created_at) -h4. Having +h3. Having SQL uses the +HAVING+ clause to specify conditions on the +GROUP BY+ fields. You can add the +HAVING+ clause to the SQL fired by the +Model.find+ by adding the +:having+ option to the find. @@ -461,7 +461,7 @@ SELECT * FROM orders GROUP BY date(created_at) HAVING created_at > '2009-01-15' This will return single order objects for each day, but only for the last month. -h4. Readonly Objects +h3. Readonly Objects Active Record provides +readonly+ method on a relation to explicitly disallow modification or deletion of any of the returned object. Any attempt to alter or destroy a readonly record will not succeed, raising an +ActiveRecord::ReadOnlyRecord+ exception. @@ -473,7 +473,7 @@ client.save As +client+ is explicitly set to be a readonly object, the above code will raise an +ActiveRecord::ReadOnlyRecord+ exception when calling +client.save+ with an updated value of _visists_. -h4. Locking Records for Update +h3. Locking Records for Update Locking is helpful for preventing race conditions when updating records in the database and ensuring atomic updates. @@ -482,7 +482,7 @@ Active Record provides two locking mechanisms: * Optimistic Locking * Pessimistic Locking -h5. Optimistic Locking +h4. Optimistic Locking Optimistic locking allows multiple users to access the same record for edits, and assumes a minimum of conflicts with the data. It does this by checking whether another process has made changes to a record since it was opened. An +ActiveRecord::StaleObjectError+ exception is thrown if that has occurred and the update is ignored. @@ -517,7 +517,7 @@ class Client < ActiveRecord::Base end -h5. Pessimistic Locking +h4. Pessimistic Locking Pessimistic locking uses a locking mechanism provided by the underlying database. Using +lock+ when building a relation obtains an exclusive lock on the selected rows. Relations using +lock+ are usually wrapped inside a transaction for preventing deadlock conditions. -- cgit v1.2.3 From cef17cd705c3529139fa1fd5bbc0e9c6ae289ba4 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Thu, 23 Dec 2010 15:44:12 +1000 Subject: Query guide: specify what type of objects scopes return --- railties/guides/source/active_record_querying.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/active_record_querying.textile b/railties/guides/source/active_record_querying.textile index b315a2b107..5264477e1c 100644 --- a/railties/guides/source/active_record_querying.textile +++ b/railties/guides/source/active_record_querying.textile @@ -723,7 +723,7 @@ Even though Active Record lets you specify conditions on the eager loaded associ h3. Scopes -Scoping allows you to specify commonly-used ARel queries which can be referenced as method calls on the association objects or models. With these scopes, you can use every method previously covered such as +where+, +joins+ and +includes+. +Scoping allows you to specify commonly-used ARel queries which can be referenced as method calls on the association objects or models. With these scopes, you can use every method previously covered such as +where+, +joins+ and +includes+. All scope methods will return an +ActiveRecord::Relation+ object which will allow for further methods (such as other scopes) to be called on it. To define a simple scope, we use the +scope+ method inside the class, passing the ARel query that we'd like run when this scope is called: -- cgit v1.2.3 From 578f9711fdb42ca9fc4b8248c494afe755cd1c17 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Thu, 23 Dec 2010 16:06:29 +1000 Subject: Query guide: arel_table, eq and eq_any --- .../guides/source/active_record_querying.textile | 26 ++++++++++++++++++++++ 1 file changed, 26 insertions(+) (limited to 'railties/guides') diff --git a/railties/guides/source/active_record_querying.textile b/railties/guides/source/active_record_querying.textile index 5264477e1c..1da12cbc9b 100644 --- a/railties/guides/source/active_record_querying.textile +++ b/railties/guides/source/active_record_querying.textile @@ -337,6 +337,32 @@ This code will generate SQL like this: SELECT * FROM clients WHERE (clients.orders_count IN (1,3,5)) +h4. +arel_table+ + +The +arel_table+ method is used in the following sections to gain access to more advanced functionality of the Active Relation building language. You may see examples such as this: + + +Post.where(Post.arel_table[:comments_count].eq(5))) + + +Don't be alarmed! This method returns an +Arel::Table+ object which provides methods for accessing fields and building queries, as you'll see in the following sections. + +h4. +eq+ + +The +eq+ method can be used to check if a field is a specific value: + + +Post.where(Post.arel_table[:comments_count].eq(5)) + + +h4. +eq_any+ + +The +eq_any+ method can be used to return objects of a relation that have the specified field matching any of the specified values. + + +Post.where(Post.arel_table[:comments_count].eq_any([1,2]) + + h3. Ordering To retrieve records from the database in a specific order, you can use the +order+ method. -- cgit v1.2.3 From 6271f3f16b5b9c6d60ba7d758d2b595be8074e00 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Thu, 23 Dec 2010 16:39:10 +1000 Subject: Query guide: Document "in" methods --- .../guides/source/active_record_querying.textile | 25 ++++++++++++++++++++++ 1 file changed, 25 insertions(+) (limited to 'railties/guides') diff --git a/railties/guides/source/active_record_querying.textile b/railties/guides/source/active_record_querying.textile index 1da12cbc9b..1bd9ec7972 100644 --- a/railties/guides/source/active_record_querying.textile +++ b/railties/guides/source/active_record_querying.textile @@ -363,6 +363,31 @@ The +eq_any+ method can be used to return objects of a relation that have the sp Post.where(Post.arel_table[:comments_count].eq_any([1,2]) +h4. +in+ + +To check if a value is within a given group of values, use the +in+ method: + + + Post.where(Post.arel_table[:id].in([1,2,3])) + + +h4. +in_any+ + +Check if a value is within any one of a group of values: + + + Post.where(Post.arel_table[:id]).in_any([1,2,3], [4,5,6]) + + +h4. +in_all+ + +Check if a value is within all of the specified groups of values: + + + Post.where(Post.arel_table[:id]).in_all([1,2,3], [1,4,6]) + + + h3. Ordering To retrieve records from the database in a specific order, you can use the +order+ method. -- cgit v1.2.3 From 8713bb6ab8ff5acf60872b0b8f0bffd13a0aa1ca Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Thu, 23 Dec 2010 18:36:39 +1000 Subject: Query guide: cover further ARel methods --- .../guides/source/active_record_querying.textile | 83 ++++++++++++++++++++-- 1 file changed, 76 insertions(+), 7 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/active_record_querying.textile b/railties/guides/source/active_record_querying.textile index 1bd9ec7972..8eb28ec953 100644 --- a/railties/guides/source/active_record_querying.textile +++ b/railties/guides/source/active_record_querying.textile @@ -355,38 +355,107 @@ The +eq+ method can be used to check if a field is a specific value: Post.where(Post.arel_table[:comments_count].eq(5)) +This method's opposite is +not_eq+. + h4. +eq_any+ -The +eq_any+ method can be used to return objects of a relation that have the specified field matching any of the specified values. +Checks if the specified field matches any of the given values. Post.where(Post.arel_table[:comments_count].eq_any([1,2]) +This method's opposite is +not_eq_any+. + h4. +in+ -To check if a value is within a given group of values, use the +in+ method: +To check if a field is within a given group of values, use the +in+ method: - Post.where(Post.arel_table[:id].in([1,2,3])) +Post.where(Post.arel_table[:id].in([1,2,3])) +This method's opposite is +not_in+. + h4. +in_any+ -Check if a value is within any one of a group of values: +Check if a field is within any one of a group of values: - Post.where(Post.arel_table[:id]).in_any([1,2,3], [4,5,6]) +Post.where(Post.arel_table[:id]).in_any([1,2,3], [4,5,6]) +This method's opposite is +not_in_any+. + h4. +in_all+ -Check if a value is within all of the specified groups of values: +Check if a field is within all of the specified groups of values: + + +Post.where(Post.arel_table[:id]).in_all([1,2,3], [1,4,6]) + + +This method's opposite is +not_in_all+. + +h4. +matches+ + +Match a specific field with a given value. Use +%+ for wildcard searching. + + +Post.where(Post.arel_table[:author].matches("Ryan%")) + + +This method's opposite is +does_not_match+. + +h4. +matches_any+ + +Match a specific field with any given value. Use +%+ for wildcard searching. + + +Post.where(Post.arel_table[:author].matches_any(["Ryan%", "Yehuda%"])) + + +This method's opposite is +does_not_match_any+ + +h4. +matches_all+ + +Match a specific field with all given values. Use +%+ for wild card searching. + + +Post.where(Post.arel_table[:author].matches_all(["Ryan%", "%Bigg"])) + + +This method's opposite is +does_not_match_all+. + +h4. +gteq+ + +Check for a field greater than or equal to a specific value. + + +Post.where(Post.arel_table[:comments_count].gteq(1)) + + +This method's opposite is +lteq+. + +h4. +gteq_any+ + +Check for a field greater than or equal to any of the given values. + + +Post.where(Post.arel_table[:comments_count].gteq_any([1,2])) + + +This method's opposite is +lteq_any+. + +h4. +gteq_all+ + +Check for a field greater than or equal to all of the given values. - Post.where(Post.arel_table[:id]).in_all([1,2,3], [1,4,6]) +Post.where(Post.arel_table[:comments_count].gteq_all([1,2])) +This method's opposite is +lteq_all+. h3. Ordering -- cgit v1.2.3 From 890105f4f1ca471491c85f2aabd21d5a183ab189 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Thu, 23 Dec 2010 22:15:08 +1000 Subject: Query guide: add or conditions --- railties/guides/source/active_record_querying.textile | 11 +++++++++++ 1 file changed, 11 insertions(+) (limited to 'railties/guides') diff --git a/railties/guides/source/active_record_querying.textile b/railties/guides/source/active_record_querying.textile index 8eb28ec953..b4db365a09 100644 --- a/railties/guides/source/active_record_querying.textile +++ b/railties/guides/source/active_record_querying.textile @@ -457,6 +457,17 @@ Post.where(Post.arel_table[:comments_count].gteq_all([1,2])) This method's opposite is +lteq_all+. +h4. +or+ + +Allows you to chain queries to get results matching either condition: + + +title = Post.arel_table[:title] +Post.where(title.eq("Active").or(title.eq("Record"))) + + +Note that this method is called on the end of the +eq+ method here, rather than the +where+. + h3. Ordering To retrieve records from the database in a specific order, you can use the +order+ method. -- cgit v1.2.3 From bb707cf7373586952d95bf574cfdeb2dbac29ea2 Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Thu, 23 Dec 2010 23:34:28 +0530 Subject: indentation fix --- railties/guides/source/3_0_release_notes.textile | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/3_0_release_notes.textile b/railties/guides/source/3_0_release_notes.textile index adb1c755df..db5a9ce644 100644 --- a/railties/guides/source/3_0_release_notes.textile +++ b/railties/guides/source/3_0_release_notes.textile @@ -357,15 +357,15 @@ Validations have been moved from Active Record into Active Model, providing an i * There is now a validates :attribute, options_hash shortcut method that allows you to pass options for all the validates class methods, you can pass more than one option to a validate method. * The +validates+ method has the following options: - * :acceptance => Boolean. - * :confirmation => Boolean. - * :exclusion => { :in => Enumerable }. - * :inclusion => { :in => Enumerable }. - * :format => { :with => Regexp, :on => :create }. - * :length => { :maximum => Fixnum }. - * :numericality => Boolean. - * :presence => Boolean. - * :uniqueness => Boolean. +** :acceptance => Boolean. +** :confirmation => Boolean. +** :exclusion => { :in => Enumerable }. +** :inclusion => { :in => Enumerable }. +** :format => { :with => Regexp, :on => :create }. +** :length => { :maximum => Fixnum }. +** :numericality => Boolean. +** :presence => Boolean. +** :uniqueness => Boolean. NOTE: All the Rails version 2.3 style validation methods are still supported in Rails 3.0, the new validates method is designed as an additional aid in your model validations, not a replacement for the existing API. -- cgit v1.2.3 From 2c8938fcba6670f2cb056ec91d631ae0e37ea006 Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Fri, 24 Dec 2010 00:03:51 +0530 Subject: fixed inject example and some minor edits --- .../guides/source/active_support_core_extensions.textile | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/active_support_core_extensions.textile b/railties/guides/source/active_support_core_extensions.textile index bddff1c987..8821a6e461 100644 --- a/railties/guides/source/active_support_core_extensions.textile +++ b/railties/guides/source/active_support_core_extensions.textile @@ -1568,7 +1568,7 @@ The method +tableize+ is +underscore+ followed by +pluralize+. "InvoiceLine".tableize # => "invoice_lines" -As a rule of thumb, +tableize+ returns the table name that corresponds to a given model for simple cases. The actual implementation in Active Record is not straight +tableize+ indeed, because it also demodulizes de class name and checks a few options that may affect the returned string. +As a rule of thumb, +tableize+ returns the table name that corresponds to a given model for simple cases. The actual implementation in Active Record is not straight +tableize+ indeed, because it also demodulizes the class name and checks a few options that may affect the returned string. NOTE: Defined in +active_support/core_ext/string/inflections.rb+. @@ -1868,7 +1868,7 @@ The sum of an empty collection is zero by default, but this is customizable: [].sum(1) # => 1 -If a block is given +sum+ becomes an iterator that yields the elements of the collection and sums the returned values: +If a block is given, +sum+ becomes an iterator that yields the elements of the collection and sums the returned values: (1..5).sum {|n| n * 2 } # => 30 @@ -1896,8 +1896,8 @@ h4. +each_with_object+ The +inject+ method offers iteration with an accumulator: -[2, 3, 4].inject(1) {|acc, i| product*i } # => 24 - +[2, 3, 4].inject(1) {|product, i| product*i } # => 24 + 1+: <% end %> -If an optional block is given +many?+ only takes into account those elements that return true: +If an optional block is given, +many?+ only takes into account those elements that return true: @see_more = videos.many? {|video| video.category == params[:category]} @@ -1952,7 +1952,7 @@ NOTE: Defined in +active_support/core_ext/enumerable.rb+. h4. +exclude?+ -The predicate +exclude?+ tests whether a given object does *not* belong to the collection. It is the negation of the builtin +include?+: +The predicate +exclude?+ tests whether a given object does *not* belong to the collection. It is the negation of the built-in +include?+: to_visit << node if visited.exclude?(node) -- cgit v1.2.3 From 5683d6883b20e5ed88e26d07c841911b225a5841 Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Fri, 24 Dec 2010 00:17:44 +0530 Subject: It's JavaScript :) --- railties/guides/source/2_2_release_notes.textile | 6 +++--- railties/guides/source/2_3_release_notes.textile | 2 +- .../guides/source/action_view_overview.textile | 22 +++++++++++----------- railties/guides/source/getting_started.textile | 2 +- .../guides/source/layouts_and_rendering.textile | 2 +- 5 files changed, 17 insertions(+), 17 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/2_2_release_notes.textile b/railties/guides/source/2_2_release_notes.textile index 5628d7e52f..8e2d528eee 100644 --- a/railties/guides/source/2_2_release_notes.textile +++ b/railties/guides/source/2_2_release_notes.textile @@ -260,15 +260,15 @@ h4. Other Action Controller Changes * Benchmarking numbers are now reported in milliseconds rather than tiny fractions of seconds * Rails now supports HTTP-only cookies (and uses them for sessions), which help mitigate some cross-site scripting risks in newer browsers. * +redirect_to+ now fully supports URI schemes (so, for example, you can redirect to a svn+ssh: URI). -* +render+ now supports a +:js+ option to render plain vanilla javascript with the right mime type. +* +render+ now supports a +:js+ option to render plain vanilla JavaScript with the right mime type. * Request forgery protection has been tightened up to apply to HTML-formatted content requests only. * Polymorphic URLs behave more sensibly if a passed parameter is nil. For example, calling +polymorphic_path([@project, @date, @area])+ with a nil date will give you +project_area_path+. h3. Action View * +javascript_include_tag+ and +stylesheet_link_tag+ support a new +:recursive+ option to be used along with +:all+, so that you can load an entire tree of files with a single line of code. -* The included Prototype javascript library has been upgraded to version 1.6.0.3. -* +RJS#page.reload+ to reload the browser's current location via javascript +* The included Prototype JavaScript library has been upgraded to version 1.6.0.3. +* +RJS#page.reload+ to reload the browser's current location via JavaScript * The +atom_feed+ helper now takes an +:instruct+ option to let you insert XML processing instructions. h3. Action Mailer diff --git a/railties/guides/source/2_3_release_notes.textile b/railties/guides/source/2_3_release_notes.textile index 72fe723687..67743a4797 100644 --- a/railties/guides/source/2_3_release_notes.textile +++ b/railties/guides/source/2_3_release_notes.textile @@ -278,7 +278,7 @@ Mime::JS =~ "text/javascript" => true Mime::JS =~ "application/javascript" => true -The other change is that the framework now uses the +Mime::JS+ when checking for javascript in various spots, making it handle those alternatives cleanly. +The other change is that the framework now uses the +Mime::JS+ when checking for JavaScript in various spots, making it handle those alternatives cleanly. * Lead Contributor: "Seth Fitzsimmons":http://www.workingwithrails.com/person/5510-seth-fitzsimmons diff --git a/railties/guides/source/action_view_overview.textile b/railties/guides/source/action_view_overview.textile index 051baa660c..30faeeaa91 100644 --- a/railties/guides/source/action_view_overview.textile +++ b/railties/guides/source/action_view_overview.textile @@ -231,7 +231,7 @@ input("post", "title") # => h4. AssetTagHelper -This module provides methods for generating HTML that links views to assets such as images, javascripts, stylesheets, and feeds. +This module provides methods for generating HTML that links views to assets such as images, JavaScript files, stylesheets, and feeds. By default, Rails links to these assets on the current host in the public folder, but you can direct Rails to link to assets from a dedicated assets server by setting +ActionController::Base.asset_host+ in the application configuration, typically in +config/environments/production.rb+. For example, let's say your asset host is +assets.example.com+: @@ -242,7 +242,7 @@ image_tag("rails.png") # => "RSS h5. image_path -Computes the path to an image asset in the public images directory. Full paths from the document root will be passed through. Used internally by +image_tag+ to build the image path. +Computes the path to an image asset in the +public/images+ directory. Full paths from the document root will be passed through. Used internally by +image_tag+ to build the image path. image_path("edit.png") # => /images/edit.png @@ -286,7 +286,7 @@ image_path("edit.png") # => /images/edit.png h5. image_tag -Returns an html image tag for the source. The source can be a full path or a file that exists in your public images directory. +Returns an html image tag for the source. The source can be a full path or a file that exists in your +public/images+ directory. image_tag("icon.png") # => Icon @@ -294,26 +294,26 @@ image_tag("icon.png") # => Icon h5. javascript_include_tag -Returns an html script tag for each of the sources provided. You can pass in the filename (+.js+ extension is optional) of javascript files that exist in your +public/javascripts+ directory for inclusion into the current page or you can pass the full path relative to your document root. +Returns an html script tag for each of the sources provided. You can pass in the filename (+.js+ extension is optional) of JavaScript files that exist in your +public/javascripts+ directory for inclusion into the current page or you can pass the full path relative to your document root. javascript_include_tag "common" # => -To include the Prototype and Scriptaculous javascript libraries in your application, pass +:defaults+ as the source. When using +:defaults+, if an +application.js+ file exists in your +public/javascripts+ directory, it will be included as well. +To include the Prototype and Scriptaculous JavaScript libraries in your application, pass +:defaults+ as the source. When using +:defaults+, if an +application.js+ file exists in your +public/javascripts+ directory, it will be included as well. javascript_include_tag :defaults -You can also include all javascripts in the javascripts directory using +:all+ as the source. +You can also include all JavaScript files in the +public/javascripts+ directory using +:all+ as the source. javascript_include_tag :all -You can also cache multiple javascripts into one file, which requires less HTTP connections to download and can better be compressed by gzip (leading to faster transfers). Caching will only happen if +ActionController::Base.perform_caching+ is set to true (which is the case by default for the Rails production environment, but not for the development environment). +You can also cache multiple JavaScript files into one file, which requires less HTTP connections to download and can better be compressed by gzip (leading to faster transfers). Caching will only happen if +ActionController::Base.perform_caching+ is set to true (which is the case by default for the Rails production environment, but not for the development environment). javascript_include_tag :all, :cache => true # => @@ -322,7 +322,7 @@ javascript_include_tag :all, :cache => true # => h5. javascript_path -Computes the path to a javascript asset in the +public/javascripts+ directory. If the source filename has no extension, +.js+ will be appended. Full paths from the document root will be passed through. Used internally by +javascript_include_tag+ to build the script path. +Computes the path to a JavaScript asset in the +public/javascripts+ directory. If the source filename has no extension, +.js+ will be appended. Full paths from the document root will be passed through. Used internally by +javascript_include_tag+ to build the script path. javascript_path "common" # => /javascripts/common.js @@ -352,7 +352,7 @@ stylesheet_link_tag :all, :cache => true h5. stylesheet_path -Computes the path to a stylesheet asset in the public stylesheets directory. If the source filename has no extension, .css will be appended. Full paths from the document root will be passed through. Used internally by stylesheet_link_tag to build the stylesheet path. +Computes the path to a stylesheet asset in the +public/stylesheets+ directory. If the source filename has no extension, .css will be appended. Full paths from the document root will be passed through. Used internally by stylesheet_link_tag to build the stylesheet path. stylesheet_path "application" # => /stylesheets/application.css @@ -1076,7 +1076,7 @@ h4. JavaScriptHelper Provides functionality for working with JavaScript in your views. -Rails includes the Prototype JavaScript framework and the Scriptaculous JavaScript controls and visual effects library. If you wish to use these libraries and their helpers, make sure +<%= javascript_include_tag :defaults, :cache => true %>+ is in the HEAD section of your page. This function will include the necessary JavaScript files Rails generated in the public/javascripts directory. +Rails includes the Prototype JavaScript framework and the Scriptaculous JavaScript controls and visual effects library. If you wish to use these libraries and their helpers, make sure +<%= javascript_include_tag :defaults, :cache => true %>+ is in the HEAD section of your page. This function will include the necessary JavaScript files Rails generated in the +public/javascripts+ directory. h5. button_to_function diff --git a/railties/guides/source/getting_started.textile b/railties/guides/source/getting_started.textile index e371632d87..ef93239b30 100644 --- a/railties/guides/source/getting_started.textile +++ b/railties/guides/source/getting_started.textile @@ -184,7 +184,7 @@ In any case, Rails will create a folder in your working directory called blo |doc/|In-depth documentation for your application.| |lib/|Extended modules for your application (not covered in this guide).| |log/|Application log files.| -|public/|The only folder seen to the world as-is. This is where your images, javascript, stylesheets (CSS), and other static files go.| +|public/|The only folder seen to the world as-is. This is where your images, JavaScript files, stylesheets (CSS), and other static files go.| |script/|Contains the rails script that starts your app and can contain other scripts you use to deploy or run your application.| |test/|Unit tests, fixtures, and other test apparatus. These are covered in "Testing Rails Applications":testing.html| |tmp/|Temporary files| diff --git a/railties/guides/source/layouts_and_rendering.textile b/railties/guides/source/layouts_and_rendering.textile index 4cdd4f2709..f0e40b0980 100644 --- a/railties/guides/source/layouts_and_rendering.textile +++ b/railties/guides/source/layouts_and_rendering.textile @@ -681,7 +681,7 @@ There are three tag options available for +auto_discovery_link_tag+: * +:type+ specifies an explicit MIME type. Rails will generate an appropriate MIME type automatically. * +:title+ specifies the title of the link -h5. Linking to Javascript Files with +javascript_include_tag+ +h5. Linking to JavaScript Files with +javascript_include_tag+ The +javascript_include_tag+ helper returns an HTML +script+ tag for each source provided. Rails looks in +public/javascripts+ for these files by default, but you can specify a full path relative to the document root, or a URL, if you prefer. For example, to include +public/javascripts/main.js+: -- cgit v1.2.3 From f1eb69c5b27050494cbc91890b107abd1dadfd48 Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Fri, 24 Dec 2010 00:24:26 +0530 Subject: fixing typo that crept in 2c8938f --- railties/guides/source/active_support_core_extensions.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/active_support_core_extensions.textile b/railties/guides/source/active_support_core_extensions.textile index 8821a6e461..33e281d59b 100644 --- a/railties/guides/source/active_support_core_extensions.textile +++ b/railties/guides/source/active_support_core_extensions.textile @@ -1897,7 +1897,7 @@ The +inject+ method offers iteration with an accumulator: [2, 3, 4].inject(1) {|product, i| product*i } # => 24 - The block is expected to return the value for the accumulator in the next iteration, and this makes building mutable objects a bit cumbersome: -- cgit v1.2.3 From 06e2f7cd173a279a4b1c17040356acca142128b5 Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Fri, 24 Dec 2010 00:34:07 +0530 Subject: minor convention edit --- railties/guides/source/getting_started.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/getting_started.textile b/railties/guides/source/getting_started.textile index ef93239b30..4466c291bb 100644 --- a/railties/guides/source/getting_started.textile +++ b/railties/guides/source/getting_started.textile @@ -227,7 +227,7 @@ NOTE: In this guide we are using an SQLite3 database for data storage, because i h5. Configuring a MySQL Database -If you choose to use MySQL instead of the shipped Sqlite3 database, your +config/database.yml+ will look a little different. Here's the development section: +If you choose to use MySQL instead of the shipped SQLite3 database, your +config/database.yml+ will look a little different. Here's the development section: development: -- cgit v1.2.3 From e4314e7d3fd93c5ed1eda1cf52ed38cdc2543d25 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Fri, 24 Dec 2010 07:22:08 +1000 Subject: Query guide: visists => visits --- railties/guides/source/active_record_querying.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/active_record_querying.textile b/railties/guides/source/active_record_querying.textile index b4db365a09..a45624809e 100644 --- a/railties/guides/source/active_record_querying.textile +++ b/railties/guides/source/active_record_querying.textile @@ -602,7 +602,7 @@ client.visits += 1 client.save -As +client+ is explicitly set to be a readonly object, the above code will raise an +ActiveRecord::ReadOnlyRecord+ exception when calling +client.save+ with an updated value of _visists_. +As +client+ is explicitly set to be a readonly object, the above code will raise an +ActiveRecord::ReadOnlyRecord+ exception when calling +client.save+ with an updated value of _visits_. h3. Locking Records for Update -- cgit v1.2.3 From d1e95e12b4d56fac58ee680fd2d8d5cdac57b2ac Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Fri, 24 Dec 2010 10:47:38 +1000 Subject: Revert "Query guide: arel_table, eq and eq_any" along with other commits that added documentation involving the arel_table method This reverts commit 578f9711fdb42ca9fc4b8248c494afe755cd1c17. Conflicts: railties/guides/source/active_record_querying.textile --- .../guides/source/active_record_querying.textile | 131 --------------------- 1 file changed, 131 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/active_record_querying.textile b/railties/guides/source/active_record_querying.textile index a45624809e..61d8205278 100644 --- a/railties/guides/source/active_record_querying.textile +++ b/railties/guides/source/active_record_querying.textile @@ -337,137 +337,6 @@ This code will generate SQL like this: SELECT * FROM clients WHERE (clients.orders_count IN (1,3,5)) -h4. +arel_table+ - -The +arel_table+ method is used in the following sections to gain access to more advanced functionality of the Active Relation building language. You may see examples such as this: - - -Post.where(Post.arel_table[:comments_count].eq(5))) - - -Don't be alarmed! This method returns an +Arel::Table+ object which provides methods for accessing fields and building queries, as you'll see in the following sections. - -h4. +eq+ - -The +eq+ method can be used to check if a field is a specific value: - - -Post.where(Post.arel_table[:comments_count].eq(5)) - - -This method's opposite is +not_eq+. - -h4. +eq_any+ - -Checks if the specified field matches any of the given values. - - -Post.where(Post.arel_table[:comments_count].eq_any([1,2]) - - -This method's opposite is +not_eq_any+. - -h4. +in+ - -To check if a field is within a given group of values, use the +in+ method: - - -Post.where(Post.arel_table[:id].in([1,2,3])) - - -This method's opposite is +not_in+. - -h4. +in_any+ - -Check if a field is within any one of a group of values: - - -Post.where(Post.arel_table[:id]).in_any([1,2,3], [4,5,6]) - - -This method's opposite is +not_in_any+. - -h4. +in_all+ - -Check if a field is within all of the specified groups of values: - - -Post.where(Post.arel_table[:id]).in_all([1,2,3], [1,4,6]) - - -This method's opposite is +not_in_all+. - -h4. +matches+ - -Match a specific field with a given value. Use +%+ for wildcard searching. - - -Post.where(Post.arel_table[:author].matches("Ryan%")) - - -This method's opposite is +does_not_match+. - -h4. +matches_any+ - -Match a specific field with any given value. Use +%+ for wildcard searching. - - -Post.where(Post.arel_table[:author].matches_any(["Ryan%", "Yehuda%"])) - - -This method's opposite is +does_not_match_any+ - -h4. +matches_all+ - -Match a specific field with all given values. Use +%+ for wild card searching. - - -Post.where(Post.arel_table[:author].matches_all(["Ryan%", "%Bigg"])) - - -This method's opposite is +does_not_match_all+. - -h4. +gteq+ - -Check for a field greater than or equal to a specific value. - - -Post.where(Post.arel_table[:comments_count].gteq(1)) - - -This method's opposite is +lteq+. - -h4. +gteq_any+ - -Check for a field greater than or equal to any of the given values. - - -Post.where(Post.arel_table[:comments_count].gteq_any([1,2])) - - -This method's opposite is +lteq_any+. - -h4. +gteq_all+ - -Check for a field greater than or equal to all of the given values. - - -Post.where(Post.arel_table[:comments_count].gteq_all([1,2])) - - -This method's opposite is +lteq_all+. - -h4. +or+ - -Allows you to chain queries to get results matching either condition: - - -title = Post.arel_table[:title] -Post.where(title.eq("Active").or(title.eq("Record"))) - - -Note that this method is called on the end of the +eq+ method here, rather than the +where+. - h3. Ordering To retrieve records from the database in a specific order, you can use the +order+ method. -- cgit v1.2.3 From e38cacb8ee24724032699148e86f9d862e6bdbdc Mon Sep 17 00:00:00 2001 From: Moiz Raja Date: Thu, 23 Dec 2010 22:51:12 -0800 Subject: correct links to rack articles --- railties/guides/source/rails_on_rack.textile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/rails_on_rack.textile b/railties/guides/source/rails_on_rack.textile index 8338777480..c1b91da7a8 100644 --- a/railties/guides/source/rails_on_rack.textile +++ b/railties/guides/source/rails_on_rack.textile @@ -223,8 +223,8 @@ h4. Learning Rack * "Official Rack Website":http://rack.github.com * "Introducing Rack":http://chneukirchen.org/blog/archive/2007/02/introducing-rack.html -* "Ruby on Rack #1 - Hello Rack!":http://m.onkey.org/2008/11/17/ruby-on-rack-1 -* "Ruby on Rack #2 - The Builder":http://m.onkey.org/2008/11/18/ruby-on-rack-2-rack-builder +* "Ruby on Rack #1 - Hello Rack!":http://m.onkey.org/ruby-on-rack-1-hello-rack +* "Ruby on Rack #2 - The Builder":http://m.onkey.org/ruby-on-rack-2-the-builder h4. Understanding Middlewares -- cgit v1.2.3 From 517b37146ab1b841c2cc878ca47746bdfc700d5b Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Sat, 25 Dec 2010 00:38:03 +0530 Subject: minor edits --- railties/guides/source/active_support_core_extensions.textile | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/active_support_core_extensions.textile b/railties/guides/source/active_support_core_extensions.textile index 33e281d59b..9a1f913ded 100644 --- a/railties/guides/source/active_support_core_extensions.textile +++ b/railties/guides/source/active_support_core_extensions.textile @@ -498,7 +498,7 @@ h4. Attributes h5. +alias_attribute+ -Model attributes have a reader, a writer, and a predicate. You can aliase a model attribute having the corresponding three methods defined for you in one shot. As in other aliasing methods, the new name is the first argument, and the old name is the second (my mnemonic is they go in the same order as if you did an assignment): +Model attributes have a reader, a writer, and a predicate. You can alias a model attribute having the corresponding three methods defined for you in one shot. As in other aliasing methods, the new name is the first argument, and the old name is the second (my mnemonic is they go in the same order as if you did an assignment): class User < ActiveRecord::Base @@ -563,7 +563,7 @@ h5. Internal Attributes When you are defining an attribute in a class that is meant to be subclassed name collisions are a risk. That's remarkably important for libraries. -Active Support defines the macros +attr_internal_reader+, +attr_internal_writer+, and +attr_internal_accessor+. They behave like their Ruby builtin +attr_*+ counterparts, except they name the underlying instance variable in a way that makes collisions less likely. +Active Support defines the macros +attr_internal_reader+, +attr_internal_writer+, and +attr_internal_accessor+. They behave like their Ruby built-in +attr_*+ counterparts, except they name the underlying instance variable in a way that makes collisions less likely. The macro +attr_internal+ is a synonym for +attr_internal_accessor+: @@ -991,7 +991,7 @@ a2.x # => 2, overridden in a2 The generation of the writer instance method can be prevented by setting the option +:instance_writer+ to false, as in -module AcitveRecord +module ActiveRecord class Base class_attribute :table_name_prefix, :instance_writer => false self.table_name_prefix = "" @@ -1001,7 +1001,7 @@ end A model may find that option useful as a way to prevent mass-assignment from setting the attribute. -For convenience +class_attribute+ defines also an instance predicate which is the double negation of what the instance reader returns. In the examples above it would be called +x?+. +For convenience +class_attribute+ also defines an instance predicate which is the double negation of what the instance reader returns. In the examples above it would be called +x?+. NOTE: Defined in +active_support/core_ext/class/attribute.rb+ -- cgit v1.2.3 From caca58e4da9a61dc4aaef0e14b80393f137004ec Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Sat, 25 Dec 2010 00:56:39 +0530 Subject: fixed typos and cut down the spaces --- railties/guides/source/plugins.textile | 92 +++++++++++++++++----------------- 1 file changed, 46 insertions(+), 46 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/plugins.textile b/railties/guides/source/plugins.textile index cb43282ace..585bc2ee86 100644 --- a/railties/guides/source/plugins.textile +++ b/railties/guides/source/plugins.textile @@ -25,7 +25,7 @@ This guide describes how to build a test-driven plugin that will: * Add a custom generator command * A custom route method that can be used in routes.rb -For the purpose of this guide pretend for a moment that you are an avid bird watcher. Your favorite bird is the Yaffle, and you want to create a plugin that allows other developers to share in the Yaffle goodness. First, you need to get setup for development. +For the purpose of this guide pretend for a moment that you are an avid bird watcher. Your favorite bird is the Yaffle, and you want to create a plugin that allows other developers to share in the Yaffle goodness. First, you need to get setup for development. endprologue. @@ -33,7 +33,7 @@ h3. Setup h4. Create the Basic Application -The examples in this guide require that you have a working rails application. To create a simple one execute: +The examples in this guide require that you have a working rails application. To create a simple one execute: gem install rails @@ -45,9 +45,9 @@ rake db:migrate rails server -Then navigate to http://localhost:3000/birds. Make sure you have a functioning rails application before continuing. +Then navigate to http://localhost:3000/birds. Make sure you have a functioning rails application before continuing. -NOTE: The aforementioned instructions will work for sqlite3. For more detailed instructions on how to create a rails application for other databases see the API docs. +NOTE: The aforementioned instructions will work for SQLite3. For more detailed instructions on how to create a Rails application for other databases see the API docs. h4. Generate the Plugin Skeleton @@ -116,7 +116,7 @@ Now you can add any +require+ statements to +lib/yaffle.rb+ and keep +init.rb+ c h3. Tests -In this guide you will learn how to test your plugin against multiple different database adapters using Active Record. To setup your plugin to allow for easy testing you'll need to add 3 files: +In this guide you will learn how to test your plugin against multiple different database adapters using Active Record. To setup your plugin to allow for easy testing you'll need to add 3 files: * A +database.yml+ file with all of your connection strings * A +schema.rb+ file with your table definitions @@ -143,7 +143,7 @@ postgresql: min_messages: ERROR mysql: - adapter: mysql + adapter: mysql2 host: localhost username: root password: password @@ -268,7 +268,7 @@ Finished in 0.002236 seconds. 1 test, 2 assertion, 0 failures, 0 errors, 0 skips -By default the setup above runs your tests with sqlite or sqlite3. To run tests with one of the other connection strings specified in +database.yml+, pass the DB environment variable to rake: +By default the setup above runs your tests with SQLite or SQLite3. To run tests with one of the other connection strings specified in +database.yml+, pass the DB environment variable to rake: rake DB=sqlite @@ -281,9 +281,9 @@ Now you are ready to test-drive your plugin! h3. Extending Core Classes -This section will explain how to add a method to String that will be available anywhere in your rails application. +This section will explain how to add a method to String that will be available anywhere in your Rails application. -In this example you will add a method to String named +to_squawk+. To begin, create a new test file with a few assertions: +In this example you will add a method to String named +to_squawk+. To begin, create a new test file with a few assertions: # vendor/plugins/yaffle/test/core_ext_test.rb @@ -345,7 +345,7 @@ $ rails console h4. Working with +init.rb+ -When Rails loads plugins it looks for a file named +init.rb+. However, when the plugin is initialized, +init.rb+ is invoked via +eval+ (not +require+) so it has slightly different behavior. +When Rails loads plugins it looks for a file named +init.rb+. However, when the plugin is initialized, +init.rb+ is invoked via +eval+ (not +require+) so it has slightly different behavior. NOTE: The plugins loader also looks for +rails/init.rb+, but that one is deprecated in favor of the top-level +init.rb+ aforementioned. @@ -377,7 +377,7 @@ end h3. Add an "acts_as" Method to Active Record -A common pattern in plugins is to add a method called 'acts_as_something' to models. In this case, you want to write a method called 'acts_as_yaffle' that adds a 'squawk' method to your models. +A common pattern in plugins is to add a method called 'acts_as_something' to models. In this case, you want to write a method called 'acts_as_yaffle' that adds a 'squawk' method to your models. To begin, set up your files so that you have: @@ -433,7 +433,7 @@ With structure you can easily separate the methods that will be used for the cla h4. Add a Class Method -This plugin will expect that you've added a method to your model named 'last_squawk'. However, the plugin users might have already defined a method on their model named 'last_squawk' that they use for something else. This plugin will allow the name to be changed by adding a class method called 'yaffle_text_field'. +This plugin will expect that you've added a method to your model named 'last_squawk'. However, the plugin users might have already defined a method on their model named 'last_squawk' that they use for something else. This plugin will allow the name to be changed by adding a class method called 'yaffle_text_field'. To start out, write a failing test that shows the behavior you'd like: @@ -486,7 +486,7 @@ ActiveRecord::Base.send :include, Yaffle h4. Add an Instance Method -This plugin will add a method named 'squawk' to any Active Record objects that call 'acts_as_yaffle'. The 'squawk' method will simply set the value of one of the fields in the database. +This plugin will add a method named 'squawk' to any Active Record objects that call 'acts_as_yaffle'. The 'squawk' method will simply set the value of one of the fields in the database. To start out, write a failing test that shows the behavior you'd like: @@ -556,11 +556,11 @@ end ActiveRecord::Base.send :include, Yaffle -NOTE: The use of +write_attribute+ to write to the field in model is just one example of how a plugin can interact with the model, and will not always be the right method to use. For example, you could also use +send("#{self.class.yaffle_text_field}=", string.to_squawk)+. +NOTE: The use of +write_attribute+ to write to the field in model is just one example of how a plugin can interact with the model, and will not always be the right method to use. For example, you could also use +send("#{self.class.yaffle_text_field}=", string.to_squawk)+. h3. Models -This section describes how to add a model named 'Woodpecker' to your plugin that will behave the same as a model in your main app. When storing models, controllers, views and helpers in your plugin, it's customary to keep them in directories that match the rails directories. For this example, create a file structure like this: +This section describes how to add a model named 'Woodpecker' to your plugin that will behave the same as a model in your main app. When storing models, controllers, views and helpers in your plugin, it's customary to keep them in directories that match the rails directories. For this example, create a file structure like this: vendor/plugins/yaffle/ @@ -594,7 +594,7 @@ class WoodpeckerTest < Test::Unit::TestCase end -This is just a simple test to make sure the class is being loaded correctly. After watching it fail with +rake+, you can make it pass like so: +This is just a simple test to make sure the class is being loaded correctly. After watching it fail with +rake+, you can make it pass like so: * *vendor/plugins/yaffle/lib/yaffle.rb:* @@ -607,7 +607,7 @@ This is just a simple test to make sure the class is being loaded correctly. Af end -Adding directories to the load path makes them appear just like files in the main app directory - except that they are only loaded once, so you have to restart the web server to see the changes in the browser. Removing directories from the 'load_once_paths' allow those changes to picked up as soon as you save the file - without having to restart the web server. This is particularly useful as you develop the plugin. +Adding directories to the load path makes them appear just like files in the main app directory - except that they are only loaded once, so you have to restart the web server to see the changes in the browser. Removing directories from the 'load_once_paths' allow those changes to picked up as soon as you save the file - without having to restart the web server. This is particularly useful as you develop the plugin. * *vendor/plugins/yaffle/lib/app/models/woodpecker.rb:* @@ -630,7 +630,7 @@ Now your test should be passing, and you should be able to use the Woodpecker mo h3. Controllers -This section describes how to add a controller named 'woodpeckers' to your plugin that will behave the same as a controller in your main app. This is very similar to adding a model. +This section describes how to add a controller named 'woodpeckers' to your plugin that will behave the same as a controller in your main app. This is very similar to adding a model. You can test your plugin's controller as you would test any other controller: @@ -661,7 +661,7 @@ class WoodpeckersControllerTest < Test::Unit::TestCase end -This is just a simple test to make sure the controller is being loaded correctly. After watching it fail with +rake+, you can make it pass like so: +This is just a simple test to make sure the controller is being loaded correctly. After watching it fail with +rake+, you can make it pass like so: * *vendor/plugins/yaffle/lib/yaffle.rb:* @@ -686,11 +686,11 @@ class WoodpeckersController < ActionController::Base end -Now your test should be passing, and you should be able to use the Woodpeckers controller in your app. If you add a route for the woodpeckers controller you can start up your server and go to http://localhost:3000/woodpeckers to see your controller in action. +Now your test should be passing, and you should be able to use the Woodpeckers controller in your app. If you add a route for the woodpeckers controller you can start up your server and go to http://localhost:3000/woodpeckers to see your controller in action. h3. Helpers -This section describes how to add a helper named 'WoodpeckersHelper' to your plugin that will behave the same as a helper in your main app. This is very similar to adding a model and a controller. +This section describes how to add a helper named 'WoodpeckersHelper' to your plugin that will behave the same as a helper in your main app. This is very similar to adding a model and a controller. You can test your plugin's helper as you would test any other helper: @@ -707,7 +707,7 @@ class WoodpeckersHelperTest < Test::Unit::TestCase end -This is just a simple test to make sure the helper is being loaded correctly. After watching it fail with +rake+, you can make it pass like so: +This is just a simple test to make sure the helper is being loaded correctly. After watching it fail with +rake+, you can make it pass like so: * *vendor/plugins/yaffle/lib/yaffle.rb:* @@ -736,9 +736,9 @@ Now your test should be passing, and you should be able to use the Woodpeckers h h3. Routes -In a standard 'routes.rb' file you use routes like 'map.connect' or 'map.resources'. You can add your own custom routes from a plugin. This section will describe how to add a custom method called that can be called with 'map.yaffles'. +You can add your own custom routes from a plugin. This section will describe how to add a custom method that can be called with 'map.yaffles'. -Testing routes from plugins is slightly different from testing routes in a standard rails application. To begin, add a test like this: +Testing routes from plugins is slightly different from testing routes in a standard Rails application. To begin, add a test like this: * *vendor/plugins/yaffle/test/routing_test.rb* @@ -802,20 +802,20 @@ You can also see if your routes work by running +rake routes+ from your app dire h3. Generators -Many plugins ship with generators. When you created the plugin above, you specified the +--generator+ option, so you already have the generator stubs in 'vendor/plugins/yaffle/generators/yaffle'. +Many plugins ship with generators. When you created the plugin above, you specified the +--generator+ option, so you already have the generator stubs in 'vendor/plugins/yaffle/generators/yaffle'. Building generators is a complex topic unto itself and this section will cover one small aspect of generators: generating a simple text file. h4. Testing Generators -Many rails plugin authors do not test their generators, however testing generators is quite simple. A typical generator test does the following: +Many rails plugin authors do not test their generators, however testing generators is quite simple. A typical generator test does the following: * Creates a new fake rails root directory that will serve as destination * Runs the generator * Asserts that the correct files were generated * Removes the fake rails root -This section will describe how to create a simple generator that adds a file. For the generator in this section, the test could look something like this: +This section will describe how to create a simple generator that adds a file. For the generator in this section, the test could look something like this: * *vendor/plugins/yaffle/test/definition_generator_test.rb* @@ -854,7 +854,7 @@ class DefinitionGeneratorTest < Test::Unit::TestCase end -You can run 'rake' from the plugin directory to see this fail. Unless you are doing more advanced generator commands it typically suffices to just test the Generate script, and trust that rails will handle the Destroy and Update commands for you. +You can run 'rake' from the plugin directory to see this fail. Unless you are doing more advanced generator commands it typically suffices to just test the Generate script, and trust that rails will handle the Destroy and Update commands for you. To make it pass, create the generator: @@ -872,9 +872,9 @@ end h4. The +USAGE+ File -If you plan to distribute your plugin, developers will expect at least a minimum of documentation. You can add simple documentation to the generator by updating the USAGE file. +If you plan to distribute your plugin, developers will expect at least a minimum of documentation. You can add simple documentation to the generator by updating the USAGE file. -Rails ships with several built-in generators. You can see all of the generators available to you by typing the following at the command line: +Rails ships with several built-in generators. You can see all of the generators available to you by typing the following at the command line: rails generate @@ -899,9 +899,9 @@ Description: h3. Add a Custom Generator Command -You may have noticed above that you can used one of the built-in rails migration commands +migration_template+. If your plugin needs to add and remove lines of text from existing files you will need to write your own generator methods. +You may have noticed above that you can used one of the built-in rails migration commands +migration_template+. If your plugin needs to add and remove lines of text from existing files you will need to write your own generator methods. -This section describes how you you can create your own commands to add and remove a line of text from 'routes.rb'. This example creates a very simple method that adds or removes a text file. +This section describes how you you can create your own commands to add and remove a line of text from 'routes.rb'. This example creates a very simple method that adds or removes a text file. To start, add the following test method: @@ -985,7 +985,7 @@ end h3. Generator Commands -You may have noticed above that you can used one of the built-in rails migration commands +migration_template+. If your plugin needs to add and remove lines of text from existing files you will need to write your own generator methods. +You may have noticed above that you can used one of the built-in rails migration commands +migration_template+. If your plugin needs to add and remove lines of text from existing files you will need to write your own generator methods. This section describes how you you can create your own commands to add and remove a line of text from 'config/routes.rb'. @@ -1125,9 +1125,9 @@ NOTE: If you haven't set up the custom route from above, 'rails destroy' will fa h3. Migrations -If your plugin requires changes to the app's database you will likely want to somehow add migrations. Rails does not include any built-in support for calling migrations from plugins, but you can still make it easy for developers to call migrations from plugins. +If your plugin requires changes to the app's database you will likely want to somehow add migrations. Rails does not include any built-in support for calling migrations from plugins, but you can still make it easy for developers to call migrations from plugins. -If you have a very simple needs, like creating a table that will always have the same name and columns, then you can use a more simple solution, like creating a custom rake task or method. If your migration needs user input to supply table names or other options, you probably want to opt for generating a migration. +If you have a very simple needs, like creating a table that will always have the same name and columns, then you can use a more simple solution, like creating a custom rake task or method. If your migration needs user input to supply table names or other options, you probably want to opt for generating a migration. Let's say you have the following migration in your plugin: @@ -1199,12 +1199,12 @@ NOTE: several plugin frameworks such as Desert and Engines provide more advanced h4. Generate Migrations -Generating migrations has several advantages over other methods. Namely, you can allow other developers to more easily customize the migration. The flow looks like this: +Generating migrations has several advantages over other methods. Namely, you can allow other developers to more easily customize the migration. The flow looks like this: * call your rails generate script and pass in whatever options they need * examine the generated migration, adding/removing columns or other options as necessary -This example will demonstrate how to use one of the built-in generator methods named 'migration_template' to create a migration file. Extending the rails migration generator requires a somewhat intimate knowledge of the migration generator internals, so it's best to write a test first: +This example will demonstrate how to use one of the built-in generator methods named 'migration_template' to create a migration file. Extending the rails migration generator requires a somewhat intimate knowledge of the migration generator internals, so it's best to write a test first: * *vendor/plugins/yaffle/test/yaffle_migration_generator_test.rb* @@ -1254,7 +1254,7 @@ class MigrationGeneratorTest < Test::Unit::TestCase end -NOTE: the migration generator checks to see if a migation already exists, and it's hard-coded to check the 'db/migrate' directory. As a result, if your test tries to generate a migration that already exists in the app, it will fail. The easy workaround is to make sure that the name you generate in your test is very unlikely to actually appear in the app. +NOTE: The migration generator checks to see if a migration already exists, and it's hard-coded to check the +db/migrate+ directory. As a result, if your test tries to generate a migration that already exists in the app, it will fail. The easy workaround is to make sure that the name you generate in your test is very unlikely to actually appear in the app. After running the test with 'rake' you can make it pass with: @@ -1288,9 +1288,9 @@ class YaffleMigrationGenerator < Rails::Generator::NamedBase end -The generator creates a new file in 'db/migrate' with a timestamp and an 'add_column' statement. It reuses the built-in rails +migration_template+ method, and reuses the built-in rails migration template. +The generator creates a new file in 'db/migrate' with a timestamp and an 'add_column' statement. It reuses the built-in Rails +migration_template+ method, and reuses the built-in rails migration template. -It's courteous to check to see if table names are being pluralized whenever you create a generator that needs to be aware of table names. This way people using your generator won't have to manually change the generated files if they've turned pluralization off. +It's courteous to check to see if table names are being pluralized whenever you create a generator that needs to be aware of table names. This way people using your generator won't have to manually change the generated files if they've turned pluralization off. To run the generator, type the following at the command line: @@ -1314,9 +1314,9 @@ class AddYaffleFieldsToBirds < ActiveRecord::Migration end -h3. Rake tasks +h3. Rake Tasks -When you created the plugin with the built-in rails generator, it generated a rake file for you in 'vendor/plugins/yaffle/tasks/yaffle_tasks.rake'. Any rake task you add here will be available to the app. +When you created the plugin with the built-in rails generator, it generated a rake file for you in 'vendor/plugins/yaffle/tasks/yaffle_tasks.rake'. Any rake task you add here will be available to the app. Many plugin authors put all of their rake tasks into a common namespace that is the same as the plugin, like so: @@ -1343,11 +1343,11 @@ Note that tasks from +vendor/plugins/yaffle/Rakefile+ are not available to the m h3. Plugins as Gems -Turning your rails plugin into a gem is a simple and straightforward task. This section will cover how to turn your plugin into a gem. It will not cover how to distribute that gem. +Turning your rails plugin into a gem is a simple and straightforward task. This section will cover how to turn your plugin into a gem. It will not cover how to distribute that gem. Rails 3 ignores both init.rb and rails/init.rb file of a gem. Also, the name of the plugin now is relevant since +config.gem+ tries to load it. Either name the main file after your gem, or document that users should use the +:lib+ option. -It's common practice to put any developer-centric rake tasks (such as tests, rdoc and gem package tasks) in +Rakefile+. A rake task that packages the gem might look like this: +It's common practice to put any developer-centric rake tasks (such as tests, rdoc and gem package tasks) in +Rakefile+. A rake task that packages the gem might look like this: * *vendor/plugins/yaffle/Rakefile:* @@ -1395,14 +1395,14 @@ h3. RDoc Documentation Once your plugin is stable and you are ready to deploy do everyone else a favor and document it! Luckily, writing documentation for your plugin is easy. -The first step is to update the README file with detailed information about how to use your plugin. A few key things to include are: +The first step is to update the README file with detailed information about how to use your plugin. A few key things to include are: * Your name * How to install * How to add the functionality to the app (several examples of common use cases) * Warning, gotchas or tips that might help save users 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 part of 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 part of the public api. Once your comments are good to go, navigate to your plugin directory and run: -- cgit v1.2.3 From f17e1b2f7fd8e09370f3a1ddb3c8526ba71d54c2 Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Sat, 25 Dec 2010 01:04:10 +0530 Subject: clean up plugin references --- railties/guides/source/plugins.textile | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/plugins.textile b/railties/guides/source/plugins.textile index 585bc2ee86..f7c4a6f85c 100644 --- a/railties/guides/source/plugins.textile +++ b/railties/guides/source/plugins.textile @@ -1416,12 +1416,12 @@ If you prefer to use RSpec instead of Test::Unit, you may be interested in the " h4. References -* http://nubyonrails.com/articles/the-complete-guide-to-rails-plugins-part-i -* http://nubyonrails.com/articles/the-complete-guide-to-rails-plugins-part-ii -* http://github.com/technoweenie/attachment_fu/tree/master -* http://daddy.platte.name/2007/05/rails-plugins-keep-initrb-thin.html -* http://www.mbleigh.com/2008/6/11/gemplugins-a-brief-introduction-to-the-future-of-rails-plugins -* http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2. +* "Complete Guide to Rails Plugins - Part 1":http://nubyonrails.com/articles/the-complete-guide-to-rails-plugins-part-i +* "Complete Guide to Rails Plugins - Part 2":http://nubyonrails.com/articles/the-complete-guide-to-rails-plugins-part-ii +* "Attachment_fu Plugin":http://github.com/technoweenie/attachment_fu/tree/master +* "Keeping init.rb thin":http://daddy.platte.name/2007/05/rails-plugins-keep-initrb-thin.html +* "GemPlugins":http://www.mbleigh.com/2008/06/11/gemplugins-a-brief-introduction-to-the-future-of-rails-plugins +* "Extending Routes":http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2 h4. Contents of +lib/yaffle.rb+ -- cgit v1.2.3 From 592f6004e13e7bdd90901acd5147c4ba9573f6db Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Sat, 25 Dec 2010 01:19:33 +0530 Subject: fixed comment in w3c_validator --- railties/guides/w3c_validator.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/w3c_validator.rb b/railties/guides/w3c_validator.rb index da5200c0b7..f1fe1e0f33 100644 --- a/railties/guides/w3c_validator.rb +++ b/railties/guides/w3c_validator.rb @@ -21,7 +21,7 @@ # # Separate many using commas: # -# # validates only +# # validates only association_basics.html and migrations.html # ONLY=assoc,migrations rake validate_guides # # --------------------------------------------------------------------------- @@ -88,4 +88,4 @@ module RailsGuides end end -RailsGuides::Validator.new.validate \ No newline at end of file +RailsGuides::Validator.new.validate -- cgit v1.2.3 From fdfa7dc6480762d2d93166daf556deef1e771331 Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Sat, 25 Dec 2010 01:52:28 +0530 Subject: fixed comment - same as 592f600 --- railties/guides/rails_guides/generator.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/rails_guides/generator.rb b/railties/guides/rails_guides/generator.rb index 0a2170a09e..68d406e31c 100644 --- a/railties/guides/rails_guides/generator.rb +++ b/railties/guides/rails_guides/generator.rb @@ -32,7 +32,7 @@ # # Separate many using commas: # -# # generates only +# # generates only association_basics.html and migrations.html # ONLY=assoc,migrations ruby rails_guides.rb # # Note that if you are working on a guide generation will by default process -- cgit v1.2.3 From b30293f2f654cfe321503520fc7caf31038f9ae3 Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Sat, 25 Dec 2010 22:04:05 +0530 Subject: minor edit --- railties/guides/source/association_basics.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/association_basics.textile b/railties/guides/source/association_basics.textile index 62abc40c81..07d0cf2e6d 100644 --- a/railties/guides/source/association_basics.textile +++ b/railties/guides/source/association_basics.textile @@ -65,7 +65,7 @@ To learn more about the different types of associations, read the next section o h3. The Types of Associations -In Rails, an _association_ is a connection between two Active Record models. Associations are implemented using macro-style calls, so that you can declaratively add features to your models. For example, by declaring that one model +belongs_to+ another, you instruct Rails to maintain Primary Key–Foreign Key information between instances of the two models, and you also get a number of utility methods added to your model. Rails supports six types of association: +In Rails, an _association_ is a connection between two Active Record models. Associations are implemented using macro-style calls, so that you can declaratively add features to your models. For example, by declaring that one model +belongs_to+ another, you instruct Rails to maintain Primary Key–Foreign Key information between instances of the two models, and you also get a number of utility methods added to your model. Rails supports six types of associations: * +belongs_to+ * +has_one+ -- cgit v1.2.3 From 8618ef7537d055dfafd922fee4301e4da4189587 Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Sat, 25 Dec 2010 22:07:31 +0530 Subject: highlighted find(array of keys) behaviour when one or more record is not found --- railties/guides/source/active_record_querying.textile | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/active_record_querying.textile b/railties/guides/source/active_record_querying.textile index 61d8205278..6e45bf3188 100644 --- a/railties/guides/source/active_record_querying.textile +++ b/railties/guides/source/active_record_querying.textile @@ -150,7 +150,7 @@ SQL equivalent of the above is: SELECT * FROM clients WHERE (clients.id IN (1,10)) -Model.find(array_of_primary_key) will raise an +ActiveRecord::RecordNotFound+ exception unless a matching record is found for all of the supplied primary keys. +WARNING: Model.find(array_of_primary_key) will raise an +ActiveRecord::RecordNotFound+ exception unless a matching record is found for all of the supplied primary keys. h4. Retrieving Multiple Objects in Batches @@ -569,9 +569,7 @@ SELECT clients.* FROM clients LEFT OUTER JOIN addresses ON addresses.client_id = h4. Using Array/Hash of Named Associations -WARNING: This method only works with +INNER JOIN+, - -
+WARNING: This method only works with +INNER JOIN+. Active Record lets you use the names of the "associations":association_basics.html defined on the model as a shortcut for specifying +JOIN+ clause for those associations when using the +joins+ method. -- cgit v1.2.3 From c6b9e47d5c59554d13d7dabedb651c7bf69da56b Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Sat, 25 Dec 2010 23:27:15 +0530 Subject: use new routes --- railties/guides/source/performance_testing.textile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/performance_testing.textile b/railties/guides/source/performance_testing.textile index b9401f3559..8cdfaf3e41 100644 --- a/railties/guides/source/performance_testing.textile +++ b/railties/guides/source/performance_testing.textile @@ -60,8 +60,8 @@ Let's assume your application has the following controller and model: # routes.rb -map.root :controller => 'home' -map.resources :posts +root :to => 'home#index' +resources :posts # home_controller.rb class HomeController < ApplicationController -- cgit v1.2.3 From 2801efbc3b3a5c5cf3406aa7063852a86898f547 Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Sat, 25 Dec 2010 23:59:57 +0530 Subject: use all and first instead of find(:all) and find(:first) --- railties/guides/source/action_view_overview.textile | 8 ++++---- railties/guides/source/association_basics.textile | 4 ++-- railties/guides/source/debugging_rails_applications.textile | 6 +++--- railties/guides/source/performance_testing.textile | 2 +- railties/guides/source/security.textile | 10 +++++----- 5 files changed, 15 insertions(+), 15 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/action_view_overview.textile b/railties/guides/source/action_view_overview.textile index 30faeeaa91..ffcc98f41b 100644 --- a/railties/guides/source/action_view_overview.textile +++ b/railties/guides/source/action_view_overview.textile @@ -367,14 +367,14 @@ This helper makes building an ATOM feed easy. Here's a full usage example: *config/routes.rb* -map.resources :posts +resources :posts *app/controllers/posts_controller.rb* def index - @posts = Post.find(:all) + @posts = Post.all respond_to do |format| format.html @@ -809,7 +809,7 @@ end Sample usage (selecting the associated Author for an instance of Post, +@post+): -collection_select(:post, :author_id, Author.find(:all), :id, :name_with_initial, {:prompt => true}) +collection_select(:post, :author_id, Author.all, :id, :name_with_initial, {:prompt => true}) If @post.author_id is already 1, this would return: @@ -910,7 +910,7 @@ Create a select tag and a series of contained option tags for the provided objec Example with @post.person_id => 1: -select("post", "person_id", Person.find(:all).collect {|p| [ p.name, p.id ] }, { :include_blank => true }) +select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, { :include_blank => true }) could become: diff --git a/railties/guides/source/association_basics.textile b/railties/guides/source/association_basics.textile index 07d0cf2e6d..f22f41e8b1 100644 --- a/railties/guides/source/association_basics.textile +++ b/railties/guides/source/association_basics.textile @@ -1135,7 +1135,7 @@ h6(#has_many-collection-find). collection.find(...) The collection.find method finds objects within the collection. It uses the same syntax and options as +ActiveRecord::Base.find+. -@open_orders = @customer.orders.find(:all, :conditions => "open = 1") +@open_orders = @customer.orders.all(:conditions => "open = 1") NOTE: Starting Rails 3, supplying options to +ActiveRecord::Base.find+ method is discouraged. Use collection.where instead when you need to pass conditions. @@ -1564,7 +1564,7 @@ h6(#has_and_belongs_to_many-collection-find). collection.find(...)< The collection.find method finds objects within the collection. It uses the same syntax and options as +ActiveRecord::Base.find+. It also adds the additional condition that the object must be in the collection. -@new_assemblies = @part.assemblies.find(:all, +@new_assemblies = @part.assemblies.all( :conditions => ["created_at > ?", 2.days.ago]) diff --git a/railties/guides/source/debugging_rails_applications.textile b/railties/guides/source/debugging_rails_applications.textile index 2c8a6619c2..b84d7d088d 100644 --- a/railties/guides/source/debugging_rails_applications.textile +++ b/railties/guides/source/debugging_rails_applications.textile @@ -269,7 +269,7 @@ If you got there by a browser request, the browser tab containing the request wi For example: -@posts = Post.find(:all) +@posts = Post.all (rdb:7) @@ -302,7 +302,7 @@ This command shows you where you are in the code by printing 10 lines centered a 3 # GET /posts.xml 4 def index 5 debugger -=> 6 @posts = Post.find(:all) +=> 6 @posts = Post.all 7 8 respond_to do |format| 9 format.html # index.html.erb @@ -380,7 +380,7 @@ Any expression can be evaluated in the current context. To evaluate an expressio This example shows how you can print the instance_variables defined within the current context: -@posts = Post.find(:all) +@posts = Post.all (rdb:11) instance_variables ["@_response", "@action_name", "@url", "@_session", "@_cookies", "@performed_render", "@_flash", "@template", "@_params", "@before_filter_chain_aborted", "@request_origin", "@_headers", "@performed_redirect", "@_request"] diff --git a/railties/guides/source/performance_testing.textile b/railties/guides/source/performance_testing.textile index 8cdfaf3e41..341525a75c 100644 --- a/railties/guides/source/performance_testing.textile +++ b/railties/guides/source/performance_testing.textile @@ -436,7 +436,7 @@ h4. Model Project.benchmark("Creating project") do project = Project.create("name" => "stuff") project.create_manager("name" => "David") - project.milestones << Milestone.find(:all) + project.milestones << Milestone.all end diff --git a/railties/guides/source/security.textile b/railties/guides/source/security.textile index fbafc40d93..7f303c3565 100644 --- a/railties/guides/source/security.textile +++ b/railties/guides/source/security.textile @@ -616,7 +616,7 @@ h5(#sql-injection-introduction). Introduction SQL injection attacks aim at influencing database queries by manipulating web application parameters. A popular goal of SQL injection attacks is to bypass authorization. Another goal is to carry out data manipulation or reading arbitrary data. Here is an example of how not to use user input data in a query: -Project.find(:all, :conditions => "name = '#{params[:name]}'") +Project.all(:conditions => "name = '#{params[:name]}'") This could be in a search action and the user may enter a project's name that he wants to find. If a malicious user enters ' OR 1 --, the resulting SQL query will be: @@ -632,7 +632,7 @@ h5. Bypassing Authorization Usually a web application includes access control. The user enters his login credentials, the web application tries to find the matching record in the users table. The application grants access when it finds a record. However, an attacker may possibly bypass this check with SQL injection. The following shows a typical database query in Rails to find the first record in the users table which matches the login credentials parameters supplied by the user. -User.find(:first, "login = '#{params[:name]}' AND password = '#{params[:password]}'") +User.first("login = '#{params[:name]}' AND password = '#{params[:password]}'") If an attacker enters ' OR '1'='1 as the name, and ' OR '2'>'1 as the password, the resulting SQL query will be: @@ -648,7 +648,7 @@ h5. Unauthorized Reading The UNION statement connects two SQL queries and returns the data in one set. An attacker can use it to read arbitrary data from the database. Let's take the example from above: -Project.find(:all, :conditions => "name = '#{params[:name]}'") +Project.all(:conditions => "name = '#{params[:name]}'") And now let's inject another query using the UNION statement: @@ -675,13 +675,13 @@ Ruby on Rails has a built-in filter for special SQL characters, which will escap Instead of passing a string to the conditions option, you can pass an array to sanitize tainted strings like this: -Model.find(:first, :conditions => ["login = ? AND password = ?", entered_user_name, entered_password]) +Model.first(:conditions => ["login = ? AND password = ?", entered_user_name, entered_password]) As you can see, the first part of the array is an SQL fragment with question marks. The sanitized versions of the variables in the second part of the array replace the question marks. Or you can pass a hash for the same result: -Model.find(:first, :conditions => {:login => entered_user_name, :password => entered_password}) +Model.first(:conditions => {:login => entered_user_name, :password => entered_password}) The array or hash form is only available in model instances. You can try +sanitize_sql()+ elsewhere. _(highlight)Make it a habit to think about the security consequences when using an external string in SQL_. -- cgit v1.2.3 From 9ed385fe1798bd469144c57dbfd89db6781d4ad6 Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Sun, 26 Dec 2010 00:09:08 +0530 Subject: fix formatting --- railties/guides/source/action_view_overview.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/action_view_overview.textile b/railties/guides/source/action_view_overview.textile index ffcc98f41b..e1fc0e7732 100644 --- a/railties/guides/source/action_view_overview.textile +++ b/railties/guides/source/action_view_overview.textile @@ -439,7 +439,7 @@ The +capture+ method allows you to extract part of a template into a variable. Y <% @greeting = capture do %>

Welcome! The date and time is <%= Time.now %>

<% end %> - + The captured variable can then be used anywhere else. -- cgit v1.2.3 From 603e0f155d66e2cab56caa65d007c7ba6c6cf03b Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Sun, 26 Dec 2010 22:10:56 +0530 Subject: use new routes in templates --- railties/guides/source/rails_application_templates.textile | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/rails_application_templates.textile b/railties/guides/source/rails_application_templates.textile index d4b887ad02..ca4f7798a6 100644 --- a/railties/guides/source/rails_application_templates.textile +++ b/railties/guides/source/rails_application_templates.textile @@ -37,7 +37,7 @@ Rails templates API is very self explanatory and easy to understand. Here's an e # template.rb run "rm public/index.html" generate(:scaffold, "person name:string") -route "map.root :controller => 'people'" +route "root :to => 'people#index'" rake("db:migrate") git :init @@ -49,7 +49,7 @@ The following sections outlines the primary methods provided by the API : h4. gem(name, options = {}) -Adds a +config.gem+ entry for the supplied gem to the generated application’s +config/environment.rb+. +Adds a +gem+ entry for the supplied gem to the generated application’s +Gemfile+. For example, if your application depends on the gems +bj+ and +nokogiri+ : @@ -183,7 +183,7 @@ 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 : -route "map.root :controller => :person" +route "root :to => 'person#index'" h4. inside(dir) -- cgit v1.2.3 From e85631849725b74d6ef59e4033ed62ced11e910b Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Sun, 26 Dec 2010 22:57:45 +0530 Subject: changed template gist to reflect Rails 3 and documented the add_source method to source gems from different locations --- railties/guides/source/rails_application_templates.textile | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/rails_application_templates.textile b/railties/guides/source/rails_application_templates.textile index ca4f7798a6..642aed661b 100644 --- a/railties/guides/source/rails_application_templates.textile +++ b/railties/guides/source/rails_application_templates.textile @@ -20,7 +20,7 @@ $ rails new blog -m ~/template.rb It's also possible to apply a template using a URL : -$ rails new blog -m http://gist.github.com/31208.txt +$ rails new blog -m https://gist.github.com/755496.txt Alternatively, you can use the rake task +rails:template+ to apply a template to an existing Rails application : @@ -66,6 +66,16 @@ rake "gems:install" And let Rails take care of installing the required gems if they’re not already installed. +h4. add_source(source, options={}) + +Adds the given source to the generated application's +Gemfile+. + +For example, if you need to source a gem from "http://code.whytheluckystiff.net": + + +add_source "http://code.whytheluckystiff.net" + + h4. plugin(name, options = {}) Installs a plugin to the generated application. -- cgit v1.2.3 From 50a2edbce6a66eeb829eeb072483670b8a9be8d7 Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Sun, 26 Dec 2010 23:00:03 +0530 Subject: fix spacing --- railties/guides/source/rails_application_templates.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/rails_application_templates.textile b/railties/guides/source/rails_application_templates.textile index 642aed661b..8f87b4cd58 100644 --- a/railties/guides/source/rails_application_templates.textile +++ b/railties/guides/source/rails_application_templates.textile @@ -66,7 +66,7 @@ rake "gems:install" And let Rails take care of installing the required gems if they’re not already installed. -h4. add_source(source, options={}) +h4. add_source(source, options = {}) Adds the given source to the generated application's +Gemfile+. -- cgit v1.2.3 From 71775807c195aaa091cca96a8f309d2422e6b351 Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Sun, 26 Dec 2010 21:15:33 +0100 Subject: no docs credits are written in first person, thanks to Vijay Dev for spotting this --- railties/guides/source/credits.html.erb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/credits.html.erb b/railties/guides/source/credits.html.erb index 825e042628..42a993cd71 100644 --- a/railties/guides/source/credits.html.erb +++ b/railties/guides/source/credits.html.erb @@ -52,7 +52,7 @@ Ruby on Rails Guides: Credits <% end %> <%= author('James Miller', 'bensie') do %> - James Miller is a software developer for JK Tech in San Diego, CA. Find me on GitHub, Gmail, Twitter, and Freenode as "bensie". + James Miller is a software developer for JK Tech in San Diego, CA. You can find James on GitHub, Gmail, Twitter, and Freenode as "bensie". <% end %> <%= author('Emilio Tagua', 'miloops') do %> -- cgit v1.2.3 From 57420dffb6663e31c12729ab3348cf824bfcff6a Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Sun, 26 Dec 2010 21:27:00 +0100 Subject: small rewording of my entry in the credits --- railties/guides/source/credits.html.erb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/credits.html.erb b/railties/guides/source/credits.html.erb index 42a993cd71..8c2f1ffeb6 100644 --- a/railties/guides/source/credits.html.erb +++ b/railties/guides/source/credits.html.erb @@ -20,7 +20,7 @@ Ruby on Rails Guides: Credits <% end %> <%= author('Xavier Noria', 'fxn', 'fxn.png') do %> - Xavier has been into Rails since 2005, he is currently a Rails consultant. Xavier is Rails committer and enjoys combining his passion for Rails and his past life as a proofreader of math textbooks. Oh, he also tweets and can be found everywhere as "fxn". + Xavier Noria has been into Ruby on Rails since 2005. He is a Rails committer and enjoys combining his passion for Rails and his past life as a proofreader of math textbooks. Xavier is currently a Ruby on Rails consultant. Oh, he also tweets and can be found everywhere as "fxn". <% end %>

Rails Guides Designers

-- cgit v1.2.3 From a78e5bcfe4672e412ed1de014a27f0ab40e8cc74 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Mon, 27 Dec 2010 13:01:08 +1000 Subject: Init guide: Cover the config variable set up which is referenced in i18n_railtie --- railties/guides/source/initialization.textile | 14 ++++++++++++++ 1 file changed, 14 insertions(+) (limited to 'railties/guides') diff --git a/railties/guides/source/initialization.textile b/railties/guides/source/initialization.textile index 1504b973a5..ad3a4ffa44 100644 --- a/railties/guides/source/initialization.textile +++ b/railties/guides/source/initialization.textile @@ -715,7 +715,21 @@ This file is the first file that sets up configuration with these lines inside t config.i18n.fallbacks = ActiveSupport::OrderedOptions.new +The +config+ method here is defined on +Rails::Railtie+ and is defined like this: + + def config + @config ||= Railtie::Configuration.new + end + + +At this point, that +Railtie::Configuration+ constant is automatically loaded which causes the +rails/railties/configuration+ file to be loaded. + +h4. +railties/lib/rails/railties/configuration.rb+ + +This file begins with a require out to +rails/configuration+ which has already been required earlier in the process and so isn't required again. + +This file defines the +Rails::Railties::Configuration+ class which is responsible for providing a way to easily configure railties. **** REVIEW IS HERE **** -- cgit v1.2.3 From 62dd85cc837f49731f4a4cd470cddb7a55609118 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Mon, 27 Dec 2010 19:14:44 +1000 Subject: Init guide: cover Railtie::Configuration and begin to cover the Initializer class and friends. --- railties/guides/source/initialization.textile | 77 +++++++++++++++++++++++++-- 1 file changed, 73 insertions(+), 4 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/initialization.textile b/railties/guides/source/initialization.textile index ad3a4ffa44..5b09406ea5 100644 --- a/railties/guides/source/initialization.textile +++ b/railties/guides/source/initialization.textile @@ -661,7 +661,7 @@ The +methods.rb+ file is responsible for defining methods such as +camelize+, +u h4. Back to +railties/lib/rails/railtie.rb+ -Once the inflector files have been loaded, the +Rails::Railtie+ class is defined. This class includes a module called +Initializable+, which is actually +Rails::Initializable+ and is automatically loaded at this point. +Once the inflector files have been loaded, the +Rails::Railtie+ class is defined. This class includes a module called +Initializable+, which is actually +Rails::Initializable+. This module includes the +initializer+ method which is used later on for setting up initializers, amongst other methods. h4. +railties/lib/rails/initializable.rb+ @@ -723,14 +723,83 @@ The +config+ method here is defined on +Rails::Railtie+ and is defined like this end -At this point, that +Railtie::Configuration+ constant is automatically loaded which causes the +rails/railties/configuration+ file to be loaded. +At this point, that +Railtie::Configuration+ constant is automatically loaded which causes the +rails/railties/configuration+ file to be loaded. The line for this is this particular line in +railties/lib/rails/railtie.rb+: -h4. +railties/lib/rails/railties/configuration.rb+ + + autoload :Configuration, "rails/railtie/configuration" + + +h4. +railties/lib/rails/railtie/configuration.rb+ This file begins with a require out to +rails/configuration+ which has already been required earlier in the process and so isn't required again. -This file defines the +Rails::Railties::Configuration+ class which is responsible for providing a way to easily configure railties. +This file defines the +Rails::Railtie::Configuration+ class which is responsible for providing a way to easily configure railties and it's the +initialize+ method here which is called by the +config+ method back in the +i18n_railtie.rb+ file. The methods on this object don't exist, and so are rescued by the +method_missing+ defined further down in +configuration.rb+: + + + def method_missing(name, *args, &blk) + if name.to_s =~ /=$/ + @@options[$`.to_sym] = args.first + elsif @@options.key?(name) + @@options[name] + else + super + end + end + + +So therefore when an option is referred to it simply stores the value as the key if it's used in a setter context, or retrieves it if used in a getter context. Nothing fancy going on there. + +h4. Back to +activesupport/lib/active_support/i18n_railtie.rb+ + +After the configuration method the +reloader+ method is defined, and then the first of of Railties' initializers is defined: +i18n.callbacks+. + + + initializer "i18n.callbacks" do + ActionDispatch::Reloader.to_prepare do + I18n::Railtie.reloader.execute_if_updated + end + end + + +The +initializer+ method (from the +Rails::Initializable+ module) here doesn't run the block, but rather stores it to be run later on: + + + def initializer(name, opts = {}, &blk) + raise ArgumentError, "A block must be passed when defining an initializer" unless blk + opts[:after] ||= initializers.last.name unless initializers.empty? || initializers.find { |i| i.name == opts[:before] } + initializers << Initializer.new(name, nil, opts, &blk) + end + + +An initializer can be configured to run before or after another initializer, which we'll see a couple of times throughout this initialization process. Anything that inherits from +Rails::Railtie+ may also make use of the +initializer+ method, something which is covered in the "Configuration guide":[http://ryanbigg.com/guides/configuring.html#rails-railtie-initializer]. + +The +Initializer+ class here is defined within the +Rails::Initializable+ module and its +initialize+ method is defined to just set up a couple of variables: + + + def initialize(name, context, options, &block) + @name, @context, @options, @block = name, context, options, block + end + + +Once this +initialize+ method is finished, the object is added to the object the +initializers+ method returns: + + + def initializers + @initializers ||= self.class.initializers_for(self) + end + + +If +@initializers+ isn't set (which it won't be at this point), the +intializers_for+ method will be called for this class. + + + def initializers_for(binding) + Collection.new(initializers_chain.map { |i| i.bind(binding) }) + end + + +The +Collection+ class in +railties/lib/rails/initializable.rb+ inherits from +Array+ and includes the +TSort+ module which is used to sort out the order of the initializers based on the order they are placed in. +The +initializers_chain+ method referenced in the +initializers_for+ method is defined like this: **** REVIEW IS HERE **** -- cgit v1.2.3 From 01febdadea36e91f91e167426ce5ef6dd0d03943 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Tue, 28 Dec 2010 13:22:28 +1000 Subject: init guide: active_support/inflector/methods is loaded by active_support/autoload first. --- railties/guides/source/initialization.textile | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/initialization.textile b/railties/guides/source/initialization.textile index 5b09406ea5..72f1ca8f5d 100644 --- a/railties/guides/source/initialization.textile +++ b/railties/guides/source/initialization.textile @@ -224,7 +224,17 @@ Action Dispatch is the routing component of the Rails framework. It depends on A h4. +activesupport/lib/active_support.rb+ -This file begins with requiring +active_support/lib/active_support/dependencies/autoload.rb+ which redefines Ruby's +autoload+ method to have a little more extra behaviour especially in regards to eager autoloading. Eager autoloading is the loading of all required classes and will happen when the +config.cache_classes+ setting is +true+. +This file begins with requiring +active_support/lib/active_support/dependencies/autoload.rb+ which redefines Ruby's +autoload+ method to have a little more extra behaviour especially in regards to eager autoloading. Eager autoloading is the loading of all required classes and will happen when the +config.cache_classes+ setting is +true+. The required file also requires another file: +active_support/lazy_load_hooks+ + +h4. +activesupport/lib/active_support/lazy_load_hooks.rb+ + +This file defines the +ActiveSupport.on_load+ hook which is used to execute code when specific parts are loaded. We'll see this in use a little later on. + +This file begins with requiring +active_support/inflector/methods+. + +h4. +activesupport/lib/active_support/inflector/methods.rb+ + +The +methods.rb+ file is responsible for defining methods such as +camelize+, +underscore+ and +dasherize+ as well as a slew of others. The "+ActiveSupport::Inflector+ documentation":http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html covers them all pretty decently. In this file there are a lot of lines such as this inside the +ActiveSupport+ module: @@ -647,6 +657,8 @@ h4. +activesupport/lib/active_support/inflector.rb+ require 'active_support/core_ext/string/inflections' +The +active_support/inflector/methods+ file has already been required by +active_support/autoload+ and so won't be loaded again here. + h4. +activesupport/lib/active_support/inflector/inflections.rb+ This file references the +ActiveSupport::Inflector+ constant which isn't loaded by this point. But there were autoloads set up in +activesupport/lib/active_support.rb+ which will load the file which loads this constant and so then it will be defined. Then this file defines pluralization and singularization rules for words in Rails. This is how Rails knows how to pluralize "tomato" to "tomatoes". @@ -655,10 +667,6 @@ h4. +activesupport/lib/active_support/inflector/transliterate.rb+ In this file is where the "+transliterate+":http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-transliterate and +parameterize+:http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-parameterize methods are defined. The documentation for both of these methods is very much worth reading. -h4. +activesupport/lib/active_support/inflector/methods.rb+ - -The +methods.rb+ file is responsible for defining methods such as +camelize+, +underscore+ and +dasherize+ as well as a slew of others. The "+ActiveSupport::Inflector+ documentation":http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html covers them all pretty decently. - h4. Back to +railties/lib/rails/railtie.rb+ Once the inflector files have been loaded, the +Rails::Railtie+ class is defined. This class includes a module called +Initializable+, which is actually +Rails::Initializable+. This module includes the +initializer+ method which is used later on for setting up initializers, amongst other methods. -- cgit v1.2.3 From 2f57353023705917369ad417080757c0f2b71885 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Tue, 28 Dec 2010 13:23:50 +1000 Subject: Init guide: finish covering initializers for i18n_railtie, moving on to covering after_initialize --- railties/guides/source/initialization.textile | 41 +++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) (limited to 'railties/guides') diff --git a/railties/guides/source/initialization.textile b/railties/guides/source/initialization.textile index 72f1ca8f5d..5013d9d7ec 100644 --- a/railties/guides/source/initialization.textile +++ b/railties/guides/source/initialization.textile @@ -809,6 +809,47 @@ 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: + + def initializers_chain + initializers = Collection.new + ancestors.reverse_each do | klass | + next unless klass.respond_to?(:initializers) + initializers = initializers + klass.initializers + end + initializers + end + + +This method collects the initializers from the ancestors of this class and adds them to a new +Collection+ object using the + method which is defined like this for the Collection class: + + + def +(other) + Collection.new(to_a + other.to_a) + end + + +So this + method is overriden to return a new collection comprising of the existing collection as an array and then using the Array#+ method combines these two collections, returning a "super" +Collection+ object. In this case, the only initializer that's going to be in this new +Collection+ object is the +i18n.callbacks+ initializer. + +The next method to be called after this +initializer+ method is the +after_initialize+ method on the +config+ object, which is defined like this: + + + def after_initialize(&block) + ActiveSupport.on_load(:after_initialize, :yield => true, &block) + end + + +The +on_load+ method here is provided by the +active_support/lazy_load_hooks+ file which was required earlier and is defined like this: + + + def self.on_load(name, options = {}, &block) + if base = @loaded[name] + execute_hook(base, options, block) + else + @load_hooks[name] << [block, options] + end + end + + **** REVIEW IS HERE **** This defines two methods on the module itself by using the familiar +class << self+ syntax. This allows you to call them as if they were class methods: +ActiveSupport.on_load_all+ and +ActiveSupport.load_all!+ respectively. The first method simply adds loading hooks to save them up for loading later on when +load_all!+ is called. By +call+'ing the block, the classes will be loaded. (NOTE: kind of guessing, I feel 55% about this). -- cgit v1.2.3 From 7b7537317c02c37c894fc65ff1b685d9d247e87a Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Tue, 28 Dec 2010 14:04:02 +1000 Subject: init guide: active_support/railtie does not require itself, actually requires i18n_railtie --- railties/guides/source/initialization.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/initialization.textile b/railties/guides/source/initialization.textile index 5013d9d7ec..ceee4639a2 100644 --- a/railties/guides/source/initialization.textile +++ b/railties/guides/source/initialization.textile @@ -709,7 +709,7 @@ Much like +active_support/version+, this file defines the +VERSION+ constant whi h4. +activesupport/lib/active_support/railtie.rb+ -This file requires +active_support+ and +rails+ which have already been required so these two lines are effectively ignored. The third require in this file is to +active_support/railtie+. +This file requires +active_support+ and +rails+ which have already been required so these two lines are effectively ignored. The third require in this file is to +active_support/i18n_railtie.rb+. h4. +activesupport/lib/active_support/i18n_railtie.rb+ -- cgit v1.2.3 From 6777b7a886440a1faa9e29fcfa57a73a28128f68 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Tue, 28 Dec 2010 14:04:19 +1000 Subject: Init guide: finish covering the process of the i18n_railtie.rb file. --- railties/guides/source/initialization.textile | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) (limited to 'railties/guides') diff --git a/railties/guides/source/initialization.textile b/railties/guides/source/initialization.textile index ceee4639a2..738d5cf71a 100644 --- a/railties/guides/source/initialization.textile +++ b/railties/guides/source/initialization.textile @@ -850,6 +850,26 @@ The +on_load+ method here is provided by the +active_support/lazy_load_hooks+ fi end +The +@loaded+ variable here is a hash containing elements representing the different components of Rails that have been loaded at this stage. Currently, this hash is empty. So the +else+ is executed here, using the +@load_hooks+ variable defined in +active_support/lazy_load_hooks+: + + + @load_hooks = Hash.new {|h,k| h[k] = [] } + + +This defines a new hash which has keys that default to empty arrays. This saves Rails from having to do something like this instead: + + + @load_hooks[name] = [] + @load_hooks[name] << [block, options] + + +The value added to this array here consists of the block and options passed to +after_initialize+. + +We'll see these +@load_hooks+ used later on in the initialization process. + +This rest of +i18n_railtie.rb+ defines the protected class methods +include_fallback_modules+, +init_fallbacks+ and +validate_fallbacks+. + + **** REVIEW IS HERE **** This defines two methods on the module itself by using the familiar +class << self+ syntax. This allows you to call them as if they were class methods: +ActiveSupport.on_load_all+ and +ActiveSupport.load_all!+ respectively. The first method simply adds loading hooks to save them up for loading later on when +load_all!+ is called. By +call+'ing the block, the classes will be loaded. (NOTE: kind of guessing, I feel 55% about this). -- cgit v1.2.3 From 0dd5433b98afb0411449a4fd45dd0f918126c4ec Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Tue, 28 Dec 2010 14:13:43 +1000 Subject: Cover the inherited method from Rails::Railtie being used when I18n::Railtie is loaded. --- railties/guides/source/initialization.textile | 34 ++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/initialization.textile b/railties/guides/source/initialization.textile index 738d5cf71a..10937626af 100644 --- a/railties/guides/source/initialization.textile +++ b/railties/guides/source/initialization.textile @@ -723,7 +723,39 @@ This file is the first file that sets up configuration with these lines inside t config.i18n.fallbacks = ActiveSupport::OrderedOptions.new -The +config+ method here is defined on +Rails::Railtie+ and is defined like this: +By inheriting from +Rails::Railtie+ the +Rails::Railtie#inherited+ method is called: + + + def inherited(base) + unless base.abstract_railtie? + base.send(:include, Railtie::Configurable) + subclasses << base + end + end + + +This first checks if the Railtie that's inheriting it is a component of Rails itself: + + +ABSTRACT_RAILTIES = %w(Rails::Railtie Rails::Plugin Rails::Engine Rails::Application) + +... + +def abstract_railtie? + ABSTRACT_RAILTIES.include?(name) +end + + +Because +I18n::Railtie+ isn't in this list, +abstract_railtie?+ returns +false+. Therefore the +Railtie::Configurable+ module is included into this class and the +subclasses+ method is called and +I18n::Railtie+ is added to this new array. + + +def subclasses + @subclasses ||= [] +end + + + +The +config+ method used at the top of +I18n::Railtie+ is defined on +Rails::Railtie+ and is defined like this: def config -- cgit v1.2.3 From 61e6a9f9d45e4c015ad10e44c9cb846ac4bb971f Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Tue, 28 Dec 2010 14:19:05 +1000 Subject: Init guide: Segue between rails/version and active_support/railtie requires --- railties/guides/source/initialization.textile | 2 ++ 1 file changed, 2 insertions(+) (limited to 'railties/guides') diff --git a/railties/guides/source/initialization.textile b/railties/guides/source/initialization.textile index 10937626af..868db6d33b 100644 --- a/railties/guides/source/initialization.textile +++ b/railties/guides/source/initialization.textile @@ -707,6 +707,8 @@ h4. +railties/lib/rails/version.rb+ Much like +active_support/version+, this file defines the +VERSION+ constant which has a +STRING+ constant on it which returns the current version of Rails. +Once this file has finished loading we go back to +railties/lib/rails.rb+ which then requires +active_support/railtie.rb+. + h4. +activesupport/lib/active_support/railtie.rb+ This file requires +active_support+ and +rails+ which have already been required so these two lines are effectively ignored. The third require in this file is to +active_support/i18n_railtie.rb+. -- cgit v1.2.3 From 5196333d6c3288c3fba414d5aa303fe5cbe91175 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Tue, 28 Dec 2010 14:19:49 +1000 Subject: init guide: cover active_support/railtie.rb --- railties/guides/source/initialization.textile | 12 ++++++++++++ 1 file changed, 12 insertions(+) (limited to 'railties/guides') diff --git a/railties/guides/source/initialization.textile b/railties/guides/source/initialization.textile index 868db6d33b..04c3cc28ed 100644 --- a/railties/guides/source/initialization.textile +++ b/railties/guides/source/initialization.textile @@ -903,6 +903,18 @@ We'll see these +@load_hooks+ used later on in the initialization process. This rest of +i18n_railtie.rb+ defines the protected class methods +include_fallback_modules+, +init_fallbacks+ and +validate_fallbacks+. +h4. Back to +activesupport/lib/active_support/railtie.rb+ + +This file defines the +ActiveSupport::Railtie+ constant which like the +I18n::Railtie+ constant just defined, inherits from +Rails::Railtie+ meaning the +inherited+ method would be called again here, including +Rails::Configurable+ into this class. This class makes use of +Rails::Railtie+'s +config+ method again, setting up the configuration options for Active Support. + +Then this Railtie sets up three more initializers: + +* +active_support.initialize_whiny_nils+ +* +active_support.deprecation_behavior+ +* +active_support.initialize_time_zone+ + +We will cover what each of these initializers do when they run. + **** REVIEW IS HERE **** -- cgit v1.2.3 From 02bb7e9b9865d0236fe43211b01cfb9667b8a0c9 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Tue, 28 Dec 2010 14:22:42 +1000 Subject: Remove old initialization guide text. Too much has changed for all of this to be useful. --- railties/guides/source/initialization.textile | 3549 ------------------------- 1 file changed, 3549 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/initialization.textile b/railties/guides/source/initialization.textile index 04c3cc28ed..ca1451faa6 100644 --- a/railties/guides/source/initialization.textile +++ b/railties/guides/source/initialization.textile @@ -914,3552 +914,3 @@ Then this Railtie sets up three more initializers: * +active_support.initialize_time_zone+ We will cover what each of these initializers do when they run. - - -**** REVIEW IS HERE **** - -This defines two methods on the module itself by using the familiar +class << self+ syntax. This allows you to call them as if they were class methods: +ActiveSupport.on_load_all+ and +ActiveSupport.load_all!+ respectively. The first method simply adds loading hooks to save them up for loading later on when +load_all!+ is called. By +call+'ing the block, the classes will be loaded. (NOTE: kind of guessing, I feel 55% about this). - -The +on_load_all+ method is called later with the +Dependencies+, +Deprecation+, +Gzip+, +MessageVerifier+, +Multibyte+ and +SecureRandom+. What each of these modules do will be covered later. - -This file goes on to define some classes that will be automatically loaded using Ruby's +autoload+ method, but not before including Rails's own variant of the +autoload+ method from _active_support/dependencies/autoload.rb_: - - - - require "active_support/inflector/methods" - require "active_support/lazy_load_hooks" - - module ActiveSupport - module Autoload - def self.extended(base) - base.extend(LazyLoadHooks) - end - - @@autoloads = {} - @@under_path = nil - @@at_path = nil - @@eager_autoload = false - - def autoload(const_name, path = @@at_path) - full = [self.name, @@under_path, const_name.to_s, path].compact.join("::") - location = path || Inflector.underscore(full) - - if @@eager_autoload - @@autoloads[const_name] = location - end - super const_name, location - end - - ... - end - end - - -h4. Lazy Hooks - -+ActiveSupport::LazyLoadHooks+ is responsible for defining methods used for running hooks that are defined during the initialization process, such as the one defined inside the +active_record.initialize_timezone+ initializer: - - - initializer "active_record.initialize_timezone" do - ActiveSupport.on_load(:active_record) do - self.time_zone_aware_attributes = true - self.default_timezone = :utc - end - end - - -When the initializer runs it invokes method +on_load+ for +ActiveRecord+ and the block passed to it would be called only when +run_load_hooks+ is called. -When the entirety of +activerecord/lib/active_record/base.rb+ has been evaluated then +run_load_hooks+ is invoked. The very last line of +activerecord/lib/active_record/base.rb+ is: - - -ActiveSupport.run_load_hooks(:active_record, ActiveRecord::Base) - - -h4. +require 'active_support'+ cont'd. - -This file also uses the method +eager_autoload+ also defined in _active_support/dependencies/autoload.rb_: - - - def eager_autoload - old_eager, @@eager_autoload = @@eager_autoload, true - yield - ensure - @@eager_autoload = old_eager - end - - -As you can see for the duration of the +eager_autoload+ block the class variable +@@eager_autoload+ is set to +true+, which has the consequence of when +autoload+ is called that the location of the file for that specific +autoload+'d constant is added to the +@@autoloads+ hash initialized at the beginning of this module declaration. So now that you have part of the context, here's the other, the code from _activesupport/lib/active_support.rb_: - - - require "active_support/dependencies/autoload" - - module ActiveSupport - extend ActiveSupport::Autoload - - autoload :DescendantsTracker - autoload :FileUpdateChecker - autoload :LogSubscriber - autoload :Notifications - - # TODO: Narrow this list down - eager_autoload do - autoload :BacktraceCleaner - autoload :Base64 - autoload :BasicObject - autoload :Benchmarkable - autoload :BufferedLogger - autoload :Cache - autoload :Callbacks - autoload :Concern - autoload :Configurable - autoload :Deprecation - autoload :Gzip - autoload :Inflector - autoload :JSON - autoload :Memoizable - autoload :MessageEncryptor - autoload :MessageVerifier - autoload :Multibyte - autoload :OptionMerger - autoload :OrderedHash - autoload :OrderedOptions - autoload :Rescuable - autoload :SecureRandom - autoload :StringInquirer - autoload :XmlMini - end - - autoload :SafeBuffer, "active_support/core_ext/string/output_safety" - autoload :TestCase - end - - autoload :I18n, "active_support/i18n" - - -So we know the ones in +eager_autoload+ are eagerly loaded and it does this by storing them in an +@@autoloads+ hash object and then loading them via +eager_autoload!+ which is called via the +preload_frameworks+ initializer defined in _railties/lib/rails/application/bootstrap.rb_. - -The classes and modules that are not +eager_autoload+'d are automatically loaded as they are references - -Note: What does it means to be autoloaded? An example of this would be calling the +ActiveSupport::TestCase+ class which hasn't yet been initialized. Because it's been specified as an +autoload+ Ruby will require the file that it's told to. The file it requires is not defined in the +autoload+ call here but, as you may have seen, in the +ActiveSupport::Autoload.autoload+ definition. So once that file has been required Ruby will try again and then if it still can't find it it will throw the all-too-familiar +uninitialized constant+ error. - -h4. +require 'action_dispatch'+ - -Back in _actionpack/lib/action_dispatch.rb_, the next require after _active_support_ is to _active_support/dependencies/autoload_ but this file has already been loaded by _activesupport/lib/active_support.rb_ and so will not be loaded again. The next require is to Rack itself: - - - require 'rack' - - -As mentioned previously, Bundler has added the gems' _lib_ directories to the load path so this _rack_ file that is referenced lives in the Rack gem: _lib/rack.rb_. This loads Rack so we can use it later on when we define +Rails::Server+ to descend from +Rack::Server+. - -This file then goes on to define the +ActionDispatch+ module and it's related autoloads: - - - module Rack - autoload :Test, 'rack/test' - end - - module ActionDispatch - extend ActiveSupport::Autoload - - autoload_under 'http' do - autoload :Request - autoload :Response - end - - autoload_under 'middleware' do - autoload :Callbacks - autoload :Cascade - autoload :Cookies - autoload :Flash - autoload :Head - autoload :ParamsParser - autoload :RemoteIp - autoload :Rescue - autoload :ShowExceptions - autoload :Static - end - - autoload :MiddlewareStack, 'action_dispatch/middleware/stack' - autoload :Routing - - module Http - extend ActiveSupport::Autoload - - autoload :Cache - autoload :Headers - autoload :MimeNegotiation - autoload :Parameters - autoload :FilterParameters - autoload :Upload - autoload :UploadedFile, 'action_dispatch/http/upload' - autoload :URL - end - - module Session - autoload :AbstractStore, 'action_dispatch/middleware/session/abstract_store' - autoload :CookieStore, 'action_dispatch/middleware/session/cookie_store' - autoload :MemCacheStore, 'action_dispatch/middleware/session/mem_cache_store' - end - - autoload_under 'testing' do - autoload :Assertions - autoload :Integration - autoload :PerformanceTest - autoload :TestProcess - autoload :TestRequest - autoload :TestResponse - end - end - - autoload :Mime, 'action_dispatch/http/mime_type' - - -h4. +require "rails/commands/server"+ - -Now that Rails has required Action Dispatch and it has required Rack, Rails can now go about defining the +Rails::Server+ class: - - - module Rails - class Server < ::Rack::Server - - ... - - def initialize(*) - super - set_environment - end - - ... - - def set_environment - ENV["RAILS_ENV"] ||= options[:environment] - end - ... - end - end - - -h4. +require "rails/commands"+ - -Back in _rails/commands_ Rails calls +Rails::Server.new+ which calls the +initialize+ method on the +Rails::Server+ class, which calls +super+, meaning it's actually calling +Rack::Server#initialize+, with it being defined like this: - - - def initialize(options = nil) - @options = options - end - - -The +options+ method like this: - - - def options - @options ||= parse_options(ARGV) - end - - -The +parse_options+ method like this: - - - def parse_options(args) - options = default_options - - # Don't evaluate CGI ISINDEX parameters. - # http://hoohoo.ncsa.uiuc.edu/cgi/cl.html - args.clear if ENV.include?("REQUEST_METHOD") - - options.merge! opt_parser.parse! args - options - end - - -And +default_options+ like this: - - - def default_options - { - :environment => "development", - :pid => nil, - :Port => 9292, - :Host => "0.0.0.0", - :AccessLog => [], - :config => "config.ru" - } - end - - -Here it is important to note that the default environment is _development_. After +Rack::Server#initialize+ has done its thing it returns to +Rails::Server#initialize+ which calls +set_environment+: - - - def set_environment - ENV["RAILS_ENV"] ||= options[:environment] - end - - -From the information given we can determine that +ENV["RAILS_ENV"]+ will be set to _development_ if no other environment is specified. - -Finally, after +Rails::Server.new+ has executed, there is one more require: - - - require APP_PATH - - -+APP_PATH+ was previously defined as _config/application.rb_ in the application's root, and so that is where Rails will go next. - -h4. +require APP_PATH+ - -This file is _config/application.rb_ in your application and makes two requires to begin with: - - - require File.expand_path('../boot', __FILE__) - require 'rails/all' - - -The +../boot+ file it references is +config/boot.rb+, which was loaded earlier in the initialization process and so will not be loaded again. - -If you generate the application with the +-O+ option this will put a couple of pick-and-choose requirements at the top of your _config/application.rb_ instead: - - - # Pick the frameworks you want: - # require "active_record/railtie" - require "action_controller/railtie" - require "action_mailer/railtie" - require "active_resource/railtie" - require "rails/test_unit/railtie" - - -For the purposes of this guide, will will assume only: - - - require 'rails/all' - - -h4. +require "rails/all"+ - -Now we'll dive into the internals of the pre-initialization stage of Rails. The file that is being required is _railties/lib/rails/all.rb_. The first line in this file is: - - - require 'rails' - - -h4. +require 'rails'+ - -This file (_railties/lib/rails.rb_) requires the very, very basics that Rails needs to get going. I'm not going to delve into these areas yet, just cover them briefly for now. Later on we will go through the ones that are important to the boot procedure. - - - require 'pathname' - - require 'active_support' - require 'active_support/core_ext/kernel/reporting' - require 'active_support/core_ext/logger' - - require 'rails/application' - require 'rails/version' - require 'rails/deprecation' - require 'rails/log_subscriber' - require 'rails/ruby_version_check' - - require 'active_support/railtie' - require 'action_dispatch/railtie' - - -+require 'pathname'+ requires the Pathname class which is used for returning a Pathname object for +Rails.root+. Although is coming to use this path name to generate paths as below: - - - Rails.root.join("app/controllers") - - -Pathname can also be converted to string, so the following syntax is preferred: - - - "#{Rails.root}/app/controllers" - - - -This works because Ruby automatically handles file path conversions. Although this is not new to Rails 3 (it was available in 2.3.5), it is something worthwhile pointing out. - -Inside this file there are other helpful helper methods defined, such as +Rails.root+, +Rails.env+, +Rails.logger+ and +Rails.application+. - -The first require: - - - require 'active_support' - - -Is not ran as this was already required by _actionpack/lib/action_dispatch.rb_. - - -h4. +require 'active_support/core_ext/kernel/reporting'+ - -This file extends the +Kernel+ module, providing the methods +silence_warnings+, +enable_warnings+, +with_warnings+, +silence_stderr+, +silence_stream+ and +suppress+. The API documentation on these overridden methods is fairly good and if you wish to know more "have a read.":http://api.rubyonrails.org/classes/Kernel.html - -For information on this file see the "Core Extensions" guide. TODO: link to guide. - -h4. +require 'active_support/core_ext/logger'+ - -For information on this file see the "Core Extensions" guide. TODO: link to guide. - -h4. +require 'rails/application'+ - -Here's where +Rails::Application+ is defined. This is the superclass of +YourApp::Application+ from _config/application.rb_ and the subclass of +Rails::Engine+ This is the main entry-point into the Rails initialization process as when your application is initialized, your class is the basis of its configuration. - -This file requires three important files before +Rails::Application+ is defined: _rails/railties_path.rb_, _rails/plugin.rb_ and _rails/engine.rb_. - - -h4. +require 'rails/railties_path'+ - -This file serves one purpose: - - - RAILTIES_PATH = File.expand_path(File.join(File.dirname(__FILE__), '..', '..')) - - -Helpful, hey? One must wonder why they just didn't define it outright. - - -h4. +require 'rails/plugin'+ - -Firstly this file requires _rails/engine.rb_, which defines our +Rails::Engine+ class, explained in the very next section. - -This file defines a class called +Rails::Plugin+ which descends from +Rails::Engine+. - -This defines the first few initializers for the Rails stack: - -* load_init_rb -* sanity_check_railties_collisons - -These are explained in the Initialization section. TODO: First write initialization section then come back here and link. -TODO: Expand. - -h4. +require 'rails/engine'+ - -This file requires _rails/railtie.rb_ which defines +Rails::Railtie+. - -+Rails::Engine+ defines a couple of further initializers for your application: - -* set_load_path -* set_autoload_paths -* add_routing_paths -* add_routing_namespaces -* add_locales -* add_view_paths -* add_generator_templates -* load_application_initializers -* load_application_classes - -These are explained in the Initialization section. TODO: First write initialization section then come back here and link. - -Also in here we see that a couple of methods are +delegate+'d: - - - delegate :middleware, :paths, :root, :to => :config - - -This means when you call either the +middleware+, +paths+ or +root+ methods you are in reality calling +config.middleware+, +config.paths+ and +config.root+ respectively. - -+Rails::Engine+ descends from +Rails::Railtie+. - -h4. +require 'rails/railtie'+ - -+Rails::Railtie+ (_pronounced Rail-tie, as in a bowtie_), provides a method of classes to hook into Rails, providing them with methods to add generators, rake tasks and subscribers. All of the facets of Rails are their own Railtie. and as you've probably already figured out, the engines that you use are railties too. Plugins also can be railties, but they do not have to be. - -Here there's requires to _rails/initializable.rb_ and and _rails/configurable.rb_. - -h4. +require 'rails/initializable'+ - -The +Rails::Initializable+ module includes methods helpful for the initialization process in rails, such as the method to define initializers: +initializer+. This is included into +Rails::Railtie+ so it's available there as well as +Rails::Engine+, +Rails::Application+ and +YourApp::Application+. In here we also see the class definition for +Rails::Initializer+, the class for all initializer objects. - -h4. +require 'rails/configuration'+ - -The +Rails::Configuration+ module sets up shared configuration for applications, engines and plugins alike. - -At the top of this file there are three +require+s: - - - require 'active_support/ordered_options' - require 'rails/paths' - require 'rails/rack' - - -h4. +require 'active_support/ordered_options'+ - -+ActiveSupport::OrderedOptions+ is a special-purpose +OrderedHash+, used for keeping track of the options specified in the configuration of your application. - -TODO: expand. - -h4. +require 'rails/paths'+ - -This file is used to set up the +Rails::Paths+ module which is used to set up helpers for referencing paths to the folders of your Rails application, such as in _railties/lib/rails/engine/configuration.rb_ where it is used to firstly define them: - - - def paths - @paths ||= begin - paths = Rails::Paths::Root.new(@root) - paths.app "app", :eager_load => true, :glob => "*" - paths.app.controllers "app/controllers", :eager_load => true - paths.app.helpers "app/helpers", :eager_load => true - paths.app.models "app/models", :eager_load => true - paths.app.mailers "app/mailers", :eager_load => true - paths.app.views "app/views", :eager_load => true - paths.lib "lib", :load_path => true - paths.lib.tasks "lib/tasks", :glob => "**/*.rake" - paths.lib.templates "lib/templates" - paths.config "config" - paths.config.initializers "config/initializers", :glob => "**/*.rb" - paths.config.locales "config/locales", :glob => "*.{rb,yml}" - paths.config.routes "config/routes.rb" - paths.public "public" - paths.public.javascripts "public/javascripts" - paths.public.stylesheets "public/stylesheets" - paths - end - end - - -You can then get to these helper methods by calling +YourApp::Application.config.paths+. - -h4. +require 'rails/rack'+ - -This file sets up some +autoload+'d constants for +Rails::Rack+: - - - module Rails - module Rack - autoload :Debugger, "rails/rack/debugger" - autoload :Logger, "rails/rack/logger" - autoload :LogTailer, "rails/rack/log_tailer" - autoload :Static, "rails/rack/static" - end - end - - -h4. +require 'rails/version'+ - -Now we're back to _rails.rb_. The line after +require 'rails/application'+ in _rails.rb_ is: - - - require 'rails/version' - - -The code in this file declares +Rails::VERSION+ so that the version number can easily be accessed. It stores it in constants, with the final version number being attainable by calling +Rails::VERSION::STRING+. - -h4. +require 'rails/deprecation'+ - -This sets up a couple of familiar constants: +RAILS_ENV+, +RAILS_ROOT+ and +RAILS_DEFAULT_LOGGER+ to still be usable, but raise a deprecation warning when they are. Their alternatives are now +Rails.env+, +Rails.root+ and +Rails.logger+ respectively. - -If you wish to know more about how they're deprecated see the +require 'active_support/deprecation/proxy_wrappers'+ section. TODO: link to section. - -h4. +require 'rails/log_subscriber'+ - -The +Rails::LogSubscriber+ provides a central location for logging in Rails 3 so as to not slow down the main thread. When you call one of the logging methods (+info+, +debug+, +warn+, +error+, +fatal+ or +unknown+) from the +Rails::LogSubscriber+ class or one of its subclasses this will notify the Rails logger to log this call in the fashion you specify, but will not write it to the file. The file writing is done at the end of the request, courtesy of the +Rails::Rack::Logger+ middleware. - -Each Railtie defines its own class that descends from +Rails::LogSubscriber+ with each defining its own methods for logging individual tasks. - -h4. +require 'rails/ruby_version_check'+ - -This file ensures that you're running a minimum of 1.8.7. If you're running an older version, it will tell you: - -
-  Rails requires Ruby version 1.8.7 or later.
-  You're running [your Ruby version here]; please upgrade to continue.
-
- -h4. +require 'activesupport/railtie'+ - -This file declares two Railties, one for ActiveSupport and the other for I18n. In these Railties there's the following initializers defined: - -* active_support.initialize_whiny_nils -* active_support.initialize_time_zone - -* i18n.initialize - -This Railtie also defines an an +after_initialize+ block, which will (as the name implies) be ran after the initialization process. More on this later. TODO: When you write the section you can link to it. - -h4. +require 'action_dispatch/railtie'+ - -This file is explained in the ActionDispatch Railtie Section. TODO: link - -h4. Return to _rails/all.rb_ - -Now that we've covered the extensive process of what the first line does in this file, lets cover the remainder: - - - %w( - active_record - action_controller - action_mailer - active_resource - rails/test_unit - ).each do |framework| - begin - require "#{framework}/railtie" - rescue LoadError - end - end - - -As you may be able to tell from the code, this is going through and loading all the Railties for Active Record, Action Controller, Action Mailer, Active Resource. Two other Railties, one for Active Support and one for Action Dispatch were required earlier, but are still covered in this section for continuity reasons. TODO: link. - -h4. ActiveSupport Railtie - -From Active Support's README: - -Active Support is a collection of various utility classes and standard library extensions that were found useful for Rails. - -TODO: Quotify. - -h5. +require 'active_support/railtie'+ - - -h4. Active Record Railtie - -The Active Record Railtie takes care of hooking Active Record into Rails. This depends on Active Support, Active Model and Arel. From Active Record's readme: - -TODO: Quotify. - - - Active Record connects business objects and database tables to create a persistable domain model where logic and data are presented in one wrapping. It's an implementation of the object-relational mapping (ORM) pattern by the same name as described by Martin Fowler: - - "An object that wraps a row in a database table or view, encapsulates - the database access, and adds domain logic on that data." - - Active Record's main contribution to the pattern is to relieve the original of two stunting problems: - lack of associations and inheritance. By adding a simple domain language-like set of macros to describe - the former and integrating the Single Table Inheritance pattern for the latter, Active Record narrows the - gap of functionality between the data mapper and active record approach. - - -h5. +require "active_record/railtie"+ - -The _activerecord/lib/active_record/railtie.rb_ file defines the Railtie for Active Record. - -This file first requires Active Record, the _railties/lib/rails.rb_ file which has already been required and so will be ignored, and the Active Model Railtie: - - - require "active_record" - require "rails" - require "active_model/railtie" - - -Active Model's Railtie is covered in the next section. TODO: Section. - -h5. +require "active_record"+ - -TODO: Why are +activesupport_path+ and +activemodel_path+ defined here? - -The first three requires require ActiveSupport, Active Model and Arel in that order: - - - require 'active_support' - require 'active_model' - require 'arel' - - - -h5. +require "active_support"+ - -This was loaded earlier by _railties/lib/rails.rb_. This line is here as a safeguard for when Active Record is loaded outside the scope of Rails. - -h5. +require "active_model"+ - -TODO: Again with the +activesupport_path+! - -Here we see another +require "active_support"+ this is again, a safeguard for when Active Model is loaded outside the scope of Rails. - -This file defines a few +autoload+'d modules for Active Model, requires +active_support/i18n+ and adds the default translation file for Active Model to +I18n.load_path+. - -The +require 'active_support/i18n'+ just loads I18n and adds Active Support's default translations file to +I18n.load_path+ too: - - - require 'i18n' - I18n.load_path << "#{File.dirname(__FILE__)}/locale/en.yml - - - -h5. +require "arel"+ - -This file in _arel/lib/arel.rb_ loads a couple of Active Support things first: - - - require 'active_support/inflector' - require 'active_support/core_ext/module/delegation' - require 'active_support/core_ext/class/attribute_accessors' - - -These files are explained in the "Common Includes" section. - -h5. +require 'arel'+ - -Back in _arel/lib/arel.rb_, the next two lines require Active Record parts: - - - require 'active_record' - require 'active_record/connection_adapters/abstract/quoting' - - -Because we're currently loading _active_record.rb_, it skips right over it. - -h5. +require 'active_record/connection_adapters/abstract/quoting'+ - -_activerecord/lib/active_record/connection_adapters/abstract/quoting.rb_ defines methods used for quoting fields and table names in Active Record. - -TODO: Explain why this is loaded especially. - -h5. +require 'active_record'+ - -Back the initial require from the _railtie.rb_. - -The _active_support_ and _active_model_ requires are again just an insurance for if we're loading Active Record outside of the scope of Rails. In _active_record.rb_ the ActiveRecord +Module+ is initialized and in it there is defined a couple of +autoloads+ and +eager_autoloads+. - -There's a new method here called +autoload_under+ which is defined in +ActiveSupport::Autoload+. This sets the autoload path to temporarily be the specified path, in this case +relation+ for the +autoload+'d classes inside the block. - -Inside this file the +AttributeMethods+, +Locking+ and +ConnectionAdapter+ modules are defined inside the +ActiveRecord+ module. The second to last line tells Arel what SQL engine we want to use. In this case it's +ActiveRecord::Base+. The final line adds in the translations for Active Record which are only for if a record is invalid or non-unique. - -h5. +require 'rails'+ - -As mentioned previously this is skipped over as it has been already loaded. If you'd still like to see what this file does go to section TODO: section. - -h5. +require 'active_model/railtie'+ - -This is covered in the Active Model Railtie section. TODO: link there. - -h5. +require 'action_controller/railtie'+ - -This is covered in the Action Controller Railtie section. TODO: link there. - -h5. The Active Record Railtie - -Inside the Active Record Railtie the +ActiveRecord::Railtie+ class is defined: - - - module ActiveRecord - class Railtie < Rails::Railtie - - ... - end - end - - -TODO: Explain the logger. - -By doing this the +ActiveRecord::Railtie+ class gains access to the methods contained within +Rails::Railtie+ such as +rake_tasks+, +log_subscriber+ and +initiailizer+, all of which the Railtie is using in this case. The initializers defined here are: - -* active_record.initialize_timezone -* active_record.logger -* active_record.set_configs -* active_record.initialize_database -* active_record.log_runtime -* active_record.initialize_database_middleware -* active_record.load_observers -* active_record.set_dispatch_hooks - -As with the engine initializers, these are explained later. - - -h4. Active Model Railtie - -This Railtie is +require+'d by Active Record's Railtie. - -From the Active Model readme: - - - Prior to Rails 3.0, if a plugin or gem developer wanted to be able to have an object interact with Action Pack helpers, it was required to either copy chunks of code from Rails, or monkey patch entire helpers to make them handle objects that did not look like Active Record. This generated code duplication and fragile applications that broke on upgrades. - - Active Model is a solution for this problem. - - Active Model provides a known set of interfaces that your objects can implement to then present a common interface to the Action Pack helpers. - - - -h5. +require "active_model/railtie"+ - -This Railtie file, _activemodel/lib/active_model/railtie.rb_ is quite small and only requires in +active_model+. As mentioned previously, the require to _rails_ is skipped over as it has been already loaded. If you'd still like to see what this file does go to section TODO: section. - - - require "active_model" - require "rails" - - -h5. +require "active_model"+ - -Active Model depends on Active Support and ensures it is required by making a +require 'active_support'+ call. It has already been loaded from _railties/lib/rails.rb_ so will not be reloaded for us here. The file goes on to define the +ActiveModel+ module and all of its autoloaded classes. This file also defines the english translations for some of the validation messages provided by Active Model, such as "is not included in the list" and "is reserved". - -h4. Action Controller Railtie - -The Action Controller Railtie takes care of all the behind-the-scenes code for your controllers; it puts the C into MVC; and does so by implementing the +ActionController::Base+ class which you may recall is where your +ApplicationController+ class descends from. - -h5. +require 'action_controller/railtie'+ - -This first makes a couple of requires: - - - require "action_controller" - require "rails" - require "action_view/railtie" - - -The _action_controller_ file is explained in the very next section. The require to _rails_ is requiring the already-required _railties/lib/rails.rb_. If you wish to know about the require to _action_view/railtie_ this is explained in the Action View Railtie section. - -h5. +require 'action_controller+ - -This file, _actionpack/lib/action_controller.rb_, defines the Action Controller module and its relative autoloads. Before it does any of that it makes two requires: one to _abstract_controller_, explored next, and the other to _action_dispatch_, explored directly after that. - -h5. +require 'abstract_controller'+ - -+AbstractController+ provides the functionality of TODO. - -This file is in _actionpack/lib/abstract_controller.rb_ and begins by attempting to add the path to Active Support to the load path, which it would succeed in if it wasn't already set by anything loaded before it. In this case, it's not going to be set due to Arel already loading it in (TODO: right?). - -The next thing in this file four +require+ calls: - - - require 'active_support/ruby/shim' - require 'active_support/dependencies/autoload' - require 'active_support/core_ext/module/attr_internal' - require 'active_support/core_ext/module/delegation' - - -After these require calls the +AbstractController+ module is defined with some standard +autoload+'d classes. - - -h5. +require 'active_support/ruby/shim'+ - -This file is explained in the "Common Includes" section beneath. - -h5. +require 'active_support/dependencies/autoload+ - -This file was loaded upon the first require of +active_support+ and is not included. If you wish to be refreshed on what this file performs visit TODO: link to section. - -h5. +require 'active_support/core_ext/module/attr_internal'+ - -This file is explained in the "Common Includes" section as it is required again later on. See the TODO: section. I also think this may be explained in the Active Support Core Extensions guide. - -h5. +require 'active_support/core_ext/module/delegation'+ - -This file is explained in the "Common Includes" section as it has already been required by Arel at this point in the initialization process (see: section TODO: LINK!). - -h5. +require 'action_controller'+ - -Back to _actionpack/lib/action_controller.rb_. - -After the initial call to +require 'abstract_controller'+, this calls +require 'action_dispatch'+ which was required earlier by _railties/lib/rails.rb_. The purpose of this file is explained in the ActionDispatch Railtie section. - -This file defines the +ActionController+ module and its autoloaded classes. - -Here we have a new method called +autoload_under+. This was covered in the Active Record Railtie but it is covered here also just in case you missed or skimmed over it. The +autoload_under+ method is defined in +ActiveSupport::Autoload+ and it sets the autoload path to temporarily be the specified path, in this case by specifying _metal_ it will load the specified +autoload+'d classes from _lib/action_controller/metal_ inside the block. - -Another new method we have here is called +autoload_at+: - - - autoload_at "action_controller/metal/exceptions" do - autoload :ActionControllerError - autoload :RenderError - autoload :RoutingError - autoload :MethodNotAllowed - autoload :NotImplemented - autoload :UnknownController - autoload :MissingFile - autoload :RenderError - autoload :SessionOverflowError - autoload :UnknownHttpMethod - end - - -This defines the path of which to find these classes defined at and is most useful for if you have multiple classes defined in a single file, as is the case for this block; all of those classes are defined inside _action_controller/metal/exceptions.rb_ and when Active Support goes looking for them it will look in that file. - -At the end of this file there are a couple more requires: - - - # All of these simply register additional autoloads - require 'action_view' - require 'action_controller/vendor/html-scanner' - - # Common Active Support usage in ActionController - require 'active_support/concern' - require 'active_support/core_ext/class/attribute_accessors' - require 'active_support/core_ext/load_error' - require 'active_support/core_ext/module/attr_internal' - require 'active_support/core_ext/module/delegation' - require 'active_support/core_ext/name_error' - require 'active_support/inflector' - - -h5. +require 'action_view'+ - -This is best covered in the Action View Railtie section, so skip there by TODO: Link / page? - -h5. +require 'action_controller/vendor/html-scanner'+ - -TODO: What is the purpose of this? Find out. - -h5. +require 'active_support/concern'+ - -TODO: I can kind of understand the purpose of this.. need to see where @_dependencies is used however. - -h5. +require 'active_support/core_ext/class/attribute_accessors'+ - -This file defines, as the path implies, attribute accessors for class. These are +cattr_reader+, +cattr_writer+, +cattr_accessor+. - -h5. +require 'active_support/core_ext/load_error'+ - -The Active Support Core Extensions (TODO: LINK!) guide has a great coverage of what this file precisely provides. - -h5. +require 'active_support/core_ext/module/attr_internal'+ - -This file is explained in the "Core Extension" guide. - -This file was required through the earlier _abstract_controller.rb_ require. - -h5. +require 'active_support/core_ext/module/delegation'+ - -This file is explained in the "Common Includes" section. - -This file was required earlier by Arel and so is not required again. - -h5. +require 'active_support/core_ext/name_error'+ - -This file includes extensions to the +NameError+ class, providing the +missing_name+ and +missing_name?+ methods. For more information see the Active Support Core Extensions guide. - -h5. +require 'active_support/inflector'+ - -This file is explained in the "Common Includes" section. - -This file was earlier required by Arel and so is not required again. - -h5. Action Controller Railtie - -So now we come back to the Action Controller Railtie with a couple more requires to go before +ActionController::Railtie+ is defined: - - - require "action_view/railtie" - require "active_support/core_ext/class/subclasses" - require "active_support/deprecation/proxy_wrappers" - require "active_support/deprecation" - - -As explained previously the +action_view/railtie+ file will be explained in the Action View Railtie section. TODO: link to it. - -h5. +require 'active_support/core_ext/class/subclasses'+ - -For an explanation of this file _activesupport/lib/active_support/core_ext/class/subclasses_, see the Active Support Core Extension guide. - -h5. +require 'active_support/deprecation/proxy_wrappers'+ - -This file, _activesupport/lib/active_support/deprecation/proxy_wrappers.rb_, defines a couple of deprecation classes, which are +DeprecationProxy+, +DeprecationObjectProxy+, +DeprecationInstanceVariableProxy+, +DeprecationConstantProxy+ which are all namespaced into +ActiveSupport::Deprecation+. These last three are all subclasses of +DeprecationProxy+. - -Why do we mention them here? Beside the obvious-by-now fact that we're covering just about everything about the initialization process in this guide, if you're deprecating something in your library and you use Active Support, you too can use the +DeprecationProxy+ class (and it's subclasses) too. - - -h6. +DeprecationProxy+ - -This class is used only in _railties/lib/rails/deprecation.rb_, loaded further on in the initialization process. It's used in this way: - - - RAILS_ROOT = (Class.new(ActiveSupport::Deprecation::DeprecationProxy) do - cattr_accessor :warned - self.warned = false - - def target - Rails.root - end - - def replace(*args) - warn(caller, :replace, *args) - end - - def warn(callstack, called, args) - unless warned - ActiveSupport::Deprecation.warn("RAILS_ROOT is deprecated! Use Rails.root instead", callstack) - self.warned = true - end - end - end).new - - -There is similar definitions for the other constants of +RAILS_ENV+ and +RAILS_DEFAULT_LOGGER+. All three of these constants are in the midst of being deprecated (most likely in Rails 3.1) so Rails will tell you if you reference them that they're deprecated using the +DeprecationProxy+ class. Whenever you call +RAILS_ROOT+ this will raise a warning, telling you: "RAILS_ROOT is deprecated! Use Rails.root instead".... TODO: investigate if simply calling it does raise this warning. This same rule applies to +RAILS_ENV+ and +RAILS_DEFAULT_LOGGER+, their new alternatives are +Rails.env+ and +Rails.logger+ respectively. - -h6. +DeprecatedObjectProxy+ - -This is used in one place _actionpack/lib/action_controller/railtie.rb_, which you may remember is how we got to the +DeprecationProxy+ section: - - - ActiveSupport::Deprecation::DeprecatedObjectProxy.new(app.routes, message) - - -This makes more sense in the wider scope of the initializer: - - - initializer "action_controller.url_helpers" do |app| - ActionController.base_hook do - extend ::ActionController::Railtie::UrlHelpers.with(app.routes) - end - - message = "ActionController::Routing::Routes is deprecated. " \ - "Instead, use Rails.application.routes" - - proxy = ActiveSupport::Deprecation::DeprecatedObjectProxy.new(app.routes, message) - ActionController::Routing::Routes = proxy - end - - -+ActionController::Routing::Routes+ was the previous constant used in defining routes in Rails 2 applications, now it's simply a method on +Rails.application+ rather than it's own individual class: +Rails.application.routes+. Both of these still call the +draw+ method on the returned object to end up defining the routes. - - -h6. +DeprecatedInstanceVariableProxy+ - -This isn't actually used anywhere in Rails anymore. It was used previously for when +@request+ and +@params+ were deprecated in Rails 2. It has been kept around as it could be useful for the same purposes in libraries that use Active Support. - -h6. +DeprecatedConstantProxy+ - -This method is used in a couple of places, _activesupport/lib/active_support/json/encoding.rb_ and _railties/lib/rails/rack.rb_. - -In _encoding.rb_ it's used to define a constant that's now been deprecated: - - - CircularReferenceError = Deprecation::DeprecatedConstantProxy.new('ActiveSupport::JSON::CircularReferenceError', Encoding::CircularReferenceError) - - - -Now when you reference +ActiveSupport::JSON::CircularReferenceError+ you'll receive a warning: - - - ActiveSupport::JSON::CircularReferenceError is deprecated! Use Encoding::CircularReferenceError instead. - - -h5. +require "active_support/deprecation"+ - -This re-opens the +ActiveSupport::Deprecation+ module which was already defined by our deprecation proxies. Before this happens however we have 4 requires: - - - require 'active_support/deprecation/behaviors' - require 'active_support/deprecation/reporting' - require 'active_support/deprecation/method_wrappers' - require 'active_support/deprecation/proxy_wrappers' - - -The remainder of this file goes about setting up the +silenced+ and +debug+ accessors: - - - module ActiveSupport - module Deprecation #:nodoc: - class << self - # The version the deprecated behavior will be removed, by default. - attr_accessor :deprecation_horizon - end - self.deprecation_horizon = '3.0' - - # By default, warnings are not silenced and debugging is off. - self.silenced = false - self.debug = false - end - end - - -h5. +require "active_support/deprecation/behaviors"+ - -This sets up some default behavior for the warnings raised by +ActiveSupport::Deprecation+, defining different ones for _development_ and _test_ and nothing for production, as we never want deprecation warnings in production: - - - # Default warning behaviors per Rails.env. Ignored in production. - DEFAULT_BEHAVIORS = { - 'test' => Proc.new { |message, callstack| - $stderr.puts(message) - $stderr.puts callstack.join("\n ") if debug - }, - 'development' => Proc.new { |message, callstack| - logger = - if defined?(Rails) && Rails.logger - Rails.logger - else - require 'logger' - Logger.new($stderr) - end - logger.warn message - logger.debug callstack.join("\n ") if debug - } - } - - -In the _test_ environment, we will see the deprecation errors displayed in +$stderr+ and in _development_ mode, these are sent to +Rails.logger+ if it exists, otherwise it is output to +$stderr+ in a very similar fashion to the _test_ environment. These are both defined as procs, so Active Support can pass arguments to the +call+ method we call on it when Active Support +warn+. - -h5. +require 'active_support/deprecation/reporting'+ - -This file defines further extensions to the +ActiveSupport::Deprecation+ module, including the +warn+ method which is used from Active Support's +DeprecationProxy+ class and an +attr_accessor+ on the class called +silenced+. This checks that we have a behavior defined, which we do in the _test_ and _development_ environments, and that we're not +silenced+ before warning about deprecations by +call+'ing the +Proc+ time. - -This file also defines a +silence+ method on the module also which you can pass a block to temporarily silence errors: - - - ActiveSupport::Deprecation.silence do - puts "YOU CAN FIND ME HERE: #{RAILS_ROOT}" - end - - -TODO: may have to correct this example. - -h5. +require 'active_support/deprecation/method_wrappers'+ - -This file defines a class method on +ActiveSupport::Deprecation+ called +deprecate_methods+. This method is used in _activesupport/lib/active_support/core_ext/module/deprecation.rb_ to allow you to declare deprecated methods on modules: - - - class Module - # Declare that a method has been deprecated. - # deprecate :foo - # deprecate :bar => 'message' - # deprecate :foo, :bar, :baz => 'warning!', :qux => 'gone!' - def deprecate(*method_names) - ActiveSupport::Deprecation.deprecate_methods(self, *method_names) - end - end - - -h5. +require 'action_controller/railtie'+ - -Inside +ActionController::Railtie+ there are another two requires: - - - require "action_controller/railties/log_subscriber" - require "action_controller/railties/url_helpers" - - - -h5. +require 'action_controller/railties/log_subscriber'+ - -+ActionController::Railties::LogSubscriber+ inherits from +Rails::LogSubscriber+ and defines methods for logging such things as action processing and file sending. - -h5. +require 'action_controller/railties/url_helpers'+ - -This file defines a +with+ method on +ActionController::Railtie::UrlHelpers+ which is later used in the +action_controller.url_helpers+ initializer. For more information see the +action_controller.url_helpers+ initializer section. - -h5. Action Controller Railtie - -After these requires it deprecates a couple of ex-Action Controller methods and points whomever references them to their ActionDispatch equivalents. These methods are +session+, +session=+, +session_store+ and +session_store=+. - -After the deprecations, Rails defines the +log_subscriber+ to be a new instance of +ActionController::Railties::LogSubscriber+ and then go about defining the following initializers, keeping in mind that these are added to the list of initializers defined before hand: - -* action_controller.logger -* action_controller.set_configs -* action_controller.initialize_framework_caches -* action_controller.set_helpers_path -* action_controller.url_helpers - -h4. Action View Railtie - -The Action View Railtie provides the backend code for your views and it puts the C into MVC. This implements the +ActionView::Base+ of which all views and partials are objects of. - -h5. +require 'action_view/railtie'+ - -The Railtie is defined in a file called _actionpack/lib/action_view/railtie.rb_ and initially makes a call to +require 'action_view'+. - -h5. +require 'action_view'+ - -Here again we have the addition of the path to Active Support to the load path attempted, but because it's already in the load path it will not be added. Similarly, we have two requires: - - - require 'active_support/ruby/shim' - require 'active_support/core_ext/class/attribute_accessors' - - -And these have already been required. If you wish to know what these files do go to the explanation of each in the "Common Includes" section. TODO: link to them! - -This file goes on to +require 'action_pack'+ which consists of all this code (comments stripped): - - - require 'action_pack/version' - - -the _version_ file contains this code (comments stripped): - - - module ActionPack #:nodoc: - module VERSION #:nodoc: - MAJOR = 3 - MINOR = 1 - TINY = 0 - BUILD = "beta" - - STRING = [MAJOR, MINOR, TINY, BUILD].join('.') - end - end - - -TODO: Why?! - -This file goes on to define the +ActionView+ module and its +autoload+'d modules and then goes on to make two more requires: - - - require 'active_support/core_ext/string/output_safety' - require 'action_view/base' - - -h5. +require 'active_support/core_ext/string/output_safety'+ - -The _actionpack/lib/active_support/core_ext/string/output_saftey.rb_ file is responsible for the code used in escaping HTML and JSON, namely the +html_escape+ and +json_escape+ methods. It does this by overriding these methods in +Erb::Util+ which is later included into +ActionView::Base+. This also defines +ActiveSupport::SafeBuffer+ which descends from +String+ and is used for concatenating safe output from your views to ERB templates. - -h5. +require 'action_view/base'+ - -This file initially makes requires to the following files: - - - require 'active_support/core_ext/module/attr_internal' - require 'active_support/core_ext/module/delegation' - require 'active_support/core_ext/class/attribute' - - -These are explained in their relevant areas inside the "Common Includes" section. - -The remainder of this file sets up the +ActionView+ module and the +ActionView::Base+ class which is the class of all view templates. Inside of +ActionView::Base+ it makes an include to several helper modules: - - - include Helpers, Rendering, Partials, Layouts, ::ERB::Util, Context - - -h5. +ActionView::Helpers+ - -This module, from _actionpack/lib/action_view/helpers.rb_, initially sets up the +autoload+'s for the various +ActionView::Helpers+ modules (TODO: mysteriously not using +autoload_under+). This also sets up a +ClassMethods+ module which is included automatically into wherever +ActionView::Helpers+ is included by defining a +self.included+ method: - - - def self.included(base) - base.extend(ClassMethods) - end - - module ClassMethods - include SanitizeHelper::ClassMethods - end - - -Inside of +SanitizeHelper::ClassMethods+ it defines, of course, methods for assisting with sanitizing in Rails such as +link_sanitizer+ which is used by the +strip_links+ method. - -Afterwards this includes the +ActiveSupport::Benchmarkable+ which is used for benchmarking how long a specific thing takes in a view. The method is simply +benchmark+ and can be used like this: - - - benchmark("potentially long running thing") do - Post.count - end - - -The "documentation":http://api.rubyonrails.org/classes/ActiveSupport/Benchmarkable.html is great about explaining what precisely this does. - -This module is also included into Active Record and +AbstractController+, meaning you can also use the +benchmark+ method in these methods. - -After including +ActiveSupport::Benchmarkable+, the helpers which we have declared to be +autoload+'d are included. I will not go through and cover what each of these helpers do, as their names should be fairly explicit about it, and it's not really within the scope of this guide. - -h5. +ActionView::Rendering+ - -This module, from _actionpack/lib/action_view/render/rendering.rb_ defines a method you may be a little too familiar with: +render+. This is the +render+ use for rendering all kinds of things, such as partials, templates and text. - -h5. +ActionView::Partials+ - -This module, from _actionpack/lib/action_view/render/partials.rb_, defines +ActionView::Partials::PartialRenderer+ which you can probably guess is used for rendering partials. - -h5. +ActionView::Layouts+ - -This module, from _actionpack/lib/action_view/render/layouts.rb_, defines +ActionView::Layouts+ which defines methods such as +find_layout+ for locating layouts. - -h5. +ERB::Util+ - -The +ERB::Util+ module from Ruby core, as the document describes it: "A utility module for conversion routines, often handy in HTML generation". It offers two methods +html_escape+ and +url_encode+, with a third called +json_escape+ being added in by the requirement of _actionpack/lib/active_support/core_ext/string/output_saftey.rb_ earlier. As explained earlier, +html_escape+ is overridden to return a string marked as safe. - -h5. +ActionView::Context+ - -TODO: Not entirely sure what this is all about. Something about the context of view rendering... can't work it out. - -h5. Action View Railtie - -Now that _actionpack/lib/action_view.rb_ has been required, the next step is to +require 'rails'+, but this will be skipped as the file was required by _railties/lib/rails/all.rb_ way back in the beginnings of the initialization process. - -Next, the Railtie itself is defined: - - - - module ActionView - class Railtie < Rails::Railtie - railtie_name :action_view - - require "action_view/railties/log_subscriber" - log_subscriber ActionView::Railties::LogSubscriber.new - - initializer "action_view.cache_asset_id" do |app| - unless app.config.cache_classes - ActiveSupport.on_load(:action_view) do - ActionView::Helpers::AssetTagHelper::AssetPaths.cache_asset_ids = false - end - end - end - end - end - - -The +ActionView::LogSubscriber+ sets up a method called +render_template+ which is called when a template is rendered. TODO: Templates only or partials and layouts also? I would imagine these fall under the templates category, but there needs to research to ensure this is correct. - -The sole initializer defined here, _action_view.cache_asset_ids_ is responsible for caching the timestamps on the ends of your assets. If you've ever seen a link generated by +image_tag+ or +stylesheet_link_tag+ you would know that I mean that this timestamp is the number after the _?_ in this example: _/javascripts/prototype.js?1265442620_. This initializer will do nothing if +cache_classes+ is set to false in any of your application's configuration. TODO: Elaborate. - -h4. Action Mailer Railtie - -The Action Mailer Railtie is responsible for including all the emailing functionality into Rails by way of the Action Mailer gem itself. Action Mailer is: - -Action Mailer is a framework for designing email-service layers. These layers -are used to consolidate code for sending out forgotten passwords, welcome -wishes on signup, invoices for billing, and any other use case that requires -a written notification to either a person or another system. - -Action Mailer is in essence a wrapper around Action Controller and the -Mail gem. It provides a way to make emails using templates in the same -way that Action Controller renders views using templates. - -TODO: Quotify. - -h5. +require 'action_mailer/railtie'+ - -This file first makes two requires: - - - require "action_mailer" - require "rails" - - -The requires in +action_mailer+ are already loaded or are core extensions: - - - require 'abstract_controller' - require 'action_view' - - # Common Active Support usage in Action Mailer - require 'active_support/core_ext/class' - require 'active_support/core_ext/object/blank' - require 'active_support/core_ext/array/uniq_by' - require 'active_support/core_ext/module/attr_internal' - require 'active_support/core_ext/module/delegation' - require 'active_support/core_ext/string/inflections' - require 'active_support/lazy_load_hooks' - - -_abstract_controller_ is covered in the "Action Controller Railtie" section. TODO: Cover AbstractController there and link to it. -_action_view_ was required by the Action View Railtie and will not be required again. - -For the core extensions you may reference the "Core Extensions" guide. TODO: Link to guide. - -_active_support/lazy_load_hooks_ was covered earlier in the guide and since it has already been required at this point in the initialization process, it will not be required again. - -The +require "rails"+ is referencing the _railties/lib/rails.rb_ file which was included back in TODO: link to section. - -_actionmailer/lib/action_mailer.rb_ then goes on to define the +ActionMailer+ module: - - - module ActionMailer - extend ::ActiveSupport::Autoload - - autoload :AdvAttrAccessor - autoload :Collector - autoload :Base - autoload :DeliveryMethods - autoload :DeprecatedApi - autoload :MailHelper - autoload :OldApi - autoload :Quoting - autoload :TestCase - autoload :TestHelper - end - - -And a +Text+ module too: - - - module Text - extend ActiveSupport::Autoload - - autoload :Format, 'text/format' - end - - -which is used by the +ActionMailer::MailerHelper+ method +block_format+: - - - def block_format(text) - formatted = text.split(/\n\r\n/).collect { |paragraph| - Text::Format.new( - :columns => 72, :first_indent => 2, :body_indent => 2, :text => paragraph - ).format - }.join("\n") - - # Make list points stand on their own line - formatted.gsub!(/[ ]*([*]+) ([^*]*)/) { |s| " #{$1} #{$2.strip}\n" } - formatted.gsub!(/[ ]*([#]+) ([^#]*)/) { |s| " #{$1} #{$2.strip}\n" } - - formatted - end - - -h5. Action Mailer Railtie - -The Railtie defines the +log_subscriber+ as +ActionMailer::Railties::LogSubscriber.new+, with this class having two logging methods: one for delivery called +deliver+ and one for receipt called +receive+. - -The initializers defined in this Railtie are: - -* action_mailer.url_for -* action_mailer.logger -* action_mailer.set_configs - -These are covered later on the Initialization section. TODO: first write then link to Initialization section. - -h4. Active Resource Railtie - -The Active Resource Railtie is responsible for creating an interface into remote sites that offer a REST API. The Active Resource Railtie depends on Active Support and Active Model. - -h5. +require 'active_resource/railtie'+ - -This file defines the Active Resource Railtie: - - - require "active_resource" - require "rails" - - module ActiveResource - class Railtie < Rails::Railtie - railtie_name :active_resource - - require "active_resource/railties/log_subscriber" - log_subscriber ActiveResource::Railties::LogSubscriber.new - - initializer "active_resource.set_configs" do |app| - app.config.active_resource.each do |k,v| - ActiveResource::Base.send "#{k}=", v - end - end - end - end - - -The +require 'rails'+ has already been done back in TODO: link to section. - -h5. +require 'active_resource'+ - -This file, _activeresource/lib/active_resource.rb_, defines the +ActiveResource+ module, first off this will add the path to Active Support and Active Model to the load path if it's not already there, then require both +active_support+ (_activesupport/lib/active_support.rb_) and +active_model+ (_activemodel/lib/active_model.rb_) - - - activesupport_path = File.expand_path('../../../activesupport/lib', __FILE__) - $:.unshift(activesupport_path) if File.directory?(activesupport_path) && !$:.include?(activesupport_path) - - activemodel_path = File.expand_path('../../../activemodel/lib', __FILE__) - $:.unshift(activemodel_path) if File.directory?(activemodel_path) && !$:.include?(activemodel_path) - - require 'active_support' - require 'active_model' - - module ActiveResource - extend ActiveSupport::Autoload - - autoload :Base - autoload :Connection - autoload :CustomMethods - autoload :Formats - autoload :HttpMock - autoload :Observing - autoload :Schema - autoload :Validations - end - - -h5. Active Resource Railtie - -The Railtie itself is fairly short as Active Resource is the smallest component of Rails. - - - module ActiveResource - class Railtie < Rails::Railtie - railtie_name :active_resource - - require "active_resource/railties/log_subscriber" - log_subscriber ActiveResource::Railties::LogSubscriber.new - - initializer "active_resource.set_configs" do |app| - app.config.active_resource.each do |k,v| - ActiveResource::Base.send "#{k}=", v - end - end - end - end - - -The Railtie defines the +log_subscriber+ as +ActiveResource::Railties::LogSubscriber.new+ which has one method defined: +request+. +request+ is used whenever a request is made to an external service. - -There is only one initializer defined here: +set_configs+. This is covered later in the Initialization section. - - -h4. ActionDispatch Railtie - -ActionDispatch handles all dispatch work for Rails. It interfaces with Action Controller to determine what action to undertake when a request comes in. TODO: I would quote the README but it is strangely absent. Flyin' blind here! - -The ActionDispatch Railtie was previously required when we called +require 'rails'+, but we will cover the Railtie here too. - -ActionDispatch depends on Active Support. - -h5. +require 'action_dispatch/railtie'+ - -This file defines the ActionDispatch Railtie: - - - require "action_dispatch" - require "rails" - - module ActionDispatch - class Railtie < Rails::Railtie - railtie_name :action_dispatch - - config.action_dispatch.x_sendfile_header = "X-Sendfile" - config.action_dispatch.ip_spoofing_check = true - - # Prepare dispatcher callbacks and run 'prepare' callbacks - initializer "action_dispatch.prepare_dispatcher" do |app| - # TODO: This used to say unless defined?(Dispatcher). Find out why and fix. - require 'rails/dispatcher' - ActionDispatch::Callbacks.to_prepare { app.routes_reloader.reload_if_changed } - end - end - end - - -The +require 'rails'+ has already been done back in TODO: link to section. - - - - -h5. +require 'action_dispatch'+ - -This file was already loaded earlier in the initialization process. TODO: link to it. - -h5. ActionDispatch Railtie - -The ActionDispatch Railtie is almost as short as the Active Resource Railtie: - - - require "action_dispatch" - require "rails" - - module ActionDispatch - class Railtie < Rails::Railtie - railtie_name :action_dispatch - - config.action_dispatch.x_sendfile_header = "X-Sendfile" - config.action_dispatch.ip_spoofing_check = true - - # Prepare dispatcher callbacks and run 'prepare' callbacks - initializer "action_dispatch.prepare_dispatcher" do |app| - # TODO: This used to say unless defined?(Dispatcher). Find out why and fix. - require 'rails/dispatcher' - ActionDispatch::Callbacks.to_prepare { app.routes_reloader.reload_if_changed } - end - end - end - - -The +config+ method here is from +Rails::Railtie+ and pertains to your application's configuration. In this case, it is setting up some defaults which you can later override in _config/application.rb_. - -This Railtie does not define a +log_subscriber+ and only defines one initializer: +prepare_dispatcher+. - -h3. Return to _config/application.rb_ - -Now that Rails has finished loading all the Railties by way of +require 'rails/all'+ Rails can now move on to the next line: - - - Bundler.require :default, Rails.env - - -NOTE: It is worth mentioning here that you are not tied to using Bundler with Rails 3, but it is (of course) advised that you do. To "turn off" Bundler, comment out or remove the corresponding lines in _config/application.rb_ and _config/boot.rb_. - -Bundler was +require+'d back in _config/boot.rb_, and so that is what makes it available here. This guide does not dive into the internals of Bundler; it's really it's own separate guide. - -The +Bundler.require+ method adds all the gems not specified inside a +group+ in the +Gemfile+ and the ones specified in groups for the +Rails.env+ (in this case, _development_), to the load path. This is how an application is able to find them. - -The rest of this file is spent defining your application's main class. This is it without the comments: - - - module YourApp - class Application < Rails::Application - config.encoding = "utf-8" - config.filter_parameters += [:password] - end - end - - -h3. Return to Rails - -On the surface, this looks like a simple class inheritance. There's more underneath though. back in +Rails::Application+, the +inherited+ method is defined: - - - def inherited(base) - raise "You cannot have more than one Rails::Application" if Rails.application - super - Rails.application = base.instance - end - - -We do not already have a +Rails.application+, so instead this resorts to calling +super+. +Rails::Application+ descends from +Rails::Engine+ and so will call the +inherited+ method in +Rails::Engine+ (in _railties/lib/rails/engine.rb_), but before that it's important to note that +called_from+ is defined an +attr_accessor+ on +Rails::Engine+ and that +YourApp::Application+ is not an +abstract_railtie+: - - - def inherited(base) - unless base.abstract_railtie? - base.called_from = begin - # Remove the line number from backtraces making sure we don't leave anything behind - call_stack = caller.map { |p| p.split(':')[0..-2].join(':') } - File.dirname(call_stack.detect { |p| p !~ %r[railties[\w\-\.]*/lib/rails|rack[\w\-\.]*/lib/rack] }) - end - end - - super - end - - -This +called_from+ setting looks a little overwhelming to begin with, but the short end of it is that it returns your application's root, something like: _/home/you/yourapp_. After +called_from+ has been set, +super+ is again called and this means the +Rails::Railtie#inherited+ method (in _railties/lib/rails/railtie.rb_): - - - def inherited(base) - unless base.abstract_railtie? - base.send(:include, self::Configurable) - subclasses << base - end - end - - -Again, +YourApp::Application+ will return false for +abstract_railtie+ and so the code inside the +unless+ will be ran. The first line: - - - base.send(:include, self::Configurable) - - -includes the +self::Configurable+ module, with self being +Rails::Application+ in this context: - - - module Rails - class Application - module Configurable - def self.included(base) - base.extend ClassMethods - end - - module ClassMethods - def inherited(base) - raise "You cannot inherit from a Rails::Application child" - end - end - - def config - @config ||= Application::Configuration.new(self.class.find_root_with_flag("config.ru", Dir.pwd)) - end - end - end - end - - -The inclusion of the +Rails::Application::Configurable+ module triggers the +included+ method in here which extends +YourApp::Application+ with the +Rails::Application::Configurable::ClassMethods+. - -Now that the chain of +super+ calls is done, we'll go back to the original +inherited+ method in +Rails::Application+ and the final line in this method: - - - Rails.application = base.instance - - -+base+ in this case is +YourApp::Application+ and calling +instance+ on this will return an instance of +YourApp::Application+ through the +instance+ method defined here: - - - def instance - if self == Rails::Application - Rails.application - else - @@instance ||= new - end - end - - -+self+ in this case is +YourApp::Application+, so it won't match to +Rails::Application+ so instead the +new+ method is called which calls the +initialize+ method. - - - - -h3. Firing it up! - -Now that we've covered the boot process of Rails the next line best to cover would be what happens after _script/rails_ has loaded _config/boot.rb_. That's quite simply that it then +require 'rails/commands'+ which is located at _railties/lib/rails/commands.rb_. Remember how +exec+ passed the arguments to +script/rails+? This is where they're used. _rails/commands.rb_ is quite a large file in Rails 3, as it contains all the Rails commands like console, about, generate and, of course, server. Because we've called +rails server+ the first argument in +ARGV+ is of course +"server"+. So assuming this we can determine that the +ARGV.shift+ in _commands.rb_ is going to return +"server"+, therefore it'll match this +when+: - - - when 's', 'server' - require 'rails/commands/server' - Dir.chdir(ROOT_PATH) - Rails::Server.start - - -The keen-eyed observer will note that this +when+ also specifies the argument could also be simply +'s'+ thereby making the full command +rails s+. This is the same with the other commands with +generate+ becoming +g+, +console+ becoming +c+ and +dbconsole+ becoming +db+. - -This code here ensures we are at the +ROOT_PATH+ of our application (this constant was defined in _script/rails_) and then calls +Rails::Server.start+. +Rails::Server+ descends from +Rack::Server+ which is defined in the rack gem. The +Rails::Server.start+ method is defined like this: - - - def start - ENV["RAILS_ENV"] = options[:environment] - - puts "=> Booting #{ActiveSupport::Inflector.demodulize(server)}" - puts "=> Rails #{Rails.version} application starting in #{Rails.env} on http://#{options[:Host]}:#{options[:Port]}" - puts "=> Call with -d to detach" unless options[:daemonize] - trap(:INT) { exit } - puts "=> Ctrl-C to shutdown server" unless options[:daemonize] - - super - ensure - puts 'Exiting' unless options[:daemonize] - end - - -We can see here that there is usual output indicating that the server is booting up. - -How the +options+ variable gets set and how Rack starts the server up is covered in the next section. - -h3. Racking it up! - - -This +Rack::Server.start+ method is defined like this: - - - def self.start - new.start - end - - -+new+ as you know calls +initialize+ in a class, and that is defined like this: - - - def initialize(options = nil) - @options = options - end - - -And then +options+, which are the options referenced by the +start+ method in +Rails::Server+. - - - def options - @options ||= parse_options(ARGV) - end - - -And +parse_options+: - - - def parse_options(args) - options = default_options - - # Don't evaluate CGI ISINDEX parameters. - # http://hoohoo.ncsa.uiuc.edu/cgi/cl.html - args.clear if ENV.include?("REQUEST_METHOD") - - options.merge! opt_parser.parse! args - options - end - - -And +default_options+: - - - def default_options - { - :environment => "development", - :pid => nil, - :Port => 9292, - :Host => "0.0.0.0", - :AccessLog => [], - :config => "config.ru" - } - end - - -Finally! We've arrived at +default_options+ which leads into our next point quite nicely. After the object has been +initialize+'d, +start+ is called: - - - def start - if options[:debug] - $DEBUG = true - require 'pp' - p options[:server] - pp wrapped_app - pp app - end - - if options[:warn] - $-w = true - end - - if includes = options[:include] - $LOAD_PATH.unshift *includes - end - - if library = options[:require] - require library - end - - daemonize_app if options[:daemonize] - write_pid if options[:pid] - server.run wrapped_app, options - end - - -We're not debugging anything, so there goes the first 7 lines, we're not warning, nor are we including, requiring, daemonising or writing out a pid file. That's everything except the final line, which calls +run+ with the +wrapped_app+ which is then defined like this: - - - def wrapped_app - @wrapped_app ||= build_app app - end - - -and +build_app+'s first and only argument is +app+ which is defined like this: - - - - def app - @app ||= begin - if !::File.exist? options[:config] - abort "configuration #{options[:config]} not found" - end - - app, options = Rack::Builder.parse_file(self.options[:config], opt_parser) - self.options.merge! options - app - end - end - - -+options+ is a method we talked about a short while ago, which is just the set of default options. +options[:config]+ in this context is therefore _config.ru_ which coincidentally we have in our application! To get an application instance from this method +Rack::Builder+ joins the fray with a call to +parse_file+ on our _config.ru_: - - - def self.parse_file(config, opts = Server::Options.new) - options = {} - if config =~ /\.ru$/ - cfgfile = ::File.read(config) - if cfgfile[/^#\\(.*)/] && opts - options = opts.parse! $1.split(/\s+/) - end - cfgfile.sub!(/^__END__\n.*/, '') - app = eval "Rack::Builder.new {( " + cfgfile + "\n )}.to_app", - TOPLEVEL_BINDING, config - else - require config - app = Object.const_get(::File.basename(config, '.rb').capitalize) - end - return app, options - end - - -First this reads your config file and checks it for +#\+ at the beginning. This is supported if you want to pass options into the +Rack::Server+ instance that you have and can be used like this: - - - #\\ -E production - # This file is used by Rack-based servers to start the application. - - require ::File.expand_path('../config/environment', __FILE__) - run YourApp::Application.instance - - - -TODO: Is the above correct? I am simply guessing! - -After that it removes all the content after any +__END__+ in your _config.ru_ (TODO: because? Is this so it doesn't get eval'd?) and then evals the content of this file which, as you've seen is quite simple. The code that's first evaluated would be the require to the _config/environment.rb_ file, which leads into the next section. - -h3. _config/environment.rb_ - -Now that we've seen that _rails/server_ gets to _config/environment.rb_ via Rack's requiring of it and Passenger requires it straight off the line. We've covered the boot process of Rails and covered the beginnings of a Rack server starting up. We have reached a common path for both _rails/server_ and Passenger now, so let's investigate what _config/environment.rb_ does. - - - # Load the rails application - require File.expand_path('../application', __FILE__) - - # Initialize the rails application - YourApp::Application.initialize! - - - -As you can see, there's a require in here for _config/application.rb_, and this file looks like this: - - - - module YourApp - class Application < Rails::Application - # Settings in config/environments/* take precedence over those specified here. - # Application configuration should go into files in config/initializers - # -- all .rb files in that directory are automatically loaded. - - # Add additional load paths for your own custom dirs - # config.load_paths += %W( #{config.root}/extras ) - - # Only load the plugins named here, in the order given (default is alphabetical). - # :all can be used as a placeholder for all plugins not explicitly named - # config.plugins = [ :exception_notification, :ssl_requirement, :all ] - - # Activate observers that should always be running - # config.active_record.observers = :cacher, :garbage_collector, :forum_observer - - # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. - # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. - # config.time_zone = 'Central Time (US & Canada)' - - # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. - # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')] - # config.i18n.default_locale = :de - - # Configure generators values. Many other options are available, be sure to check the documentation. - # config.generators do |g| - # g.orm :active_record - # g.template_engine :erb - # g.test_framework :test_unit, :fixture => true - # end - end - end - - -These options (and their siblings) are explained in a later section. What's important to note for this file currently is that this is where the +YourApp::Application+ class is initialized and that it's a subclass of +Rails::Application+. This is the first point where your application begins to initialize Rails and as you can see all of this is configuration stuff which your initializers and really, the rest of your application will depend on. These options and what they do will be covered later. - - -h3. Rails Initialization Process - -Now begins the actual initialization of Rails. Previously we have covered how _rails server_ and Passenger get to this stage and the parts of Rails that they have both loaded. - -h3. +Rails::Application+ - -The first steps for the initialization process of Rails begins when +YourApp::Application+ descends from +Rails::Application+. The +Rails::Application+ class descends from +Rails::Engine+ class which itself descends from +Rails::Railtie+ defined in _railties/lib/rails/railtie.rb_. Along this fantastical chain of superclasses, there's defined a couple of inherited class methods. These methods just so happen to be called when a class inherits from (aka: is made a subclass of) this class. This first one is for +Rails::Application+: - - - def inherited(base) - raise "You cannot have more than one Rails::Application" if Rails.application - super - Rails.application = base.instance - end - - -This goes up the chain by using +super+ to calling +Rails::Engine.inherited+: - - - def inherited(base) - unless abstract_railtie?(base) - base.called_from = begin - call_stack = caller.map { |p| p.split(':').first } - File.dirname(call_stack.detect { |p| p !~ %r[railties/lib/rails|rack/lib/rack] }) - end - end - - super - end - - -+called_from+ references where this code was called from. This is covered later on in the "Bootstrap Initializers" section. - -Which then calls +Rails::Railtie.inherited+: - - - def inherited(base) - unless abstract_railtie?(base) - base.send(:include, self::Configurable) - subclasses << base - end - end - - -This +inherited+ first includes the +Rails::Configurable+ module on +base+, which is +YourApp::Application+. This module defines the +config+ method on +YourApp::Application+, and now it's starting to come together. You may notice that in your +config/application.rb+ file there's a +config+ method called there. This is the method from +Rails::Configurable+. - -Then this adds to +Rails::Railtie.subclasses+ your application's class because... TODO: explain. - -With +Rails::Railtie.inherited+ out of the way, and that being the last thing to do in +Rails::Engine.inherited+ we return to +Rails::Application.inherited+ which calls the following: - - - Rails.application = base.instance - - -As you already know, +base+ is +YourApp::Application+ and now it's calling the +instance+ method on it. This method is defined in +Rails::Application+ like this: - - - def instance - if self == Rails::Application - Rails.application - else - @@instance ||= new - end - end - - -The +new+ method here simply creates a new +Rails::Application+ and sets it to the +@@instance+ class variable. No magic. - -h3. Your Application's Configuration - -Now that +inherited+ has finished doing its job, next up in _config/application.rb_ is the call to the +config+ object's methods. As explained before, this +config+ object is an instance of +Rails::Railtie::Configuration+, put into place by the call of +include Rails::Configurable+ back in +Rails::Railtie.inherited+. This defined it as such: - - - def config - @config ||= Railtie::Configuration.new - end - - -All the methods for +Rails::Railtie::Configuration+ are defined like this in _railties/lib/rails/railtie/configuration.rb_: - - - require 'rails/configuration' - - module Rails - class Railtie - class Configuration - include Rails::Configuration::Shared - end - end - end - - -As you can probably guess here, the +Rails::Configuration+ module is defined by _rails/configuration_ (_railties/lib/rails/configuration.rb_). - -h3. +Rails::Configuration::Shared+ - -In a standard application, the +application.rb+ looks like this with all the comments stripped out: - - - require File.expand_path('../boot', __FILE__) - - module YourApp - class Application < Rails::Application - config.filter_parameters << :password - end - end - - -The +config+ method being the one defined on +Rails::Application::Configurable+: - - - def config - @config ||= Application::Configuration.new(self.class.find_root_with_flag("config.ru", Dir.pwd)) - end - - -The method +find_with_root_flag+ is defined on +Rails::Engine+ (the superclass of +Rails::Application+) and it will find the directory containing a certain flag. In this case it's the +config.ru+ file: - - - def find_root_with_flag(flag, default=nil) - root_path = self.called_from - - while root_path && File.directory?(root_path) && !File.exist?("#{root_path}/#{flag}") - parent = File.dirname(root_path) - root_path = parent != root_path && parent - end - - root = File.exist?("#{root_path}/#{flag}") ? root_path : default - raise "Could not find root path for #{self}" unless root - - RUBY_PLATFORM =~ /(:?mswin|mingw)/ ? - Pathname.new(root).expand_path : Pathname.new(root).realpath - end - - -+called_from+ goes through the +caller+ which is the stacktrace of the current thread, in the case of your application it would go a little like this: - -
-  /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.0.0/lib/rails/application.rb:30:in `inherited'
-  /home/you/yourapp/config/application.rb:4:in `'
-  /home/you/yourapp/config/application.rb:3:in `'
-  /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:167:in `require'
-  /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:167:in `block in require'
-  /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:537:in `new_constants_in'
-  /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:167:in `require'
-  /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.0.0/lib/rails/commands.rb:33:in `'
-  /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:167:in `require'
-  /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:167:in `block in require'
-  /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:537:in `new_constants_in'
-  /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:167:in `require'
-  /var/www/rboard/script/rails:10:in `
' -
- -+called_from+ is defined in the +inherited+ method for +Rails::Engine+ which looks like this: - - - base.called_from = begin - call_stack = caller.map { |p| p.split(':').first } - File.dirname(call_stack.detect { |p| p !~ %r[railties/lib/rails|rack/lib/rack] }) - end - - -The +call_stack+ here is the +caller+ output shown previously, minus everything after the first +:+ on all the lines. The first path that matches this is _/usr/local/lib/ruby/gems/1.9.1/gems/railties-3.0.0/lib/rails_. Yours may vary slightly, but should always end in _railties-x.x.x/lib/rails_. - -The code in +find_root_with_flag+ will go up this directory structure until it reaches the top, which in this case is +/+. - - - while root_path && File.directory?(root_path) && !File.exist?("#{root_path}/#{flag}") - parent = File.dirname(root_path) - root_path = parent != root_path && parent - end - - root = File.exist?("#{root_path}/#{flag}") ? root_path : default - raise "Could not find root path for #{self}" unless root - - -TODO: What is all this for? - -At the root of the system it looks for +config.ru+. TODO: Why? Obviously it's not going to find it, so it uses the +default+ option we've specified which is +Dir.pwd+ which will default to the root folder of your Rails application. This path is then passed to +Rails::Application::Configuration.new+. +Rails::Application::Configuration+ descends from +Rails::Engine::Configuration+ and the +initialize+ method goes like this: - - - def initialize(*) - super - @allow_concurrency = false - @colorize_logging = true - @filter_parameters = [] - @dependency_loading = true - @serve_static_assets = true - @time_zone = "UTC" - @consider_all_requests_local = true - end - - -The +super+ method here is the +initialize+ method in +Rails::Engine::Configuration+: - - - def initialize(root=nil) - @root = root - end - - -Here, the +@root+ variable is assigned the path of your application and then the remainder of +Rails::Application::Configuration.initialize+ is ran, setting up a few instance variables for basic configuration, including one for +@filter_parameters+. - -Now with the +config+ option set up, we can go onwards and call +filter_parameters+ on it. This +filter_parameters+ method is not defined on +Rails::Configuration::Shared+ and actually falls to the +method_missing+ defined there instead: - - - def method_missing(name, *args, &blk) - if name.to_s =~ config_key_regexp - return $2 == '=' ? options[$1] = args.first : options[$1] - end - super - end - - -We're not calling +filter_parameters=+, we're calling +filter_parameters+, therefore it'll be the second part of this ternary argument: +options[$1]+. The options method is defined like this: - - - def options - @@options ||= Hash.new { |h,k| h[k] = ActiveSupport::OrderedOptions.new } - end - - -OrderedOptions exists... TODO: explain. - - -So from this we can determine that our +options+ hash now has a key for +filter_parameters+ which's value is an array consisting of a single symbol: +:password+. How this option manages to get into the +@filter_parameters+ variable defined on the +Rails::Application::Configuration.initialize+ method is explained later. - -h3. Application Configured! - -Now your application has finished being configured (at least in the sense of _config/application.rb_, there's more to come!) in _config/environment.rb_ the final line calls +YourApp::Application.initalize!+. - -h3. Initialization begins - -This is one of those magical uses of +method_missing+ which, for the purposes of debugging, is something that you don't expect to come across as often as you do and as a consequence you'll spend a good portion of an hour looking for method definitions that don't exist because +method_missing+ is taking care of it. There's some pretty crafty use of +method_missing+ all over Rails and it's encouraged to take note of its power. - -+Rails::Application+ has a +method_missing+ definition which does this: - - - def method_missing(*args, &block) - instance.send(*args, &block) - end - - -With our +instance+ being our already initialized by the +inherited+ method, this will just return the value of the +@@instance+ variable, a +Rails::Application+ object. Calling +initialize!+ on this method does this: - - - def initialize! - run_initializers(self) - self - end - - -The initializers it is talking about running here are the initializers for our application. The object passed in to +run_initializers+ is +YourApp::Application+. - - -h3. +run_initializers+ - -This method begins the running of all the defined initializers. In the section "The Boot Process" we covered the loading sequence of Rails before any initialization happens and during this time we saw that the +Rails::Railtie+ class includes the +Initializable+ module. As we've also seen +YourApp::Application+ is a descendant of this class, so it too has these methods. - -+run_initializers+ looks like this: - - - def run_initializers(*args) - return if instance_variable_defined?(:@ran) - initializers.each do |initializer| - initializer.run(*args) - end - @ran = true - end - - -Here the +initializers+ method is defined in _railties/lib/rails/application.rb_: - - - def initializers - initializers = Bootstrap.initializers_for(self) - railties.all { |r| initializers += r.initializers } - initializers += super - initializers += Finisher.initializers_for(self) - initializers - end - - -h3. +Bootstrap+ initializers - -The first line here references a +Bootstrap+ class we haven't seen before. Or have we? The keen-eyed observer would have spotted an +autoload+ for it at the top of +Rails::Application+: - - - autoload :Bootstrap, 'rails/application/bootstrap' - - -Now that we've referenced that class, it will be required for us. You'll notice inside this class that there's an +include Initializable+, providing the afore-mentioned methods from this module. Inside this class a number of initializers are defined. - -* load_environment_config -* load_all_active_support -* preload_frameworks -* initialize_logger -* initialize_cache -* initialize_subscriber -* set_clear_dependencies_hook -* initialize_dependency_mechanism - -These are all defined using the +initializer+ method: - - - def initializer(name, opts = {}, &blk) - raise ArgumentError, "A block must be passed when defining an initializer" unless blk - opts[:after] ||= initializers.last.name unless initializers.empty? || initializers.find { |i| i.name == opts[:before] } - initializers << Initializer.new(name, nil, opts, &blk) - end - - -The +initializers+ method defined here just references an +@initializers+ variable: - - - def initializers - @initializers ||= [] - end - - -As you can see from this method it will set +opts[:after]+ if there are previously defined initializers. So we can determine from this that the order our initializers are defined in is the same order that they run in, but only by default. It is possible to change this by specifying an +:after+ or +:before+ option as we will see later on. Each initializer is its own instance of the +Initializer+ class: - - - class Initializer - attr_reader :name, :block - - def initialize(name, context, options, &block) - @name, @context, @options, @block = name, context, options, block - end - - def before - @options[:before] - end - - def after - @options[:after] - end - - def run(*args) - @context.instance_exec(*args, &block) - end - - def bind(context) - return self if @context - Initializer.new(@name, context, @options, &block) - end - end - - -Now that +Rails::Application::Bootstrap+ has finished loading, we can continue on with our initialization. We saw that it called this: - - - initializers = Bootstrap.initializers_for(self) - - -Calling +initializers_for+, defined like this: - - - def initializers_for(binding) - Collection.new(initializers_chain.map { |i| i.bind(binding) }) - end - - -The +binding+ argument here is +YourApp::Application+ and this will return a new +Initializer+ object for all the initializers in +initializers_chain+ for this particular context. +initializers_chain+ goes like this: - - - def initializers_chain - initializers = Collection.new - ancestors.reverse_each do |klass| - next unless klass.respond_to?(:initializers) - initializers = initializers + klass.initializers - end - initializers - end - - -The ancestors list is relatively short for +Rails::Application::Bootstrap+, consisting of itself and +Rails::Initializable+. Rails will go through these ancestors in reverse and check them all if they +respond_to?(:initializers)+. +Rails::Initializable+ does not and so it's skipped. +Rails::Application::Bootstrap+ of course does, and this is the list of initializers we covered earlier. - -After +initializers_chain+ is finished, then they are +map+'d like this, with the +binding+ of course being +YourApp::Application+ as explained previously. - - - def initializers_for(binding) - Collection.new(initializers_chain.map { |i| i.bind(binding) }) - end - - -Wow. All that to cover just the first line in the +initializers+ method for +Rails::Application+. - -h3. Railties Initializers - -This section covers the loading of the initializers and we will go into depth for each initializer in the next section, as they make more sense explained in their chain. - -The second line in +Rails::Application#initializers+: - - - def initializers - railties.all { |r| initializers += r.initializers } - end - - -calls +railties+, which is defined like this: - - - def railties - @railties ||= Railties.new(config) - end - - -This sets up a new +Rails::Application::Railties+ object like this: - - - def initialize(config) - @config = config - end - - -And calls +all+ on it: - - - def all(&block) - @all ||= railties + engines + plugins - @all.each(&block) if block - @all - end - - -This +all+ method executes code on all the +Rails::Railtie+ and +Rails::Engine+ subclasses, retreived by the +railties+ and +engines+ methods defined right after +all+: - - - def railties - @railties ||= ::Rails::Railtie.subclasses.map(&:new) - end - - def engines - @engines ||= ::Rails::Engine.subclasses.map(&:new) - end - - -By default, the railties are: - -* +ActiveSupport::Railtie+ -* +I18n::Railtie+ -* +ActionDispatch::Railtie+ -* +ActionController::Railtie+ -* +ActiveRecord::Railtie+ -* +ActionView::Railtie+ -* +ActionMailer::Railtie+ -* +ActiveResource::Railtie+ -* +Rails::TestUnitRailtie+ - -And these all descend from +Rails::Railtie+. - -The default +engines+ are +[]+. - -The +plugins+ method it calls is a little more complex: - - - def plugins - @plugins ||= begin - plugin_names = (@config.plugins || [:all]).map { |p| p.to_sym } - Plugin.all(plugin_names, @config.paths.vendor.plugins) - end - end - - -+@config.paths+ is defined in the +Rails::Application::Configuration+ like this: - - - def paths - @paths ||= begin - paths = super - paths.app.controllers << builtin_controller if builtin_controller - paths.config.database "config/database.yml" - paths.config.environment "config/environments", :glob => "#{Rails.env}.rb" - paths.log "log/#{Rails.env}.log" - paths.tmp "tmp" - paths.tmp.cache "tmp/cache" - paths.vendor "vendor", :load_path => true - paths.vendor.plugins "vendor/plugins" - - if File.exists?("#{root}/test/mocks/#{Rails.env}") - ActiveSupport::Deprecation.warn "\"RAILS_ROOT/test/mocks/#{Rails.env}\" won't be added " << - "automatically to load paths anymore in future releases" - paths.mocks_path "test/mocks", :load_path => true, :glob => Rails.env - end - - paths - end - end - - -When we call +@config.paths.vendor.plugins+ it will return +"vendor/plugins"+. - - -If you've defined specific plugin requirements for your application in _config/application.rb_ by using this code: - - - config.plugins = [:will_paginate, :by_star] - - -or specific plugin loading using a similar statement such as this next one: - - - config.plugins = [:will_paginate, :by_star, :all] - - - -Then this is where the +@config.plugins+ comes from. If you wish to load only certain plugins for your application, use the first example. If you wish to load certain plugins before the rest then the second example is what you would use. - -If +config.plugins+ is not defined then +:all+ is specified in its place. Whatever the +plugin_names+ is specified as, is passed to +Plugin.all+ along with the path to the plugins, +@config.path.vendor.plugins+ (which defaults to _vendor/plugins_): - - - def self.all(list, paths) - plugins = [] - paths.each do |path| - Dir["#{path}/*"].each do |plugin_path| - plugin = new(plugin_path) - next unless list.include?(plugin.name) || list.include?(:all) - plugins << plugin - end - end - - plugins.sort_by do |p| - [list.index(p.name) || list.index(:all), p.name.to_s] - end - end - - -As we can see here it will go through the paths and for every folder in _vendor/plugins_ and +initialize+ a new +Rails::Plugin+ object for each: - - - def initialize(root) - @name = File.basename(root).to_sym - config.root = root - end - - -This sets the plugin name to be the same name as the folder so the plugin located at _vendor/plugins/by\_star_'s name is +by_star+. After that, the +config+ object is initialized: - - - def config - @config ||= Engine::Configuration.new - end - - -and the root of the plugin defined as that folder. The reasoning for defining a +root+ is so that the initializer called +load_init_rb+ has some place to look for this file: - - - initializer :load_init_rb, :before => :load_application_initializers do |app| - file = Dir["#{root}/{rails/init,init}.rb"].first - config = app.config - eval(File.read(file), binding, file) if file && File.file?(file) - end - - -A little more on that later, however. - -If the plugin is not included in the list then it moves on to the next one. For all plugins included in the list (or if +:all+ is specified in the list) they are put into a +plugins+ local variable which is then sorted: - - - plugins.sort_by do |p| - [list.index(p.name) || list.index(:all), p.name.to_s] - end - - -The sort order is the same order as which they appear in the +config.plugins+ setting, or in alphabetical order if there is no setting specified. - -Now that we have our railties, engines, and plugins in a line we can finally get back to the +all+ code: - - - def initializers - railties.all { |r| initializers += r.initializers } - end - - -This block will gather add the railties' initializers to it. - -h3. Engine Initializers - -The third line in this +initializers+ method: - - - initializers += super - - -The +super+ method it's referring to is of course +Rails::Engine.initializers+, which isn't defined on the class but, as we have seen before, is defined on the +Rails::Railtie+ class it inherits from through the +Rails::Initializable+ module. Therefore we can determine the initializers to be added are now the ones defined in +Rails::Engine+. - -h3. Finisher Initializers - -The final set of initializers in this chain are those in +Rails::Finisher+. This involves running any after initialize code, building the middleware stack and adding the route for _rails/info/properties_. - -h3. Running the Initializers - -Now that we have all the initializers we can go back to the +run_initializers+ in +Rails::Initializable+: - - - def run_initializers(*args) - return if instance_variable_defined?(:@ran) - initializers.each do |initializer| - initializer.run(*args) - end - @ran = true - end - - -Now we finally have all the +initializers+ we can go through them and call +run+: - - - def run(*args) - @context.instance_exec(*args, &block) - end - - -You may remember that the +@context+ in this code is +YourApp::Application+ and calling +instance_exec+ on this class will make a new instance of it and execute the code within the +&block+ passed to it. This code within the block is the code from all the initializers. - -h3. Bootstrap Initializers - -These initializers are the very first initializers that will be used to get your application going. - -h4. +load_environment_config+ - - - initializer :load_environment_config do - require_environment! - end - - -This quite simply makes a call to +require_environment!+ which is defined like this in +Rails::Application+: - - - def require_environment! - environment = config.paths.config.environment.to_a.first - require environment if environment - end - - -We've seen +config.paths+ before when loading the plugins and they're explained in more detail in the Bonus section at the end of this guide. +config.enviroment+ for +paths+ is defined like this: - - - paths.config.environment "config/environments", :glob => "#{Rails.env}.rb" - - -+Rails.env+ was defined way back in the boot process when +railties/lib/rails.rb+ was required: - - -module Rails - class << self - - ... - - def env - @_env ||= ActiveSupport::StringInquirer.new(ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development") - end - - ... - - end -end - - -With +ENV["RAILS_ENV"]+ and +ENV["RACK_ENV"]+ not set to anything for our server booting process, this will default to +"development"+. - -Therefore the path to this config file line would look like this with a substitution made: - - - paths.config.environment "config/environments", :glob => "development.rb" - - -This method returns a +Path+ object (which acts as an +Enumerable+). - -Back to +require_environment+ now: - - - def require_environment! - environment = config.paths.config.environment.to_a.first - require environment if environment - end - - -And we've determined that +config.paths.config.environment+ is +Path+ object, and calling +to_a+ on that object calls +paths+ because it's +alias+'d at the bottom of the +Path+ class definition: - - - alias to_a paths - - - - def paths - raise "You need to set a path root" unless @root.path - result = @paths.map do |p| - path = File.expand_path(p, @root.path) - @glob ? Dir[File.join(path, @glob)] : path - end - result.flatten! - result.uniq! - result - end - - -This returns an array of files according to our +path+ and +@glob+ which are +config/environments+ and +development.rb+ respectively, therefore we can determine that: - - - Dir[File.join(path, @glob)] - - -will return an +Array+ containing one element, +"config/enviroments/development.rb"+. Of course when we call +first+ on this Array we'll get the first element and because that exists, we now +require "config/environments/development.rb"+. - -This file contains the following by default: - - - YourApp::Application.configure do - # Settings specified here will take precedence over those in config/environment.rb - - # In the development environment your application's code is reloaded on - # every request. This slows down response time but is perfect for development - # since you don't have to restart the webserver when you make code changes. - config.cache_classes = false - - # Log error messages when you accidentally call methods on nil. - config.whiny_nils = true - - # Show full error reports and disable caching - config.consider_all_requests_local = true - config.action_view.debug_rjs = true - config.action_controller.perform_caching = false - - # Don't care if the mailer can't send - config.action_mailer.raise_delivery_errors = false - end - - -This +configure+ method is an +alias+ of +class_eval+ on +Rails::Application+: - - - alias :configure :class_eval - - -therefore, the code inside of the +configure+ is evaluated within the context of +YourApp::Application+. - -The +config+ object here is the same one that was set up when _config/application.rb_ was loaded, therefore the methods called in this object will fall to the +method_missing+ defined in +Rails::Configuration::Shared+: - - - def method_missing(name, *args, &blk) - if name.to_s =~ config_key_regexp - return $2 == '=' ? options[$1] = args.first : options[$1] - end - super - end - - -This time we are using methods ending in +\=+, so it will set the key in the +options+ to be the value specified. The first couple of options, +cache_classes+, +whiny_nils+, +consider_all_requests_local+ are just simple keys on the +options+. If you recall how options were setup then you may be able to work out how the remaining +action_view+, +action_controller+ and +action_mailer+ methods work. - -Firstly, we'll cover how +config_key_regexp+ is defined: - - - def config_key_regexp - bits = config_keys.map { |n| Regexp.escape(n.to_s) }.join('|') - /^(#{bits})(?:=)?$/ - end - - -And also +config_keys+: - - - def config_keys - (Railtie.railtie_names + Engine.engine_names).map { |n| n.to_s }.uniq - end - - -+config_keys+ in here returns: - - - [:active_support, :i18n, :action_dispatch, :action_view, :action_controller, :active_record, :action_mailer, :active_resource, :test_unit] - - -With all of those keys coming from +Railtie::railtie_names+. If you've elected to not load some of the frameworks here they won't be available as configuration keys, so you'll need to remove them too. - -Now a reminder of how the +options+ key is defined: - - - def options - @@options ||= Hash.new { |h,k| h[k] = ActiveSupport::OrderedOptions.new } - end - - -The values for these framework keys are +ActiveSupport::OrderedOptions+ objects, with the class defined like this: - - - module ActiveSupport #:nodoc: - class OrderedOptions < OrderedHash - def []=(key, value) - super(key.to_sym, value) - end - - def [](key) - super(key.to_sym) - end - - def method_missing(name, *args) - if name.to_s =~ /(.*)=$/ - self[$1.to_sym] = args.first - else - self[name] - end - end - end - end - - -We can determine when we call +config.action_view.debug_rjs+ it's falling back to the +method_missing+ defined on +ActiveSupport::OrderedOptions+, which ends up either setting or retrieving a key. In this case because we're using a setter, it will set the key for this hash. This completes the loading of _config/environments/development.rb_. - -h4. +load_all_active_support+ - -This initializer does exactly what it says: - - - initializer :load_all_active_support do - require "active_support/all" unless config.active_support.bare - end - - -If you don't want this to happen you can specify the +config.active_support.bare+ option to +true+ in either _config/application.rb_ or any of your environment files. - -h4. +preload_frameworks+ - -Remember earlier how we had all that stuff +eager_autoload+'d for Active Support? - - - initializer :preload_frameworks do - require 'active_support/dependencies' - ActiveSupport::Autoload.eager_autoload! if config.preload_frameworks - end - - -This is where it gets loaded. The +eager_autoload!+ method is defined like this: - - - def self.eager_autoload! - @@autoloads.values.each { |file| require file } - end - - -With +@@autoloads+ being - - -* load_all_active_support -* preload_frameworks -* initialize_logger -* initialize_cache -* initialize_subscriber -* set_clear_dependencies_hook -* initialize_dependency_mechanism - -h4. Active Support Initializers - -Active Support - -**Active Support Initializers** - -* active_support.initialize_whiny_nils -* active_support.initialize_time_zone - -**I18n Initializers** - -* i18n.initialize - -The +I18n::Railtie+ also defines an +after_initialize+ which we will return to later when discussing the initializers in detail. - -**Action Dispatch Initializers** - -* action_dispatch.prepare_dispatcher - -**Action Controller Initializers** - -* action_controller.logger -* action_controller.set_configs -* action_controller.initialize_framework_caches -* action_controller.set_helpers_path - -**Active Record Initializers** - -* active_record.initialize_time_zone -* active_record.logger -* active_record.set_configs -* active_record.log_runtime -* active_record.initialize_database_middleware -* active_record.load_observers -* active_record.set_dispatch_hooks - -**Action View Initializers ** - -* action_view.cache_asset_ids - -**Action Mailer Initializers ** - -* action_mailer.logger -* action_mailer.set_configs -* action_mailer.url_for - -**Active Resource Initializers** - -* active_resource.set_configs - -**Rails::Engine Initializers** - -* set_load_path -* set_autoload_paths -* add_routing_paths - - -h4. +Rails::Engine.new+ - -The +new+ method doesn't exist, but in Ruby classes calling +new+ on the class instantiates a new instance of that class and calls the instance method +initialize+ on it. This method for +Rails::Application+ goes like this: - - - def initialize - require_environment - Rails.application ||= self - @route_configuration_files = [] - end - - -h4. +Rails::Application#require_environment+ - -This is not a crafty method like the previous ones, it just does as it says on the box: - - - def require_environment - require config.environment_path - rescue LoadError - end - - -The +config+ object here is actually another +delegate+'d method (along with +routes+), this time to +self.class+: - - - delegate :config, :routes, :to => :'self.class' - - -So the method call is actually +self.class.config+. - - -h4. +Rails::Application.config+ - -Defined back inside the +class << self+ for +Rails::Application+, +config+ makes a new +Rails::Application::Configuration+ object and caches it in a variable called +@config+: - - - def config - @config ||= Configuration.new(Plugin::Configuration.default) - end - - -h4. +Rails::Plugin::Configuration.default+ - -The +Rails::Plugin::Configuration+ class may be a bit difficult to find at first, but if you look for _plugin.rb_ in Rails, you'll find it in _railties/lib/rails/plugin.rb_. In this file, we see the following: - - - module Rails - class Plugin < Engine - ... - end - end - - -So we note here that +Rails::Plugin+ descends from +Rails::Railtie+ and secondly we note that the class +Configuration+ is not actually included in the +Plugin+ class, but it **is** in the +Railtie+ class! - -h4. +Rails::Railtie::Configuration+ - -We've now tracked down the +Plugin::Configuration.default+ method to being +Railtie::Configuration.default+, which is defined like this in _railties/lib/rails/configuration.rb_: - - - class Railtie::Configuration - def self.default - @default ||= new - end - ... - end - - -In this case we have effectively seen that it's doing Configuration.new(Configuration.new). I'll explain why. - -h4. +Rails::Application::Configuration.new+ - -TODO: CLEAN THIS UP! This subclassing is only temporary and will probably not be separate in Rails 3. This is based solely off what the comment at the top of the Railtie::Configuration class says! - -The first thing to note here is that this class is subclassed from +Railtie::Configuration+ and therefore the method here is actually +Railtie::Configuration.new+. As mentioned previously, calling +new+ will make a new object of this class and then call +initialize+ on it, which is defined like this: - - - def initialize(base = nil) - if base - @options = base.options.dup - @middleware = base.middleware.dup - else - @options = Hash.new { |h,k| h[k] = ActiveSupport::OrderedOptions.new } - @middleware = self.class.default_middleware_stack - end - end - - -This method is not called with a +base+ argument for +Plugin::Configuration.default+ but it is for the +Configuration.new+ wrapped around it. We'll go for the internal one first, since that's the order Rails loads them in. - -h4. +default_middleware_stack+ - -This method is defined like this: - - - def self.default_middleware_stack - ActionDispatch::MiddlewareStack.new.tap do |middleware| - middleware.use('ActionDispatch::Static', lambda { Rails.public_path }, :if => lambda { Rails.application.config.serve_static_assets }) - middleware.use('::Rack::Lock', :if => lambda { !ActionController::Base.allow_concurrency }) - middleware.use('::Rack::Runtime') - middleware.use('ActionDispatch::ShowExceptions', lambda { ActionController::Base.consider_all_requests_local }) - middleware.use('ActionDispatch::Notifications') - middleware.use('ActionDispatch::Callbacks', lambda { !Rails.application.config.cache_classes }) - middleware.use('ActionDispatch::Cookies') - middleware.use(lambda { ActionController::Base.session_store }, lambda { ActionController::Base.session_options }) - middleware.use('ActionDispatch::Flash', :if => lambda { ActionController::Base.session_store }) - middleware.use('ActionDispatch::ParamsParser') - middleware.use('::Rack::MethodOverride') - middleware.use('::ActionDispatch::Head') - end - end - - -To really understand this method we need to dig a little deeper, down into where +ActionDispatch::MiddlewareStack.new+ is defined and what in particular it does for us. - -h4. +ActionDispatch::MiddlewareStack.new+ - -+ActionDispatch+ is our first foray outside of the +railties+ gem, as this is actually defined in the +actionpack+ part of Rails. The class definition is as important as the method: - - - module ActionDispatch - class MiddlewareStack < Array - - ... - - def initialize(*args, &block) - super(*args) - block.call(self) if block_given? - end - end - end - - -When it's calling +super+ here it's actually calling +initialize+ on the Array class and from this we can determine that an +ActionDispatch::MiddlewareStack+ object is just an +Array+ object with special powers. One of those special powers is the ability to take a block, and +call+ it with +self+, meaning the block's parameter is the object itself! - -h4. +ActionDispatch::MiddlewareStack.use+ - -Previously we saw a chunk of code that I'll re-show you stripped down: - - - def self.default_middleware_stack - ActionDispatch::MiddlewareStack.new.tap do |middleware| - middleware.use('ActionDispatch::Static', lambda { Rails.public_path }, :if => lambda { Rails.application.config.serve_static_assets }) - ... - end - end - - -As explained in the previous section, we know that the +new+ on +ActionDispatch::MiddlewareStack+ takes a block and that block has one parameter which is the object itself. On this object we call the +use+ method to include middleware into our application. The use method simply does this: - - - def use(*args, &block) - middleware = Middleware.new(*args, &block) - push(middleware) - end - - -We'll come back to this method later on. - -h4. +ActionController::Middleware.new+ - -This +initialize+ method also is in a class who's ancestry is important so once again I'll show the ancestry and we'll go up that particular chain: - - - module ActionController - class Middleware < Metal - - ... - - def initialize(app) - super() - @_app = app - end - end - end - - -Here our method calls +super+ but with a difference: it's passing in no arguments intentionally by putting the two brackets at the end. The method called here is therefore +ActionController::Metal.initialize+. - -h4. +ActionController::Metal.initialize+ - -This is another subclassed class, this time from +ActionController::AbstractController+ and I'm sure you can guess what that means: - - - class Metal < AbstractController::Base - - ... - - def initialize(*) - @_headers = {} - super - end - end - - -The single +*+ in the argument listing means we can accept any number of arguments, we just don't care what they are. - -h4. +AbstractController::Base.initialize+ - -This may be anti-climatic, but the initialize method here just returns an +AbstractController::Base+ object: - - - # Initialize controller with nil formats. - def initialize #:nodoc: - @_formats = nil - end - - -h4. +ActionDispatch::MiddlewareStack.use+ - -Now we're back to this method, from our foray into the depths of how +Middleware.new+ works, we've showed that it is an instance of +AbstractController::Base+. Therefore it does - -TODO: ELABORATE ON THIS SECTION, including explaining what all the pieces of middleware do. Then explain how the default_middleware_stack does what it does, whatever that is. - -h4. Back to +Rails::Application::Configuration.new+ - -Now that the first call to this method is complete (+Plugin::Configuration.default+), we can move onto the second call. Here's a refresher of what this method does: - - - def initialize(base = nil) - if base - @options = base.options.dup - @middleware = base.middleware.dup - else - @options = Hash.new { |h,k| h[k] = ActiveSupport::OrderedOptions.new } - @middleware = self.class.default_middleware_stack - end - end - - -You'll note now that this method is being called now is +Configuration.new(Plugin::Configuration.default)+ and with the argument, it's going to perform differently than before, this time duplicating the +options+ and +middleware+ of the object it was passed. - -TODO: Find out what purpose the +@options+ and +@middleware+ variables serve. - -Finally, a +Rails::Application::Configuration+ object will be returned. On this class there are a couple of +attr_accessor+s and +attr_writer+s defined: - - - attr_accessor :after_initialize_blocks, :cache_classes, :colorize_logging, - :consider_all_requests_local, :dependency_loading, - :load_once_paths, :logger, :plugins, - :preload_frameworks, :reload_plugins, :serve_static_assets, - :time_zone, :whiny_nils - - attr_writer :cache_store, :controller_paths, - :database_configuration_file, :eager_load_paths, - :i18n, :load_paths, :log_level, :log_path, :paths, - :routes_configuration_file, :view_path - - -Along with these are a lot of helper methods, and one of them is +environment_path+: - - - def environment_path - "#{root}/config/environments/#{Rails.env}.rb" - end - - -h4. Back to +Rails::Application#require_environment+ - -Now that we have a +Rails::Application::Configuration+ object for the +config+ method, we call the +environment_path+ which, as we've seen above, just requires the current environment file which in this case is _config/environments/development.rb_. If this file cannot be found, the +LoadError+ +require+ throws will be +rescue+'d and Rails will continue on its merry way. - -h4. _config/environments/development.rb_ - -In a standard Rails application we have this in our _config/environments/development.rb_ file: - - - YourApp::Application.configure do - # Settings specified here will take precedence over those in config/environment.rb - - # In the development environment your application's code is reloaded on - # every request. This slows down response time but is perfect for development - # since you don't have to restart the webserver when you make code changes. - config.cache_classes = false - - # Log error messages when you accidentally call methods on nil. - config.whiny_nils = true - - # Show full error reports and disable caching - config.action_controller.consider_all_requests_local = true - config.action_view.debug_rjs = true - config.action_controller.perform_caching = false - - # Don't care if the mailer can't send - config.action_mailer.raise_delivery_errors = false - end - - -It's a little bit sneaky here, but +configure+ is +alias+'d to +class_eval+ on subclasses of +Rails::Application+ which of course includes +YourApp::Application+. This means that the code inside the +configure do+ block will be evaled within the context of +YourApp::Application+. The +config+ method here is the one mentioned before: the +Rails::Application::Configuration+ object. The methods on it should look familiar too: they're the ones that had +attr_accessor+ and +attr_writer+ definitions. - -The ones down the bottom, +config.action_controller+, +config.action_view+ and +config.action_mailer+ aren't defined by +attr_accessor+ or +attr_writer+, rather they're undefined methods and therefore will trigger the +method_missing+ on the +Rails::Application::Configuration+ option. - -h5. config.cache_classes= - -The first method call in this file, this tells Rails to not cache the classes for every request. This means for every single request Rails will reload the classes of your application. If you have a lot of classes, this will slow down the request cycle of your application. This is set to +false+ in the _development_ environment, and +true+ in the _test_ & _production_ environments. - -h5. config.whiny_nils= - -If this is set to +true+, like it is here in the _development_ environment, _activesupport/whiny_nil_ will be +require+'d. Have you ever seen this error: - - - Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id - - -Or perhaps this one? - - - You have a nil object when you didn't expect it! - You might have expected an instance of Array. - The error occurred while evaluating nil.flatten! - - -If you have, then this is _activesupport/whiny_nil_ at work. - - -h5. The frameworks - -As mentioned before, the methods +action_controller+, +action_view+ and +action_mailer+ aren't defined on the +Rails::Application::Configuration+ object, rather they are caught by +method_missing+ which does this: - - - def method_missing(name, *args, &blk) - if name.to_s =~ config_key_regexp - return $2 == '=' ? @options[$1] = args.first : @options[$1] - end - - super - end - - -Whilst this code is not obvious at first, a little bit of further explanation will help you understand. +config_key_regexp+ is another method (a private one, like +method_missing+) defined here: - - - def config_key_regexp - bits = config_keys.map { |n| Regexp.escape(n.to_s) }.join('|') - /^(#{bits})(?:=)?$/ - end - - -As is +config_keys+: - - - def config_keys - ([ :active_support, :action_view ] + - Railtie.plugin_names).map { |n| n.to_s }.uniq - end - - -Aha! There we've got mention of +action_view+, but what is in +Railtie.plugin_names+? Most likely in this case the other frameworks. - -h5. +Railtie.plugin_names+ - -I'm going to show you two methods since the third one, +self.plugin_name+, calls the second one, +self.plugins+ and they're right after each other: - - - module Rails - class Railtie - def self.inherited(klass) - @plugins ||= [] - @plugins << klass unless klass == Plugin - end - - def self.plugins - @plugins - end - - def self.plugin_names - plugins.map { |p| p.plugin_name } - end - end - end - - -In here we see that we get the +plugin_names+ from a variable called +@plugins+... which we haven't seen yet. Through the power of the wonderful +inherited+ the +@plugins+ variable is populated. +inherited+ is called when a class inherits, or subclasses, from this class. Therefore we can determine that the other classes are probably inheriting or subclassing from +Rails::Railtie+. - -h3. Serving a Request - -Now that your application is fully initialized, it's now ready to start serving requests. - -h4. _rails server_ - -For servers running through _rails server_ you may recall that this uses +Rails::Server+ which is a subclass of +Rack::Server+. Previously we covered the initialization process of Rack but not completely up to the point where the server was running. Now that's what we'll do. Back when the +Rack::Server+ class was first covered there was a mention of the +start+ method which we only touched on. It goes a little like this: - - - def start - if options[:debug] - $DEBUG = true - require 'pp' - p options[:server] - pp wrapped_app - pp app - end - - if options[:warn] - $-w = true - end - - if includes = options[:include] - $LOAD_PATH.unshift *includes - end - - if library = options[:require] - require library - end - - daemonize_app if options[:daemonize] - write_pid if options[:pid] - server.run wrapped_app, options - end - - -We were at the point of explaining what +wrapped_app+ was before we dived into the Rails initialization process.Now that we have a +wrapped_app+ we pass it as the first argument to +server.run+. +server+ in this instance is defined like this: - - - def server - @_server ||= Rack::Handler.get(options[:server]) || Rack::Handler.default - end - - -Our +options+ Hash is still the default, and there is no +server+ key set in +default_options+, so it will default to +Rack::Handler.default+. This code works like this: - - - def self.default(options = {}) - # Guess. - if ENV.include?("PHP_FCGI_CHILDREN") - # We already speak FastCGI - options.delete :File - options.delete :Port - - Rack::Handler::FastCGI - elsif ENV.include?("REQUEST_METHOD") - Rack::Handler::CGI - else - begin - Rack::Handler::Mongrel - rescue LoadError => e - Rack::Handler::WEBrick - end - end - end - - - -We don't have +PHP_FCGI_CHILDREN+ in our +ENV+, so it's not going to be +FastCGI+. We also don't have +REQUEST_METHOD+ in there, so it's not going to be +CGI+. If we have Mongrel installed it'll default to that and then finally it'll use WEBrick. For this, we'll assume a bare-bones installation and assume WEBrick. So from this we can determine our default handler is +Rack::Handler::WEBrick+. - -(side-note: Mongrel doesn't install on 1.9. TODO: How do we format these anyway?) - -h5. +Rack::Handler::WEBrick+ - -This class is subclassed from +WEBrick::HTTPServlet::AbstractServlet+ which is a class that comes with the Ruby standard library. This is the magical class that serves the requests and deals with the comings (requests) and goings (responses) for your server. - - -+Rack::Server+ has handlers for the request and by default the handler for a _rails server_ server is - -h3. Cruft! - -The final line of _config/environment.rb_: - - - YourApp::Application.initialize! - - -gets down to actually initializing the application! - -TODO: Cover the other +config.*+ methods in perhaps a "Bonus" section near the end. If they aren't referenced in a config file they aren't that important, right? - - -TODO: This belongs in the guide, I just don't know where yet. Maybe towards the end, since this is really the "final" thing to be done before being able to serve requests. - - - def build_app(app) - middleware[options[:environment]].reverse_each do |middleware| - middleware = middleware.call(self) if middleware.respond_to?(:call) - next unless middleware - klass = middleware.shift - app = klass.new(app, *middleware) - end - app - end - - -Because we don't have any middleware for our application, this returns the application itself( Guessing here!! TODO: Investigate if this is really the case.) - -Now that we have an app instance, the last line in +start+ calls +server.run wrapped_app, options+. We know what our app is, and that our options are just the default options, so what is +server+? +server+ is this: - - - def server - @_server ||= Rack::Handler.get(options[:server]) || Rack::Handler.default - end - - -Since we have default options, the server is obviously going to be +Rack::Handler.default+. The +default+ method goes like this: - - - def self.default(options = {}) - # Guess. - if ENV.include?("PHP_FCGI_CHILDREN") - # We already speak FastCGI - options.delete :File - options.delete :Port - - Rack::Handler::FastCGI - elsif ENV.include?("REQUEST_METHOD") - Rack::Handler::CGI - else - begin - Rack::Handler::Mongrel - rescue LoadError => e - Rack::Handler::WEBrick - end - end - end - - -h3. +Rails::Paths+ - - -The +super+ method it references comes from +Rails::Engine::Configuration+ which defines these paths: - - - def paths - @paths ||= begin - paths = Rails::Paths::Root.new(@root) - paths.app "app", :eager_load => true, :glob => "*" - paths.app.controllers "app/controllers", :eager_load => true - paths.app.helpers "app/helpers", :eager_load => true - paths.app.models "app/models", :eager_load => true - paths.app.views "app/views" - paths.lib "lib", :load_path => true - paths.lib.tasks "lib/tasks", :glob => "**/*.rake" - paths.lib.templates "lib/templates" - paths.config "config" - paths.config.initializers "config/initializers", :glob => "**/*.rb" - paths.config.locales "config/locales", :glob => "*.{rb,yml}" - paths.config.routes "config/routes.rb" - paths - end - end - - -h3. Appendix A - -This file is _activesupport/lib/active_support/inflector/inflections.rb_ and defines the +ActiveSupport::Inflector::Inflections+ class which defines the +singularize+, +pluralize+, +humanize+, +tableize+, +titleize+ and +classify+ methods as well as the code to defining how to work out the irregular, singular, plural and human versions of words. These methods are called +irregular+, +singular+, +plural+ and +human+ respectively, as is the Rails way. - -This file is _activesupport/lib/active_support/inflector/transliterate.rb_ and defines two methods, +transliterate+ and +parameterize+. - -This file first requires _activesupport/lib/active_support/core_ext/string/multibyte.rb_, which requires _activesupport/lib/active_support/multibyte.rb_, which subsequently requires _activesupport/core_ext/module/attribute_accessors.rb_. The _attribute_accessors.rb_ file is needed to gain access to the +mattr_accessor+ (module attribute accessor) method, which is called in _active_suport/multibyte.rb_. The file _active_support/multibyte.rb_ also autoloads three other classes: - - -module ActiveSupport #:nodoc: - module Multibyte - autoload :EncodingError, 'active_support/multibyte/exceptions' - autoload :Chars, 'active_support/multibyte/chars' - autoload :Unicode, 'active_support/multibyte/unicode' - ... - end -end - - -There are also these method definitions: - - - # The proxy class returned when calling mb_chars. You can use this accessor to configure your own proxy - # class so you can support other encodings. See the ActiveSupport::Multibyte::Chars implementation for - # an example how to do this. - # - # Example: - # ActiveSupport::Multibyte.proxy_class = CharsForUTF32 - def self.proxy_class=(klass) - @proxy_class = klass - end - - # Returns the currect proxy class - def self.proxy_class - @proxy_class ||= ActiveSupport::Multibyte::Chars - end - - -These methods are used in _activesupport/lib/active_support/core_ext/string/multibyte.rb_. - -The file _activesupport/lib/active_support/core_ext/string/chars.rb_ defines the default proxy class that will be returned by +mb_chars+. - -Because Ruby 1.9's +String+ class has support for multibyte encodings, some methods are defined only for Ruby 1.8: - -* +self.wants?+ -* +++ -* +=~+ -* +=~+ -* +center+ -* +include?+ -* +index+ -* +insert+ -* +ljust+ -* +lstrip+, +lstrip!+ -* +ord+ -* +rindex+ -* +rjust+ -* +rstrip+, +rstrip!+ -* +size+ -* +strip+, +strip!+ - -However, Ruby 1.9 lacks support for some needed operations, so the following methods are defined for both Ruby 1.8 and Ruby 1.9: - -* +<=>+ -* +[]=+ -* +capitalize+, +capitalize!+ -* +compose+ -* +decompose+ -* +downcase+, +downcase!+ -* +g_length+ -* +limit+ -* +normalize+ -* +reverse+, +reverse+! -* +slice+, +slice!+ -* +split+ -* +tidy_bytes+, +tidy_bytes!+ -* +titleize+ -* +upcase+, +upcase!+ - - - class String - if RUBY_VERSION >= "1.9" - def mb_chars - if ActiveSupport::Multibyte.proxy_class.consumes?(self) - ActiveSupport::Multibyte.proxy_class.new(self) - else - self - end - end - - def is_utf8? #:nodoc - case encoding - when Encoding::UTF_8 - valid_encoding? - when Encoding::ASCII_8BIT, Encoding::US_ASCII - dup.force_encoding(Encoding::UTF_8).valid_encoding? - else - false - end - end - else - def mb_chars - if ActiveSupport::Multibyte.proxy_class.wants?(self) - ActiveSupport::Multibyte.proxy_class.new(self) - else - self - end - end - - # Returns true if the string has UTF-8 semantics (a String used for purely byte resources is unlikely to have - # them), returns false otherwise. - def is_utf8? - ActiveSupport::Multibyte::Chars.consumes?(self) - end - end - - -As you can see, +mb_chars+ is where the +proxy_class+ property comes in handy. This method will create a new instance of the configured proxy class using the instance of +String+ as a constructor argument. By default, the new +String+-like object will be an instance of the proxy class +ActiveSupport::Multibyte::Chars+. You can use +ActiveSupport::Multibyte.proxy_class=+ to set a different proxy class if you wish. - -Here, +mb_chars+ invokes +is_utf8?+ to checks if the string can be treated as UTF-8. On 1.9, the string's +encoding+ property is checked. On 1.8, +wants?+ checks to see if +$KCODE+ is "UTF-8" and, and +consumes?+ checks whether the string can be unpacked as UTF-8 without raising an error. - -The keen eye will have seen +ActiveSupport::Multibyte::Chars+ was specified as an +autoload+ earlier: _activesupport/lib/active_support/multibyte/chars.rb_ will be loaded without an explicit +require+ when we call +is_utf8+ on 1.8, or +mb_chars+ on any Ruby version. This file includes _activesupport/lib/active_support/string/access.rb_ which defines methods such as +at+, +from+, +to+, +first+ and +last+. These methods will return parts of the string depending on what is passed to them. - -The second file included is _activesupport/lib/active_support/string/behavior.rb_ which only defines +acts_like_string?+ on +String+, a method which always returns +true+. This method is used by +Object#acts_like?+, which accepts a single argument representing the downcased and symbolised version of a class, and returns true if the object's behavior is like that class. In this case the code would be +acts_like?(:string)+. - -The +Chars+ class also defines other important methods such as the "spaceship" method +<=>+, which is needed by the +Comparable+ module, in order to allow UTF-8-aware sorting. - -h3. Common Includes - -TODO: I feel this section would be better at the end of the guide as it breaks the flow. - -This section is for all the common includes in the Railties. - -h4. +require 'active_support/inflector'+ - -This file is _activesupport/lib/active_support/inflector.rb_ and makes a couple of requires out different files tasked with putting inflections in place: - - - require 'active_support/inflector/inflections' - require 'active_support/inflector/transliterate' - require 'active_support/inflector/methods' - - require 'active_support/inflections' - require 'active_support/core_ext/string/inflections' - - -The files included here define methods for modifying strings, such as +transliterate+ which will convert a Unicode string to its ASCII version, +parameterize+ for making strings into url-safe versions, +camelize+ for camel-casing a string such as +string_other+ into +StringOther+ and +ordinalize+ converting a string such as +101+ into +101st+. More information about these methods can be found in the Active Support Core Extensions Guide. TODO: Link to AS Guide. - -h4. +require 'active_support/core_ext/module/delegation'+ - -_activesupport/lib/active_support/core_ext/module/delegation.rb_ defines the +delegate+ method which can be used to delegate methods to other methods in your code. Take the following code example: - - - class Client < ActiveRecord::Base - has_one :address - - delegate :address_line_1, :to => :address - end - - -This defines an +address_line_1+ method which is defined as: - - - def address_line_1(*args, &block) - address.__send__(:address_line_1, *args, &block) - rescue NoMethodError - if address.nil? - raise "address_line_1 is delegated to address.address_line_1, but address is nil: #{client.inspect}" - end - end - - -h4. +require 'active_support/core_ext/class/attribute_accessors'+ - -The file, _activesupport/lib/active_support/core_ext/class/attribute_accessors.rb_, defines the class accessor methods +cattr_writer+, +cattr_reader+ and +cattr_accessor+. +cattr_accessor+ defines a +cattr_reader+ and +cattr_writer+ for the symbol passed in. These methods work by defining class variables when you call their dynamic methods. - -Throughout the Railties there a couple of common includes. They are listed here for your convenience. - -h4. +require 'active_support/core_ext/module/attr_internal+ - -This file defines three methods +attr_internal_reader+, +attr_internal_writer+ and +attr_internal_accessor+. These work very similar to the +attr_reader+, +attr_writer+ and +attr_accessor+ methods, except the variables they define begin with +@_+. This was done to ensure that they do not clash with variables used people using Rails, as people are less-likely to define say, +@_request+ than they are to define +@request+. An example of where this method is used is for +params+ in the +ActionController::Metal+ class. - -h4. +require 'active_support/ruby/shim'+ - -The _activesupport/lib/active_support/ruby/shim.rb_ file requires methods that have been implemented in Ruby versions greater than 1.9. This is done so you can use Rails 3 on versions earlier than 1.9, such as 1.8.7. These methods are: - -* +Date#next_month+ -* +Date#next_year+ -* +DateTime#to_date+ -* +DateTime#to_datetime+ -* +DateTime#xmlschema+ -* +Enumerable#group_by+ -* +Enumerable#each_with_object+ -* +Enumerable#none?+ -* +Process#daemon+ -* +String#ord+ -* +Time#to_date+ -* +Time.to_time+ -* +Time.to_datetime+ - -For more information see the Active Support Core Extensions guide TODO: link to relevant sections for each method. - -And "the REXML security fix detailed here":[http://weblog.rubyonrails.org/2008/8/23/dos-vulnerabilities-in-rexml] -- cgit v1.2.3 From 84477543435ef6e4327c7e5e46e3559d7e936cfe Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Tue, 28 Dec 2010 15:06:26 +1000 Subject: init guide: Cover the action_dispatch/railtie require from rails.rb --- railties/guides/source/initialization.textile | 112 ++++++++++++++++++++++++++ 1 file changed, 112 insertions(+) (limited to 'railties/guides') diff --git a/railties/guides/source/initialization.textile b/railties/guides/source/initialization.textile index ca1451faa6..5aecdfde7b 100644 --- a/railties/guides/source/initialization.textile +++ b/railties/guides/source/initialization.textile @@ -914,3 +914,115 @@ Then this Railtie sets up three more initializers: * +active_support.initialize_time_zone+ We will cover what each of these initializers do when they run. + +Once the +active_support/railtie+ file has finished loading the next file required from +railties/lib/rails.rb+ is the +action_dispatch/railtie+. + +h4. +activesupport/lib/action_dispatch/railtie.rb+ + +This file defines the +ActionDispatch::Railtie+ class, but not before requiring +action_dispatch+. + +h4. +activesupport/lib/action_dispatch.rb+ + +This file attempts to locate the +active_support+ and +active_model+ libraries by looking a couple of directories back from the current file and then adds the +active_support+ and +active_model+ +lib+ directories to the load path, but only if they aren't already, which they are. + + + activesupport_path = File.expand_path('../../../activesupport/lib', __FILE__) + $:.unshift(activesupport_path) if File.directory?(activesupport_path) && !$:.include?(activesupport_path) + + activemodel_path = File.expand_path('../../../activemodel/lib', __FILE__) + $:.unshift(activemodel_path) if File.directory?(activemodel_path) && !$:.include?(activemodel_path) + + +In effect, these lines only define the +activesupport_path+ and +activemodel_path+ variables and nothing more. + +The next two requires in this file are already done, so they are not run: + + + require 'active_support' + require 'active_support/dependencies/autoload' + + +The following require is to +action_pack+ (+activesupport/lib/action_pack.rb+) which has a 22-line copyright notice at the top of it and ends in a simple require to +action_pack/version+. This file, like other +version.rb+ files before it, defines the +ActionPack::VERSION+ constant: + + + module ActionPack + module VERSION #:nodoc: + MAJOR = 3 + MINOR = 1 + TINY = 0 + PRE = "beta" + + STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.') + end + end + + +Once +action_pack+ is finished, then +active_model+ is required. + +h4. +activemodel/lib/active_model.rb+ + +This file makes a require to +active_model/version+ which defines the version for Active Model: + + + module ActiveModel + module VERSION #:nodoc: + MAJOR = 3 + MINOR = 1 + TINY = 0 + PRE = "beta" + + STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.') + end + end + + +Once the +version.rb+ file is loaded, the +ActiveModel+ module has its autoloaded constants defined as well as a sub-module called +ActiveModel::Serializers+ which has autoloads of its own. When the +ActiveModel+ module is closed the +active_support/i18n+ file is required. + +h4. +activesupport/lib/active_support/i18n.rb+ + +This is where the +i18n+ gem is required and first configured: + + + begin + require 'i18n' + require 'active_support/lazy_load_hooks' + rescue LoadError => e + $stderr.puts "You don't have i18n installed in your application. Please add it to your Gemfile and run bundle install" + raise e + end + + I18n.load_path << "#{File.dirname(__FILE__)}/locale/en.yml" + + +In effect, the +I18n+ module first defined by +i18n_railtie+ is extended by the +i18n+ gem, rather than the other way around. This has no ill effect. They both work on the same way. + +This is another spot where +active_support/lazy_load_hooks+ is required, but it has already been required so it's not loaded again. + +If +i18n+ cannot be loaded, the user is presented with an error which says that it cannot be loaded and recommends that it's added to the +Gemfile+. However, in a normal Rails application this gem would be loaded. + +Once it has finished loading, the +I18n.load_path+ method is used to add the +activesupport/lib/active_support/locale/en.yml+ file to I18n's load path. When the translations are loaded in the initialization process, this is one of the files where they will be sourced from. + +The loading of this file finishes the loading of +active_model+ and so we go back to +action_dispatch+. + +h4. Back to +activesupport/lib/action_dispatch.rb+ + +The remainder of this file requires the +rack+ file from the Rack gem which defines the +Rack+ module. After +rack+, there's autoloads defined for the +Rack+, +ActionDispatch+, +ActionDispatch::Http+, +ActionDispatch::Session+. A new method called +autoload_under+ is used here, and this simply prefixes the files where the modules are autoloaded from with the path specified. For example here: + + + autoload_under 'testing' do + autoload :Assertions + ... + + +The +Assertions+ module is in the +action_dispatch/testing+ folder rather than simply +action_dispatch+. + +Finally, this file defines a top-level autoload, the +Mime+ constant. + +h4. Back to +activesupport/lib/action_dispatch/railtie.rb+ + +After +action_dispatch+ is required in this file, the +ActionDispatch::Railtie+ class is defined and is yet another class that inherits from +Rails::Railtie+. This class defines some initial configuration option defaults for +config.action_dispatch+ before setting up a single initializer called +action_dispatch.configure+. + +With +action_dispatch/railtie+ now complete, we go back to +railties/lib/rails.rb+. + + + -- cgit v1.2.3 From 591c01123826d10ec8d31ef4c9e7c55ef62edc5b Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Tue, 28 Dec 2010 15:10:13 +1000 Subject: Init: finish coverage of railties/lib/rails.rb --- railties/guides/source/initialization.textile | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'railties/guides') diff --git a/railties/guides/source/initialization.textile b/railties/guides/source/initialization.textile index 5aecdfde7b..ba204ad980 100644 --- a/railties/guides/source/initialization.textile +++ b/railties/guides/source/initialization.textile @@ -1024,5 +1024,12 @@ After +action_dispatch+ is required in this file, the +ActionDispatch::Railtie+ With +action_dispatch/railtie+ now complete, we go back to +railties/lib/rails.rb+. +h4. Back to +railties/lib/rails.rb+ + +With the Active Support and Action Dispatch railties now both loaded, the rest of this file deals with setting up UTF-8 to be the default encoding for Rails and then finally setting up the +Rails+ module. This module defines useful methods such as +Rails.logger+, +Rails.application+, +Rails.env+, and +Rails.root+. + + + + -- cgit v1.2.3 From 777a1f125ddc2e6f56e07b9ecb4463203fdd8218 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Tue, 28 Dec 2010 16:01:16 +1000 Subject: Init guide: begin down the rabbit warren that is active_record/railtie --- railties/guides/source/initialization.textile | 77 +++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) (limited to 'railties/guides') diff --git a/railties/guides/source/initialization.textile b/railties/guides/source/initialization.textile index ba204ad980..b1663a334c 100644 --- a/railties/guides/source/initialization.textile +++ b/railties/guides/source/initialization.textile @@ -1028,8 +1028,85 @@ h4. Back to +railties/lib/rails.rb+ With the Active Support and Action Dispatch railties now both loaded, the rest of this file deals with setting up UTF-8 to be the default encoding for Rails and then finally setting up the +Rails+ module. This module defines useful methods such as +Rails.logger+, +Rails.application+, +Rails.env+, and +Rails.root+. +h4. Back to +railties/lib/rails/all.rb+ +Now that +rails.rb+ is required, the remaining railties are loaded next, beginning with +active_record/railtie+. +h4. +activerecord/lib/active_record/railtie.rb+ +Before this file gets into the swing of defining the +ActiveRecord::Railtie+ class, there's a couple of files that are required first. The first one of these is +active_record+. +h4. +activerecord/lib/active_record.rb+ +This file begins by detecting if the +lib+ directories of +active_support+ and +active_model+ are not in the load path and if they aren't then adds them. As we saw back in +action_dispatch.rb+, these directories are already there. + +The first three requires have already been done by other files and so aren't loaded here, but the 4th require, the one to +arel+ will require the file provided by the Arel gem, which defines the +Arel+ module. + + + require 'active_support' + require 'active_support/i18n' + require 'active_model' + require 'arel' + + +The 5th require in this file is one to +active_record/version+ which defines the +ActiveRecord::VERSION+ constant: + + + module ActiveRecord + module VERSION #:nodoc: + MAJOR = 3 + MINOR = 1 + TINY = 0 + PRE = "beta" + + STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.') + end + end + + +Once these requires are finished, the base for the +ActiveRecord+ module is defined along with its autoloads. + +Near the end of the file, we see this line: + + + ActiveSupport.on_load(:active_record) do + Arel::Table.engine = self + end + + +This will set the engine for +Arel::Table+ to be +ActiveRecord::Base+. + +The file then finishes with this line: + + + I18n.load_path << File.dirname(__FILE__) + '/active_record/locale/en.yml' + + +This will add the translations from +activerecord/lib/active_record/locale/en.yml+ to the load path for +I18n+, with this file being parsed when all the translations are loaded. + +h4. Back to +activerecord/lib/active_record/railtie.rb+ + +The next two requires in this file aren't run because their files are already required, with +rails+ being required by +rails/all+ and +active_model/railtie+ being required from +action_dispatch+. + + + require "rails" + require "active_model/railtie" + + +The next +require+ in this file is to +action_controller/railtie+. + +h4. +actionpack/lib/action_controller/railtie.rb+ + +This file begins with a couple more requires to files that have already been loaded: + + + require "rails" + require "action_controller" + require "action_dispatch/railtie" + + +However the require after these is to a file that hasn't yet been loaded, +action_view/railtie+, which begins by requiring +action_view+. + +h4. +actionpack/lib/action_view.rb+ + ++action_view.rb+ -- cgit v1.2.3 From bb99c944d3b57fd40b19ea0c07ef984e2be46da3 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Tue, 28 Dec 2010 17:32:41 +1000 Subject: There's a couple -> There are a couple --- railties/guides/source/initialization.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/initialization.textile b/railties/guides/source/initialization.textile index b1663a334c..0cbbe1f389 100644 --- a/railties/guides/source/initialization.textile +++ b/railties/guides/source/initialization.textile @@ -1034,7 +1034,7 @@ Now that +rails.rb+ is required, the remaining railties are loaded next, beginni h4. +activerecord/lib/active_record/railtie.rb+ -Before this file gets into the swing of defining the +ActiveRecord::Railtie+ class, there's a couple of files that are required first. The first one of these is +active_record+. +Before this file gets into the swing of defining the +ActiveRecord::Railtie+ class, there are a couple of files that are required first. The first one of these is +active_record+. h4. +activerecord/lib/active_record.rb+ -- cgit v1.2.3 From 8e8c13ab1ed1140f708c8af74f386a3f6dec6e0a Mon Sep 17 00:00:00 2001 From: Karel Minarik Date: Tue, 28 Dec 2010 08:45:09 +0100 Subject: Fixed incorrect command for displaying options for new application Generator in Getting Started guide --- railties/guides/source/getting_started.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/getting_started.textile b/railties/guides/source/getting_started.textile index 4466c291bb..43525d7a57 100644 --- a/railties/guides/source/getting_started.textile +++ b/railties/guides/source/getting_started.textile @@ -163,7 +163,7 @@ $ rails new blog This will create a Rails application called Blog in a directory called blog. -TIP: You can see all of the switches that the Rails application builder accepts by running rails -h. +TIP: You can see all of the switches that the Rails application builder accepts by running rails new -h. After you create the blog application, switch to its folder to continue work directly in that application: -- cgit v1.2.3 From e2c2c2983a83ed53e2287a936a0ab59080be16f6 Mon Sep 17 00:00:00 2001 From: Karel Minarik Date: Tue, 28 Dec 2010 09:24:49 +0100 Subject: Added TIP box with information about the `--database` switch for the application generator in the "Getting Started" guide --- railties/guides/source/getting_started.textile | 2 ++ 1 file changed, 2 insertions(+) (limited to 'railties/guides') diff --git a/railties/guides/source/getting_started.textile b/railties/guides/source/getting_started.textile index 43525d7a57..97c050ded3 100644 --- a/railties/guides/source/getting_started.textile +++ b/railties/guides/source/getting_started.textile @@ -258,6 +258,8 @@ development: Change the username and password in the +development+ section as appropriate. +TIP: You don't have to update the database configurations manually. If you had a look at the options of application generator, you have seen that one of them is named --database. It lets you choose an adapter for couple of most used relational databases. You can even run the generator repeatedly: cd .. && rails new blog --database=mysql. When you confirm the overwriting of the +config/database.yml+ file, your application will be configured for MySQL instead of SQLite. + h4. Creating the Database Now that you have your database configured, it's time to have Rails create an empty database for you. You can do this by running a rake command: -- cgit v1.2.3 From 8031b7e42ba1b4d3e671e6ed52ffca890da160b0 Mon Sep 17 00:00:00 2001 From: Karel Minarik Date: Tue, 28 Dec 2010 10:25:55 +0100 Subject: Fixed incorrect instructions for calling the `rails` command explicitely in the "Getting Started" guide --- railties/guides/source/getting_started.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/getting_started.textile b/railties/guides/source/getting_started.textile index 97c050ded3..6a5a2b2d3b 100644 --- a/railties/guides/source/getting_started.textile +++ b/railties/guides/source/getting_started.textile @@ -300,7 +300,7 @@ To get Rails saying "Hello", you need to create at minimum a controller and a vi $ rails generate controller home index -TIP: If you're on Windows, or your Ruby is set up in some non-standard fashion, you may need to explicitly pass Rails +rails+ commands to Ruby: +ruby \path\to\rails controller home index+. +TIP: If you're on Windows, or your Ruby is set up in some non-standard fashion, you may need to explicitly pass Rails +rails+ commands to Ruby: ruby \path\to\your\application\script\rails generate controller home index. Rails will create several files for you, including +app/views/home/index.html.erb+. This is the template that will be used to display the results of the +index+ action (method) in the +home+ controller. Open this file in your text editor and edit it to contain a single line of code: -- cgit v1.2.3 From cb4b5c8ad39e9e7a44ec13ded88083fe76cf8405 Mon Sep 17 00:00:00 2001 From: Karel Minarik Date: Tue, 28 Dec 2010 16:37:11 +0100 Subject: Adding information and link to guide on customizing generators into "Getting Started" guide. --- railties/guides/source/getting_started.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/getting_started.textile b/railties/guides/source/getting_started.textile index 6a5a2b2d3b..f45e6cab11 100644 --- a/railties/guides/source/getting_started.textile +++ b/railties/guides/source/getting_started.textile @@ -349,7 +349,7 @@ In the case of the blog application, you can start by generating a scaffolded Po $ rails generate scaffold Post name:string title:string content:text -NOTE. While scaffolding will get you up and running quickly, the "one size fits all" code that it generates is unlikely to be a perfect fit for your application. In most cases, you'll need to customize the generated code. Many experienced Rails developers avoid scaffolding entirely, preferring to write all or most of their source code from scratch. +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 15 files in your application, along with some folders, and edit one more. Here's a quick overview of what it creates: -- cgit v1.2.3 From 9f75545e5d0aded71f973edd0e5ff4daf3e7c580 Mon Sep 17 00:00:00 2001 From: Karel Minarik Date: Tue, 28 Dec 2010 17:30:13 +0100 Subject: Added information about invoking migrations in non-default environments to NOTE box in the "Getting Started" guide Reason: When the guide already mentions "default environment", I think it is more then appropriate to tell the whole story. --- railties/guides/source/getting_started.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/getting_started.textile b/railties/guides/source/getting_started.textile index f45e6cab11..82700532c0 100644 --- a/railties/guides/source/getting_started.textile +++ b/railties/guides/source/getting_started.textile @@ -411,7 +411,7 @@ Rails will execute this migration command and tell you it created the Posts tabl == CreatePosts: migrated (0.0020s) =========================================== -NOTE. Because you're working in the development environment by default, this command will apply to the database defined in the +development+ section of your +config/database.yml+ file. +NOTE. Because you're working in the development environment by default, this command will apply to the database defined in the +development+ section of your +config/database.yml+ file. If you would like to execute migrations in other environment, for instance in production, you must explicitely pass it when invoking the command: rake db:migrate RAILS_ENV=production. h4. Adding a Link -- cgit v1.2.3 From 6b43a3a6271faa81ee53bd798b290320217e3262 Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Mon, 27 Dec 2010 16:29:03 +0100 Subject: complete revision of the Contributing to Ruby on Rails guide * adds instructions for PostgreSQL * adds references to mysql2 here and there * puts documentation contributions on par with code contributions * adds a section about Rails Contributors * documents C dependencies for Nokogiri and the database libs * everything double-checked and revised step by step * adds a section about warnings in the test suite * removes section about the Rails wiki * title and filename renamed * overall rewording --- .../guides/source/contributing_to_rails.textile | 311 ------------------ .../source/contributing_to_ruby_on_rails.textile | 355 +++++++++++++++++++++ 2 files changed, 355 insertions(+), 311 deletions(-) delete mode 100644 railties/guides/source/contributing_to_rails.textile create mode 100644 railties/guides/source/contributing_to_ruby_on_rails.textile (limited to 'railties/guides') diff --git a/railties/guides/source/contributing_to_rails.textile b/railties/guides/source/contributing_to_rails.textile deleted file mode 100644 index 1a1f4e9858..0000000000 --- a/railties/guides/source/contributing_to_rails.textile +++ /dev/null @@ -1,311 +0,0 @@ -h2. Contributing to Rails - -This guide covers ways in which _you_ can become a part of the ongoing development of Rails. After reading it, you should be familiar with: - -* Using Lighthouse to report issues with Rails -* Cloning edge Rails and running the test suite -* Helping to resolve existing issues -* Contributing to the Rails documentation -* Contributing to the Rails code - -Rails is not "someone else's framework." Over the years, hundreds of people have contributed code ranging from a single character to massive architectural changes, all with the goal of making Rails better for everyone. Even if you don't feel up to writing code yet, there are a variety of other ways that you can contribute, from reporting issues to testing patches to contributing documentation. - -endprologue. - -h3. Reporting a Rails Issue - -Rails uses a "Lighthouse project":http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/ to track issues (primarily bugs and contributions of new code). If you've found a bug in Rails, this is the place to start. You'll need to create a (free) Lighthouse account in order to comment on issues or to upload tests or patches. - -NOTE: Bugs in the most recent released version of Rails are likely to get the most attention. Also, the Rails core team is always interested in feedback from those who can take the time to test _edge Rails_ (the code for the version of Rails that is currently under development). Later in this Guide you'll find out how to get edge Rails for testing. - -h4. Creating a Bug Report - -If you've found a problem in Rails, you can start by "adding a new ticket":http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/new to the Rails Lighthouse. At the minimum, your ticket needs a title and descriptive text. But that's only a minimum. You should include as much relevant information as possible. You need to at least post the code sample that has the issue. Even better is to include a unit test that shows how the expected behavior is not occurring. Your goal should be to make it easy for yourself - and others - to replicate the bug and figure out a fix. - -You shouldn't assign the bug to a particular core developer (through the *Who's Responsible* select list) unless you know for sure which developer will be handling any patch. The core team periodically reviews issues and assigns developers and milestones to them. - -You should set tags for your issue. Use the "bug" tag for a bug report, and add the "patch" tag if you are attaching a patch. Try to find some relevant tags from the existing tag list (which will appear as soon as you start typing in the *Choose some tags* textbox), rather than creating new tags. - -Then don't get your hopes up. Unless you have a "Code Red, Mission Critical, The World is Coming to an End" kind of bug, you're creating this ticket in the hope that others with the same problem will be able to collaborate with you on solving it. Do not expect that the ticket automatically will see any activity or that others will jump to fix it. Creating a ticket like this is mostly to help yourself start on the path of fixing the problem and for others to confirm it with a "I'm having this problem too" comment. - -h4. Special Treatment for Security Issues - -If you've found a security vulnerability in Rails, please do *not* report it via a Lighthouse ticket. Lighthouse tickets are public as soon as they are entered. Instead, you should use the dedicated email address "security@rubyonrails.org":mailto:security@rubyonrails.org to report any vulnerabilities. This alias is monitored and the core team will work with you to quickly and completely address any such vulnerabilities. - -WARNING: Just to emphasize the point, _please do not report security vulnerabilities on public Lighthouse tickets_. This will only expose your fellow Rails developers to needless risks. - -You should receive an acknowledgement and detailed response to any reported security issue within 48 hours. If you don't think you're getting adequate response from the security alias, refer to the "Rails security policy page":http://rubyonrails.org/security for direct emails for the current Rails security coordinators. - -h4. What About Feature Requests? - -Please don't put "feature request" tickets into Lighthouse. If there's a new feature that you want to see added to Rails, you'll need to write the code yourself - or convince someone else to partner with you to write the code. Later in this guide you'll find detailed instructions for proposing a patch to Rails. If you enter a wishlist item in Lighthouse with no code, you can expect it to be marked "invalid" as soon as it's reviewed. - -h3. Running the Rails Test Suite - -To move on from submitting bugs to helping resolve existing issues or contributing your own code to Rails, you _must_ be able to run the Rails test suite. In this section of the guide you'll learn how to set up the tests on your own computer. - -h4. Install git - -Rails uses git for source code control. You won’t be able to do anything without the Rails source code, and this is a prerequisite. The "git homepage":http://git-scm.com/ has installation instructions. If you’re on OS X, use the "Git for OS X":http://code.google.com/p/git-osx-installer/ installer. If you're unfamiliar with git, there are a variety of resources on the net that will help you learn more: - -* "Everyday Git":http://www.kernel.org/pub/software/scm/git/docs/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://github.com/guides/home 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. Get the Rails Source Code - -Don’t fork the main Rails repository. Instead, you want to clone it to your own computer. Navigate to the folder where you want the source code (it will create its own /rails subdirectory) and run: - - -git clone git://github.com/rails/rails.git -cd rails - - -h4. Set up and Run the Tests - -All of the Rails tests must pass with any code you submit, otherwise you have no chance of getting code accepted. This means you need to be able to run the tests. First, you need to install all Rails dependencies with bundler: - -NOTE: Ensure you install bundler v1.0 - - -gem install bundler -bundle install --without db - - -The second command will install all dependencies, except MySQL and PostgreSQL. We will come back at these soon. With dependencies installed, you can run the whole Rails test suite with: - - -rake test - - -You can also run tests for an specific framework, like Action Pack, by going into its directory and executing the same command: - - -cd actionpack -rake test - - -h4. Testing Active Record - -By default, when you run Active Record tests, it will execute the test suite three times, one for each of the main databases: SQLite3, MySQL and PostgreSQL. If you are adding a feature that is not specific to the database, you can run the test suite (or just one file) for just one of them. Here is an example for SQLite3: - - -cd activerecord -rake test_sqlite3 -rake test_sqlite3 TEST=test/cases/validations_test.rb - - -If you want to use another database, as MySQL, you need to create a user named +rails+ with privileges on the test databases. - - -mysql> GRANT ALL PRIVILEGES ON activerecord_unittest.* - to 'rails'@'localhost'; -mysql> GRANT ALL PRIVILEGES ON activerecord_unittest2.* - to 'rails'@'localhost'; - - -Now you'll have to install Active Record dependencies. This step is a little tricky because just running +bundle install+ without the +--without db+ parameter won't get those dependencies installed. It turns out that bundler remembers the +--without db+ parameter between calls so you'll have to manually override this. (See the "+bundle_install+ man page":http://gembundler.com/man/bundle-install.1.html for details) - -The easiest way to do this is to remove bundler's config file and then run +install+ again: - - -rm .bundle/config -bundle install - - -INFO: If you don't feel comfortable deleting bundler's config file, you can achieve the same effect by manually removing the "+BUNDLE_WITHOUT: db+" line on +.bundle/config+. - -Finally, enter this from the +activerecord+ directory to create the test databases: - - -rake mysql:build_databases - - -NOTE: Using the rake task to create the test databases ensures they have the correct character set and collation. - -If you’re using another database, check the files under +activerecord/test/connections+ in the Rails source code for default connection information. You can edit these files if you _must_ on your machine to provide different credentials, but obviously you should not push any such changes back to Rails. - -You can now run tests as you did for +sqlite3+: - - -rake test_mysql - - -You can also replace +mysql+ with +postgresql+, +jdbcmysql+, +jdbcsqlite3+ or +jdbcpostgresql+. Check out the file +activerecord/RUNNING_UNIT_TESTS+ for information on running more targeted database tests, or the file +ci/ci_build.rb+ to see the test suite that the Rails continuous integration server runs. - -NOTE: If you're working with Active Record code, you _must_ ensure that the tests pass for at least MySQL, PostgreSQL, and SQLite 3. Subtle differences between the various Active Record database adapters have been behind the rejection of many patches that looked OK when tested only against MySQL. - -h4. Older versions of Rails - -If you want to work add a fix to older versions of Rails, you'll need to set up and switch to your own local tracking branch. Here is an example to switch to Rails 2.3 branch: - - -git branch --track 2-3-stable origin/2-3-stable -git checkout 2-3-stable - - -TIP: You may want to "put your git branch name in your shell prompt":http://github.com/guides/put-your-git-branch-name-in-your-shell-prompt to make it easier to remember which version of the code you're working with. - -h3. Helping to Resolve Existing Issues - -As a next step beyond reporting issues, you can help the core team resolve existing issues. If you check the "open tickets":https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets?q=state%3Aopen list in Lighthouse, you'll find hundreds of issues already requiring attention. What can you do for these? Quite a bit, actually: - -h4. Verifying Bug Reports - -For starters, it helps to just verify bug reports. Can you reproduce the reported issue on your own computer? If so, you can add a comment to the ticket saying that you're seeing the same thing. - -If something is very vague, can you help squish it down into something specific? Maybe you can provide additional information to help reproduce a bug, or eliminate needless steps that aren't required to help demonstrate the problem. - -If you find a bug report without a test, it's very useful to contribute a failing test. This is also a great way to get started exploring the Rails source: looking at the existing test files will teach you how to write more tests for Rails. New tests are best contributed in the form of a patch, as explained later on in the "Contributing to the Rails Code" section. - -Anything you can do to make bug reports more succinct or easier to reproduce is a help to folks trying to write code to fix those bugs - whether you end up writing the code yourself or not. - -h4. Testing Patches - -You can also help out by examining patches that have been submitted to Rails via Lighthouse. To apply someone's changes you need to first create a branch of the Rails source code: - - -git checkout -b testing_branch - - -Then you can apply their patch: - - -git apply their-patch-file.diff - - -After applying a patch, test it out! Here are some things to think about: - -* Does the patch actually work? -* Are you happy with the tests? Can you follow what they're testing? Are there any tests missing? -* Does the documentation still seem right to you? -* Do you like the implementation? Can you think of a nicer or faster way to implement a part of their change? - -Once you're happy that the patch contains a good change, comment on the Lighthouse ticket indicating your approval. Your comment should indicate that you like the change and what you like about it. Something like: - -
-I like the way you've restructured that code in generate_finder_sql, much nicer. The tests look good too. -
- -If your comment simply says "+1", then odds are that other reviewers aren't going to take it too seriously. Show that you took the time to review the patch. Once three people have approved it, add the "verified" tag. This will bring it to the attention of a core team member who will review the changes looking for the same kinds of things. - -h3. Contributing to the Rails Documentation - -Another area where you can help out if you're not yet ready to take the plunge to writing Rails core code is with Rails documentation. You can help with the Rails Guides or the Rails API documentation. - -TIP: "docrails":http://github.com/lifo/docrails/tree/master is the documentation branch for Rails with an *open commit policy*, it has public write access. Documentation changes made as part of the "docrails":http://github.com/lifo/docrails/tree/master project are merged back to the Rails master code from time to time. Check out the "original announcement":http://weblog.rubyonrails.org/2008/5/2/help-improve-rails-documentation-on-git-branch for more details. - -h4. The Rails Guides - -The "Rails Guides":http://guides.rubyonrails.org/ are a set of online resources that are designed to make people productive with Rails and to understand how all of the pieces fit together. These guides (including this one!) are written as part of the "docrails":http://github.com/lifo/docrails/tree/master project. If you have an idea for a new guide, or improvements for an existing guide, you can refer to the "contribution page":contribute.html for instructions on getting involved. - -h4. The Rails API Documentation - -The "Rails API documentation":http://api.rubyonrails.org/ is automatically generated from the Rails source code via "RDoc":http://rdoc.rubyforge.org/. If you find some part of the documentation to be incomplete, confusing, or just plain wrong, you can step in and fix it. - -To contribute an update to the API documentation, you can contact "lifo":http://github.com/lifo on GitHub and ask for commit rights to the docrails repository and push your changes to the docrails repository. Please follow the "docrails RDoc conventions":http://wiki.github.com/lifo/docrails/rails-api-documentation-conventions when contributing the changes. - -h3. The Rails Wiki - -The "Rails wiki":http://wiki.rubyonrails.org/ is a collection of user-generated and freely-editable information about Rails. It covers everything from getting started to FAQs to how-tos and popular plugins. To contribute to the wiki, just find some useful information that isn't there already and add it. There are style guidelines to help keep the wiki a coherent resources; see the section on "contributing to the wiki":http://wiki.rubyonrails.org/#contributing_to_the_wiki for more details. - -h3. Contributing to the Rails Code - -When you're ready to take the plunge, one of the most helpful ways to contribute to Rails is to actually submit source code. Here's a step-by-step listing of the things you need to do to make this a successful experience. - -h4. Learn the Language and the Framework - -Learn at least _something_ about Ruby and Rails. If you don’t understand the syntax of the language, common Ruby idioms, and the code that already exists in Rails, you’re unlikely to be able to build a good patch (that is, one that will get accepted). You don’t have to know every in-and-out of the language and the framework; some of the Rails code is fiendishly complex. But Rails is probably not appropriate as the first place that you ever write Ruby code. You should at least understand (though not necessarily memorize) "The Ruby Programming Language":http://www.amazon.com/gp/product/0596516177?ie=UTF8&linkCode=as2&camp=1789&creative=390957&creativeASIN=0596516177 and have browsed the Rails source code. - -h4. Fork the Rails Source Code - -Fork Rails. You’re not going to put your patches right into the master branch, OK? This is where you need that copy of Rails that you cloned earlier. Think of a name for your new branch and run - - -git checkout -b my_new_branch - - -It doesn’t really matter what name you use, because this branch will only exist on your local computer. - -h4. Write Your Code - -Now get busy and add your code to Rails (or edit the existing code). You’re on your branch now, so you can write whatever you want (you can check to make sure you’re on the right branch with +git branch -a+). But if you’re planning to submit your change back for inclusion in Rails, keep a few things in mind: - -* Get the code right -* Use Rails idioms and helpers -* Include tests that fail without your code, and pass with it -* Update the documentation - -h4. Follow the Coding Conventions - -Rails follows a simple set of coding style conventions. - -* Two spaces, no tabs -* Prefer +&&+/+||+ over +and+/+or+ -* +MyClass.my_method(my_arg)+ not +my_method( my_arg )+ or +my_method my_arg+ -* Follow the conventions you see used in the source already - -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. - -You might also want to check out the "RailsBridge BugMash":http://wiki.railsbridge.org/projects/railsbridge/wiki/BugMash as a way to get involved in a group effort to improve Rails. This can help you get started and help check your code when you're writing your first patches. - -h4. Commit Your Changes - -When you're happy with the code on your computer, you need to commit the changes to git: - - -git commit -a -m "Here is a commit message" - - -h4. Update Rails - -Update your copy of Rails. It’s pretty likely that other changes to core Rails have happened while you were working. Go get them: - - -git checkout master -git pull - - -Now reapply your patch on top of the latest changes: - - -git checkout my_new_branch -git rebase master - - -No conflicts? Tests still pass? Change still seems reasonable to you? Then move on. - -h4. Create a Patch - -Now you can create a patch file to share with other developers (and with the Rails core team). Still in your branch, run - - -git commit -a -git format-patch master --stdout > my_new_patch.diff - - -Sanity check the results of this operation: open the diff file in your text editor of choice and make sure that no unintended changes crept in. - -h4. Create a Lighthouse Ticket - -Now create a ticket with your patch. Go to the "new ticket":http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/new page at Lighthouse. Fill in a reasonable title and description, remember to attach your patch file, and tag the ticket with the ‘patch’ tag and whatever other subject area tags make sense. - -h4. Get Some Feedback - -Now you need to get other people to look at your patch, just as you've looked at other people's patches. You can use the rubyonrails-core mailing list or the #rails-contrib channel on IRC freenode for this. You might also try just talking to Rails developers that you know. - -h4. Iterate as Necessary - -It’s entirely possible that the feedback you get will suggest changes. Don’t get discouraged: the whole point of contributing to an active open source project is to tap into community knowledge. If people are encouraging you to tweak your code, then it’s worth making the tweaks and resubmitting. If the feedback is that your code doesn’t belong in the core, you might still think about releasing it as a plugin. - -And then...think about your next contribution! - -h3. Changelog - -* April 6, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com -* August 1, 2009: Updates/amplifications by "Mike Gunderloy":credits.html#mgunderloy -* March 2, 2009: Initial draft by "Mike Gunderloy":credits.html#mgunderloy - diff --git a/railties/guides/source/contributing_to_ruby_on_rails.textile b/railties/guides/source/contributing_to_ruby_on_rails.textile new file mode 100644 index 0000000000..7c0f32d9ca --- /dev/null +++ b/railties/guides/source/contributing_to_ruby_on_rails.textile @@ -0,0 +1,355 @@ +h2. Contributing to Ruby on Rails + +This guide covers ways in which _you_ can become a part of the ongoing development of Ruby on Rails. After reading it, you should be familiar with: + +* Using Lighthouse to report issues +* Cloning master and running the test suite +* Helping to resolve existing issues +* Contributing to the Ruby on Rails documentation +* Contributing to the Ruby on Rails code + +Ruby on Rails is not "someone else's framework." Over the years, hundreds of people have contributed to Ruby on Rails ranging from a single character to massive architectural changes or significant documentation. All with the goal of making Ruby on Rails better for everyone. Even if you don't feel up to writing code or documentation yet, there are a variety of other ways that you can contribute, from reporting issues to testing patches. + +endprologue. + +h3. Reporting an Issue + +Ruby on Rails uses a "Lighthouse project":http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/ to track issues (primarily bugs and contributions of new code). If you've found a bug in Ruby on Rails, this is the place to start. You'll need to create a (free) Lighthouse account in order to comment on issues or to upload patches. + +NOTE: Bugs in the most recent released version of Ruby on Rails are likely to get the most attention. Also, the Rails core team is always interested in feedback from those who can take the time to test _edge Rails_ (the code for the version of Rails that is currently under development). Later in this guide you'll find out how to get edge Rails for testing. + +h4. Creating a Bug Report + +If you've found a problem in Ruby on Rails which is not a security risk do a search in Lighthouse in case it was already reported. If you find no ticket addressing it you can "add a new one":http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/new. (See the next section for reporting security issues.) + +At the minimum, your ticket needs a title and descriptive text. But that's only a minimum. You should include as much relevant information as possible. You need to at least post the code sample that has the issue. Even better is to include a unit test that shows how the expected behavior is not occurring. Your goal should be to make it easy for yourself - and others - to replicate the bug and figure out a fix. + +You shouldn't assign the bug to a particular core developer unless you know for sure which developer will be handling that issue. The core team periodically reviews issues and assigns developers and milestones to them. + +You should set tags for your issue. Use the "bug" tag for a bug report, and add the "patch" tag if you are attaching a patch. Try to find some relevant tags from the existing tag list (which will appear as soon as you start typing in the "Choose some tags" textbox), rather than creating new tags. + +Then don't get your hopes up. Unless you have a "Code Red, Mission Critical, The World is Coming to an End" kind of bug, you're creating this ticket in the hope that others with the same problem will be able to collaborate with you on solving it. Do not expect that the ticket automatically will see any activity or that others will jump to fix it. Creating a ticket like this is mostly to help yourself start on the path of fixing the problem and for others to confirm it with a "I'm having this problem too" comment. + +h4. Special Treatment for Security Issues + +WARNING: Please do not report security vulnerabilities on public Lighthouse tickets. The "Rails security policy page":http://rubyonrails.org/security details the procedure to follow for security issues. + +h4. What About Feature Requests? + +Please don't put "feature request" tickets into Lighthouse. If there's a new feature that you want to see added to Ruby on Rails, you'll need to write the code yourself - or convince someone else to partner with you to write the code. Later in this guide you'll find detailed instructions for proposing a patch to Ruby on Rails. If you enter a wishlist item in Lighthouse with no code, you can expect it to be marked "invalid" as soon as it's reviewed. + +h3. Running the Test Suite + +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 + +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://www.kernel.org/pub/software/scm/git/docs/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://github.com/guides/home 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. 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: + + +git clone git://github.com/rails/rails.git +cd rails + + +h4. 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. + +Install first libxml2 and libxslt together with their development files for Nokogiri. Also, SQLite3 and its development files for the +sqlite3-ruby+ gem. + +Get a recent version of "Bundler":http://gembundler.com/: + + +gem install bundler + + +and run: + + +bundle install --without db + + +This command will install all dependencies except the MySQL and PostgreSQL Ruby drivers. We will come back at these soon. With dependencies installed, you can run the test suite with: + + +rake test + + +You can also run tests for an specific framework, like Action Pack, by going into its directory and executing the same command: + + +cd actionpack +rake test + + +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. + +As of this writing 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: + + +RUBYOPT=-W0 rake test + + +h4. Testing Active Record + +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 setup 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. 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: + + +cd activerecord +rake test_sqlite3 + + +h5. 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. + +After that run: + + +rm .bundle/config +bundle install + + +We need first to delete +.bundle/config+ because Bundler remembers in that file that we didn't want to install the "db" group (alternatively you can edit the file). + +In order to be able to run the test suite against MySQL you need to create a user named +rails+ with privileges on the test databases: + + +mysql> GRANT ALL PRIVILEGES ON activerecord_unittest.* + to 'rails'@'localhost'; +mysql> GRANT ALL PRIVILEGES ON activerecord_unittest2.* + to 'rails'@'localhost'; + + +and create the test databases: + + +cd activerecord +rake mysql:build_databases + + +PostgreSQL's authentication works differently. A simple way to setup the development environment for example is to run with your development account + + +sudo -u postgres createuser --superuser $USER + + +and after that create the test databases with + + +cd activerecord +rake postgresql:build_databases + + +NOTE: Using the rake task to create the test databases ensures they have the correct character set and collation. + +If you’re using another database, check the files under +activerecord/test/connections+ for default connection information. You can edit these files if you _must_ on your machine to provide different credentials, but obviously you should not push any such changes back to Rails. + +You can now run tests as you did for +sqlite3+, the tasks are + + +test_mysql +test_mysql2 +test_postgresql + + +respectively. As we mentioned before + + +rake test + + +will now run the four of them in turn. + +You can also invoke +test_jdbcmysql+, +test_jdbcsqlite3+ or +test_jdbcpostgresql+. Check out the file +activerecord/RUNNING_UNIT_TESTS+ for information on running more targeted database tests, or the file +ci/ci_build.rb+ to see the test suite that the continuous integration server runs. + +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 2-3-stable branch: + + +git branch --track 2-3-stable origin/2-3-stable +git checkout 2-3-stable + + +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 + +As a next step beyond reporting issues, you can help the core team resolve existing issues. If you check the "open tickets":https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets?q=state%3Aopen list in Lighthouse, you'll find lots of issues already requiring attention. What can you do for these? Quite a bit, actually: + +h4. Verifying Bug Reports + +For starters, it helps to just verify bug reports. Can you reproduce the reported issue on your own computer? If so, you can add a comment to the ticket saying that you're seeing the same thing. + +If something is very vague, can you help squish it down into something specific? Maybe you can provide additional information to help reproduce a bug, or eliminate needless steps that aren't required to help demonstrate the problem. + +If you find a bug report without a test, it's very useful to contribute a failing test. This is also a great way to get started exploring the source code: looking at the existing test files will teach you how to write more tests. New tests are best contributed in the form of a patch, as explained later on in the "Contributing to the Rails Code" section. + +Anything you can do to make bug reports more succinct or easier to reproduce is a help to folks trying to write code to fix those bugs - whether you end up writing the code yourself or not. + +h4. Testing Patches + +You can also help out by examining patches that have been submitted to Ruby on Rails via Lighthouse. To apply someone's changes you need to first create a dedicated branch: + + +git checkout -b testing_branch + + +Then you can apply their patch: + + +git apply their-patch-file.diff + + +After applying a patch, test it out! Here are some things to think about: + +* Does the patch actually work? +* Are you happy with the tests? Can you follow what they're testing? Are there any tests missing? +* Does it have proper documentation coverage? Should documentation elsewhere be updated? +* Do you like the implementation? Can you think of a nicer or faster way to implement a part of their change? + +Once you're happy that the patch contains a good change, comment on the Lighthouse ticket indicating your approval. Your comment should indicate that you like the change and what you like about it. Something like: + +
+I like the way you've restructured that code in generate_finder_sql, much nicer. The tests look good too. +
+ +If your comment simply says "+1", then odds are that other reviewers aren't going to take it too seriously. Show that you took the time to review the patch. Once three people have approved it, add the "verified" tag. This will bring it to the attention of a core team member who will review the changes looking for the same kinds of things. + +h3. Contributing to the Rails Documentation + +Ruby on Rails has two main sets of documentation: The guides help you to learn Ruby on Rails, and the API is a reference. + +You can create a ticket in Lighthouse to fix or expand documentation. However, if you're confident about your changes you can push them yourself directly via "docrails":http://github.com/lifo/docrails/tree/master. docrails is a branch with an *open commit policy* and public write access. Commits to docrails are still reviewed, but that happens after they are pushed. docrails is merged with master regularly, so you are effectively editing the Ruby on Rails documentation. + +When working with documentation, please take into account the "API Documentation Guidelines":api_documentation_guidelines.html and the "Ruby on Rails Guides Guidelines":ruby_on_rails_guides_guidelines.html. + +NOTE: As explained above, ordinary code patches should have proper documentation coverage. docrails is only used for isolated documentation improvements. + +WARNING: docrails has a very strict policy: no code can be touched whatsoever, no matter how trivial or small the change. Only RDoc and guides can be edited via docrails. + +If you have an idea for a new guide you can refer to the "contribution page":contribute.html for instructions on getting involved. + +h3. Contributing to the Rails Code + +h4. Clone the Rails Repository + +The first thing you need to do to be able to contribute code is to clone the repository: + + +git clone git://github.com/rails/rails.git + + +and create a dedicated branch: + + +cd rails +git checkout -b my_new_branch + + +It doesn’t really matter what name you use, because this branch will only exist on your local computer. + +h4. Write Your Code + +Now get busy and add or edit code. You’re on your branch now, so you can write whatever you want (you can check to make sure you’re on the right branch with +git branch -a+). But if you’re planning to submit your change back for inclusion in Rails, keep a few things in mind: + +* Get the code right +* Use Rails idioms and helpers +* Include tests that fail without your code, and pass with it +* Update the documentation, the surrounding one, examples elsewhere, guides, whatever is affected by your contribution + +h4. Follow the Coding Conventions + +Rails follows a simple set of coding style conventions. + +* Two spaces, no tabs +* Prefer +&&+/+||+ over +and+/+or+ +* +MyClass.my_method(my_arg)+ not +my_method( my_arg )+ or +my_method my_arg+ +* Follow the conventions you see used in the source already + +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. + +You might also want to check out the "RailsBridge BugMash":http://wiki.railsbridge.org/projects/railsbridge/wiki/BugMash as a way to get involved in a group effort to improve Rails. This can help you get started and help check your code when you're writing your first patches. + +h4. Commit Your Changes + +When you're happy with the code on your computer, you need to commit the changes to git: + + +git commit -a -m "Here is a commit message" + + +h4. Update master + +It’s pretty likely that other changes to master have happened while you were working. Go get them: + + +git checkout master +git pull + + +Now reapply your patch on top of the latest changes: + + +git checkout my_new_branch +git rebase master + + +No conflicts? Tests still pass? Change still seems reasonable to you? Then move on. + +h4. Create a Patch + +Now you can create a patch file to share with other developers (and with the core team). Still in your branch, run + + +git commit -a +git format-patch master --stdout > my_new_patch.diff + + +Sanity check the results of this operation: open the diff file in your text editor of choice and make sure that no unintended changes crept in. + +h4. Create a Lighthouse Ticket + +Now create a ticket with your patch. Go to the "new ticket":http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/new page at Lighthouse. Fill in a reasonable title and description, remember to attach your patch file, and tag the ticket with the ‘patch’ tag and whatever other subject area tags make sense. + +h4. Get Some Feedback + +Now you need to get other people to look at your patch, just as you've looked at other people's patches. You can use the rubyonrails-core mailing list or the #rails-contrib channel on IRC freenode for this. You might also try just talking to Rails developers that you know. + +h4. Iterate as Necessary + +It’s entirely possible that the feedback you get will suggest changes. Don’t get discouraged: the whole point of contributing to an active open source project is to tap into community knowledge. If people are encouraging you to tweak your code, then it’s worth making the tweaks and resubmitting. If the feedback is that your code doesn’t belong in the core, you might still think about releasing it as a plugin. + +And then...think about your next contribution! + +h3. Rails Contributors + +All contributions, either via master or docrails, get credit in "Rails Contributors":http://contributors.rubyonrails.org. + +h3. Changelog + +* December 28, 2010: Complete revision by "Xavier Noria":credits.html#fxn +* April 6, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com +* August 1, 2009: Updates/amplifications by "Mike Gunderloy":credits.html#mgunderloy +* March 2, 2009: Initial draft by "Mike Gunderloy":credits.html#mgunderloy + -- cgit v1.2.3 From 98368546719cf09b3bc2c88735f7d72ffc048679 Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Wed, 29 Dec 2010 02:07:22 +0530 Subject: fixed examples & minor typos --- railties/guides/source/i18n.textile | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/i18n.textile b/railties/guides/source/i18n.textile index 46e3b80a76..de2bc78eac 100644 --- a/railties/guides/source/i18n.textile +++ b/railties/guides/source/i18n.textile @@ -10,7 +10,7 @@ So, in the process of _internationalizing_ your Rails application you have to: * Tell Rails where to find locale dictionaries * Tell Rails how to set, preserve and switch locale -In the process of _localizing_ your application you'll probably want to do following three things: +In the process of _localizing_ your application you'll probably want to do the following three things: * Replace or supplement Rails' default locale -- e.g. date and time formats, month names, Active Record model names, etc * Abstract strings in your application into keyed dictionaries -- e.g. flash messages, static text in your views, etc. @@ -305,12 +305,12 @@ end # app/controllers/home_controller.rb class HomeController < ApplicationController def index - flash[:notice] = "Hello flash!" + flash[:notice] = "Hello Flash" end end # app/views/home/index.html.erb -

Hello world!

+

Hello World

<%= flash[:notice] %>

@@ -344,8 +344,8 @@ So let's add the missing translations into the dictionary files (i.e. do the "lo # config/locales/en.yml en: - hello_world: Hello World - hello_flash: Hello Flash + hello_world: Hello world! + hello_flash: Hello flash! # config/locales/pirate.yml pirate: @@ -586,7 +586,7 @@ I18n.t :foo I18n.l Time.now -Explicitely passing a locale: +Explicitly passing a locale: I18n.t :foo, :locale => :de @@ -623,7 +623,7 @@ pt: bar: baz -As you see, in both cases the toplevel key is the locale. +:foo+ is a namespace key and +:bar+ is the key for the translation "baz". +As you see, in both cases the top level key is the locale. +:foo+ is a namespace key and +:bar+ is the key for the translation "baz". Here is a "real" example from the Active Support +en.yml+ translations YAML file: -- cgit v1.2.3 From dd166c60c48e4d644a627a548fdd9087d3f2aeec Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Wed, 29 Dec 2010 02:09:47 +0530 Subject: fixed incorrect spacing from 98368546719cf09b3bc2 --- railties/guides/source/i18n.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/i18n.textile b/railties/guides/source/i18n.textile index de2bc78eac..bb8bf8b240 100644 --- a/railties/guides/source/i18n.textile +++ b/railties/guides/source/i18n.textile @@ -623,7 +623,7 @@ pt: bar: baz -As you see, in both cases the top level key is the locale. +:foo+ is a namespace key and +:bar+ is the key for the translation "baz". +As you see, in both cases the top level key is the locale. +:foo+ is a namespace key and +:bar+ is the key for the translation "baz". Here is a "real" example from the Active Support +en.yml+ translations YAML file: -- cgit v1.2.3 From 60447d8b00c5181d2988c15c3d7f6ac3081fd04d Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Wed, 29 Dec 2010 10:54:42 +1000 Subject: Routing guide: mention that routes are matched from the top down in a note. --- railties/guides/source/routing.textile | 3 +++ 1 file changed, 3 insertions(+) (limited to 'railties/guides') diff --git a/railties/guides/source/routing.textile b/railties/guides/source/routing.textile index 32346e8f2b..15b26d8f9e 100644 --- a/railties/guides/source/routing.textile +++ b/railties/guides/source/routing.textile @@ -85,6 +85,9 @@ creates seven different routes in your application, all mapping to the +Photos+ |PUT |/photos/:id |update |update a specific photo | |DELETE |/photos/:id |destroy |delete a specific photo | + +NOTE: Rails routes are matched in the order they are specified, so if you have a +resources :photos+ above a +get 'photos/poll'+ the +show+ action's route for the +resources+ line will be matched before the +get+ line. To fix this, move the +get+ line *above* the +resources+ line so that it is matched first. + h4. Paths and URLs Creating a resourceful route will also expose a number of helpers to the controllers in your application. In the case of +resources :photos+: -- cgit v1.2.3 From 5fc02dbd03e79e24505cda60423de2979fea4124 Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Wed, 29 Dec 2010 11:38:54 +0100 Subject: since a lot of people use Ubuntu, document specific aptitude calls for some C dependencies in the contrib guide --- .../source/contributing_to_ruby_on_rails.textile | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/contributing_to_ruby_on_rails.textile b/railties/guides/source/contributing_to_ruby_on_rails.textile index 7c0f32d9ca..484c36aeea 100644 --- a/railties/guides/source/contributing_to_ruby_on_rails.textile +++ b/railties/guides/source/contributing_to_ruby_on_rails.textile @@ -64,7 +64,17 @@ h4. 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. -Install first libxml2 and libxslt together with their development files for Nokogiri. Also, SQLite3 and its development files for the +sqlite3-ruby+ gem. +Install first libxml2 and libxslt together with their development files for Nokogiri. In Ubuntu that's + + +sudo aptitude install libxml2 libxml2-dev libxslt1-dev + + +Also, SQLite3 and its development files for the +sqlite3-ruby+ gem, in Ubuntu you're done with + + +sudo aptitude install sqlite3 libsqlite3-dev + Get a recent version of "Bundler":http://gembundler.com/: @@ -118,7 +128,12 @@ rake test_sqlite3 h5. 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. +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 + + +sudo aptitude install mysql-server libmysqlclient15-dev +sudo aptitude install postgresql postgresql-client postgresql-contrib libpq-dev + After that run: -- cgit v1.2.3 From 83e1938916d1d6bc63d3c8031da29d973ec6f41e Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Wed, 29 Dec 2010 11:42:11 +0100 Subject: renames the contrib guide in the index --- railties/guides/source/index.html.erb | 4 ++-- railties/guides/source/layout.html.erb | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/index.html.erb b/railties/guides/source/index.html.erb index 771cfbb794..933bf66b3f 100644 --- a/railties/guides/source/index.html.erb +++ b/railties/guides/source/index.html.erb @@ -151,10 +151,10 @@ Ruby on Rails Guides <% end %> -

Contributing to Rails

+

Contributing to Ruby on Rails

- <%= guide("Contributing to Rails", 'contributing_to_rails.html') do %> + <%= guide("Contributing to Ruby on Rails", 'contributing_to_ruby_on_rails.html') do %>

Rails is not "somebody else's framework." This guide covers a variety of ways that you can get involved in the ongoing development of Rails.

<% end %> diff --git a/railties/guides/source/layout.html.erb b/railties/guides/source/layout.html.erb index dbb48124d0..91dab18b21 100644 --- a/railties/guides/source/layout.html.erb +++ b/railties/guides/source/layout.html.erb @@ -75,8 +75,8 @@
Rails on Rack
Creating and Customizing Rails Generators
-
Contributing to Rails
-
Contributing to Rails
+
Contributing to Ruby on Rails
+
Contributing to Ruby on Rails
API Documentation Guidelines
Ruby on Rails Guides Guidelines
-- cgit v1.2.3 From eb1e727544d9719cf0aa4d914c484a83e707b601 Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Thu, 30 Dec 2010 07:12:17 +0100 Subject: contrib_guide.gsub!("aptitude", "apt-get") MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit It turns out aptitude has been removed from Ubuntu 10.10 and while you can manually install it, apt-get is the blessed package manager. Google for "aptitude removed from Ubuntu" for more details. Thanks to Rafael Mendonça França for pointing this out. --- railties/guides/source/contributing_to_ruby_on_rails.textile | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/contributing_to_ruby_on_rails.textile b/railties/guides/source/contributing_to_ruby_on_rails.textile index 484c36aeea..504cd92d90 100644 --- a/railties/guides/source/contributing_to_ruby_on_rails.textile +++ b/railties/guides/source/contributing_to_ruby_on_rails.textile @@ -67,13 +67,13 @@ The test suite must pass with any submitted code. No matter whether you are writ Install first libxml2 and libxslt together with their development files for Nokogiri. In Ubuntu that's -sudo aptitude install libxml2 libxml2-dev libxslt1-dev +sudo apt-get install libxml2 libxml2-dev libxslt1-dev Also, SQLite3 and its development files for the +sqlite3-ruby+ gem, in Ubuntu you're done with -sudo aptitude install sqlite3 libsqlite3-dev +sudo apt-get install sqlite3 libsqlite3-dev Get a recent version of "Bundler":http://gembundler.com/: @@ -131,8 +131,8 @@ h5. 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 -sudo aptitude install mysql-server libmysqlclient15-dev -sudo aptitude install postgresql postgresql-client postgresql-contrib libpq-dev +sudo apt-get install mysql-server libmysqlclient15-dev +sudo apt-get install postgresql postgresql-client postgresql-contrib libpq-dev After that run: -- cgit v1.2.3 From eaf67ca9c3fbe3e45c8096ea7ffbde562ebfb76d Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Fri, 31 Dec 2010 17:38:04 +1000 Subject: Routing guide: improve documentation for the scope method, demonstrating use of named parameters --- railties/guides/source/routing.textile | 10 ++++++++++ 1 file changed, 10 insertions(+) (limited to 'railties/guides') diff --git a/railties/guides/source/routing.textile b/railties/guides/source/routing.textile index 15b26d8f9e..fda5c6c668 100644 --- a/railties/guides/source/routing.textile +++ b/railties/guides/source/routing.textile @@ -200,6 +200,16 @@ or, for a single case resources :posts, :path => "/admin/posts" +You can even set named parameters for the paths: + + +scope ":username" do + resources :posts +end + + +This will provide you with URLs such as +/bob/posts/1+ and will allow you to reference the +username+ part of the path as +params[:username]+ in controllers, helpers and views. + In each of these cases, the named routes remain the same as if you did not use +scope+. In the last case, the following paths map to +PostsController+: |_.HTTP Verb |_.Path |_.action |_.named helper | -- cgit v1.2.3 From 9aef64f7a347cdc1eab70b44f55a050e28af5074 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Fri, 31 Dec 2010 17:45:03 +1000 Subject: Routing guide: move scope documentation down to where it is referenced more plainly --- railties/guides/source/routing.textile | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/routing.textile b/railties/guides/source/routing.textile index fda5c6c668..b1cef26932 100644 --- a/railties/guides/source/routing.textile +++ b/railties/guides/source/routing.textile @@ -200,16 +200,6 @@ or, for a single case resources :posts, :path => "/admin/posts" -You can even set named parameters for the paths: - - -scope ":username" do - resources :posts -end - - -This will provide you with URLs such as +/bob/posts/1+ and will allow you to reference the +username+ part of the path as +params[:username]+ in controllers, helpers and views. - In each of these cases, the named routes remain the same as if you did not use +scope+. In the last case, the following paths map to +PostsController+: |_.HTTP Verb |_.Path |_.action |_.named helper | @@ -724,8 +714,20 @@ end resources :photos, :accounts +This will generate routes such as +admin_photos_path+ and +admin_accounts_path+. + NOTE: The +namespace+ scope will automatically add +:as+ as well as +:module+ and +:path+ prefixes. +You can prefix routes with a named parameter also: + + +scope ":username" do + resources :posts +end + + +This will provide you with URLs such as +/bob/posts/1+ and will allow you to reference the +username+ part of the path as +params[:username]+ in controllers, helpers and views. + h4. Restricting the Routes Created By default, Rails creates routes for the seven default actions (index, show, new, create, edit, update, and destroy) for every RESTful route in your application. You can use the +:only+ and +:except+ options to fine-tune this behavior. The +:only+ option tells Rails to create only the specified routes: -- cgit v1.2.3 From 224e2d478a825c312128a1b3c2797d0a95fd7109 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Fri, 31 Dec 2010 17:50:37 +1000 Subject: Routing guide: clarify what the :as option does for scopes --- railties/guides/source/routing.textile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/routing.textile b/railties/guides/source/routing.textile index b1cef26932..f60d72352d 100644 --- a/railties/guides/source/routing.textile +++ b/railties/guides/source/routing.textile @@ -704,7 +704,7 @@ resources :photos This will provide route helpers such as +admin_photos_path+, +new_admin_photo_path+ etc. -To prefix a group of routes, use +:as+ with +scope+: +To prefix a group of route helpers, use +:as+ with +scope+: scope "admin", :as => "admin" do @@ -714,7 +714,7 @@ end resources :photos, :accounts -This will generate routes such as +admin_photos_path+ and +admin_accounts_path+. +This will generate routes such as +admin_photos_path+ and +admin_accounts_path+ which map to +/admin/photos+ and +/admin/accounts+ respectively. NOTE: The +namespace+ scope will automatically add +:as+ as well as +:module+ and +:path+ prefixes. -- cgit v1.2.3 From 56221faecdb47163cb463531506821aa6ba50370 Mon Sep 17 00:00:00 2001 From: Karel Minarik Date: Sat, 1 Jan 2011 17:54:02 +0100 Subject: Added support for generating translated guides (stored in `source/`) via setting the LANG environment variable --- railties/guides/rails_guides/generator.rb | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/rails_guides/generator.rb b/railties/guides/rails_guides/generator.rb index 68d406e31c..e4f9ea4916 100644 --- a/railties/guides/rails_guides/generator.rb +++ b/railties/guides/rails_guides/generator.rb @@ -38,6 +38,10 @@ # Note that if you are working on a guide generation will by default process # only that one, so ONLY is rarely used nowadays. # +# LANG +# Use LANG when you want to generate translated guides in source/ +# folder (such as source/es). Ignore it when generating English guides. +# # EDGE # Set to "1" to indicate generated guides should be marked as edge. This # inserts a badge and changes the preamble of the home page. @@ -63,6 +67,7 @@ module RailsGuides GUIDES_RE = /\.(?:textile|html\.erb)$/ def initialize(output=nil) + @lang = ENV['LANG'] initialize_dirs(output) create_output_dir_if_needed set_flags_from_environment @@ -76,8 +81,8 @@ module RailsGuides private def initialize_dirs(output) @guides_dir = File.join(File.dirname(__FILE__), '..') - @source_dir = File.join(@guides_dir, "source") - @output_dir = output || File.join(@guides_dir, "output") + @source_dir = File.join(@guides_dir, "source", @lang.to_s) + @output_dir = output || File.join(@guides_dir, "output", @lang.to_s) end def create_output_dir_if_needed -- cgit v1.2.3 From ebb732a7ecc0502299ee5948c31f536c3d6ef15c Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Sun, 2 Jan 2011 02:53:15 +0530 Subject: fix typos --- railties/guides/source/routing.textile | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/routing.textile b/railties/guides/source/routing.textile index f60d72352d..1d81c8f95b 100644 --- a/railties/guides/source/routing.textile +++ b/railties/guides/source/routing.textile @@ -498,7 +498,7 @@ You specify a request-based constraint the same way that you specify a segment c match "photos", :constraints => {:subdomain => "admin"} -You can also specify constrains in a block form: +You can also specify constraints in a block form: namespace :admin do @@ -598,7 +598,7 @@ You can specify what Rails should route +"/"+ to with the +root+ method: root :to => 'pages#main' -You should put the +root+ route at the end of the file. You also need to delete the public/index.html.erb file for the root route to take effect. +You should put the +root+ route at the end of the file. You also need to delete the +public/index.html+ file for the root route to take effect. h3. Customizing Resourceful Routes @@ -633,7 +633,7 @@ You can use the +:constraints+ option to specify a required format on the implic resources :photos, :constraints => {:id => /[A-Z][A-Z][0-9]+/} -This declaration constrains the +:id+ parameter to match the supplied regular expression. So, in this case, the router would no longer match +/photos/1+ to this route. Instead, +/photos/RR27+ would match. +This declaration constraints the +:id+ parameter to match the supplied regular expression. So, in this case, the router would no longer match +/photos/1+ to this route. Instead, +/photos/RR27+ would match. You can specify a single constraint to apply to a number of routes by using the block form: -- cgit v1.2.3 From a388c10f96a32d5be6154b813662f1a085ec23f1 Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Mon, 3 Jan 2011 02:01:04 +0530 Subject: Fix typos and JavaScript case. --- railties/guides/source/ajax_on_rails.textile | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/ajax_on_rails.textile b/railties/guides/source/ajax_on_rails.textile index 972e7ea840..3d7fcdc198 100644 --- a/railties/guides/source/ajax_on_rails.textile +++ b/railties/guides/source/ajax_on_rails.textile @@ -1,10 +1,10 @@ h2. AJAX on Rails -This guide covers the built-in Ajax/Javascript functionality of Rails (and more); it will enable you to create rich and dynamic AJAX applications with ease! We will cover the following topics: +This guide covers the built-in Ajax/JavaScript functionality of Rails (and more); it will enable you to create rich and dynamic AJAX applications with ease! We will cover the following topics: * Quick introduction to AJAX and related technologies -* Handling Javascript the Rails way: Rails helpers, RJS, Prototype and script.aculo.us -* Testing Javascript functionality +* Handling JavaScript the Rails way: Rails helpers, RJS, Prototype and script.aculo.us +* Testing JavaScript functionality endprologue. @@ -12,7 +12,7 @@ h3. Hello AJAX - a Quick Intro If you are a 'show me the code' type of person, you might want to skip this part and jump to the RJS section right away. However, I would really recommend to read it - you'll need the basics of DOM, http requests and other topics discussed here to really understand Ajax on Rails. -h4. Asynchronous Javascript + XML +h4. Asynchronous JavaScript + XML Basic terminology, new style of creating web apps @@ -31,7 +31,7 @@ How do 'standard' and AJAX requests differ, why does this matter for understandi 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. +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: @@ -136,7 +136,7 @@ link_to_remote "Add new item", :before => "$('progress').show()", :complete => "$('progress').hide()", :success => "display_item_added(request)", - :failure => "display_error(request)", + :failure => "display_error(request)" ** *:type* If you want to fire a synchronous request for some obscure reason (blocking the browser while the request is processed and doesn't return a status code), you can use the +:type+ option with the value of +:synchronous+. * Finally, using the +html_options+ parameter you can add HTML attributes to the generated tag. It works like the same parameter of the +link_to+ helper. There are interesting side effects for the +href+ and +onclick+ parameters though: @@ -153,7 +153,7 @@ There are three different ways of adding AJAX forms to your view using Rails Pro * +form_remote_tag+ AJAXifies the form by serializing and sending it's data in the background * +submit_to_remote+ and +button_to_remote+ is more rarely used than the previous two. Rather than creating an AJAX form, you add a button/input -Let's se them in action one by one! +Let's see them in action one by one! h5. +remote_form_for+ @@ -183,7 +183,7 @@ h3. JavaScript the Rails way: RJS In the last section we sent some AJAX requests to the server, and inserted the HTML response into the page (with the +:update+ option). However, sometimes a more complicated interaction with the page is needed, which you can either achieve with JavaScript... or with RJS! You are sending JavaScript instructions to the server in both cases, but while in the former case you have to write vanilla JavaScript, in the second you can code Rails, and sit back while Rails generates the JavaScript for you - so basically RJS is a Ruby DSL to write JavaScript in your Rails code. -h4. Javascript without RJS +h4. JavaScript without RJS First we'll check out how to send JavaScript to the server manually. You are practically never going to need this, but it's interesting to understand what's going on under the hood. @@ -329,9 +329,9 @@ h4. Drag and Drop -h3. Testing Javascript +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: +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: * (Fire)Watir * Selenium @@ -339,4 +339,4 @@ Javascript testing reminds me the definition of the world 'classic' by Mark Twai * Cucumber+Webrat * Mention stuff like screw.unit/jsSpec -Note to self: check out the RailsConf JS testing video \ No newline at end of file +Note to self: check out the RailsConf JS testing video -- cgit v1.2.3 From 1877faa7ac2053628b63a665ab822e18f2939a83 Mon Sep 17 00:00:00 2001 From: Karel Minarik Date: Sun, 2 Jan 2011 22:09:09 +0100 Subject: [FIX] Renamed ENV['LANG'] for generating translated guides to ENV['LANGUAGE'] so there's no mixup with OS env vars --- railties/guides/rails_guides/generator.rb | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/rails_guides/generator.rb b/railties/guides/rails_guides/generator.rb index e4f9ea4916..154355cac1 100644 --- a/railties/guides/rails_guides/generator.rb +++ b/railties/guides/rails_guides/generator.rb @@ -38,8 +38,8 @@ # Note that if you are working on a guide generation will by default process # only that one, so ONLY is rarely used nowadays. # -# LANG -# Use LANG when you want to generate translated guides in source/ +# LANGUAGE +# Use LANGUAGE when you want to generate translated guides in source/ # folder (such as source/es). Ignore it when generating English guides. # # EDGE @@ -67,7 +67,7 @@ module RailsGuides GUIDES_RE = /\.(?:textile|html\.erb)$/ def initialize(output=nil) - @lang = ENV['LANG'] + @lang = ENV['LANGUAGE'] initialize_dirs(output) create_output_dir_if_needed set_flags_from_environment -- cgit v1.2.3 From 27717655ad7ab4549a5799285975e425e8f80b15 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Mon, 3 Jan 2011 12:00:14 +1000 Subject: Re-add "Using initializer files" section to configuring guide --- railties/guides/source/configuring.textile | 9 +++++++++ 1 file changed, 9 insertions(+) (limited to 'railties/guides') diff --git a/railties/guides/source/configuring.textile b/railties/guides/source/configuring.textile index 6e72ae6ead..a3da5e93f1 100644 --- a/railties/guides/source/configuring.textile +++ b/railties/guides/source/configuring.textile @@ -397,6 +397,15 @@ Some parts of Rails can also be configured externally by supplying environment v * +ENV["RAILS_CACHE_ID"]+ and +ENV["RAILS_APP_VERSION"]+ are used to generate expanded cache keys in Rails' caching code. This allows you to have multiple separate caches from the same application. + +h3. Using Initializer Files + +After loading the framework and any gems and plugins in your application, Rails turns to loading initializers. An initializer is any file of Ruby code stored under +config/initializers+ in your application. You can use initializers to hold configuration settings that should be made after all of the frameworks, plugins and gems are loaded, such as options to configure settings for these parts. + +NOTE: You can use subfolders to organize your initializers if you like, because Rails will look into the whole file hierarchy from the initializers folder on down. + +TIP: If you have any ordering dependency in your initializers, you can control the load order by naming. For example, +01_critical.rb+ will be loaded before +02_normal.rb+. + h3. Initialization events Rails has 5 initialization events which can be hooked into (listed in order that they are ran): -- cgit v1.2.3 From a41d33431fa19a08aec52030aeb7225fefe7aa47 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Mon, 3 Jan 2011 12:04:21 +1000 Subject: config guide: add basic description for disable_dependency_loading initializer --- railties/guides/source/configuring.textile | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/configuring.textile b/railties/guides/source/configuring.textile index a3da5e93f1..eee18f1131 100644 --- a/railties/guides/source/configuring.textile +++ b/railties/guides/source/configuring.textile @@ -560,8 +560,7 @@ TIP: If you have any ordering dependency in your initializers, you can control t *+set_routes_reloader+* Configures Action Dispatch to reload the routes file using +ActionDispatch::Callbacks.to_prepare+. -*+disable_dependency_loading+* - +*+disable_dependency_loading+* Disables the automatic dependency loading if the +config.cache_classes+ is set to +true+ and +config.dependency_loading+ is set to +false+. h3. Changelog -- cgit v1.2.3 From bc6e1a154a2df3096d36ed3612b0b93c0a466728 Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Sat, 8 Jan 2011 23:35:36 +0530 Subject: fix template url --- railties/guides/source/generators.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/generators.textile b/railties/guides/source/generators.textile index 4fec1760c4..3adbbfa7aa 100644 --- a/railties/guides/source/generators.textile +++ b/railties/guides/source/generators.textile @@ -396,7 +396,7 @@ This command will generate the +Thud+ application, and then apply the template t Templates don't have to be stored on the local system, the +-m+ option also supports online templates: - rails new thud -m https://gist.github.com/722911 + rails new thud -m https://gist.github.com/722911.txt Whilst the final section of this guide doesn't cover how to generate the most awesome template known to man, it will take you through the methods available at your disposal so that you can develop it yourself. These same methods are also available for generators. -- cgit v1.2.3 From 4d29816fdad8bd8ed8eb98f12fda6a7b107cc7f4 Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Sun, 9 Jan 2011 02:24:30 +0530 Subject: fixed query output --- railties/guides/source/active_record_querying.textile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/active_record_querying.textile b/railties/guides/source/active_record_querying.textile index 6e45bf3188..22358029d4 100644 --- a/railties/guides/source/active_record_querying.textile +++ b/railties/guides/source/active_record_querying.textile @@ -440,7 +440,7 @@ And this will give you a single +Order+ object for each date where there are ord The SQL that would be executed would be something like this: -SELECT * FROM orders GROUP BY date(created_at) +SELECT * FROM orders GROUP BY date(created_at) ORDER BY created_at h3. Having @@ -664,7 +664,7 @@ Eager loading is the mechanism for loading the associated records of the objects Consider the following code, which finds 10 clients and prints their postcodes: -clients = Client.all(:limit => 10) +clients = Client.limit(10) clients.each do |client| puts client.address.postcode -- cgit v1.2.3 From 74188cbff426f35378be876e3c83c798aa6a4a43 Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Wed, 12 Jan 2011 21:12:44 +0100 Subject: upgrades RedCloth dependency to ~> 4.2, adds RedCloth to the project's Rakefile, removes gem call from the guides generator (use bundle exec if needed) --- railties/guides/rails_guides.rb | 4 ++-- railties/guides/source/contribute.textile | 4 ++-- railties/guides/source/ruby_on_rails_guides_guidelines.textile | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/rails_guides.rb b/railties/guides/rails_guides.rb index dfbb06cc76..feb5fe3937 100644 --- a/railties/guides/rails_guides.rb +++ b/railties/guides/rails_guides.rb @@ -24,14 +24,14 @@ rescue LoadError end begin - gem 'RedCloth', '>= 4.1.1' require 'redcloth' rescue Gem::LoadError + # This can happen if doc:guides is executed in an application. $stderr.puts('Generating guides requires RedCloth 4.1.1+.') $stderr.puts(<= 4.1.1' + gem 'RedCloth', '~> 4.2' to the Gemfile, run diff --git a/railties/guides/source/contribute.textile b/railties/guides/source/contribute.textile index 3d4607de1d..8d19d78324 100644 --- a/railties/guides/source/contribute.textile +++ b/railties/guides/source/contribute.textile @@ -13,8 +13,8 @@ h3. How to Contribute? * Assets are stored in the +railties/guides/assets+ directory. * Sample format : "Active Record Associations":http://github.com/lifo/docrails/blob/3e56a3832415476fdd1cb963980d0ae390ac1ed3/railties/guides/source/association_basics.textile. * Sample output : "Active Record Associations":association_basics.html. -* You can build the Guides during testing by running +rake generate_guides+ in the +railties+ directory. -* You're encouraged to validate XHTML for the generated guides before commiting your changes by running +rake validate_guides+ in the +railties+ directory. +* You can build the Guides during testing by running +bundle exec rake generate_guides+ in the +railties+ directory. +* You're encouraged to validate XHTML for the generated guides before commiting your changes by running +bundle exec rake validate_guides+ in the +railties+ directory. * Edge guides "can be consulted online":http://edgeguides.rubyonrails.org/. That website is generated periodically from docrails. h3. What to Contribute? diff --git a/railties/guides/source/ruby_on_rails_guides_guidelines.textile b/railties/guides/source/ruby_on_rails_guides_guidelines.textile index a2e830b574..655c3462d2 100644 --- a/railties/guides/source/ruby_on_rails_guides_guidelines.textile +++ b/railties/guides/source/ruby_on_rails_guides_guidelines.textile @@ -45,7 +45,7 @@ h3. HTML Generation To generate all the guides just cd into the +railties+ directory and execute -rake generate_guides +bundle exec rake generate_guides You'll need the gems erubis, i18n, and RedCloth. @@ -53,7 +53,7 @@ You'll need the gems erubis, i18n, and RedCloth. To process +my_guide.textile+ and nothing else use the +ONLY+ environment variable: -rake generate_guides ONLY=my_guide +bundle exec rake generate_guides ONLY=my_guide Although by default guides that have not been modified are not processed, so +ONLY+ is rarely needed in practice. -- cgit v1.2.3 From 31767b003227148ce06b7c8df0f533b7cdeddd9b Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Fri, 14 Jan 2011 22:10:22 +0530 Subject: ends_width => ends_with --- railties/guides/source/active_support_core_extensions.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/active_support_core_extensions.textile b/railties/guides/source/active_support_core_extensions.textile index 9a1f913ded..c283a9bd99 100644 --- a/railties/guides/source/active_support_core_extensions.textile +++ b/railties/guides/source/active_support_core_extensions.textile @@ -1264,7 +1264,7 @@ Active Support adds that functionality to % in previous versions of Rub NOTE: Defined in +active_support/core_ext/string/interpolation.rb+. -h4. +starts_with?+ and +ends_width?+ +h4. +starts_with?+ and +ends_with?+ Active Support defines 3rd person aliases of +String#start_with?+ and +String#end_with?+: -- cgit v1.2.3 From 93c208a630e5cd96071ed5581fcd1c23708b3817 Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Fri, 14 Jan 2011 22:51:15 +0530 Subject: use new AR api --- railties/guides/source/active_record_basics.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/active_record_basics.textile b/railties/guides/source/active_record_basics.textile index f0081b48c0..b7926f3a3b 100644 --- a/railties/guides/source/active_record_basics.textile +++ b/railties/guides/source/active_record_basics.textile @@ -180,7 +180,7 @@ Active Record provides a rich API for accessing data within a database. Below ar # find all users named David who are Code Artists and sort by created_at in reverse chronological order - users = User.all(:conditions => { :name => 'David', :occupation => 'Code Artist'}, :order => 'created_at DESC') + users = User.where(:name => 'David', :occupation => 'Code Artist').order('created_at DESC') You can learn more about querying an Active Record model in the "Active Record Query Interface":"active_record_querying.html" guide. -- cgit v1.2.3 From 100ab5bd431e1cf9f4fdf08c8724918f482c4684 Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Sat, 15 Jan 2011 23:39:32 +0530 Subject: Documented the except and only conditions in the guides. Took the cue from Jordi Ramero's commit (b31ef7ee83f3fe808f7534172ce2bf22ef6c7cc0) --- .../guides/source/active_record_querying.textile | 32 ++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/active_record_querying.textile b/railties/guides/source/active_record_querying.textile index 22358029d4..64a68f7592 100644 --- a/railties/guides/source/active_record_querying.textile +++ b/railties/guides/source/active_record_querying.textile @@ -19,8 +19,6 @@ Code examples throughout this guide will refer to one or more of the following m TIP: All of the following models use +id+ as the primary key, unless specified otherwise. -
- class Client < ActiveRecord::Base has_one :address @@ -461,6 +459,36 @@ SELECT * FROM orders GROUP BY date(created_at) HAVING created_at > '2009-01-15' This will return single order objects for each day, but only for the last month. +h3. Overriding Conditions + +You can specify certain conditions to be excepted by using the +except+ method. + +For example: + + +Post.where('id > 10').limit(20).order('id asc').except(:order) + + +The SQL that would be executed: + + +SELECT * FROM posts WHERE id > 10 LIMIT 20 + + +You can also override conditions using the +only+ method. + +For example: + + +Post.where('id > 10').limit(20).order('id desc').only(:order, :where) + + +The SQL that would be executed: + + +SELECT * FROM posts WHERE id > 10 ORDER BY id DESC + + h3. Readonly Objects Active Record provides +readonly+ method on a relation to explicitly disallow modification or deletion of any of the returned object. Any attempt to alter or destroy a readonly record will not succeed, raising an +ActiveRecord::ReadOnlyRecord+ exception. -- cgit v1.2.3 From 3c6c2404319931bb27256f190d1f9950149e9a53 Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Sat, 15 Jan 2011 23:47:41 +0530 Subject: Document the LANGUAGE option for generating guides --- railties/guides/source/ruby_on_rails_guides_guidelines.textile | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/ruby_on_rails_guides_guidelines.textile b/railties/guides/source/ruby_on_rails_guides_guidelines.textile index a2e830b574..07f86edfb7 100644 --- a/railties/guides/source/ruby_on_rails_guides_guidelines.textile +++ b/railties/guides/source/ruby_on_rails_guides_guidelines.textile @@ -62,7 +62,13 @@ To force process of all the guides, pass +ALL=1+. It is also recommended that you work with +WARNINGS=1+, this detects duplicate IDs and warns about broken internal links. -h3. HTML validation +If you want to generate guides in languages other than English, you can keep them in a separate directory under +source+ (eg. source/es) and use the +LANGUAGE+ environment variable. + + +rake generate_guides LANGUAGE=es + + +h3. HTML Validation Please do validate the generated HTML with -- cgit v1.2.3 From 77e1a99970c8bd454beaae502d4379309402afa5 Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Mon, 17 Jan 2011 00:16:00 +0530 Subject: minor edits --- railties/guides/source/testing.textile | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/testing.textile b/railties/guides/source/testing.textile index 733c8a755e..5f0889f406 100644 --- a/railties/guides/source/testing.textile +++ b/railties/guides/source/testing.textile @@ -229,13 +229,13 @@ $ rake db:test:load Above +rake db:migrate+ runs any pending migrations on the _development_ environment and updates +db/schema.rb+. +rake db:test:load+ recreates the test database from the current +db/schema.rb+. On subsequent attempts, it is a good idea to first run +db:test:prepare+, as it first checks for pending migrations and warns you appropriately. -NOTE: +db:test:prepare+ will fail with an error if +db/schema.rb+ doesn't exists. +NOTE: +db:test:prepare+ will fail with an error if +db/schema.rb+ doesn't exist. h5. Rake Tasks for Preparing your Application for Testing |_.Tasks |_.Description| |+rake db:test:clone+ |Recreate the test database from the current environment's database schema| -|+rake db:test:clone_structure+ |Recreate the test databases from the development structure| +|+rake db:test:clone_structure+ |Recreate the test database from the development structure| |+rake db:test:load+ |Recreate the test database from the current +schema.rb+| |+rake db:test:prepare+ |Check for pending migrations and load the test schema| |+rake db:test:purge+ |Empty the test database.| @@ -512,12 +512,12 @@ After a request has been made by using one of the 5 methods (+get+, +post+, etc. As is the case with normal Hash objects, you can access the values by referencing the keys by string. You can also reference them by symbol name, except for +assigns+. For example: - flash["gordon"] flash[:gordon] - session["shmession"] session[:shmession] - cookies["are_good_for_u"] cookies[:are_good_for_u] +flash["gordon"] flash[:gordon] +session["shmession"] session[:shmession] +cookies["are_good_for_u"] cookies[:are_good_for_u] # Because you can't use assigns[:something] for historical reasons: - assigns["something"] assigns(:something) +assigns["something"] assigns(:something) h4. Instance Variables Available -- cgit v1.2.3 From 94e0f1db1cf17aa86fed5d7dad50f9e82238900a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tobias=20B=C3=BChlmann?= Date: Wed, 19 Jan 2011 22:03:54 +0100 Subject: use name instead of title in example --- railties/guides/source/i18n.textile | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/i18n.textile b/railties/guides/source/i18n.textile index bb8bf8b240..e47ac7aed6 100644 --- a/railties/guides/source/i18n.textile +++ b/railties/guides/source/i18n.textile @@ -713,12 +713,12 @@ end Then Active Record will look for messages in this order: -activerecord.errors.models.admin.attributes.title.blank +activerecord.errors.models.admin.attributes.name.blank activerecord.errors.models.admin.blank -activerecord.errors.models.user.attributes.title.blank +activerecord.errors.models.user.attributes.name.blank activerecord.errors.models.user.blank activerecord.errors.messages.blank -errors.attributes.title.blank +errors.attributes.name.blank errors.messages.blank -- cgit v1.2.3 From 6641bf877a8408eb28d76077bb0a346a97465485 Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Sun, 23 Jan 2011 20:22:17 +0530 Subject: fix csrf_meta_tag --- railties/guides/source/getting_started.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/getting_started.textile b/railties/guides/source/getting_started.textile index 82700532c0..61f66d5de2 100644 --- a/railties/guides/source/getting_started.textile +++ b/railties/guides/source/getting_started.textile @@ -561,7 +561,7 @@ The view is only part of the story of how HTML is displayed in your web browser. Blog <%= stylesheet_link_tag :all %> <%= javascript_include_tag :defaults %> - <%= csrf_meta_tags %> + <%= csrf_meta_tag %> -- cgit v1.2.3 From 340c7d182e3eabf7fd514d4c9697fbf550a22d2d Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Sun, 23 Jan 2011 20:29:03 +0530 Subject: filter_parameter_logging => config.filter_parameters --- railties/guides/source/action_controller_overview.textile | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/action_controller_overview.textile b/railties/guides/source/action_controller_overview.textile index 8f9afb9c6d..be015c4f9b 100644 --- a/railties/guides/source/action_controller_overview.textile +++ b/railties/guides/source/action_controller_overview.textile @@ -737,16 +737,12 @@ GET /clients/1.pdf h3. Parameter Filtering -Rails keeps a log file for each environment in the +log+ folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. The +filter_parameter_logging+ method can be used to filter out sensitive information from the log. It works by replacing certain values in the +params+ hash with "[FILTERED]" as they are written to the log. As an example, let's see how to filter all parameters with keys that include "password": +Rails keeps a log file for each environment in the +log+ folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. You can filter certain request parameters from your log files by appending them to config.filter_parameters in the application configuration. These parameters will be marked [FILTERED] in the log. -class ApplicationController < ActionController::Base - filter_parameter_logging :password -end +config.filter_parameters << :password -The method works recursively through all levels of the +params+ hash and takes an optional second parameter which is used as the replacement string if present. It can also take a block which receives each key in turn and replaces those for which the block returns true. - h3. Rescue Most likely your application is going to contain bugs or otherwise throw an exception that needs to be handled. For example, if the user follows a link to a resource that no longer exists in the database, Active Record will throw the +ActiveRecord::RecordNotFound+ exception. -- cgit v1.2.3 From 7af3b3988c5eb415c1f90c14c318163ac578f675 Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Mon, 24 Jan 2011 02:32:53 +0530 Subject: Revert "fix csrf_meta_tag" This reverts commit 6641bf877a8408eb28d76077bb0a346a97465485. --- railties/guides/source/getting_started.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/getting_started.textile b/railties/guides/source/getting_started.textile index 61f66d5de2..82700532c0 100644 --- a/railties/guides/source/getting_started.textile +++ b/railties/guides/source/getting_started.textile @@ -561,7 +561,7 @@ The view is only part of the story of how HTML is displayed in your web browser. Blog <%= stylesheet_link_tag :all %> <%= javascript_include_tag :defaults %> - <%= csrf_meta_tag %> + <%= csrf_meta_tags %> -- cgit v1.2.3 From 7ada0fb598b98bbb5a1dab371adb8f2348505df1 Mon Sep 17 00:00:00 2001 From: Keith Wansbrough Date: Thu, 27 Jan 2011 11:39:47 -0800 Subject: Refer to the correct action - it's the update action, in the special case where we want to render the edit view. --- railties/guides/source/layouts_and_rendering.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/layouts_and_rendering.textile b/railties/guides/source/layouts_and_rendering.textile index f0e40b0980..fe400d3358 100644 --- a/railties/guides/source/layouts_and_rendering.textile +++ b/railties/guides/source/layouts_and_rendering.textile @@ -211,7 +211,7 @@ h5. Wrapping it up The above three ways of rendering (rendering another template within the controller, rendering a template within another controller and rendering an arbitrary file on the file system) are actually variants of the same action. -In fact, in the BooksController class, inside of the edit action where we want to render the edit template if the book does not update successfully, all of the following render calls would all render the +edit.html.erb+ template in the +views/books+ directory: +In fact, in the BooksController class, inside of the update action where we want to render the edit template if the book does not update successfully, all of the following render calls would all render the +edit.html.erb+ template in the +views/books+ directory: render :edit -- cgit v1.2.3 From cb3e6c36657d7e335bbb41d3672197963308705e Mon Sep 17 00:00:00 2001 From: Paul Yoder Date: Mon, 31 Jan 2011 13:48:58 -0600 Subject: small edit on options extraction documentation --- railties/guides/source/active_support_core_extensions.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/active_support_core_extensions.textile b/railties/guides/source/active_support_core_extensions.textile index c283a9bd99..cf9ebf44e6 100644 --- a/railties/guides/source/active_support_core_extensions.textile +++ b/railties/guides/source/active_support_core_extensions.textile @@ -2007,7 +2007,7 @@ User.exists?(:email => params[:email]) That syntactic sugar is used a lot in Rails to avoid positional arguments where there would be too many, offering instead interfaces that emulate named parameters. In particular it is very idiomatic to use a trailing hash for options. -If a method expects a variable number of arguments and uses * in its declaration, however, such an options hash ends up being an item of the array of arguments, where kind of loses its role. +If a method expects a variable number of arguments and uses * in its declaration, however, such an options hash ends up being an item of the array of arguments, where it loses its role. In those cases, you may give an options hash a distinguished treatment with +extract_options!+. That method checks the type of the last item of an array. If it is a hash it pops it and returns it, otherwise returns an empty hash. -- cgit v1.2.3 From 19e68b49095439bab9a8a2fd90c2278e4bcd9f33 Mon Sep 17 00:00:00 2001 From: Fred Wu Date: Wed, 2 Feb 2011 11:24:01 +1100 Subject: Fixed the SelectorAssertions documentation url. --- railties/guides/source/testing.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/testing.textile b/railties/guides/source/testing.textile index 5f0889f406..a6d70da76c 100644 --- a/railties/guides/source/testing.textile +++ b/railties/guides/source/testing.textile @@ -582,7 +582,7 @@ assert_select "ol" do end -The +assert_select+ assertion is quite powerful. For more advanced usage, refer to its "documentation":http://api.rubyonrails.org/classes/ActionController/Assertions/SelectorAssertions.html. +The +assert_select+ assertion is quite powerful. For more advanced usage, refer to its "documentation":http://api.rubyonrails.org/classes/ActionDispatch/Assertions/SelectorAssertions.html. h5. Additional View-Based Assertions -- cgit v1.2.3 From da2d24f7cf4dfb826843cda96b413ca2ba326158 Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Fri, 4 Feb 2011 21:36:10 -0200 Subject: git am is better here --- railties/guides/source/contributing_to_ruby_on_rails.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/contributing_to_ruby_on_rails.textile b/railties/guides/source/contributing_to_ruby_on_rails.textile index 504cd92d90..4f51c0f859 100644 --- a/railties/guides/source/contributing_to_ruby_on_rails.textile +++ b/railties/guides/source/contributing_to_ruby_on_rails.textile @@ -231,7 +231,7 @@ git checkout -b testing_branch Then you can apply their patch: -git apply their-patch-file.diff +git am their-patch-file.diff After applying a patch, test it out! Here are some things to think about: -- cgit v1.2.3 From b9309b47cda12db34ac3427fbafff2dca0314ed7 Mon Sep 17 00:00:00 2001 From: "Timothy N. Tsvetkov" Date: Sat, 5 Feb 2011 18:37:53 +0300 Subject: Added tests for form_for and an authenticity_token option. Added docs for for_for and authenticity_token option. Added section to form helpers guide about forms for external resources and new authenticity_token option for form_tag and form_for helpers. [#6228 state:committed] Signed-off-by: Santiago Pastorino --- railties/guides/source/form_helpers.textile | 36 +++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) (limited to 'railties/guides') diff --git a/railties/guides/source/form_helpers.textile b/railties/guides/source/form_helpers.textile index 7b4426b335..cdb311c726 100644 --- a/railties/guides/source/form_helpers.textile +++ b/railties/guides/source/form_helpers.textile @@ -9,6 +9,7 @@ In this guide you will: * Generate select boxes from multiple types of data * Understand the date and time helpers Rails provides * Learn what makes a file upload form different +* Learn some cases of building forms to external resources * Find out where to look for complex forms endprologue. @@ -763,6 +764,40 @@ As a shortcut you can append [] to the name and omit the +:index+ option. This i produces exactly the same output as the previous example. +h3. Forms to external resources + +If you need to post some data to an external resource it is still great to build your from using rails form helpers. But sometimes you need to set an +authenticity_token+ for this resource. You can do it by passing an +:authenticity_token => 'your_external_token'+ parameter to the +form_tag+ options: + + +<%= form_tag 'http://farfar.away/form', :authenticity_token => 'external_token') do %> + Form contents +<% end %> + + +Sometimes when you submit data to an external resource, like payment gateway, fields you can use in your form are limited by an external API. So you may want not to generate an +authenticity_token+ hidden field at all. For doing this just pass +false+ to the +:authenticity_token+ option: + + +<%= form_tag 'http://farfar.away/form', :authenticity_token => 'external_token') do %> + Form contents +<% end %> + + +The same technique is available for the +form_for+ too. You need just to set an +authenticity_token+ through +html+ options: + + +<%= form_for @invoice, :url => external_url, :html => { :authenticity_token => 'external_token' } do |f| + Form contents +<% end %> + + +Or if you don't want to render an +authenticity_token+ field: + + +<%= form_for @invoice, :url => external_url, :html => { :authenticity_token => false } do |f| + Form contents +<% end %> + + h3. Building Complex Forms Many apps grow beyond simple forms editing a single object. For example when creating a Person you might want to allow the user to (on the same form) create multiple address records (home, work, etc.). When later editing that person the user should be able to add, remove or amend addresses as necessary. While this guide has shown you all the pieces necessary to handle this, Rails does not yet have a standard end-to-end way of accomplishing this, but many have come up with viable approaches. These include: @@ -776,6 +811,7 @@ Many apps grow beyond simple forms editing a single object. For example when cre h3. Changelog +* February 5, 2011: Added 'Forms to external resources' section. Timothy N. Tsvetkov * April 6, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com h3. Authors -- cgit v1.2.3 From 742f5f4a5d0deec132d2bfed53706e05d51871cb Mon Sep 17 00:00:00 2001 From: Henry Phan Date: Sat, 5 Feb 2011 13:09:35 -0800 Subject: Add CSS fix for WebKit/Mac rendering issue. --- railties/guides/assets/stylesheets/fixes.css | 16 ++++++++++++++++ railties/guides/source/layout.html.erb | 2 ++ 2 files changed, 18 insertions(+) create mode 100644 railties/guides/assets/stylesheets/fixes.css (limited to 'railties/guides') diff --git a/railties/guides/assets/stylesheets/fixes.css b/railties/guides/assets/stylesheets/fixes.css new file mode 100644 index 0000000000..54efa5b9b7 --- /dev/null +++ b/railties/guides/assets/stylesheets/fixes.css @@ -0,0 +1,16 @@ +/* + Fix a rendering issue affecting WebKits on Mac. + See https://github.com/lifo/docrails/issues#issue/16 for more information. +*/ +.syntaxhighlighter a, +.syntaxhighlighter div, +.syntaxhighlighter code, +.syntaxhighlighter table, +.syntaxhighlighter table td, +.syntaxhighlighter table tr, +.syntaxhighlighter table tbody, +.syntaxhighlighter table thead, +.syntaxhighlighter table caption, +.syntaxhighlighter textarea { + line-height: 1.2em !important; +} diff --git a/railties/guides/source/layout.html.erb b/railties/guides/source/layout.html.erb index 91dab18b21..e924f2f6c0 100644 --- a/railties/guides/source/layout.html.erb +++ b/railties/guides/source/layout.html.erb @@ -12,6 +12,8 @@ + + <% if @edge %> -- cgit v1.2.3 From cc2b2719d87a7c3a81fe810211ab39755aec1a8f Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Mon, 7 Feb 2011 01:34:12 +0530 Subject: fix minor typo --- railties/guides/source/getting_started.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/getting_started.textile b/railties/guides/source/getting_started.textile index 82700532c0..52e398a497 100644 --- a/railties/guides/source/getting_started.textile +++ b/railties/guides/source/getting_started.textile @@ -411,7 +411,7 @@ Rails will execute this migration command and tell you it created the Posts tabl == CreatePosts: migrated (0.0020s) =========================================== -NOTE. Because you're working in the development environment by default, this command will apply to the database defined in the +development+ section of your +config/database.yml+ file. If you would like to execute migrations in other environment, for instance in production, you must explicitely pass it when invoking the command: rake db:migrate RAILS_ENV=production. +NOTE. Because you're working in the development environment by default, this command will apply to the database defined in the +development+ section of your +config/database.yml+ file. If you would like to execute migrations in other environment, for instance in production, you must explicitly pass it when invoking the command: rake db:migrate RAILS_ENV=production. h4. Adding a Link -- cgit v1.2.3 From 58dccf305a63e5a77695206453a669bb3fffa17f Mon Sep 17 00:00:00 2001 From: Paul Annesley Date: Sun, 6 Feb 2011 16:04:29 -0800 Subject: ActiveRecord :default_timezone is :utc in Rails, as set by active_record/railtie.rb --- railties/guides/source/configuring.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/configuring.textile b/railties/guides/source/configuring.textile index eee18f1131..62b846e871 100644 --- a/railties/guides/source/configuring.textile +++ b/railties/guides/source/configuring.textile @@ -218,7 +218,7 @@ h4. Configuring Active Record * +config.active_record.pluralize_table_names+ specifies whether Rails will look for singular or plural table names in the database. If set to +true+ (the default), then the Customer class will use the +customers+ table. If set to +false+, then the Customers class will use the +customer+ table. -* +config.active_record.default_timezone+ determines whether to use +Time.local+ (if set to +:local+) or +Time.utc+ (if set to +:utc+) when pulling dates and times from the database. The default is +:local+. +* +config.active_record.default_timezone+ determines whether to use +Time.local+ (if set to +:local+) or +Time.utc+ (if set to +:utc+) when pulling dates and times from the database. The default is +:utc+ for Rails, although ActiveRecord defaults to +:local+ when used outside of Rails. * +config.active_record.schema_format+ controls the format for dumping the database schema to a file. The options are +:ruby+ (the default) for a database-independent version that depends on migrations, or +:sql+ for a set of (potentially database-dependent) SQL statements. -- cgit v1.2.3 From 7a774259010acec2a3b4c85e1a4b3289e4010ba8 Mon Sep 17 00:00:00 2001 From: "Timothy N. Tsvetkov" Date: Mon, 7 Feb 2011 14:35:47 +0300 Subject: Updated form rails guide for new place of authenticity_token option Signed-off-by: Santiago Pastorino --- railties/guides/source/form_helpers.textile | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/form_helpers.textile b/railties/guides/source/form_helpers.textile index cdb311c726..40db43079c 100644 --- a/railties/guides/source/form_helpers.textile +++ b/railties/guides/source/form_helpers.textile @@ -782,10 +782,10 @@ Sometimes when you submit data to an external resource, like payment gateway, fi <% end %> -The same technique is available for the +form_for+ too. You need just to set an +authenticity_token+ through +html+ options: +The same technique is available for the +form_for+ too: -<%= form_for @invoice, :url => external_url, :html => { :authenticity_token => 'external_token' } do |f| +<%= form_for @invoice, :url => external_url, :authenticity_token => 'external_token' do |f| Form contents <% end %> @@ -793,7 +793,7 @@ The same technique is available for the +form_for+ too. You need just to set an Or if you don't want to render an +authenticity_token+ field: -<%= form_for @invoice, :url => external_url, :html => { :authenticity_token => false } do |f| +<%= form_for @invoice, :url => external_url, :authenticity_token => false do |f| Form contents <% end %> -- cgit v1.2.3 From 77582075a66ca6fcd6959e29b4d6625021e67edf Mon Sep 17 00:00:00 2001 From: Kevin Skoglund Date: Mon, 7 Feb 2011 09:25:22 -0500 Subject: Add note that validates_length_of will incorrectly pluralize min. length 1 --- railties/guides/source/active_record_validations_callbacks.textile | 2 ++ 1 file changed, 2 insertions(+) (limited to 'railties/guides') diff --git a/railties/guides/source/active_record_validations_callbacks.textile b/railties/guides/source/active_record_validations_callbacks.textile index a15571fe58..6f857ab9cc 100644 --- a/railties/guides/source/active_record_validations_callbacks.textile +++ b/railties/guides/source/active_record_validations_callbacks.textile @@ -314,6 +314,8 @@ class Essay < ActiveRecord::Base end +Note that the default error messages are plural (e.g., "is too short (minimum is %{count} characters)"). For this reason, when +:minimum+ is 1 you should provide a personalized message or use +validates_presence_of+ instead. When +:in+ or +:within+ have a lower limit of 1, you should either provide a personalized message or call +validates_presence_of+ prior to +validates_length_of+. + The +validates_size_of+ helper is an alias for +validates_length_of+. h4. +validates_numericality_of+ -- cgit v1.2.3 From 435bf4ca4bb4193b18589289ca2cff07dbd3771a Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Wed, 9 Feb 2011 03:18:12 +0530 Subject: minor fixes in generators --- railties/guides/source/command_line.textile | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/command_line.textile b/railties/guides/source/command_line.textile index 1e570c9992..255b9ab190 100644 --- a/railties/guides/source/command_line.textile +++ b/railties/guides/source/command_line.textile @@ -81,7 +81,7 @@ The +rails generate+ command uses templates to create a whole lot of things. You $ rails generate -Usage: rails generate generator [options] [args] +Usage: rails generate generator [args] [options] ... ... @@ -105,7 +105,7 @@ INFO: All Rails console utilities have help text. As with most *nix utilities, y $ rails generate controller -Usage: rails generate controller ControllerName [options] +Usage: rails generate controller NAME [action action] [options] ... ... @@ -122,7 +122,7 @@ Example: Modules Example: rails generate controller 'admin/credit_card' suspend late_fee - Credit card admin controller with URLs /admin/credit_card/suspend. + Credit card admin controller with URLs like /admin/credit_card/suspend. Controller: app/controllers/admin/credit_card_controller.rb Views: app/views/admin/credit_card/debit.html.erb [...] Helper: app/helpers/admin/credit_card_helper.rb @@ -138,10 +138,13 @@ $ rails generate controller Greetings hello invoke erb create app/views/greetings create app/views/greetings/hello.html.erb - error rspec [not found] + invoke test_unit + create test/functional/greetings_controller_test.rb invoke helper create app/helpers/greetings_helper.rb - error rspec [not found] + invoke test_unit + create test/unit/helpers/greetings_helper_test.rb + What all did this generate? It made sure a bunch of directories were in our application, and created a controller file, a functional test file, a helper for the view, and a view file. @@ -153,7 +156,6 @@ class GreetingsController < ApplicationController def hello @message = "Hello, how are you today?" end - end
@@ -164,7 +166,7 @@ Then the view, to display our message (in +app/views/greetings/hello.html.erb+):

<%= @message %>

-Deal. Go check it out in your browser. Fire up your server. Remember? +rails server+ at the root of your Rails application should do it. +Deal. Go check it out in your browser. Fire up your server using +rails server+. $ rails server @@ -181,7 +183,7 @@ Rails comes with a generator for data models too: $ rails generate model -Usage: rails generate model ModelName [field:type, field:type] +Usage: rails generate model NAME [field:type field:type] [options] ... @@ -223,7 +225,7 @@ $ rails generate scaffold HighScore game:string score:integer create app/controllers/high_scores_controller.rb create test/functional/high_scores_controller_test.rb create app/helpers/high_scores_helper.rb - route map.resources :high_scores + route resources :high_scores dependency model exists app/models/ exists test/unit/ @@ -284,7 +286,7 @@ Let's say you're creating a website for a client who wants a small accounting sy There is such a thing! The plugin we're installing is called +acts_as_paranoid+, and it lets models implement a +deleted_at+ column that gets set when you call destroy. Later, when calling find, the plugin will tack on a database check to filter out "deleted" things. -$ rails plugin install http://svn.techno-weenie.net/projects/plugins/acts_as_paranoid +$ rails plugin install https://github.com/technoweenie/acts_as_paranoid.git + ./CHANGELOG + ./MIT-LICENSE ... -- cgit v1.2.3 From 04eaacca967830b41a655ce8bb3c816d6e5ff056 Mon Sep 17 00:00:00 2001 From: John Paul Ashenfelter Date: Wed, 9 Feb 2011 11:23:42 -0500 Subject: replaced MODEL.human_name with MODEL.model_name.human now that .human_name is deprecated --- railties/guides/source/i18n.textile | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/i18n.textile b/railties/guides/source/i18n.textile index e47ac7aed6..337ef52d3b 100644 --- a/railties/guides/source/i18n.textile +++ b/railties/guides/source/i18n.textile @@ -1,4 +1,4 @@ -h2. Rails Internationalization (I18n) API +lh2. 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. @@ -649,7 +649,7 @@ Generally we recommend using YAML as a format for storing translations. There ar h4. Translations for Active Record Models -You can use the methods +Model.human_name+ and +Model.human_attribute_name(attribute)+ to transparently look up translations for your model and attribute names. +You can use the methods +Model.model_name.human+ and +Model.human_attribute_name(attribute)+ to transparently look up translations for your model and attribute names. For example when you add the following translations: @@ -664,7 +664,7 @@ en: # will translate User attribute "login" as "Handle" -Then +User.human_name+ will return "Dude" and +User.human_attribute_name("login")+ will return "Handle". +Then +User.model_name.human+ will return "Dude" and +User.human_attribute_name("login")+ will return "Handle". h5. Error Message Scopes @@ -786,9 +786,9 @@ h5. Action View Helper Methods h5. Active Record Methods -* +human_name+ and +human_attribute_name+ use translations for model names and attribute names if available in the "activerecord.models":http://github.com/rails/rails/blob/master/activerecord/lib/active_record/locale/en.yml#L29 scope. They also support translations for inherited class names (e.g. for use with STI) as explained above in "Error message scopes". +* +model_name.human+ and +human_attribute_name+ use translations for model names and attribute names if available in the "activerecord.models":http://github.com/rails/rails/blob/master/activerecord/lib/active_record/locale/en.yml#L29 scope. They also support translations for inherited class names (e.g. for use with STI) as explained above in "Error message scopes". -* +ActiveRecord::Errors#generate_message+ (which is used by Active Record validations but may also be used manually) uses +human_name+ and +human_attribute_name+ (see above). It also translates the error message and supports translations for inherited class names as explained above in "Error message scopes". +* +ActiveRecord::Errors#generate_message+ (which is used by Active Record validations but may also be used manually) uses +model_name.human+ and +human_attribute_name+ (see above). It also translates the error message and supports translations for inherited class names as explained above in "Error message scopes". *+ ActiveRecord::Errors#full_messages+ prepends the attribute name to the error message using a separator that will be looked up from "activerecord.errors.format.separator":http://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L91 (and which defaults to +' '+). -- cgit v1.2.3 From cb1f8413def871e7fd42064e5144dfeb8460c1fc Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Wed, 9 Feb 2011 20:05:28 +0100 Subject: now that the API guidelines are a guide, it is enough to assert that the names of Rails components have a space, no need to say it was checked with David in the past --- railties/guides/source/api_documentation_guidelines.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/api_documentation_guidelines.textile b/railties/guides/source/api_documentation_guidelines.textile index 2bbb1b5919..68665dce98 100644 --- a/railties/guides/source/api_documentation_guidelines.textile +++ b/railties/guides/source/api_documentation_guidelines.textile @@ -27,7 +27,7 @@ Communicate to the reader the current way of doing things, both explicitly and i Documentation has to be concise but comprehensive. Explore and document edge cases. What happens if a module is anonymous? What if a collection is empty? What if an argument is nil? -The proper names of Rails components have a space in between the words, like "Active Support". +ActiveRecord+ is a Ruby module, whereas Active Record is an ORM. Historically there has been lack of consistency regarding this, but we checked with David when docrails started. All Rails documentation consistently refer to Rails components by their proper name, and if in your next blog post or presentation you remember this tidbit and take it into account that'd be fenomenal :). +The proper names of Rails components have a space in between the words, like "Active Support". +ActiveRecord+ is a Ruby module, whereas Active Record is an ORM. All Rails documentation should consistently refer to Rails components by their proper name, and if in your next blog post or presentation you remember this tidbit and take it into account that'd be fenomenal :). Spell names correctly: Arel, Test::Unit, RSpec, HTML, MySQL, JavaScript, ERb. When in doubt, please have a look at some authoritative source like their official documentation. -- cgit v1.2.3 From f68287f0be387c858766bbab237424d2d54edf71 Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Thu, 10 Feb 2011 23:37:55 +0530 Subject: fix typos, minor edits --- railties/guides/source/command_line.textile | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/command_line.textile b/railties/guides/source/command_line.textile index 255b9ab190..81d181fe02 100644 --- a/railties/guides/source/command_line.textile +++ b/railties/guides/source/command_line.textile @@ -378,8 +378,8 @@ $ rails new . --git --database=postgresql add 'Rakefile' create README add 'README' - create app/controllers/application_controller_.rb -add 'app/controllers/application_controller_.rb' + create app/controllers/application_controller.rb +add 'app/controllers/application_controller.rb' create app/helpers/application_helper.rb ... create log/test.log @@ -451,7 +451,7 @@ The Rails generator by default looks in these places for available generators, w * Inside any plugin with a directory like "generators" or "rails_generators" * ~/.rails/generators * Inside any Gem you have installed with a name ending in "_generator" -* Inside *any* Gem installed with a "rails_generators" path, and a file ending in "_generator.rb" +* Inside any Gem installed with a "rails_generators" path, and a file ending in "_generator.rb" * Finally, the builtin Rails generators (controller, model, mailer, etc.) Let's try the fourth option (in our home directory), which will be easy to clean up later: @@ -578,13 +578,13 @@ You can list all the timezones Rails knows about with +rake time:zones:all+, whi h5. +tmp:+ Temporary files -The tmp directory is, like in 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 an +rm -rf *+ gone awry. +The tmp directory is, like in 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. h5. Miscellaneous Tasks +rake stats+ is great for looking at statistics on your code, displaying things like KLOCs (thousands of lines of code) and your code to test ratio. - +rake secret+ will give you a psuedo-random key to use for your session secret. + +rake secret+ will give you a pseudo-random key to use for your session secret. +rake routes+ will list all of your defined routes, which is useful for tracking down routing problems in your app, or giving you a good overview of the URLs in an app you're trying to get familiar with. -- cgit v1.2.3 From 0db9de6cf66b6a4388794efd8801f720ea95f242 Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Fri, 11 Feb 2011 00:17:03 +0530 Subject: updated reference to remote_form_for --- railties/guides/source/form_helpers.textile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/form_helpers.textile b/railties/guides/source/form_helpers.textile index 7b4426b335..7a033a30d7 100644 --- a/railties/guides/source/form_helpers.textile +++ b/railties/guides/source/form_helpers.textile @@ -187,7 +187,7 @@ output: Hidden inputs are not shown to the user, but they hold data like any textual input. Values inside them can be changed with JavaScript. -TIP: If you're using password input fields (for any purpose), you might want to prevent their values showing up in application logs by activating +filter_parameter_logging(:password)+ in your ApplicationController. +TIP: If you're using password input fields (for any purpose), you might want to configure your application to prevent those parameters from being logged. h3. Dealing with Model Objects @@ -594,7 +594,7 @@ NOTE: If the user has not selected a file the corresponding parameter will be an h4. Dealing with Ajax -Unlike other forms making an asynchronous file upload form is not as simple as replacing +form_for+ with +remote_form_for+. With an Ajax form the serialization is done by JavaScript running inside the browser and since JavaScript cannot read files from your hard drive the file cannot be uploaded. The most common workaround is to use an invisible iframe that serves as the target for the form submission. +Unlike other forms making an asynchronous file upload form is not as simple as providing +form_for+ with :remote => true. With an Ajax form the serialization is done by JavaScript running inside the browser and since JavaScript cannot read files from your hard drive the file cannot be uploaded. The most common workaround is to use an invisible iframe that serves as the target for the form submission. h3. Customizing Form Builders -- cgit v1.2.3 From 46ebbcd56b16734fa6ba6f81138827918976a9d5 Mon Sep 17 00:00:00 2001 From: jonnii Date: Thu, 10 Feb 2011 12:22:19 -0800 Subject: Change fenomenal to phenomenal. --- railties/guides/source/api_documentation_guidelines.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/api_documentation_guidelines.textile b/railties/guides/source/api_documentation_guidelines.textile index 2bbb1b5919..5bac75fe8f 100644 --- a/railties/guides/source/api_documentation_guidelines.textile +++ b/railties/guides/source/api_documentation_guidelines.textile @@ -27,7 +27,7 @@ Communicate to the reader the current way of doing things, both explicitly and i Documentation has to be concise but comprehensive. Explore and document edge cases. What happens if a module is anonymous? What if a collection is empty? What if an argument is nil? -The proper names of Rails components have a space in between the words, like "Active Support". +ActiveRecord+ is a Ruby module, whereas Active Record is an ORM. Historically there has been lack of consistency regarding this, but we checked with David when docrails started. All Rails documentation consistently refer to Rails components by their proper name, and if in your next blog post or presentation you remember this tidbit and take it into account that'd be fenomenal :). +The proper names of Rails components have a space in between the words, like "Active Support". +ActiveRecord+ is a Ruby module, whereas Active Record is an ORM. Historically there has been lack of consistency regarding this, but we checked with David when docrails started. All Rails documentation consistently refer to Rails components by their proper name, and if in your next blog post or presentation you remember this tidbit and take it into account that'd be phenomenal:). Spell names correctly: Arel, Test::Unit, RSpec, HTML, MySQL, JavaScript, ERb. When in doubt, please have a look at some authoritative source like their official documentation. -- cgit v1.2.3 From 0d40e2c397c9ce92c839a3c318ed8757cf213413 Mon Sep 17 00:00:00 2001 From: Corey Ward Date: Sat, 12 Feb 2011 08:12:24 -0800 Subject: Add note about running `bundle install` as root. Solves issue with '#' not being rendered, and it's more clear for beginners. --- railties/guides/source/getting_started.textile | 1 + 1 file changed, 1 insertion(+) (limited to 'railties/guides') diff --git a/railties/guides/source/getting_started.textile b/railties/guides/source/getting_started.textile index 52e398a497..bf45c48547 100644 --- a/railties/guides/source/getting_started.textile +++ b/railties/guides/source/getting_started.textile @@ -195,6 +195,7 @@ h4. Installing the Required Gems Rails applications manage gem dependencies with "Bundler":http://gembundler.com/v1.0/index.html by default. As we don't need any other gems beyond the ones in the generated +Gemfile+ we can directly run +Usually as root user: # bundle install -- cgit v1.2.3 From bc6554f63ccf7a0ab8797472cded62bdea8fbabc Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Sun, 13 Feb 2011 01:37:37 +0100 Subject: Revert "Add note about running `bundle install` as root. Solves issue with '#' not being rendered, and it's more clear for beginners." Reason: Running bundle as root is not recommended. This reverts commit 0d40e2c397c9ce92c839a3c318ed8757cf213413. --- railties/guides/source/getting_started.textile | 1 - 1 file changed, 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/getting_started.textile b/railties/guides/source/getting_started.textile index bf45c48547..52e398a497 100644 --- a/railties/guides/source/getting_started.textile +++ b/railties/guides/source/getting_started.textile @@ -195,7 +195,6 @@ h4. Installing the Required Gems Rails applications manage gem dependencies with "Bundler":http://gembundler.com/v1.0/index.html by default. As we don't need any other gems beyond the ones in the generated +Gemfile+ we can directly run -Usually as root user: # bundle install -- cgit v1.2.3 From 69f07dad62b4927b001046012c5a5cdab87dc1ae Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Sun, 13 Feb 2011 01:40:32 +0100 Subject: the shell prompt for non-root sessions is "$" by convention --- railties/guides/source/getting_started.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/getting_started.textile b/railties/guides/source/getting_started.textile index 52e398a497..bf15afcd62 100644 --- a/railties/guides/source/getting_started.textile +++ b/railties/guides/source/getting_started.textile @@ -195,7 +195,7 @@ h4. Installing the Required Gems Rails applications manage gem dependencies with "Bundler":http://gembundler.com/v1.0/index.html by default. As we don't need any other gems beyond the ones in the generated +Gemfile+ we can directly run -# bundle install +$ bundle install to have them ready. -- cgit v1.2.3 From 0617d3e3c607d6e65a107190cff5404d0b55c790 Mon Sep 17 00:00:00 2001 From: Mike Gehard Date: Sun, 13 Feb 2011 14:21:17 -0700 Subject: change plugins guide to favor gem based plugins, clean up to reflect the state of Rails3 plugins, remove information not compatible with Rails3. --- railties/guides/source/plugins.textile | 1523 +++++--------------------------- 1 file changed, 237 insertions(+), 1286 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/plugins.textile b/railties/guides/source/plugins.textile index f7c4a6f85c..2135c0da4e 100644 --- a/railties/guides/source/plugins.textile +++ b/railties/guides/source/plugins.textile @@ -10,285 +10,71 @@ After reading this guide you should be familiar with: * Creating a plugin from scratch * Writing and running tests for the plugin -* Storing models, views, controllers, helpers and even other plugins in your plugins -* Writing generators -* Writing custom Rake tasks in your plugin -* Generating RDoc documentation for your plugin -* Avoiding common pitfalls with 'init.rb' This guide describes how to build a test-driven plugin that will: * Extend core ruby classes like Hash and String * Add methods to ActiveRecord::Base in the tradition of the 'acts_as' plugins -* Add a view helper that can be used in erb templates -* Add a new generator that will generate a migration -* Add a custom generator command -* A custom route method that can be used in routes.rb +* Give you information about where to put generators in your plugin. -For the purpose of this guide pretend for a moment that you are an avid bird watcher. Your favorite bird is the Yaffle, and you want to create a plugin that allows other developers to share in the Yaffle goodness. First, you need to get setup for development. +For the purpose of this guide pretend for a moment that you are an avid bird watcher. +Your favorite bird is the Yaffle, and you want to create a plugin that allows other developers to share in the Yaffle +goodness. endprologue. h3. Setup -h4. Create the Basic Application +h4. Generating the Plugin Skeleton -The examples in this guide require that you have a working rails application. To create a simple one execute: +Rails currently ships with a generator to generate a plugin within a Rails application. Help text is available that will explain +how this generator works. -gem install rails -rails new yaffle_guide -cd yaffle_guide -bundle install -rails generate scaffold bird name:string -rake db:migrate -rails server + rails generate plugin --help -Then navigate to http://localhost:3000/birds. Make sure you have a functioning rails application before continuing. +This generator places the plugin into the vendor/plugins directory. -NOTE: The aforementioned instructions will work for SQLite3. For more detailed instructions on how to create a Rails application for other databases see the API docs. +Vendored plugins are useful for quickly prototyping your plugin but current thinking in the Rails community is shifting towards +packaging plugins as gems, especially with the inclusion of Bundler as the Rails dependency manager. +Packaging a plugin as a gem may be overkill for any plugins that will not be shared across projects but doing so from the start makes it easier to share the plugin going forward without adding too much additional overhead during development. - -h4. Generate the Plugin Skeleton - -Rails ships with a plugin generator which creates a basic plugin skeleton. Pass the plugin name, either 'CamelCased' or 'under_scored', as an argument. Pass +--generator+ to add an example generator also. - -This creates a plugin in +vendor/plugins+ including an +init.rb+ and +README+ as well as standard +lib+, +task+, and +test+ directories. - -Examples: - -rails generate plugin yaffle -rails generate plugin yaffle --generator - - -To get more detailed help on the plugin generator, type +rails generate plugin+. - -Later on this guide will describe how to work with generators, so go ahead and generate your plugin with the +--generator+ option now: - - -rails generate plugin yaffle --generator - - -You should see the following output: - - -create vendor/plugins/yaffle -create vendor/plugins/yaffle/init.rb -create vendor/plugins/yaffle/install.rb -create vendor/plugins/yaffle/MIT-LICENSE -create vendor/plugins/yaffle/Rakefile -create vendor/plugins/yaffle/README -create vendor/plugins/yaffle/uninstall.rb -create vendor/plugins/yaffle/lib -create vendor/plugins/yaffle/lib/yaffle.rb -invoke generator -inside vendor/plugins/yaffle -create lib/generators -create lib/generators/yaffle_generator.rb -create lib/generators/USAGE -create lib/generators/templates -invoke test_unit -inside vendor/plugins/yaffle -create test -create test/yaffle_test.rb -create test/test_helper.rb - - -h4. Organize Your Files - -To make it easy to organize your files and to make the plugin more compatible with GemPlugins, start out by altering your file system to look like this: +Rails 3.1 will ship with a plugin generator that will default to setting up a plugin +as a gem. This tutorial will begin to bridge that gap by demonstrating how to create a gem based plugin using the +"Enginex gem":http://www.github.com/josevalim/enginex. -|-- lib -| |-- yaffle -| `-- yaffle.rb -`-- init.rb + gem install enginex + enginex --help + enginex yaffle - -# vendor/plugins/yaffle/init.rb - -require 'yaffle' - - -Now you can add any +require+ statements to +lib/yaffle.rb+ and keep +init.rb+ clean. - -h3. Tests - -In this guide you will learn how to test your plugin against multiple different database adapters using Active Record. To setup your plugin to allow for easy testing you'll need to add 3 files: - - * A +database.yml+ file with all of your connection strings - * A +schema.rb+ file with your table definitions - * A test helper method that sets up the database - -h4. Test Setup - - -# vendor/plugins/yaffle/test/database.yml - -sqlite: - adapter: sqlite - database: vendor/plugins/yaffle/test/yaffle_plugin.sqlite.db - -sqlite3: - adapter: sqlite3 - database: vendor/plugins/yaffle/test/yaffle_plugin.sqlite3.db - -postgresql: - adapter: postgresql - username: postgres - password: postgres - database: yaffle_plugin_test - min_messages: ERROR - -mysql: - adapter: mysql2 - host: localhost - username: root - password: password - database: yaffle_plugin_test - - -For this guide you'll need 2 tables/models, Hickwalls and Wickwalls, so add the following: - - -# vendor/plugins/yaffle/test/schema.rb - -ActiveRecord::Schema.define(:version => 0) do - create_table :hickwalls, :force => true do |t| - t.string :name - t.string :last_squawk - t.datetime :last_squawked_at - end - create_table :wickwalls, :force => true do |t| - t.string :name - t.string :last_tweet - t.datetime :last_tweeted_at - end - create_table :woodpeckers, :force => true do |t| - t.string :name - end -end - - - -# vendor/plugins/yaffle/test/test_helper.rb - -ENV['RAILS_ENV'] = 'test' -ENV['RAILS_ROOT'] ||= File.dirname(__FILE__) + '/../../../..' - -require 'test/unit' -require File.expand_path(File.join(ENV['RAILS_ROOT'], 'config/environment.rb')) - -def load_schema - config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml')) - ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log") - - db_adapter = ENV['DB'] - - # no db passed, try one of these fine config-free DBs before bombing. - db_adapter ||= - begin - require 'rubygems' - require 'sqlite' - 'sqlite' - rescue MissingSourceFile - begin - require 'sqlite3' - 'sqlite3' - rescue MissingSourceFile - end - end - - if db_adapter.nil? - raise "No DB Adapter selected. Pass the DB= option to pick one, or install Sqlite or Sqlite3." - end - - ActiveRecord::Base.establish_connection(config[db_adapter]) - load(File.dirname(__FILE__) + "/schema.rb") - require File.dirname(__FILE__) + '/../init' -end - - -Now whenever you write a test that requires the database, you can call 'load_schema'. - -h4. Run the Plugin Tests - -Once you have these files in place, you can write your first test to ensure that your plugin-testing setup is correct. By default rails generates a file in +vendor/plugins/yaffle/test/yaffle_test.rb+ with a sample test. Replace the contents of that file with: - - -# vendor/plugins/yaffle/test/yaffle_test.rb - -require 'test_helper' - -class YaffleTest < ActiveSupport::TestCase - load_schema - - class Hickwall < ActiveRecord::Base - end - - class Wickwall < ActiveRecord::Base - end - - def test_schema_has_loaded_correctly - assert_equal [], Hickwall.all - assert_equal [], Wickwall.all - end - -end - - -To run this, go to the plugin directory and run +rake+: - - -cd vendor/plugins/yaffle -rake - +This command will create a new directory named "yaffle" within the current directory. -You should see output like: +h3. Testing your newly generated plugin - -/opt/local/bin/ruby -Ilib:lib "/opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader.rb" "test/yaffle_test.rb" - create_table(:hickwalls, {:force=>true}) - -> 0.0220s --- create_table(:wickwalls, {:force=>true}) - -> 0.0077s --- create_table(:woodpeckers, {:force=>true}) - -> 0.0069s --- initialize_schema_migrations_table() - -> 0.0007s --- assume_migrated_upto_version(0, "db/migrate") - -> 0.0007s -Loaded suite /opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader -Started -. -Finished in 0.002236 seconds. - -1 test, 2 assertion, 0 failures, 0 errors, 0 skips - +You can navigate to the directory that contains the plugin, run the +bundle install+ command + and run the one generated test using the +rake+ command. -By default the setup above runs your tests with SQLite or SQLite3. To run tests with one of the other connection strings specified in +database.yml+, pass the DB environment variable to rake: +You should see: -rake DB=sqlite -rake DB=sqlite3 -rake DB=mysql -rake DB=postgresql + 2 tests, 2 assertions, 0 failures, 0 errors, 0 skips -Now you are ready to test-drive your plugin! +This will tell you that everything got generated properly and you are ready to start adding functionality. h3. Extending Core Classes -This section will explain how to add a method to String that will be available anywhere in your Rails application. +This section will explain how to add a method to String that will be available anywhere in your rails application. -In this example you will add a method to String named +to_squawk+. To begin, create a new test file with a few assertions: +In this example you will add a method to String named +to_squawk+. To begin, create a new test file with a few assertions: -# vendor/plugins/yaffle/test/core_ext_test.rb +# yaffle/test/core_ext_test.rb -require File.dirname(__FILE__) + '/test_helper' +require 'test_helper' class CoreExtTest < Test::Unit::TestCase def test_to_squawk_prepends_the_word_squawk @@ -297,20 +83,13 @@ class CoreExtTest < Test::Unit::TestCase end -Navigate to your plugin directory and run +rake test+: - - -cd vendor/plugins/yaffle -rake test - - -The test above should fail with the message: +Run +rake+ to run the test. This test should fail because we haven't implemented the +to_squak+ method: - 1) Error: -test_to_squawk_prepends_the_word_squawk(CoreExtTest): -NoMethodError: undefined method `to_squawk' for "Hello World":String - ./test/core_ext_test.rb:5:in `test_to_squawk_prepends_the_word_squawk' + 1) Error: + test_to_squawk_prepends_the_word_squawk(CoreExtTest): + NoMethodError: undefined method `to_squawk' for "Hello World":String + test/core_ext_test.rb:5:in `test_to_squawk_prepends_the_word_squawk' Great - now you are ready to start development. @@ -318,15 +97,18 @@ Great - now you are ready to start development. Then in +lib/yaffle.rb+ require +lib/core_ext+: -# vendor/plugins/yaffle/lib/yaffle.rb +# yaffle/lib/yaffle.rb require "yaffle/core_ext" + +module Yaffle +end Finally, create the +core_ext.rb+ file and add the +to_squawk+ method: -# vendor/plugins/yaffle/lib/yaffle/core_ext.rb +# yaffle/lib/yaffle/core_ext.rb String.class_eval do def to_squawk @@ -335,7 +117,13 @@ String.class_eval do end -To test that your method does what it says it does, run the unit tests with +rake+ from your plugin directory. To see this in action, fire up a console and start squawking: +To test that your method does what it says it does, run the unit tests with +rake+ from your plugin directory. + + + 3 tests, 3 assertions, 0 failures, 0 errors, 0 skips + + +To see this in action, change to the test/dummy directory, fire up a console and start squawking: $ rails console @@ -343,168 +131,204 @@ $ rails console => "squawk! Hello World" -h4. Working with +init.rb+ - -When Rails loads plugins it looks for a file named +init.rb+. However, when the plugin is initialized, +init.rb+ is invoked via +eval+ (not +require+) so it has slightly different behavior. - -NOTE: The plugins loader also looks for +rails/init.rb+, but that one is deprecated in favor of the top-level +init.rb+ aforementioned. +h3. Add an "acts_as" Method to Active Record -Under certain circumstances if you reopen classes or modules in +init.rb+ you may inadvertently create a new class, rather than reopening an existing class. A better alternative is to reopen the class in a different file, and require that file from +init.rb+, as shown above. +A common pattern in plugins is to add a method called 'acts_as_something' to models. In this case, you +want to write a method called 'acts_as_yaffle' that adds a 'squawk' method to your Active Record models. -If you must reopen a class in +init.rb+ you can use +module_eval+ or +class_eval+ to avoid any issues: +To begin, set up your files so that you have: -# vendor/plugins/yaffle/init.rb +# yaffle/test/acts_as_yaffle_test.rb -Hash.class_eval do - def is_a_special_hash? - true - end +require 'test_helper' + +class ActsAsYaffleTest < Test::Unit::TestCase end -Another way is to explicitly define the top-level module space for all modules and classes, like +::Hash+: - -# vendor/plugins/yaffle/init.rb +# yaffle/lib/yaffle.rb -class ::Hash - def is_a_special_hash? - true - end +require "yaffle/core_ext" +require 'yaffle/acts_as_yaffle' + +module Yaffle end -h3. Add an "acts_as" Method to Active Record - -A common pattern in plugins is to add a method called 'acts_as_something' to models. In this case, you want to write a method called 'acts_as_yaffle' that adds a 'squawk' method to your models. - -To begin, set up your files so that you have: - -* *vendor/plugins/yaffle/test/acts_as_yaffle_test.rb* - -require File.dirname(__FILE__) + '/test_helper' +# yaffle/lib/yaffle/acts_as_yaffle.rb -class ActsAsYaffleTest < Test::Unit::TestCase +module Yaffle + module ActsAsYaffle + # your code will go here + end end -* *vendor/plugins/yaffle/lib/yaffle.rb* +h4. Add a Class Method - -require 'yaffle/acts_as_yaffle' - +This plugin will expect that you've added a method to your model named 'last_squawk'. However, the +plugin users might have already defined a method on their model named 'last_squawk' that they use +for something else. This plugin will allow the name to be changed by adding a class method called 'yaffle_text_field'. -* *vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb* +To start out, write a failing test that shows the behavior you'd like: -module Yaffle - # your code will go here -end - - -Note that after requiring 'acts_as_yaffle' you also have to include it into ActiveRecord::Base so that your plugin methods will be available to the rails models. +# yaffle/test/acts_as_yaffle_test.rb -One of the most common plugin patterns for 'acts_as_yaffle' plugins is to structure your file like so: +require 'test_helper' -* *vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb* +class ActsAsYaffleTest < Test::Unit::TestCase - -module Yaffle - def self.included(base) - base.send :extend, ClassMethods + def test_a_hickwalls_yaffle_text_field_should_be_last_squawk + assert_equal "last_squawk", Hickwall.yaffle_text_field end - module ClassMethods - # any method placed here will apply to classes, like Hickwall - def acts_as_something - send :include, InstanceMethods - end + def test_a_wickwalls_yaffle_text_field_should_be_last_tweet + assert_equal "last_tweet", Wickwall.yaffle_text_field end - module InstanceMethods - # any method placed here will apply to instaces, like @hickwall - end end -With structure you can easily separate the methods that will be used for the class (like +Hickwall.some_method+) and the instance (like +@hickwell.some_method+). +When you run +rake+, you should see the following: -h4. Add a Class Method + + 1) Error: + test_a_hickwalls_yaffle_text_field_should_be_last_squawk(ActsAsYaffleTest): + NameError: uninitialized constant ActsAsYaffleTest::Hickwall + test/acts_as_yaffle_test.rb:6:in `test_a_hickwalls_yaffle_text_field_should_be_last_squawk' -This plugin will expect that you've added a method to your model named 'last_squawk'. However, the plugin users might have already defined a method on their model named 'last_squawk' that they use for something else. This plugin will allow the name to be changed by adding a class method called 'yaffle_text_field'. + 2) Error: + test_a_wickwalls_yaffle_text_field_should_be_last_tweet(ActsAsYaffleTest): + NameError: uninitialized constant ActsAsYaffleTest::Wickwall + test/acts_as_yaffle_test.rb:10:in `test_a_wickwalls_yaffle_text_field_should_be_last_tweet' -To start out, write a failing test that shows the behavior you'd like: + 5 tests, 3 assertions, 0 failures, 2 errors, 0 skips + + +This tells us that we don't have the necessary models (Hickwall and Wickwall) that we are trying to test. +We can easily generate these models in our "dummy" Rails application by running the following commands from the +test/dummy directory: + + + cd test/dummy + rails generate model Hickwall last_squak:string + rails generate model Wickwall last_squak:string last_tweet:string + + +Now you can create the necessary database tables in your testing database by navigating to your dummy app +and migrating the database. First + + + cd test/dummy + rake db:migrate + rake db:test:prepare + -* *vendor/plugins/yaffle/test/acts_as_yaffle_test.rb* +While you are here, change the Hickwall and Wickwall models so that they know that they are supposed to act +like yaffles. -require File.dirname(__FILE__) + '/test_helper' +# test/dummy/app/models/hickwall.rb class Hickwall < ActiveRecord::Base acts_as_yaffle end +# test/dummy/app/models/wickwall.rb + class Wickwall < ActiveRecord::Base acts_as_yaffle :yaffle_text_field => :last_tweet end -class ActsAsYaffleTest < Test::Unit::TestCase - load_schema + - def test_a_hickwalls_yaffle_text_field_should_be_last_squawk - assert_equal "last_squawk", Hickwall.yaffle_text_field - end +We will also add code to define the acts_as_yaffle method. - def test_a_wickwalls_yaffle_text_field_should_be_last_tweet - assert_equal "last_tweet", Wickwall.yaffle_text_field + +# yaffle/lib/yaffle/acts_as_yaffle.rb +module Yaffle + module ActsAsYaffle + extend ActiveSupport::Concern + + included do + end + + module ClassMethods + def acts_as_yaffle(options = {}) + # your code will go here + end + end end end + +ActiveRecord::Base.send :include, Yaffle::ActsAsYaffle -To make these tests pass, you could modify your +acts_as_yaffle+ file like so: +You can then return to the root directory (+cd ../..+) of your plugin and rerun the tests using +rake+. + + + 1) Error: + test_a_hickwalls_yaffle_text_field_should_be_last_squawk(ActsAsYaffleTest): + NoMethodError: undefined method `yaffle_text_field' for # + /Users/xxx/.rvm/gems/ruby-1.9.2-p136@xxx/gems/activerecord-3.0.3/lib/active_record/base.rb:1008:in `method_missing' + test/acts_as_yaffle_test.rb:5:in `test_a_hickwalls_yaffle_text_field_should_be_last_squawk' + + 2) Error: + test_a_wickwalls_yaffle_text_field_should_be_last_tweet(ActsAsYaffleTest): + NoMethodError: undefined method `yaffle_text_field' for # + Users/xxx/.rvm/gems/ruby-1.9.2-p136@xxx/gems/activerecord-3.0.3/lib/active_record/base.rb:1008:in `method_missing' + test/acts_as_yaffle_test.rb:9:in `test_a_wickwalls_yaffle_text_field_should_be_last_tweet' + + 5 tests, 3 assertions, 0 failures, 2 errors, 0 skips + + -* *vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb* +Getting closer...now we will implement the code of the acts_as_yaffle method to make the tests pass. +# yaffle/lib/yaffle/acts_as_yaffle.rb + module Yaffle - def self.included(base) - base.send :extend, ClassMethods - end + module ActsAsYaffle + extend ActiveSupport::Concern + + included do + end - module ClassMethods - def acts_as_yaffle(options = {}) - cattr_accessor :yaffle_text_field - self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s + module ClassMethods + def acts_as_yaffle(options = {}) + cattr_accessor :yaffle_text_field + self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s + end end end end -ActiveRecord::Base.send :include, Yaffle +ActiveRecord::Base.send :include, Yaffle::ActsAsYaffle +When you run +rake+ you should see the tests all pass: + + + 5 tests, 5 assertions, 0 failures, 0 errors, 0 skips + + h4. Add an Instance Method -This plugin will add a method named 'squawk' to any Active Record objects that call 'acts_as_yaffle'. The 'squawk' method will simply set the value of one of the fields in the database. +This plugin will add a method named 'squawk' to any Active Record objects that call 'acts_as_yaffle'. The 'squawk' +method will simply set the value of one of the fields in the database. To start out, write a failing test that shows the behavior you'd like: -* *vendor/plugins/yaffle/test/acts_as_yaffle_test.rb* - -require File.dirname(__FILE__) + '/test_helper' - -class Hickwall < ActiveRecord::Base - acts_as_yaffle -end - -class Wickwall < ActiveRecord::Base - acts_as_yaffle :yaffle_text_field => :last_tweet -end +# yaffle/test/acts_as_yaffle_test.rb +require 'test_helper' class ActsAsYaffleTest < Test::Unit::TestCase - load_schema def test_a_hickwalls_yaffle_text_field_should_be_last_squawk assert_equal "last_squawk", Hickwall.yaffle_text_field @@ -528,990 +352,117 @@ class ActsAsYaffleTest < Test::Unit::TestCase end -Run this test to make sure the last two tests fail, then update 'acts_as_yaffle.rb' to look like this: - -* *vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb* +Run the test to make sure the last two tests fail the an error that contains "NoMethodError: undefined method `squawk'", +then update 'acts_as_yaffle.rb' to look like this: +# yaffle/lib/yaffle/acts_as_yaffle.rb + module Yaffle - def self.included(base) - base.send :extend, ClassMethods - end + module ActsAsYaffle + extend ActiveSupport::Concern - module ClassMethods - def acts_as_yaffle(options = {}) - cattr_accessor :yaffle_text_field - self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s - send :include, InstanceMethods + included do + end + + module ClassMethods + def acts_as_yaffle(options = {}) + cattr_accessor :yaffle_text_field + self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s + end end - end - module InstanceMethods def squawk(string) write_attribute(self.class.yaffle_text_field, string.to_squawk) end + end end -ActiveRecord::Base.send :include, Yaffle +ActiveRecord::Base.send :include, Yaffle::ActsAsYaffle -NOTE: The use of +write_attribute+ to write to the field in model is just one example of how a plugin can interact with the model, and will not always be the right method to use. For example, you could also use +send("#{self.class.yaffle_text_field}=", string.to_squawk)+. - -h3. Models - -This section describes how to add a model named 'Woodpecker' to your plugin that will behave the same as a model in your main app. When storing models, controllers, views and helpers in your plugin, it's customary to keep them in directories that match the rails directories. For this example, create a file structure like this: - +Run +rake+ one final time and you should see: -vendor/plugins/yaffle/ -|-- lib -| |-- app -| | |-- controllers -| | |-- helpers -| | |-- models -| | | `-- woodpecker.rb -| | `-- views -| |-- yaffle -| | |-- acts_as_yaffle.rb -| | |-- commands.rb -| | `-- core_ext.rb -| `-- yaffle.rb + 7 tests, 7 assertions, 0 failures, 0 errors, 0 skips -As always, start with a test: - -* *vendor/plugins/yaffle/test/woodpecker_test.rb:* - - -require File.dirname(__FILE__) + '/test_helper' - -class WoodpeckerTest < Test::Unit::TestCase - load_schema - - def test_woodpecker - assert_kind_of Woodpecker, Woodpecker.new - end -end - - -This is just a simple test to make sure the class is being loaded correctly. After watching it fail with +rake+, you can make it pass like so: - -* *vendor/plugins/yaffle/lib/yaffle.rb:* - - -%w{ models }.each do |dir| - path = File.join(File.dirname(__FILE__), 'app', dir) - $LOAD_PATH << path - ActiveSupport::Dependencies.autoload_paths << path - ActiveSupport::Dependencies.autoload_once_paths.delete(path) -end - - -Adding directories to the load path makes them appear just like files in the main app directory - except that they are only loaded once, so you have to restart the web server to see the changes in the browser. Removing directories from the 'load_once_paths' allow those changes to picked up as soon as you save the file - without having to restart the web server. This is particularly useful as you develop the plugin. - -* *vendor/plugins/yaffle/lib/app/models/woodpecker.rb:* - - -class Woodpecker < ActiveRecord::Base -end - - -Finally, add the following to your plugin's 'schema.rb': - -* *vendor/plugins/yaffle/test/schema.rb:* - - -create_table :woodpeckers, :force => true do |t| - t.string :name -end - +NOTE: The use of +write_attribute+ to write to the field in model is just one example of how a plugin can +interact with the model, and will not always be the right method to use. For example, you could also +use +send("#{self.class.yaffle_text_field}=", string.to_squawk)+. -Now your test should be passing, and you should be able to use the Woodpecker model from within your rails application, and any changes made to it are reflected immediately when running in development mode. - -h3. Controllers - -This section describes how to add a controller named 'woodpeckers' to your plugin that will behave the same as a controller in your main app. This is very similar to adding a model. - -You can test your plugin's controller as you would test any other controller: - -* *vendor/plugins/yaffle/test/woodpeckers_controller_test.rb:* +h3. Generators - -require File.dirname(__FILE__) + '/test_helper' -require 'woodpeckers_controller' -require 'action_controller/test_process' +Generators can be included in your gem simply by creating them in a lib/generators directory of your plugin. More information about +the creation of generators can be found in the "Generators Guide":generators.html -class WoodpeckersController; def rescue_action(e) raise e end; end +h3. Publishing your Gem -class WoodpeckersControllerTest < Test::Unit::TestCase - def setup - @controller = WoodpeckersController.new - @request = ActionController::TestRequest.new - @response = ActionController::TestResponse.new +Gem plugins in progress can be 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 any application: - ActionController::Routing::Routes.draw do |map| - map.resources :woodpeckers - end - end +gem 'yaffle', :git => 'git://github.com/yaffle_watcher/yaffle.git' - def test_index - get :index - assert_response :success - end -end - +After running +bundle install+, your gem functionality will be available to the application. -This is just a simple test to make sure the controller is being loaded correctly. After watching it fail with +rake+, you can make it pass like so: +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 -* *vendor/plugins/yaffle/lib/yaffle.rb:* +h3. Non-Gem Plugins - -%w{ models controllers }.each do |dir| - path = File.join(File.dirname(__FILE__), 'app', dir) - $LOAD_PATH << path - ActiveSupport::Dependencies.autoload_paths << path - ActiveSupport::Dependencies.autoload_once_paths.delete(path) -end - +Non-gem plugins are useful for functionality that won't be shared with another project. Keeping your custom functionality in the +vendor/plugins directory un-clutters the rest of the application. -* *vendor/plugins/yaffle/lib/app/controllers/woodpeckers_controller.rb:* +Move the directory that you created for the gem based plugin into the vendor/plugins directory of a generated Rails application, create a vendor/plugins/yaffle/init.rb file that contains "require 'yaffle'" and everything will still work. -class WoodpeckersController < ActionController::Base - - def index - render :text => "Squawk!" - end +# yaffle/init.rb -end +require 'yaffle' -Now your test should be passing, and you should be able to use the Woodpeckers controller in your app. If you add a route for the woodpeckers controller you can start up your server and go to http://localhost:3000/woodpeckers to see your controller in action. +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. + + cd my_app + rails console + String.instance_methods.sort + -h3. Helpers +You can also remove the .gemspec, Gemfile and Gemfile.lock files as they will no longer be needed. -This section describes how to add a helper named 'WoodpeckersHelper' to your plugin that will behave the same as a helper in your main app. This is very similar to adding a model and a controller. +h3. RDoc Documentation -You can test your plugin's helper as you would test any other helper: +Once your plugin is stable and you are ready to deploy do everyone else a favor and document it! Luckily, writing documentation for your plugin is easy. -* *vendor/plugins/yaffle/test/woodpeckers_helper_test.rb* +The first step is to update the README file with detailed information about how to use your plugin. A few key things to include are: - -require File.dirname(__FILE__) + '/test_helper' -include WoodpeckersHelper +* Your name +* How to install +* How to add the functionality to the app (several examples of common use cases) +* Warning, gotchas or tips that might help save users time -class WoodpeckersHelperTest < Test::Unit::TestCase - def test_tweet - assert_equal "Tweet! Hello", tweet("Hello") - end -end - +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 part of the public api. -This is just a simple test to make sure the helper is being loaded correctly. After watching it fail with +rake+, you can make it pass like so: +Once your comments are good to go, navigate to your plugin directory and run: -* *vendor/plugins/yaffle/lib/yaffle.rb:* + +rake rdoc + - -%w{ models controllers helpers }.each do |dir| - path = File.join(File.dirname(__FILE__), 'app', dir) - $LOAD_PATH << path - ActiveSupport::Dependencies.autoload_paths << path - ActiveSupport::Dependencies.autoload_once_paths.delete(path) -end - +!!!!!!!!!!!!!! Make sure these still make sense. Add any references that you see fit. !!!!!!!!!!!!! -* *vendor/plugins/yaffle/lib/app/helpers/woodpeckers_helper.rb:* +h4. References - -module WoodpeckersHelper - - def tweet(text) - "Tweet! #{text}" - end - -end - - -Now your test should be passing, and you should be able to use the Woodpeckers helper in your app. - -h3. Routes - -You can add your own custom routes from a plugin. This section will describe how to add a custom method that can be called with 'map.yaffles'. - -Testing routes from plugins is slightly different from testing routes in a standard Rails application. To begin, add a test like this: - -* *vendor/plugins/yaffle/test/routing_test.rb* - - -require "#{File.dirname(__FILE__)}/test_helper" - -class RoutingTest < Test::Unit::TestCase - - def setup - ActionController::Routing::Routes.draw do |map| - map.yaffles - end - end - - def test_yaffles_route - assert_recognition :get, "/yaffles", :controller => "yaffles_controller", :action => "index" - end - - private - - def assert_recognition(method, path, options) - result = ActionController::Routing::Routes.recognize_path(path, :method => method) - assert_equal options, result - end -end - - -Once you see the tests fail by running 'rake', you can make them pass with: - -* *vendor/plugins/yaffle/lib/yaffle.rb* - - -require "yaffle/routing" - - -* *vendor/plugins/yaffle/lib/yaffle/routing.rb* - - -module Yaffle #:nodoc: - module Routing #:nodoc: - module MapperExtensions - def yaffles - @set.add_route("/yaffles", {:controller => "yaffles_controller", :action => "index"}) - end - end - end -end - -ActionController::Routing::RouteSet::Mapper.send :include, Yaffle::Routing::MapperExtensions - - -* *config/routes.rb* - - -ActionController::Routing::Routes.draw do |map| - map.yaffles -end - - -You can also see if your routes work by running +rake routes+ from your app directory. - -h3. Generators - -Many plugins ship with generators. When you created the plugin above, you specified the +--generator+ option, so you already have the generator stubs in 'vendor/plugins/yaffle/generators/yaffle'. - -Building generators is a complex topic unto itself and this section will cover one small aspect of generators: generating a simple text file. - -h4. Testing Generators - -Many rails plugin authors do not test their generators, however testing generators is quite simple. A typical generator test does the following: - - * Creates a new fake rails root directory that will serve as destination - * Runs the generator - * Asserts that the correct files were generated - * Removes the fake rails root - -This section will describe how to create a simple generator that adds a file. For the generator in this section, the test could look something like this: - -* *vendor/plugins/yaffle/test/definition_generator_test.rb* - - -require File.dirname(__FILE__) + '/test_helper' -require 'rails_generator' -require 'rails_generator/scripts/generate' - -class DefinitionGeneratorTest < Test::Unit::TestCase - - def setup - FileUtils.mkdir_p(fake_rails_root) - @original_files = file_list - end - - def teardown - FileUtils.rm_r(fake_rails_root) - end - - def test_generates_correct_file_name - Rails::Generator::Scripts::Generate.new.run(["yaffle_definition"], :destination => fake_rails_root) - new_file = (file_list - @original_files).first - assert_equal "definition.txt", File.basename(new_file) - end - - private - - def fake_rails_root - File.join(File.dirname(__FILE__), 'rails_root') - end - - def file_list - Dir.glob(File.join(fake_rails_root, "*")) - end - -end - - -You can run 'rake' from the plugin directory to see this fail. Unless you are doing more advanced generator commands it typically suffices to just test the Generate script, and trust that rails will handle the Destroy and Update commands for you. - -To make it pass, create the generator: - -* *vendor/plugins/yaffle/generators/yaffle_definition/yaffle_definition_generator.rb* - - -class YaffleDefinitionGenerator < Rails::Generator::Base - def manifest - record do |m| - m.file "definition.txt", "definition.txt" - end - end -end - - -h4. The +USAGE+ File - -If you plan to distribute your plugin, developers will expect at least a minimum of documentation. You can add simple documentation to the generator by updating the USAGE file. - -Rails ships with several built-in generators. You can see all of the generators available to you by typing the following at the command line: - - -rails generate - - -You should see something like this: - - -Installed Generators - Plugins (vendor/plugins): yaffle_definition - Builtin: controller, integration_test, mailer, migration, model, observer, plugin, resource, scaffold, session_migration - - -When you run +rails generate yaffle_definition -h+ you should see the contents of your 'vendor/plugins/yaffle/generators/yaffle_definition/USAGE'. - -For this plugin, update the USAGE file could look like this: - - -Description: - Adds a file with the definition of a Yaffle to the app's main directory - - -h3. Add a Custom Generator Command - -You may have noticed above that you can used one of the built-in rails migration commands +migration_template+. If your plugin needs to add and remove lines of text from existing files you will need to write your own generator methods. - -This section describes how you you can create your own commands to add and remove a line of text from 'routes.rb'. This example creates a very simple method that adds or removes a text file. - -To start, add the following test method: - -* *vendor/plugins/yaffle/test/generator_test.rb* - - -def test_generates_definition - Rails::Generator::Scripts::Generate.new.run(["yaffle", "bird"], :destination => fake_rails_root) - definition = File.read(File.join(fake_rails_root, "definition.txt")) - assert_match /Yaffle\:/, definition -end - - -Run +rake+ to watch the test fail, then make the test pass add the following: - -* *vendor/plugins/yaffle/generators/yaffle/templates/definition.txt* - - -Yaffle: A bird - - -* *vendor/plugins/yaffle/lib/yaffle.rb* - - -require "yaffle/commands" - - -* *vendor/plugins/yaffle/lib/commands.rb* - - -require 'rails_generator' -require 'rails_generator/commands' - -module Yaffle #:nodoc: - module Generator #:nodoc: - module Commands #:nodoc: - module Create - def yaffle_definition - file("definition.txt", "definition.txt") - end - end - - module Destroy - def yaffle_definition - file("definition.txt", "definition.txt") - end - end - - module List - def yaffle_definition - file("definition.txt", "definition.txt") - end - end - - module Update - def yaffle_definition - file("definition.txt", "definition.txt") - end - end - end - end -end - -Rails::Generator::Commands::Create.send :include, Yaffle::Generator::Commands::Create -Rails::Generator::Commands::Destroy.send :include, Yaffle::Generator::Commands::Destroy -Rails::Generator::Commands::List.send :include, Yaffle::Generator::Commands::List -Rails::Generator::Commands::Update.send :include, Yaffle::Generator::Commands::Update - - -Finally, call your new method in the manifest: - -* *vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb* - - -class YaffleGenerator < Rails::Generator::NamedBase - def manifest - m.yaffle_definition - end -end - - -h3. Generator Commands - -You may have noticed above that you can used one of the built-in rails migration commands +migration_template+. If your plugin needs to add and remove lines of text from existing files you will need to write your own generator methods. - -This section describes how you you can create your own commands to add and remove a line of text from 'config/routes.rb'. - -To start, add the following test method: - -* *vendor/plugins/yaffle/test/route_generator_test.rb* - - -require File.dirname(__FILE__) + '/test_helper' -require 'rails_generator' -require 'rails_generator/scripts/generate' -require 'rails_generator/scripts/destroy' - -class RouteGeneratorTest < Test::Unit::TestCase - - def setup - FileUtils.mkdir_p(File.join(fake_rails_root, "config")) - end - - def teardown - FileUtils.rm_r(fake_rails_root) - end - - def test_generates_route - content = <<-END - ActionController::Routing::Routes.draw do |map| - map.connect ':controller/:action/:id' - map.connect ':controller/:action/:id.:format' - end - END - File.open(routes_path, 'wb') {|f| f.write(content) } - - Rails::Generator::Scripts::Generate.new.run(["yaffle_route"], :destination => fake_rails_root) - assert_match /map\.yaffles/, File.read(routes_path) - end - - def test_destroys_route - content = <<-END - ActionController::Routing::Routes.draw do |map| - map.yaffles - map.connect ':controller/:action/:id' - map.connect ':controller/:action/:id.:format' - end - END - File.open(routes_path, 'wb') {|f| f.write(content) } - - Rails::Generator::Scripts::Destroy.new.run(["yaffle_route"], :destination => fake_rails_root) - assert_no_match /map\.yaffles/, File.read(routes_path) - end - - private - - def fake_rails_root - File.join(File.dirname(__FILE__), "rails_root") - end - - def routes_path - File.join(fake_rails_root, "config", "routes.rb") - end - -end - - -Run +rake+ to watch the test fail, then make the test pass add the following: - -* *vendor/plugins/yaffle/lib/yaffle.rb* - - -require "yaffle/commands" - - -* *vendor/plugins/yaffle/lib/yaffle/commands.rb* - - -require 'rails_generator' -require 'rails_generator/commands' - -module Yaffle #:nodoc: - module Generator #:nodoc: - module Commands #:nodoc: - module Create - def yaffle_route - logger.route "map.yaffle" - look_for = 'ActionController::Routing::Routes.draw do |map|' - unless options[:pretend] - gsub_file('config/routes.rb', /(#{Regexp.escape(look_for)})/mi){|match| "#{match}\n map.yaffles\n"} - end - end - end - - module Destroy - def yaffle_route - logger.route "map.yaffle" - gsub_file 'config/routes.rb', /\n.+?map\.yaffles/mi, '' - end - end - - module List - def yaffle_route - end - end - - module Update - def yaffle_route - end - end - end - end -end - -Rails::Generator::Commands::Create.send :include, Yaffle::Generator::Commands::Create -Rails::Generator::Commands::Destroy.send :include, Yaffle::Generator::Commands::Destroy -Rails::Generator::Commands::List.send :include, Yaffle::Generator::Commands::List -Rails::Generator::Commands::Update.send :include, Yaffle::Generator::Commands::Update - - -* *vendor/plugins/yaffle/generators/yaffle_route/yaffle_route_generator.rb* - - -class YaffleRouteGenerator < Rails::Generator::Base - def manifest - record do |m| - m.yaffle_route - end - end -end - - -To see this work, type: - - -rails generate yaffle_route -rails destroy yaffle_route - - -NOTE: If you haven't set up the custom route from above, 'rails destroy' will fail and you'll have to remove it manually. - -h3. Migrations - -If your plugin requires changes to the app's database you will likely want to somehow add migrations. Rails does not include any built-in support for calling migrations from plugins, but you can still make it easy for developers to call migrations from plugins. - -If you have a very simple needs, like creating a table that will always have the same name and columns, then you can use a more simple solution, like creating a custom rake task or method. If your migration needs user input to supply table names or other options, you probably want to opt for generating a migration. - -Let's say you have the following migration in your plugin: - -* *vendor/plugins/yaffle/lib/db/migrate/20081116181115_create_birdhouses.rb:* - - -class CreateBirdhouses < ActiveRecord::Migration - def self.up - create_table :birdhouses, :force => true do |t| - t.string :name - t.timestamps - end - end - - def self.down - drop_table :birdhouses - end -end - - -Here are a few possibilities for how to allow developers to use your plugin migrations: - -h4. Create a Custom Rake Task - -* *vendor/plugins/yaffle/tasks/yaffle_tasks.rake:* - - -namespace :db do - namespace :migrate do - description = "Migrate the database through scripts in vendor/plugins/yaffle/lib/db/migrate" - description << "and update db/schema.rb by invoking db:schema:dump." - description << "Target specific version with VERSION=x. Turn off output with VERBOSE=false." - - desc description - task :yaffle => :environment do - ActiveRecord::Migration.verbose = ENV["VERBOSE"] ? ENV["VERBOSE"] == "true" : true - ActiveRecord::Migrator.migrate("vendor/plugins/yaffle/lib/db/migrate/", ENV["VERSION"] ? ENV["VERSION"].to_i : nil) - Rake::Task["db:schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby - end - end -end - - -h4. Call Migrations Directly - -* *vendor/plugins/yaffle/lib/yaffle.rb:* - - -Dir.glob(File.join(File.dirname(__FILE__), "db", "migrate", "*")).each do |file| - require file -end - - -* *db/migrate/20081116181115_create_birdhouses.rb:* - - -class CreateBirdhouses < ActiveRecord::Migration - def self.up - Yaffle::CreateBirdhouses.up - end - - def self.down - Yaffle::CreateBirdhouses.down - end -end - - -NOTE: several plugin frameworks such as Desert and Engines provide more advanced plugin functionality. - -h4. Generate Migrations - -Generating migrations has several advantages over other methods. Namely, you can allow other developers to more easily customize the migration. The flow looks like this: - - * call your rails generate script and pass in whatever options they need - * examine the generated migration, adding/removing columns or other options as necessary - -This example will demonstrate how to use one of the built-in generator methods named 'migration_template' to create a migration file. Extending the rails migration generator requires a somewhat intimate knowledge of the migration generator internals, so it's best to write a test first: - -* *vendor/plugins/yaffle/test/yaffle_migration_generator_test.rb* - - -require File.dirname(__FILE__) + '/test_helper' -require 'rails_generator' -require 'rails_generator/scripts/generate' - -class MigrationGeneratorTest < Test::Unit::TestCase - - def setup - FileUtils.mkdir_p(fake_rails_root) - @original_files = file_list - end - - def teardown - ActiveRecord::Base.pluralize_table_names = true - FileUtils.rm_r(fake_rails_root) - end - - def test_generates_correct_file_name - Rails::Generator::Scripts::Generate.new.run(["yaffle_migration", "some_name_nobody_is_likely_to_ever_use_in_a_real_migration"], - :destination => fake_rails_root) - new_file = (file_list - @original_files).first - assert_match /add_yaffle_fields_to_some_name_nobody_is_likely_to_ever_use_in_a_real_migrations/, new_file - assert_match /add_column :some_name_nobody_is_likely_to_ever_use_in_a_real_migrations do |t|/, File.read(new_file) - end - - def test_pluralizes_properly - ActiveRecord::Base.pluralize_table_names = false - Rails::Generator::Scripts::Generate.new.run(["yaffle_migration", "some_name_nobody_is_likely_to_ever_use_in_a_real_migration"], - :destination => fake_rails_root) - new_file = (file_list - @original_files).first - assert_match /add_yaffle_fields_to_some_name_nobody_is_likely_to_ever_use_in_a_real_migration/, new_file - assert_match /add_column :some_name_nobody_is_likely_to_ever_use_in_a_real_migration do |t|/, File.read(new_file) - end - - private - def fake_rails_root - File.join(File.dirname(__FILE__), 'rails_root') - end - - def file_list - Dir.glob(File.join(fake_rails_root, "db", "migrate", "*")) - end - -end - - -NOTE: The migration generator checks to see if a migration already exists, and it's hard-coded to check the +db/migrate+ directory. As a result, if your test tries to generate a migration that already exists in the app, it will fail. The easy workaround is to make sure that the name you generate in your test is very unlikely to actually appear in the app. - -After running the test with 'rake' you can make it pass with: - -* *vendor/plugins/yaffle/generators/yaffle_migration/yaffle_migration_generator.rb* - - -class YaffleMigrationGenerator < Rails::Generator::NamedBase - def manifest - record do |m| - m.migration_template 'migration:migration.rb', "db/migrate", {:assigns => yaffle_local_assigns, - :migration_file_name => "add_yaffle_fields_to_#{custom_file_name}" - } - end - end - - private - def custom_file_name - custom_name = class_name.underscore.downcase - custom_name = custom_name.pluralize if ActiveRecord::Base.pluralize_table_names - custom_name - end - - def yaffle_local_assigns - {}.tap do |assigns| - assigns[:migration_action] = "add" - assigns[:class_name] = "add_yaffle_fields_to_#{custom_file_name}" - assigns[:table_name] = custom_file_name - assigns[:attributes] = [Rails::Generator::GeneratedAttribute.new("last_squawk", "string")] - end - end -end - - -The generator creates a new file in 'db/migrate' with a timestamp and an 'add_column' statement. It reuses the built-in Rails +migration_template+ method, and reuses the built-in rails migration template. - -It's courteous to check to see if table names are being pluralized whenever you create a generator that needs to be aware of table names. This way people using your generator won't have to manually change the generated files if they've turned pluralization off. - -To run the generator, type the following at the command line: - - -rails generate yaffle_migration bird - - -and you will see a new file: - -* *db/migrate/20080529225649_add_yaffle_fields_to_birds.rb* - - -class AddYaffleFieldsToBirds < ActiveRecord::Migration - def self.up - add_column :birds, :last_squawk, :string - end - - def self.down - remove_column :birds, :last_squawk - end -end - - -h3. Rake Tasks - -When you created the plugin with the built-in rails generator, it generated a rake file for you in 'vendor/plugins/yaffle/tasks/yaffle_tasks.rake'. Any rake task you add here will be available to the app. - -Many plugin authors put all of their rake tasks into a common namespace that is the same as the plugin, like so: - -* *vendor/plugins/yaffle/tasks/yaffle_tasks.rake* - - -namespace :yaffle do - desc "Prints out the word 'Yaffle'" - task :squawk => :environment do - puts "squawk!" - end -end - - -When you run +rake -T+ from your plugin you will see: - - -yaffle:squawk # Prints out the word 'Yaffle' - - -You can add as many files as you want in the tasks directory, and if they end in .rake Rails will pick them up. - -Note that tasks from +vendor/plugins/yaffle/Rakefile+ are not available to the main app. - -h3. Plugins as Gems - -Turning your rails plugin into a gem is a simple and straightforward task. This section will cover how to turn your plugin into a gem. It will not cover how to distribute that gem. - -Rails 3 ignores both init.rb and rails/init.rb file of a gem. Also, the name of the plugin now is relevant since +config.gem+ tries to load it. Either name the main file after your gem, or document that users should use the +:lib+ option. - -It's common practice to put any developer-centric rake tasks (such as tests, rdoc and gem package tasks) in +Rakefile+. A rake task that packages the gem might look like this: - -* *vendor/plugins/yaffle/Rakefile:* - - -PKG_FILES = FileList[ - '[a-zA-Z]*', - 'generators/**/*', - 'lib/**/*', - 'rails/**/*', - 'tasks/**/*', - 'test/**/*' -] - -spec = Gem::Specification.new do |s| - s.name = "yaffle" - s.version = "0.0.1" - s.author = "Gleeful Yaffler" - s.email = "yaffle@example.com" - s.homepage = "http://yafflers.example.com/" - s.platform = Gem::Platform::RUBY - s.summary = "Sharing Yaffle Goodness" - s.files = PKG_FILES.to_a - s.require_path = "lib" - s.has_rdoc = false - s.extra_rdoc_files = ["README"] -end - -desc 'Turn this plugin into a gem.' -Rake::GemPackageTask.new(spec) do |pkg| - pkg.gem_spec = spec -end - - -To build and install the gem locally, run the following commands: - - -cd vendor/plugins/yaffle -rake gem -sudo gem install pkg/yaffle-0.0.1.gem - - -To test this, create a new rails application, add +config.gem "yaffle"+ to +config/environment.rb+ and all of your plugin's functionality will be available to you. - -h3. RDoc Documentation - -Once your plugin is stable and you are ready to deploy do everyone else a favor and document it! Luckily, writing documentation for your plugin is easy. - -The first step is to update the README file with detailed information about how to use your plugin. A few key things to include are: - -* Your name -* How to install -* How to add the functionality to the app (several examples of common use cases) -* Warning, gotchas or tips that might help save users 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 part of the public api. - -Once your comments are good to go, navigate to your plugin directory and run: - - -rake rdoc - - -h3. Appendix - -If you prefer to use RSpec instead of Test::Unit, you may be interested in the "RSpec Plugin Generator":http://github.com/patmaddox/rspec-plugin-generator. - -h4. References - -* "Complete Guide to Rails Plugins - Part 1":http://nubyonrails.com/articles/the-complete-guide-to-rails-plugins-part-i -* "Complete Guide to Rails Plugins - Part 2":http://nubyonrails.com/articles/the-complete-guide-to-rails-plugins-part-ii -* "Attachment_fu Plugin":http://github.com/technoweenie/attachment_fu/tree/master -* "Keeping init.rb thin":http://daddy.platte.name/2007/05/rails-plugins-keep-initrb-thin.html +* "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/ +* "Gemspec Reference":http://docs.rubygems.org/read/chapter/20 * "GemPlugins":http://www.mbleigh.com/2008/06/11/gemplugins-a-brief-introduction-to-the-future-of-rails-plugins -* "Extending Routes":http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2 - -h4. Contents of +lib/yaffle.rb+ - -* *vendor/plugins/yaffle/lib/yaffle.rb:* - - -require "yaffle/core_ext" -require "yaffle/acts_as_yaffle" -require "yaffle/commands" -require "yaffle/routing" - -%w{ models controllers helpers }.each do |dir| - path = File.join(File.dirname(__FILE__), 'app', dir) - $LOAD_PATH << path - ActiveSupport::Dependencies.autoload_paths << path - ActiveSupport::Dependencies.autoload_once_paths.delete(path) -end - -# optionally: -# Dir.glob(File.join(File.dirname(__FILE__), "db", "migrate", "*")).each do |file| -# require file -# end - - -h4. Final Plugin Directory Structure - -The final plugin should have a directory structure that looks something like this: - - -|-- MIT-LICENSE -|-- README -|-- Rakefile -|-- generators -| |-- yaffle_definition -| | |-- USAGE -| | |-- templates -| | | `-- definition.txt -| | `-- yaffle_definition_generator.rb -| |-- yaffle_migration -| | |-- USAGE -| | |-- templates -| | `-- yaffle_migration_generator.rb -| `-- yaffle_route -| |-- USAGE -| |-- templates -| `-- yaffle_route_generator.rb -|-- install.rb -|-- lib -| |-- app -| | |-- controllers -| | | `-- woodpeckers_controller.rb -| | |-- helpers -| | | `-- woodpeckers_helper.rb -| | `-- models -| | `-- woodpecker.rb -| |-- db -| | `-- migrate -| | `-- 20081116181115_create_birdhouses.rb -| |-- yaffle -| | |-- acts_as_yaffle.rb -| | |-- commands.rb -| | |-- core_ext.rb -| | `-- routing.rb -| `-- yaffle.rb -|-- pkg -| `-- yaffle-0.0.1.gem -|-- rails -| `-- init.rb -|-- tasks -| `-- yaffle_tasks.rake -|-- test -| |-- acts_as_yaffle_test.rb -| |-- core_ext_test.rb -| |-- database.yml -| |-- debug.log -| |-- definition_generator_test.rb -| |-- migration_generator_test.rb -| |-- route_generator_test.rb -| |-- routes_test.rb -| |-- schema.rb -| |-- test_helper.rb -| |-- woodpecker_test.rb -| |-- woodpeckers_controller_test.rb -| |-- wookpeckers_helper_test.rb -| |-- yaffle_plugin.sqlite3.db -| `-- yaffle_test.rb -`-- uninstall.rb - +* "Keeping init.rb thin":http://daddy.platte.name/2007/05/rails-plugins-keep-initrb-thin.html h3. Changelog +* February 13, 2011: Get guide in synch with Rails 3.0.3. Remove information not compatible with Rails 3. Send reader elsewhere +for information that is covered elsewhere. * April 4, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com * November 17, 2008: Major revision by Jeff Dean -- cgit v1.2.3 From f7a31ce1cd23b2f05a80d5c954e9a9b833665618 Mon Sep 17 00:00:00 2001 From: Dan Neumann Date: Sun, 13 Feb 2011 17:50:39 -0600 Subject: Added simple demonstration of has_many :through --- railties/guides/source/association_basics.textile | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'railties/guides') diff --git a/railties/guides/source/association_basics.textile b/railties/guides/source/association_basics.textile index f22f41e8b1..23bfafa640 100644 --- a/railties/guides/source/association_basics.textile +++ b/railties/guides/source/association_basics.textile @@ -165,6 +165,12 @@ class Paragraph < ActiveRecord::Base end +With +:through => :sections+ specified, Rails will now understand: + + + @document.paragraphs + + h4. The +has_one :through+ Association A +has_one :through+ association sets up a one-to-one connection with another model. This association indicates that the declaring model can be matched with one instance of another model by proceeding _through_ a third model. For example, if each supplier has one account, and each account is associated with one account history, then the customer model could look like this: -- cgit v1.2.3 From 48fe62ee571002bdee694a5722285d4055a5e695 Mon Sep 17 00:00:00 2001 From: Andrew White Date: Mon, 14 Feb 2011 00:09:05 +0000 Subject: Remove incorrect assert_recognizes example --- railties/guides/source/routing.textile | 6 ------ 1 file changed, 6 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/routing.textile b/railties/guides/source/routing.textile index 1d81c8f95b..28a207c436 100644 --- a/railties/guides/source/routing.textile +++ b/railties/guides/source/routing.textile @@ -852,12 +852,6 @@ You can supply a +:method+ argument to specify the HTTP verb: assert_recognizes({ :controller => "photos", :action => "create" }, { :path => "photos", :method => :post }) -You can also use the resourceful helpers to test recognition of a RESTful route: - - -assert_recognizes new_photo_url, { :path => "photos", :method => :post } - - h5. The +assert_routing+ Assertion The +assert_routing+ assertion checks the route both ways: it tests that the path generates the options, and that the options generate the path. Thus, it combines the functions of +assert_generates+ and +assert_recognizes+. -- cgit v1.2.3 From a1cc07c35eb5f2f66d39fd2ba22a84cdd9cf99be Mon Sep 17 00:00:00 2001 From: Dan Neumann Date: Sun, 13 Feb 2011 18:14:05 -0600 Subject: Added --sandbox option to rails console explanation. --- railties/guides/source/getting_started.textile | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/getting_started.textile b/railties/guides/source/getting_started.textile index bf15afcd62..6fb54bfd49 100644 --- a/railties/guides/source/getting_started.textile +++ b/railties/guides/source/getting_started.textile @@ -274,7 +274,7 @@ TIP: Rake is a general-purpose command-runner that Rails uses for many things. Y h3. Hello, Rails! -One of the traditional places to start with a new language is by getting some text up on screen quickly, to do this, you need to get your Rails application server running. +One of the traditional places to start with a new language is by getting some text up on screen quickly. To do this, you need to get your Rails application server running. h4. Starting up the Web Server @@ -469,6 +469,8 @@ To see your validations in action, you can use the console. The console is a com $ rails console +TIP: The default console will make changes to your database. You can instead open a console that will roll back any changes you make by using +rails console --sandbox+. + After the console loads, you can use it to work with your application's models: -- cgit v1.2.3 From fd7605826a6e4f7590e4abf42c6c9d0923afc4ef Mon Sep 17 00:00:00 2001 From: Andrew White Date: Mon, 14 Feb 2011 00:40:53 +0000 Subject: Add notes on how to override the default :id constraint [#5994 state:resolved] --- railties/guides/source/routing.textile | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'railties/guides') diff --git a/railties/guides/source/routing.textile b/railties/guides/source/routing.textile index 28a207c436..d214031b31 100644 --- a/railties/guides/source/routing.textile +++ b/railties/guides/source/routing.textile @@ -391,6 +391,8 @@ NOTE: You can't use +namespace+ or +:module+ with a +:controller+ path segment. match ':controller(/:action(/:id))', :controller => /admin\/[^\/]+/ +TIP: By default dynamic segments don't accept dots - this is because the dot is used as a separator for formatted routes. If you need to use a dot within a dynamic segment add a constraint which overrides this - for example +:id => /[^\/]+/+ allows anything except a slash. + h4. Static Segments You can specify static segments when creating a route: @@ -646,6 +648,8 @@ end NOTE: Of course, you can use the more advanced constraints available in non-resourceful routes in this context. +TIP: By default the +:id+ parameter doesn't accept dots - this is because the dot is used as a separator for formatted routes. If you need to use a dot within an +:id+ add a constraint which overrides this - for example +:id => /[^\/]+/+ allows anything except a slash. + h4. Overriding the Named Helpers The +:as+ option lets you override the normal naming for the named route helpers. For example: -- cgit v1.2.3 From 35a266edfd9ac0f3afe7f7f13c2dcf29cb4b651f Mon Sep 17 00:00:00 2001 From: Ben Orenstein Date: Tue, 15 Feb 2011 11:51:07 -0500 Subject: Fix error: docrails is a fork, not a branch. --- railties/guides/source/contributing_to_ruby_on_rails.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/contributing_to_ruby_on_rails.textile b/railties/guides/source/contributing_to_ruby_on_rails.textile index 4f51c0f859..830b055359 100644 --- a/railties/guides/source/contributing_to_ruby_on_rails.textile +++ b/railties/guides/source/contributing_to_ruby_on_rails.textile @@ -253,7 +253,7 @@ h3. Contributing to the Rails Documentation Ruby on Rails has two main sets of documentation: The guides help you to learn Ruby on Rails, and the API is a reference. -You can create a ticket in Lighthouse to fix or expand documentation. However, if you're confident about your changes you can push them yourself directly via "docrails":http://github.com/lifo/docrails/tree/master. docrails is a branch with an *open commit policy* and public write access. Commits to docrails are still reviewed, but that happens after they are pushed. docrails is merged with master regularly, so you are effectively editing the Ruby on Rails documentation. +You can create a ticket in Lighthouse to fix or expand documentation. However, if you're confident about your changes you can push them yourself directly via "docrails":http://github.com/lifo/docrails/tree/master. docrails is a fork of the Rails repository with an *open commit policy* and public write access. Commits to docrails are still reviewed, but that happens after they are pushed. docrails is merged with master regularly, so you are effectively editing the Ruby on Rails documentation. When working with documentation, please take into account the "API Documentation Guidelines":api_documentation_guidelines.html and the "Ruby on Rails Guides Guidelines":ruby_on_rails_guides_guidelines.html. -- cgit v1.2.3 From 5444ed56ab38a742b3ddf6612eadd8cf50d8d517 Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Tue, 15 Feb 2011 22:17:25 +0100 Subject: Revert "Fix error: docrails is a fork, not a branch." Reason: Calling docrails a "branch" is fine, no need to change the terminology. It is a remote in my machine, and it has been called branch since the very beginning: http://weblog.rubyonrails.org/2008/5/2/help-improve-rails-documentation-on-git-branch This reverts commit 35a266edfd9ac0f3afe7f7f13c2dcf29cb4b651f. --- railties/guides/source/contributing_to_ruby_on_rails.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/contributing_to_ruby_on_rails.textile b/railties/guides/source/contributing_to_ruby_on_rails.textile index 830b055359..4f51c0f859 100644 --- a/railties/guides/source/contributing_to_ruby_on_rails.textile +++ b/railties/guides/source/contributing_to_ruby_on_rails.textile @@ -253,7 +253,7 @@ h3. Contributing to the Rails Documentation Ruby on Rails has two main sets of documentation: The guides help you to learn Ruby on Rails, and the API is a reference. -You can create a ticket in Lighthouse to fix or expand documentation. However, if you're confident about your changes you can push them yourself directly via "docrails":http://github.com/lifo/docrails/tree/master. docrails is a fork of the Rails repository with an *open commit policy* and public write access. Commits to docrails are still reviewed, but that happens after they are pushed. docrails is merged with master regularly, so you are effectively editing the Ruby on Rails documentation. +You can create a ticket in Lighthouse to fix or expand documentation. However, if you're confident about your changes you can push them yourself directly via "docrails":http://github.com/lifo/docrails/tree/master. docrails is a branch with an *open commit policy* and public write access. Commits to docrails are still reviewed, but that happens after they are pushed. docrails is merged with master regularly, so you are effectively editing the Ruby on Rails documentation. When working with documentation, please take into account the "API Documentation Guidelines":api_documentation_guidelines.html and the "Ruby on Rails Guides Guidelines":ruby_on_rails_guides_guidelines.html. -- cgit v1.2.3 From ed630dfc72109cbe0d89884a9ceacb20ef5b0fa3 Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Thu, 17 Feb 2011 16:59:03 +0530 Subject: fix typo --- railties/guides/source/active_support_core_extensions.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/active_support_core_extensions.textile b/railties/guides/source/active_support_core_extensions.textile index cf9ebf44e6..9da8ecc6fc 100644 --- a/railties/guides/source/active_support_core_extensions.textile +++ b/railties/guides/source/active_support_core_extensions.textile @@ -2190,7 +2190,7 @@ Array.wrap(0) # => [0] This method is similar in purpose to Kernel#Array, but there are some differences: -* If the argument responds to +to_ary+ the method is invoked. Kernel#Array moves on to try +to_a+ if the returned value is +nil+, but Arraw.wrap returns such a +nil+ right away. +* If the argument responds to +to_ary+ the method is invoked. Kernel#Array moves on to try +to_a+ if the returned value is +nil+, but Array.wrap returns +nil+ right away. * If the returned value from +to_ary+ is neither +nil+ nor an +Array+ object, Kernel#Array raises an exception, while Array.wrap does not, it just returns the value. * It does not call +to_a+ on the argument, though special-cases +nil+ to return an empty array. -- cgit v1.2.3 From fead0fc44850480f2f431b8befb5cba284e5e633 Mon Sep 17 00:00:00 2001 From: Brian Durand Date: Thu, 17 Feb 2011 10:12:28 -0600 Subject: update caching guide with the changes to ActiveSupport::Cache from the 3.0.0 release. --- railties/guides/source/caching_with_rails.textile | 94 +++++++++++++---------- 1 file changed, 52 insertions(+), 42 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/caching_with_rails.textile b/railties/guides/source/caching_with_rails.textile index 63c52da32a..1b5ec40d16 100644 --- a/railties/guides/source/caching_with_rails.textile +++ b/railties/guides/source/caching_with_rails.textile @@ -238,86 +238,95 @@ h3. Cache Stores Rails provides different stores for the cached data created by action and fragment caches. Page caches are always stored on disk. -Rails 2.1 and above provide +ActiveSupport::Cache::Store+ which can be used to cache strings. Some cache store implementations, like +MemoryStore+, are able to cache arbitrary Ruby objects, but don't count on every cache store to be able to do that. +h4. Configuration -The default cache stores provided with Rails include: - -1) +ActiveSupport::Cache::MemoryStore+: A cache store implementation which stores everything into memory in the same process. If you're running multiple Ruby on Rails server processes (which is the case if you're using mongrel_cluster or Phusion Passenger), then this means that your Rails server process instances won't be able to share cache data with each other. If your application never performs manual cache item expiry (e.g. when you‘re using generational cache keys), then using +MemoryStore+ is ok. Otherwise, consider carefully whether you should be using this cache store. - -+MemoryStore+ is not only able to store strings, but also arbitrary Ruby objects. - -+MemoryStore+ is not thread-safe. Use +SynchronizedMemoryStore+ instead if you need thread-safety. +You can set up your application's default cache store by calling +config.cache_store=+ in the Application definition inside your +config/application.rb+ file or in an Application.configure block in an environment specific configuration file (i.e. +config/environments/*.rb+). The first argument will be the cache store to use and the rest of the argument will be passed as arguments to the cache store constructor. -ActionController::Base.cache_store = :memory_store +config.cache_store = :memory_store -2) +ActiveSupport::Cache::FileStore+: Cached data is stored on the disk, this is the default store and the default path for this store is +tmp/cache+. Works well for all types of environments and allows all processes running from the same application directory to access the cached content. If +tmp/cache+ does not exist, the default store becomes +MemoryStore+. +Alternatively, you can call +ActionController::Base.cache_store+ outside of a configuration block. - -ActionController::Base.cache_store = :file_store, "/path/to/cache/directory" - +You can access the cache by calling +Rails.cache+. -3) +ActiveSupport::Cache::DRbStore+: Cached data is stored in a separate shared DRb process that all servers communicate with. This works for all environments and only keeps one cache around for all processes, but requires that you run and manage a separate DRb process. +h4. ActiveSupport::Cache::Store - -ActionController::Base.cache_store = :drb_store, "druby://localhost:9192" - +This class provides the foundation for interacting with the cache in Rails. This is an abstract class and you cannot use it on its own. Rather you must use a concrete implementation of the class tied to a storage engine. Rails ships with several implementations documented below. + +The main methods to call are +read+, +write+, +delete+, +exist?+, and +fetch+. The fetch method takes a block and will either return an existing value from the cache, or evaluate the block and write the result to the cache if no value exists. -4) +ActiveSupport::Cache::MemCacheStore+: Works like +DRbStore+, but uses Danga's +memcached+ instead. Rails uses the bundled +memcached-client+ gem by default. This is currently the most popular cache store for production websites. +There are some common options used by all cache implementations. These can be passed to the constructor or the various methods to interact with entries. -Special features: +* +:namespace+ - This option can be used to create a namespace within the cache store. It is especially useful if your application shares a cache with other applications. The default value will include the application name and Rails environment. -* Clustering and load balancing. One can specify multiple memcached servers, and +MemCacheStore+ will load balance between all available servers. If a server goes down, then +MemCacheStore+ will ignore it until it goes back online. -* Time-based expiry support. See +write+ and the +:expires_in+ option. -* Per-request in memory cache for all communication with the +memcached+ server(s). +* +:compress+ - This option can be used to indicate that compression should be used in the cache. This can be useful for transferring large cache entries over a slow network. -It also accepts a hash of additional options: +* +:compress_threshold+ - This options is used in conjunction with the +:compress+ option to indicate a threshold under which cache entries should not be compressed. This defaults to 16 kilobytes. -* +:namespace+: specifies a string that will automatically be prepended to keys when accessing the memcached store. -* +:readonly+: a boolean value that when set to true will make the store read-only, with an error raised on any attempt to write. -* +:multithread+: a boolean value that adds thread safety to read/write operations - it is unlikely you'll need to use this option as the Rails threadsafe! method offers the same functionality. +* +:expires_in+ - This option sets an expiration time in seconds for the cache entry when it will be automatically removed from the cache. -The read and write methods of the +MemCacheStore+ accept an options hash too. When reading you can specify +:raw => true+ to prevent the object being marshaled (by default this is false which means the raw value in the cache is passed to +Marshal.load+ before being returned to you.) +* +:race_condition_ttl+ - This option is used in conjunction with the +:expires_in+ option. It will prevent race conditions when cache entries expire by preventing multiple processes from simultaneously regenerating the same entry (also known as the dog pile effect). This option sets the number of seconds that an expired entry can be reused while a new value is being regenerated. It's a good practice to set this value if you use the +:expires_in+ option. -When writing to the cache it is also possible to specify +:raw => true+ means the value is not passed to +Marshal.dump+ before being stored in the cache (by default this is false). +h4. ActiveSupport::Cache::MemoryStore -The write method also accepts an +:unless_exist+ flag which determines whether the memcached add (when true) or set (when false) method is used to store the item in the cache and an +:expires_in+ option that specifies the time-to-live for the cached item in seconds. +This cache store keeps entries in memory in the same Ruby process. The cache store has a bounded size specified by the +:size+ options to the initializer (default is 32Mb). When the cache exceeds the allotted size, a cleanup will occur and the least recently used entries will be removed. -ActionController::Base.cache_store = :mem_cache_store, "localhost" +ActionController::Base.cache_store = :memory_store, :size => 64.megabytes -5) +ActiveSupport::Cache::SynchronizedMemoryStore+: Like +MemoryStore+ but thread-safe. +If you're running multiple Ruby on Rails server processes (which is the case if you're using mongrel_cluster or Phusion Passenger), then your Rails server process instances won't be able to share cache data with each other. This cache store is not appropriate for large application deployments, but can work well for small, low traffic sites with only a couple of server processes or for development and test environments. + +This is the default cache store implementation. + +h4. ActiveSupport::Cache::FileStore + +This cache store uses the file system to store entries. The path to the directory where the store files will be stored must be specified when initializing the cache. -ActionController::Base.cache_store = :synchronized_memory_store +ActionController::Base.cache_store = :file_store, "/path/to/cache/directory" -6) +ActiveSupport::Cache::CompressedMemCacheStore+: Works just like the regular +MemCacheStore+ but uses GZip to decompress/compress on read/write. +With this cache store, multiple server processes on the same host can share a cache. Servers processes running on different hosts could share a cache by using a shared file system, but that set up would not be ideal and is not recommended. The cache store is appropriate for low to medium traffic sites that are served off one or two hosts. + +Note that the cache will grow until the disk is full unless you periodically clear out old entries. + +h4. ActiveSupport::Cache::MemCacheStore + +This cache store uses Danga's +memcached+ server to provide a centralized cache for your application. Rails uses the bundled +memcached-client+ gem by default. This is currently the most popular cache store for production websites. It can be used to provide a single, shared cache cluster with very a high performance and redundancy. + +When initializing the cache, you need to specify the addresses for all memcached servers in your cluster. If none is specified, it will assume memcached is running on the local host on the default port, but this is not an ideal set up for larger sites. + +The +write+ and +fetch+ methods on this cache accept two additional options that take advantage of features specific to memcached. You can specify +:raw+ to send a value directly to the server with no serialization. The value must be a string or number. You can use memcached direct operation like +increment+ and +decrement+ only on raw values. You can also specify +:unless_exist+ if you don't want memcached to overwrite an existing entry. -ActionController::Base.cache_store = :compressed_mem_cache_store, "localhost" +ActionController::Base.cache_store = :mem_cache_store, "cache-1.example.com", "cache-2.example.com" -7) Custom store: You can define your own cache store (new in Rails 2.1). +h4. Custom Cache Stores + +You can create your own custom cache store by simply extending +ActiveSupport::Cache::Store+ and implementing the appropriate methods. In this way, you can swap in any number of caching technologies into your Rails application. + +To use a custom cache store, simple set the cache store to a new instance of the class. -ActionController::Base.cache_store = MyOwnStore.new("parameter") +ActionController::Base.cache_store = MyCacheStore.new -NOTE: +config.cache_store+ can be used in place of +ActionController::Base.cache_store+ in your +Rails::Initializer.run+ block in +environment.rb+ +h4. Cache Keys -In addition to all of this, Rails also adds the +ActiveRecord::Base#cache_key+ method that generates a key using the class name, +id+ and +updated_at+ timestamp (if available). +The keys used in a cache can be any object that responds to either +:cache_key+ or to +:to_param+. You can implement the +:cache_key+ method on your classes if you need to generate custom keys. ActiveRecord will generate keys based on the class name and record id. -You can access these cache stores at a low level for storing queries and other objects. Here's an example: +You can use Hashes and Arrays of values as cache keys. -Rails.cache.read("city") # => nil -Rails.cache.write("city", "Duckburgh") -Rails.cache.read("city") # => "Duckburgh" +# This is a legal cache key +Rails.cache.read(:site => "mysite", :owners => [owner_1, owner2]) +The keys you use on +Rails.cache+ will not be the same as those actually used with the storage engine. They may be modified with a namespace or altered to fit technology backend constraints. This means, for instance, that you can't save values with +Rails.cache+ and then try to pull them out with the +memcache-client+ gem. However, you also don't need to worry about exceeding the memcached size limit or violating syntax rules. + h3. Conditional GET support Conditional GETs are a feature of the HTTP specification that provide a way for web servers to tell browsers that the response to a GET request hasn't changed since the last request and can be safely pulled from the browser cache. @@ -369,6 +378,7 @@ h3. Further reading h3. Changelog +* Feb 17, 2011: Document 3.0.0 changes to ActiveSupport::Cache * May 02, 2009: Formatting cleanups * April 26, 2009: Clean up typos in submitted patch * April 1, 2009: Made a bunch of small fixes -- cgit v1.2.3 From 017012b43ac80a79b99afbe35e1d9e7f73e62ee9 Mon Sep 17 00:00:00 2001 From: Brian Durand Date: Thu, 17 Feb 2011 10:18:56 -0600 Subject: Add description of transaction callbacks to ActiveRecord callbacks guide. --- .../active_record_validations_callbacks.textile | 35 ++++++++++++++++++++++ 1 file changed, 35 insertions(+) (limited to 'railties/guides') diff --git a/railties/guides/source/active_record_validations_callbacks.textile b/railties/guides/source/active_record_validations_callbacks.textile index 6f857ab9cc..ea8cf8afaf 100644 --- a/railties/guides/source/active_record_validations_callbacks.textile +++ b/railties/guides/source/active_record_validations_callbacks.textile @@ -1160,8 +1160,43 @@ In this example, the +after_create+ method would be called whenever a +Registrat config.active_record.observers = :mailer_observer +h3. Transaction Callbacks + +There are two additional callbacks that are triggered by the completion of a database transaction: +after_commit+ and +after_rollback+. These callbacks are very similar to the +after_save+ callback except that they don't execute until after database changes have either been committed or rolled back. They are most useful when your active record models need to interact with external systems which are not part of the database transaction. + +Consider, for example, the previous example where the +PictureFile+ model needs to delete a file after a record is destroyed. If anything raises an exception after the +after_destroy+ callback is called and the transaction rolls back, the file will have been deleted and the model will be left in an inconsistent state. For example, suppose that +picture_file_2+ in the code below is not valid and the +save!+ method raises an error. + + +PictureFile.transaction do + picture_file_1.destroy + picture_file_2.save! +end + + +By using the +after_commit+ callback we can account for this case. + + +class PictureFile < ActiveRecord::Base + attr_accessor :delete_file + + after_destroy do |picture_file| + picture_file.delete_file = picture_file.filepath + end + + after_commit do |picture_file| + if picture_file.delete_file && File.exist?(picture_file.delete_file) + File.delete(picture_file.delete_file) + picture_file.delete_file = nil + end + end +end + + +The +after_commit+ and +after_rollback+ callbacks are guaranteed to be called for all models created, updated, or destroyed within a transaction block. If any exceptions are raised within one of these callbacks, they will be ignored so that they don't interfere with the other callbacks. As such, if your callback code could raise an exception, you'll need to rescue it and handle it appropriately within the callback. + h3. Changelog +* February 17, 2011: Add description of transaction callbacks. * July 20, 2010: Fixed typos and rephrased some paragraphs for clarity. "Jaime Iniesta":http://jaimeiniesta.com * May 24, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com * May 15, 2010: Validation Errors section updated by "Emili Parreño":http://www.eparreno.com -- cgit v1.2.3 From 1c21f75f1b32ee8723c74a9bc7af70dfa02a509c Mon Sep 17 00:00:00 2001 From: Kedar Mhaswade Date: Thu, 17 Feb 2011 16:27:01 -0800 Subject: Created a new Troubleshooting section in the migrations guide. Added a bullet point there showing how the Uninitialized Constant (missing migration class) error looks like. --- railties/guides/source/migrations.textile | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/migrations.textile b/railties/guides/source/migrations.textile index 0d13fbc10a..1a23abff2c 100644 --- a/railties/guides/source/migrations.textile +++ b/railties/guides/source/migrations.textile @@ -82,7 +82,7 @@ On databases that support transactions with statements that change the schema (s h4. What's in a Name -Migrations are stored in files in +db/migrate+, one for each migration class. The name of the file is of the form +YYYYMMDDHHMMSS_create_products.rb+, that is to say a UTC timestamp identifying the migration followed by an underscore followed by the name of the migration. The name of the migration class (CamelCased version) should match the latter part of the file name. For example +20080906120000_create_products.rb+ should define +CreateProducts+ and +20080906120001_add_details_to_products.rb+ should define +AddDetailsToProducts+. If you do feel the need to change the file name then you have to update the name of the class inside or Rails will complain about a missing class. +Migrations are stored in files in +db/migrate+, one for each migration class. The name of the file is of the form +YYYYMMDDHHMMSS_create_products.rb+, that is to say a UTC timestamp identifying the migration followed by an underscore followed by the name of the migration. The name of the migration class (CamelCased version) should match the latter part of the file name. For example +20080906120000_create_products.rb+ should define +CreateProducts+ and +20080906120001_add_details_to_products.rb+ should define +AddDetailsToProducts+. If you do feel the need to change the file name then you have to update the name of the class inside or Rails will complain about a "missing class":#missing-class-while-running-a-migration. Internally Rails only uses the migration's number (the timestamp) to identify them. Prior to Rails 2.1 the migration number started at 1 and was incremented each time a migration was generated. With multiple developers it was easy for these to clash requiring you to rollback migrations and renumber them. With Rails 2.1 this is largely avoided by using the creation time of the migration to identify them. You can revert to the old numbering scheme by adding the following line to +config/application.rb+. @@ -588,6 +588,19 @@ Validations such as +validates :foreign_key, :uniqueness => true+ are one way in Although Active Record does not provide any tools for working directly with such features, the +execute+ method can be used to execute arbitrary SQL. There are also a number of plugins such as "foreign_key_migrations":http://github.com/harukizaemon/redhillonrails/tree/master/foreign_key_migrations/ which add foreign key support to Active Record (including support for dumping foreign keys in +db/schema.rb+). +h3. Troubleshooting + +h4. Missing Class While Running a Migration + +Sometimes the names of the migration classes and migration files don't match. In such cases, +rake db:migrate+ generates the following error: + +rake aborted! +An error has occurred, this and all later migrations canceled: + +uninitialized constant CreateOs + +When you get such an error, make sure the names match. For example, in above case, name of the migration class was +CreateOs+, and the name of the migration file was +20110217235207_create_oses.rb+. One possible way to fix this is to delete the migration file, modify pluralization rules for your model and recreate and rerun the migration. + h3. Changelog * July 15, 2010: minor typos corrected by "Jaime Iniesta":http://jaimeiniesta.com -- cgit v1.2.3 From 9a9d895481ada301143c0554dabd4ec9914b8703 Mon Sep 17 00:00:00 2001 From: Nicholas Rowe Date: Thu, 17 Feb 2011 20:46:52 -0500 Subject: Fix Typos: remove several occurences of the the --- railties/guides/source/action_view_overview.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/action_view_overview.textile b/railties/guides/source/action_view_overview.textile index e1fc0e7732..39f4c33397 100644 --- a/railties/guides/source/action_view_overview.textile +++ b/railties/guides/source/action_view_overview.textile @@ -888,7 +888,7 @@ Note: Only the +option+ tags are returned, you have to wrap this call in a regul h5. options_from_collection_for_select -Returns a string of option tags that have been compiled by iterating over the +collection+ and assigning the the result of a call to the +value_method+ as the option value and the +text_method+ as the option text. +Returns a string of option tags that have been compiled by iterating over the +collection+ and assigning the result of a call to the +value_method+ as the option value and the +text_method+ as the option text. # options_from_collection_for_select(collection, value_method, text_method, selected = nil) -- cgit v1.2.3 From 7d9a80be93509b47796318caba08c79ab92f4c8d Mon Sep 17 00:00:00 2001 From: Nicholas Rowe Date: Thu, 17 Feb 2011 20:49:25 -0500 Subject: Remove awkward phrasing from Ajax on Rails guide --- railties/guides/source/ajax_on_rails.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/ajax_on_rails.textile b/railties/guides/source/ajax_on_rails.textile index 3d7fcdc198..b80df4aa58 100644 --- a/railties/guides/source/ajax_on_rails.textile +++ b/railties/guides/source/ajax_on_rails.textile @@ -42,7 +42,7 @@ You are ready to add some AJAX love to your Rails app! h4. The Quintessential AJAX Rails Helper: link_to_remote -Let's start with the the probably most often used helper: +link_to_remote+, which has an interesting feature from the documentation point of view: the options supplied to +link_to_remote+ are shared by all other AJAX helpers, so learning the mechanics and options of +link_to_remote+ is a great help when using other helpers. +Let's start with what is probably the most often used helper: +link_to_remote+. It has an interesting feature from the documentation point of view: the options supplied to +link_to_remote+ are shared by all other AJAX helpers, so learning the mechanics and options of +link_to_remote+ is a great help when using other helpers. The signature of +link_to_remote+ function is the same as that of the standard +link_to+ helper: -- cgit v1.2.3 From 7c52da44edec9eae6c26f9ff3187d1cc27e5c120 Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Fri, 18 Feb 2011 23:03:54 +0100 Subject: Revert "Created a new Troubleshooting section in the migrations guide." Mismatches between migrations and constants have nothing to do with pluralization rules or model names. The mismatch happens between the camelization of the filename minus timestamp, and the name of the migration class itself. This reverts commit 1c21f75f1b32ee8723c74a9bc7af70dfa02a509c. --- railties/guides/source/migrations.textile | 15 +-------------- 1 file changed, 1 insertion(+), 14 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/migrations.textile b/railties/guides/source/migrations.textile index 1a23abff2c..0d13fbc10a 100644 --- a/railties/guides/source/migrations.textile +++ b/railties/guides/source/migrations.textile @@ -82,7 +82,7 @@ On databases that support transactions with statements that change the schema (s h4. What's in a Name -Migrations are stored in files in +db/migrate+, one for each migration class. The name of the file is of the form +YYYYMMDDHHMMSS_create_products.rb+, that is to say a UTC timestamp identifying the migration followed by an underscore followed by the name of the migration. The name of the migration class (CamelCased version) should match the latter part of the file name. For example +20080906120000_create_products.rb+ should define +CreateProducts+ and +20080906120001_add_details_to_products.rb+ should define +AddDetailsToProducts+. If you do feel the need to change the file name then you have to update the name of the class inside or Rails will complain about a "missing class":#missing-class-while-running-a-migration. +Migrations are stored in files in +db/migrate+, one for each migration class. The name of the file is of the form +YYYYMMDDHHMMSS_create_products.rb+, that is to say a UTC timestamp identifying the migration followed by an underscore followed by the name of the migration. The name of the migration class (CamelCased version) should match the latter part of the file name. For example +20080906120000_create_products.rb+ should define +CreateProducts+ and +20080906120001_add_details_to_products.rb+ should define +AddDetailsToProducts+. If you do feel the need to change the file name then you have to update the name of the class inside or Rails will complain about a missing class. Internally Rails only uses the migration's number (the timestamp) to identify them. Prior to Rails 2.1 the migration number started at 1 and was incremented each time a migration was generated. With multiple developers it was easy for these to clash requiring you to rollback migrations and renumber them. With Rails 2.1 this is largely avoided by using the creation time of the migration to identify them. You can revert to the old numbering scheme by adding the following line to +config/application.rb+. @@ -588,19 +588,6 @@ Validations such as +validates :foreign_key, :uniqueness => true+ are one way in Although Active Record does not provide any tools for working directly with such features, the +execute+ method can be used to execute arbitrary SQL. There are also a number of plugins such as "foreign_key_migrations":http://github.com/harukizaemon/redhillonrails/tree/master/foreign_key_migrations/ which add foreign key support to Active Record (including support for dumping foreign keys in +db/schema.rb+). -h3. Troubleshooting - -h4. Missing Class While Running a Migration - -Sometimes the names of the migration classes and migration files don't match. In such cases, +rake db:migrate+ generates the following error: - -rake aborted! -An error has occurred, this and all later migrations canceled: - -uninitialized constant CreateOs - -When you get such an error, make sure the names match. For example, in above case, name of the migration class was +CreateOs+, and the name of the migration file was +20110217235207_create_oses.rb+. One possible way to fix this is to delete the migration file, modify pluralization rules for your model and recreate and rerun the migration. - h3. Changelog * July 15, 2010: minor typos corrected by "Jaime Iniesta":http://jaimeiniesta.com -- cgit v1.2.3 From 220cb107b672d65fdc0488d4ff310ab04b62b463 Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Fri, 18 Feb 2011 23:13:29 +0100 Subject: removes indent from guides example --- railties/guides/source/association_basics.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/association_basics.textile b/railties/guides/source/association_basics.textile index 23bfafa640..e5b8c73c43 100644 --- a/railties/guides/source/association_basics.textile +++ b/railties/guides/source/association_basics.textile @@ -168,7 +168,7 @@ end With +:through => :sections+ specified, Rails will now understand: - @document.paragraphs +@document.paragraphs h4. The +has_one :through+ Association -- cgit v1.2.3 From e2d54fb3f17ac30c91d855c45060ec5518b75ec5 Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Sun, 20 Feb 2011 10:52:24 +0100 Subject: documents the backported Range#cover?, and related stuff --- railties/guides/source/active_support_core_extensions.textile | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/active_support_core_extensions.textile b/railties/guides/source/active_support_core_extensions.textile index 9da8ecc6fc..535a048b3b 100644 --- a/railties/guides/source/active_support_core_extensions.textile +++ b/railties/guides/source/active_support_core_extensions.textile @@ -528,7 +528,7 @@ The default value can be also specified with a block, which is called in the con class User attr_accessor :name, :surname attr_accessor_with_default(:full_name) { - [name, surname].compact.join(" ") + [name, surname].compact.join(" ") } end @@ -2713,6 +2713,14 @@ WARNING: The original +Range#include?+ is still the one aliased to +Range#===+. NOTE: Defined in +active_support/core_ext/range/include_range.rb+. +h4. +cover?+ + +Ruby 1.9 provides +cover?+, and Active Support defines it for previous versions as an alias for +include?+. + +The method +include?+ in Ruby 1.9 is different from the one in 1.8 for non-numeric ranges: instead of being based on comparisons between the value and the range's endpoints, it walks the range with +succ+ looking for value. This works better for ranges with holes, but it has different complexity and may not finish in some other cases. + +In Ruby 1.9 the old behavior is still available in the new +cover?+, which Active Support backports for forward compatibility. For example, Rails uses +cover?+ for ranges in +validates_inclusion_of+. + h4. +overlaps?+ The method +Range#overlaps?+ says whether any two given ranges have non-void intersection: -- cgit v1.2.3 From 9345e9cca241c201443ae1feec08de967851b231 Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Sun, 20 Feb 2011 01:18:03 +0530 Subject: session is reset on token mismatch --- railties/guides/source/security.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/security.textile b/railties/guides/source/security.textile index 7f303c3565..5613156245 100644 --- a/railties/guides/source/security.textile +++ b/railties/guides/source/security.textile @@ -240,7 +240,7 @@ There are many other possibilities, including Ajax to attack the victim in the b protect_from_forgery :secret => "123456789012345678901234567890..." -This will automatically include a security token, calculated from the current session and the server-side secret, in all forms and Ajax requests generated by Rails. You won't need the secret, if you use CookieStorage as session storage. It will raise an ActionController::InvalidAuthenticityToken error, if the security token doesn't match what was expected. +This will automatically include a security token, calculated from the current session and the server-side secret, in all forms and Ajax requests generated by Rails. You won't need the secret, if you use CookieStorage as session storage. If the security token doesn't match what was expected, the session will be reset. *Note:* In Rails versions prior to 3.0.4, this raised an ActionController::InvalidAuthenticityToken error. Note that _(highlight)cross-site scripting (XSS) vulnerabilities bypass all CSRF protections_. XSS gives the attacker access to all elements on a page, so he can read the CSRF security token from a form or directly submit the form. Read more about XSS later. -- cgit v1.2.3 From 1e2ecc4d6f2bc528100d994a48118c560b87445c Mon Sep 17 00:00:00 2001 From: Brandon Tilley Date: Sat, 19 Feb 2011 14:49:42 -0800 Subject: Add info about I18n::Backend::Chain to I18n guide --- railties/guides/source/i18n.textile | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'railties/guides') diff --git a/railties/guides/source/i18n.textile b/railties/guides/source/i18n.textile index 337ef52d3b..8b37543342 100644 --- a/railties/guides/source/i18n.textile +++ b/railties/guides/source/i18n.textile @@ -809,6 +809,12 @@ That does not mean you're stuck with these limitations, though. The Ruby I18n ge I18n.backend = Globalize::Backend::Static.new +You can also use the Chain backend to chain multiple backends together. This is useful when you want to use standard translations with a Simple backend but store custom application translations in a database or other backends. For example, you could use the ActiveRecord backend and fall back to the (default) Simple backend: + + +I18n.backend = I18n::Backend::Chain.new(I18n::Backend::ActiveRecord.new, I18n.backend) + + h4. Using Different Exception Handlers The I18n API defines the following exceptions that will be raised by backends when the corresponding unexpected conditions occur: -- cgit v1.2.3 From 2394ad69a4b5055a282ea978eed506ebef68cef9 Mon Sep 17 00:00:00 2001 From: Ben Orenstein Date: Sat, 19 Feb 2011 18:07:00 -0500 Subject: Edit a few lines for readability. --- railties/guides/source/active_support_core_extensions.textile | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/active_support_core_extensions.textile b/railties/guides/source/active_support_core_extensions.textile index 535a048b3b..788c243d2a 100644 --- a/railties/guides/source/active_support_core_extensions.textile +++ b/railties/guides/source/active_support_core_extensions.textile @@ -20,7 +20,7 @@ Thus, after a simple require like: require 'active_support' -objects do not even respond to +blank?+, let's see how to load its definition. +objects do not even respond to +blank?+. Let's see how to load its definition. h5. Cherry-picking a Definition @@ -42,7 +42,7 @@ h5. Loading Grouped Core Extensions The next level is to simply load all extensions to +Object+. As a rule of thumb, extensions to +SomeClass+ are available in one shot by loading +active_support/core_ext/some_class+. -Thus, if that would do, to have +blank?+ available we could just load all extensions to +Object+: +Thus, to load all extensions to +Object+ (including +blank?+): require 'active_support/core_ext/object' @@ -432,7 +432,7 @@ h4. +require_library_or_gem+ The convenience method +require_library_or_gem+ tries to load its argument with a regular +require+ first. If it fails loads +rubygems+ and tries again. -If the first attempt is a failure and +rubygems+ can't be loaded the method raises +LoadError+. On the other hand, if +rubygems+ is available but the argument is not loadable as a gem, the method gives up and +LoadError+ is also raised. +If the first attempt is a failure and +rubygems+ can't be loaded the method raises +LoadError+. A +LoadError+ is also raised if +rubygems+ is available but the argument is not loadable as a gem. For example, that's the way the MySQL adapter loads the MySQL library: @@ -503,7 +503,7 @@ Model attributes have a reader, a writer, and a predicate. You can alias a model class User < ActiveRecord::Base # let me refer to the email column as "login", - # much meaningful for authentication code + # possibly meaningful for authentication code alias_attribute :login, :email end -- cgit v1.2.3 From c86cdea1b85b9f616e09c1c0ee19ca47a2d82dcf Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Sun, 20 Feb 2011 21:31:12 +0530 Subject: minor rephrasing --- railties/guides/source/rails_application_templates.textile | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/rails_application_templates.textile b/railties/guides/source/rails_application_templates.textile index 8f87b4cd58..8e51f9e23b 100644 --- a/railties/guides/source/rails_application_templates.textile +++ b/railties/guides/source/rails_application_templates.textile @@ -198,7 +198,7 @@ route "root :to => 'person#index'" h4. inside(dir) -I have my edge rails lying at +~/commit-rails/rails+. So every time i have to manually symlink edge from my new app. But now : +Enables you to run a command from the given directory. For example, if you have a copy of edge rails that you wish to symlink from your new apps, you can do this: inside('vendor') do @@ -206,8 +206,6 @@ inside('vendor') do end -So +inside()+ runs the command from the given directory. - h4. ask(question) +ask()+ gives you a chance to get some feedback from the user and use it in your templates. Lets say you want your user to name the new shiny library you’re adding : -- cgit v1.2.3 From 406f7ebe6944249afab94a4d11007c7fd339ee60 Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Sun, 20 Feb 2011 21:37:39 +0530 Subject: cleans up PS1. Sorry lifo :) --- railties/guides/source/performance_testing.textile | 18 +++++++++--------- railties/guides/source/rails_on_rack.textile | 4 ++-- 2 files changed, 11 insertions(+), 11 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/performance_testing.textile b/railties/guides/source/performance_testing.textile index 341525a75c..cd0a8fa384 100644 --- a/railties/guides/source/performance_testing.textile +++ b/railties/guides/source/performance_testing.textile @@ -316,16 +316,16 @@ Compile Ruby and apply this "GC Patch":http://rubyforge.org/tracker/download.php h5. Download and Extract -[lifo@null ~]$ mkdir rubygc -[lifo@null ~]$ wget -[lifo@null ~]$ tar -xzvf -[lifo@null ~]$ cd +$ mkdir rubygc +$ wget +$ tar -xzvf +$ cd h5. Apply the Patch -[lifo@null ruby-version]$ curl http://rubyforge.org/tracker/download.php/1814/7062/17676/3291/ruby186gc.patch | patch -p0 +$ curl http://rubyforge.org/tracker/download.php/1814/7062/17676/3291/ruby186gc.patch | patch -p0 h5. Configure and Install @@ -333,8 +333,8 @@ h5. Configure and Install The following will install ruby in your home directory's +/rubygc+ directory. Make sure to replace +<homedir>+ with a full patch to your actual home directory. -[lifo@null ruby-version]$ ./configure --prefix=//rubygc -[lifo@null ruby-version]$ make && make install +$ ./configure --prefix=//rubygc +$ make && make install h5. Prepare Aliases @@ -364,8 +364,8 @@ Additionally, install the following gems: If installing +mysql+ fails, you can try to install it manually: -[lifo@null mysql]$ gcruby extconf.rb --with-mysql-config -[lifo@null mysql]$ make && make install +$ gcruby extconf.rb --with-mysql-config +$ make && make install And you're ready to go. Don't forget to use +gcruby+ and +gcrake+ aliases when running the performance tests. diff --git a/railties/guides/source/rails_on_rack.textile b/railties/guides/source/rails_on_rack.textile index c1b91da7a8..b1db2942dd 100644 --- a/railties/guides/source/rails_on_rack.textile +++ b/railties/guides/source/rails_on_rack.textile @@ -63,13 +63,13 @@ run ActionController::Dispatcher.new And start the server: -[lifo@null application]$ rackup config.ru +$ rackup config.ru To find out more about different +rackup+ options: -[lifo@null application]$ rackup --help +$ rackup --help h3. Action Controller Middleware Stack -- cgit v1.2.3 From 2b6845b1ef595737002dccae23a6e1719d0dc104 Mon Sep 17 00:00:00 2001 From: Andy Lindeman Date: Sun, 20 Feb 2011 13:52:41 -0600 Subject: Specifying :partial is required when passing additional options such as :layout --- railties/guides/source/layouts_and_rendering.textile | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/layouts_and_rendering.textile b/railties/guides/source/layouts_and_rendering.textile index fe400d3358..8442a6e257 100644 --- a/railties/guides/source/layouts_and_rendering.textile +++ b/railties/guides/source/layouts_and_rendering.textile @@ -1006,11 +1006,13 @@ h5. Partial Layouts A partial can use its own layout file, just as a view can use a layout. For example, you might call a partial like this: -<%= render "link_area", :layout => "graybar" %> +<%= render :partial => "link_area", :layout => "graybar" %> This would look for a partial named +_link_area.html.erb+ and render it using the layout +_graybar.html.erb+. Note that layouts for partials follow the same leading-underscore naming as regular partials, and are placed in the same folder with the partial that they belong to (not in the master +layouts+ folder). +Also note that explicitly specifying +:partial+ is required when passing additional options such as +:layout+. + h5. Passing Local Variables You can also pass local variables into partials, making them even more powerful and flexible. For example, you can use this technique to reduce duplication between new and edit pages, while still keeping a bit of distinct content: -- cgit v1.2.3 From ae78e462bcb8b207492582071a4760a5e06679a6 Mon Sep 17 00:00:00 2001 From: Mani Tadayon Date: Mon, 21 Feb 2011 13:45:21 -0800 Subject: Fix typo in i18n guide: 'explicitely' --- railties/guides/source/i18n.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/i18n.textile b/railties/guides/source/i18n.textile index 8b37543342..ac05e1c6c7 100644 --- a/railties/guides/source/i18n.textile +++ b/railties/guides/source/i18n.textile @@ -780,7 +780,7 @@ h5. Action View Helper Methods * +distance_of_time_in_words+ translates and pluralizes its result and interpolates the number of seconds, minutes, hours, and so on. See "datetime.distance_in_words":http://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L51 translations. -* +datetime_select+ and +select_month+ use translated month names for populating the resulting select tag. See "date.month_names":http://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L15 for translations. +datetime_select+ also looks up the order option from "date.order":http://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L18 (unless you pass the option explicitely). All date selection helpers translate the prompt using the translations in the "datetime.prompts":http://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L83 scope if applicable. +* +datetime_select+ and +select_month+ use translated month names for populating the resulting select tag. See "date.month_names":http://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L15 for translations. +datetime_select+ also looks up the order option from "date.order":http://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L18 (unless you pass the option explicitly). All date selection helpers translate the prompt using the translations in the "datetime.prompts":http://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L83 scope if applicable. * The +number_to_currency+, +number_with_precision+, +number_to_percentage+, +number_with_delimiter+, and +number_to_human_size+ helpers use the number format settings located in the "number":http://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L2 scope. -- cgit v1.2.3 From 20f2785849bc17b2512465e8bfdb5560803cc9f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateus=20Paix=C3=A3o?= Date: Tue, 22 Feb 2011 10:37:59 -0300 Subject: alteracao de HTML para HTTP --- railties/guides/source/layouts_and_rendering.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/layouts_and_rendering.textile b/railties/guides/source/layouts_and_rendering.textile index 8442a6e257..5bfbf97ea7 100644 --- a/railties/guides/source/layouts_and_rendering.textile +++ b/railties/guides/source/layouts_and_rendering.textile @@ -339,7 +339,7 @@ render :layout => false h6. The +:status+ Option -Rails will automatically generate a response with the correct HTML status code (in most cases, this is +200 OK+). You can use the +:status+ option to change this: +Rails will automatically generate a response with the correct HTTP status code (in most cases, this is +200 OK+). You can use the +:status+ option to change this: render :status => 500 -- cgit v1.2.3 From 29399e00c9a0875b6823989c636058910fd7c86b Mon Sep 17 00:00:00 2001 From: Rodrigo Navarro Date: Wed, 23 Feb 2011 10:22:03 -0800 Subject: ActiveModel::Validator#validate must receive have a record parameter. --- .../guides/source/active_record_validations_callbacks.textile | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/active_record_validations_callbacks.textile b/railties/guides/source/active_record_validations_callbacks.textile index ea8cf8afaf..d27ba39104 100644 --- a/railties/guides/source/active_record_validations_callbacks.textile +++ b/railties/guides/source/active_record_validations_callbacks.textile @@ -417,7 +417,7 @@ class Person < ActiveRecord::Base end class GoodnessValidator < ActiveModel::Validator - def validate + def validate(record) if record.first_name == "Evil" record.errors[:base] << "This person is evil" end @@ -427,10 +427,7 @@ end The +validates_with+ helper takes a class, or a list of classes to use for validation. There is no default error message for +validates_with+. You must manually add errors to the record's errors collection in the validator class. -The validator class has two attributes by default: - -* +record+ - the record to be validated -* +options+ - the extra options that were passed to +validates_with+ +To implement the validate method, you must have an +record+ parameter defined, which is the record to be validated. Like all other validations, +validates_with+ takes the +:if+, +:unless+ and +:on+ options. If you pass any other options, it will send those options to the validator class as +options+: @@ -440,7 +437,7 @@ class Person < ActiveRecord::Base end class GoodnessValidator < ActiveRecord::Validator - def validate + def validate(record) if options[:fields].any?{|field| record.send(field) == "Evil" } record.errors[:base] << "This person is evil" end -- cgit v1.2.3 From 0b2412978f5adfd245670e61e46f224b25b041e4 Mon Sep 17 00:00:00 2001 From: Rodrigo Navarro Date: Wed, 23 Feb 2011 10:23:01 -0800 Subject: Fixing wrong class name. --- railties/guides/source/active_record_validations_callbacks.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/active_record_validations_callbacks.textile b/railties/guides/source/active_record_validations_callbacks.textile index d27ba39104..526e62a97a 100644 --- a/railties/guides/source/active_record_validations_callbacks.textile +++ b/railties/guides/source/active_record_validations_callbacks.textile @@ -436,7 +436,7 @@ class Person < ActiveRecord::Base validates_with GoodnessValidator, :fields => [:first_name, :last_name] end -class GoodnessValidator < ActiveRecord::Validator +class GoodnessValidator < ActiveModel::Validator def validate(record) if options[:fields].any?{|field| record.send(field) == "Evil" } record.errors[:base] << "This person is evil" -- cgit v1.2.3 From 287bb6990cf0c8a6e4b5ff4c0d75ecfa9bab33fa Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Fri, 25 Feb 2011 02:59:37 +0530 Subject: standardize all shell commands with the $ prefix --- railties/guides/source/3_0_release_notes.textile | 8 +-- .../guides/source/action_mailer_basics.textile | 2 +- .../guides/source/action_view_overview.textile | 12 ++-- .../active_record_validations_callbacks.textile | 2 +- railties/guides/source/command_line.textile | 2 +- .../source/contributing_to_ruby_on_rails.textile | 72 +++++++++++----------- .../source/debugging_rails_applications.textile | 8 +-- railties/guides/source/generators.textile | 4 +- .../guides/source/layouts_and_rendering.textile | 2 +- railties/guides/source/migrations.textile | 20 +++--- railties/guides/source/performance_testing.textile | 2 +- railties/guides/source/plugins.textile | 22 +++---- 12 files changed, 78 insertions(+), 78 deletions(-) (limited to 'railties/guides') diff --git a/railties/guides/source/3_0_release_notes.textile b/railties/guides/source/3_0_release_notes.textile index db5a9ce644..001f458fd9 100644 --- a/railties/guides/source/3_0_release_notes.textile +++ b/railties/guides/source/3_0_release_notes.textile @@ -22,7 +22,7 @@ To install Rails 3: # Use sudo if your setup requires it -gem install rails +$ gem install rails @@ -47,8 +47,8 @@ h4. script/* replaced by script/rails The new script/rails replaces all the scripts that used to be in the script directory. You do not run script/rails directly though, the +rails+ command detects it is being invoked in the root of a Rails application and runs the script for you. Intended usage is: -rails console # instead of script/console -rails g scaffold post title:string # instead of script/generate scaffold post title:string +$ rails console # instead of script/console +$ rails g scaffold post title:string # instead of script/generate scaffold post title:string Run rails --help for a list of all the options. @@ -64,7 +64,7 @@ To help with the upgrade process, a plugin named "Rails Upgrade":http://github.c Simply install the plugin, then run +rake rails:upgrade:check+ to check your app for pieces that need to be updated (with links to information on how to update them). It also offers a task to generate a +Gemfile+ based on your current +config.gem+ calls and a task to generate a new routes file from your current one. To get the plugin, simply run the following: -ruby script/plugin install git://github.com/rails/rails_upgrade.git +$ ruby script/plugin install git://github.com/rails/rails_upgrade.git You can see an example of how that works at "Rails Upgrade is now an Official Plugin":http://omgbloglol.com/post/364624593/rails-upgrade-is-now-an-official-plugin diff --git a/railties/guides/source/action_mailer_basics.textile b/railties/guides/source/action_mailer_basics.textile index 6ee17ee5b8..56da360972 100644 --- a/railties/guides/source/action_mailer_basics.textile +++ b/railties/guides/source/action_mailer_basics.textile @@ -19,7 +19,7 @@ h4. Walkthrough to Generating a Mailer h5. Create the Mailer -rails generate mailer UserMailer +$ rails generate mailer UserMailer create app/mailers/user_mailer.rb invoke erb create app/views/user_mailer diff --git a/railties/guides/source/action_view_overview.textile b/railties/guides/source/action_view_overview.textile index 39f4c33397..bf592c06ed 100644 --- a/railties/guides/source/action_view_overview.textile +++ b/railties/guides/source/action_view_overview.textile @@ -29,8 +29,8 @@ Action View works well with Action Record, but it can also be used with other Ru Let's start by ensuring that you have the Action Pack and Rack gems installed: -gem install actionpack -gem install rack +$ gem install actionpack +$ gem install rack Now we'll create a simple "Hello World" application that uses the +titleize+ method provided by Active Support. @@ -52,7 +52,7 @@ Rack::Handler::Mongrel.run method(:hello_world), :Port => 4567 We can see this all come together by starting up the application and then visiting +http://localhost:4567/+ -ruby hello_world.rb +$ ruby hello_world.rb TODO needs a screenshot? I have one - not sure where to put it. @@ -64,8 +64,8 @@ Action View can also be used with "Sinatra":http://www.sinatrarb.com/ in the sam Let's start by ensuring that you have the Action Pack and Sinatra gems installed: -gem install actionpack -gem install sinatra +$ gem install actionpack +$ gem install sinatra Now we'll create the same "Hello World" application in Sinatra. @@ -85,7 +85,7 @@ end Then, we can run the application: -ruby hello_world.rb +$ ruby hello_world.rb Once the application is running, you can see Sinatra and Action View working together by visiting +http://localhost:4567/+ diff --git a/railties/guides/source/active_record_validations_callbacks.textile b/railties/guides/source/active_record_validations_callbacks.textile index 526e62a97a..5dc6ef3774 100644 --- a/railties/guides/source/active_record_validations_callbacks.textile +++ b/railties/guides/source/active_record_validations_callbacks.textile @@ -1112,7 +1112,7 @@ h4. Creating Observers For example, imagine a +User+ model where we want to send an email every time a new user is created. Because sending emails is not directly related to our model's purpose, we could create an observer to contain this functionality. -rails generate observer User +$ rails generate observer User diff --git a/railties/guides/source/command_line.textile b/railties/guides/source/command_line.textile index 81d181fe02..581fece1ab 100644 --- a/railties/guides/source/command_line.textile +++ b/railties/guides/source/command_line.textile @@ -539,7 +539,7 @@ Rake is a standalone Ruby utility that replaces the Unix utility 'make', and use You can get a list of Rake tasks available to you, which will often depend on your current directory, by typing +rake --tasks+. Each task has a description, and should help you find the thing you need. - rake --tasks +$ rake --tasks (in /home/foobar/commandsapp) rake db:abort_if_pending_migrations # Raises an error if there are pending migrations rake db:charset # Retrieves the charset for the current environment's database diff --git a/railties/guides/source/contributing_to_ruby_on_rails.textile b/railties/guides/source/contributing_to_ruby_on_rails.textile index 4f51c0f859..1977f8d0ce 100644 --- a/railties/guides/source/contributing_to_ruby_on_rails.textile +++ b/railties/guides/source/contributing_to_ruby_on_rails.textile @@ -56,8 +56,8 @@ h4. 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: -git clone git://github.com/rails/rails.git -cd rails +$ git clone git://github.com/rails/rails.git +$ cd rails h4. Set up and Run the Tests @@ -67,38 +67,38 @@ The test suite must pass with any submitted code. No matter whether you are writ Install first libxml2 and libxslt together with their development files for Nokogiri. In Ubuntu that's -sudo apt-get install libxml2 libxml2-dev libxslt1-dev +$ sudo apt-get install libxml2 libxml2-dev libxslt1-dev Also, SQLite3 and its development files for the +sqlite3-ruby+ gem, in Ubuntu you're done with -sudo apt-get install sqlite3 libsqlite3-dev +$ sudo apt-get install sqlite3 libsqlite3-dev Get a recent version of "Bundler":http://gembundler.com/: -gem install bundler +$ gem install bundler and run: -bundle install --without db +$ bundle install --without db This command will install all dependencies except the MySQL and PostgreSQL Ruby drivers. We will come back at these soon. With dependencies installed, you can run the test suite with: -rake test +$ rake test You can also run tests for an specific framework, like Action Pack, by going into its directory and executing the same command: -cd actionpack -rake test +$ cd actionpack +$ rake test h4. Warnings @@ -108,7 +108,7 @@ The test suite runs with warnings enabled. Ideally Ruby on Rails should issue no As of this writing 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: -RUBYOPT=-W0 rake test +$ RUBYOPT=-W0 rake test h4. Testing Active Record @@ -122,8 +122,8 @@ 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: -cd activerecord -rake test_sqlite3 +$ cd activerecord +$ rake test_sqlite3 h5. MySQL and PostgreSQL @@ -131,15 +131,15 @@ h5. 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 -sudo apt-get install mysql-server libmysqlclient15-dev -sudo apt-get install postgresql postgresql-client postgresql-contrib libpq-dev +$ sudo apt-get install mysql-server libmysqlclient15-dev +$ sudo apt-get install postgresql postgresql-client postgresql-contrib libpq-dev After that run: -rm .bundle/config -bundle install +$ rm .bundle/config +$ bundle install We need first to delete +.bundle/config+ because Bundler remembers in that file that we didn't want to install the "db" group (alternatively you can edit the file). @@ -156,21 +156,21 @@ mysql> GRANT ALL PRIVILEGES ON activerecord_unittest2.* and create the test databases: -cd activerecord -rake mysql:build_databases +$ cd activerecord +$ rake mysql:build_databases PostgreSQL's authentication works differently. A simple way to setup the development environment for example is to run with your development account -sudo -u postgres createuser --superuser $USER +$ sudo -u postgres createuser --superuser $USER and after that create the test databases with -cd activerecord -rake postgresql:build_databases +$ cd activerecord +$ rake postgresql:build_databases NOTE: Using the rake task to create the test databases ensures they have the correct character set and collation. @@ -188,7 +188,7 @@ test_postgresql respectively. As we mentioned before -rake test +$ rake test will now run the four of them in turn. @@ -200,8 +200,8 @@ 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 2-3-stable branch: -git branch --track 2-3-stable origin/2-3-stable -git checkout 2-3-stable +$ git branch --track 2-3-stable origin/2-3-stable +$ git checkout 2-3-stable 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. @@ -225,13 +225,13 @@ h4. Testing Patches You can also help out by examining patches that have been submitted to Ruby on Rails via Lighthouse. To apply someone's changes you need to first create a dedicated branch: -git checkout -b testing_branch +$ git checkout -b testing_branch Then you can apply their patch: -git am their-patch-file.diff +$ git am their-patch-file.diff After applying a patch, test it out! Here are some things to think about: @@ -270,14 +270,14 @@ h4. Clone the Rails Repository The first thing you need to do to be able to contribute code is to clone the repository: -git clone git://github.com/rails/rails.git +$ git clone git://github.com/rails/rails.git and create a dedicated branch: -cd rails -git checkout -b my_new_branch +$ cd rails +$ git checkout -b my_new_branch It doesn’t really matter what name you use, because this branch will only exist on your local computer. @@ -311,7 +311,7 @@ h4. Commit Your Changes When you're happy with the code on your computer, you need to commit the changes to git: -git commit -a -m "Here is a commit message" +$ git commit -a -m "Here is a commit message" h4. Update master @@ -319,15 +319,15 @@ h4. Update master It’s pretty likely that other changes to master have happened while you were working. Go get them: -git checkout master -git pull +$ git checkout master +$ git pull Now reapply your patch on top of the latest changes: -git checkout my_new_branch -git rebase master +$ git checkout my_new_branch +$ git rebase master No conflicts? Tests still pass? Change still seems reasonable to you? Then move on. @@ -337,8 +337,8 @@ h4. Create a Patch Now you can create a patch file to share with other developers (and with the core team). Still in your branch, run -git commit -a -git format-patch master --stdout > my_new_patch.diff +$ git commit -a +$ git format-patch master --stdout > my_new_patch.diff Sanity check the results of this operation: open the diff file in your text editor of choice and make sure that no unintended changes crept in. diff --git a/railties/guides/source/debugging_rails_applications.textile b/railties/guides/source/debugging_rails_applications.textile index b84d7d088d..d51cdf5169 100644 --- a/railties/guides/source/debugging_rails_applications.textile +++ b/railties/guides/source/debugging_rails_applications.textile @@ -251,7 +251,7 @@ If you see the message in the console or logs: Make sure you have started your web server with the option +--debugger+: -~/PathTo/rails_project$ rails server --debugger +$ rails server --debugger => Booting WEBrick => Rails 3.0.0 application starting on http://0.0.0.0:3000 => Debugger enabled @@ -477,7 +477,7 @@ end TIP: You can use ruby-debug while using +rails console+. Just remember to +require "ruby-debug"+ before calling the +debugger+ method. -/PathTo/project $ rails console +$ rails console Loading development environment (Rails 2.1.0) >> require "ruby-debug" => [] @@ -626,7 +626,7 @@ If a Ruby object does not go out of scope, the Ruby Garbage Collector won't swee To install it run: -sudo gem install bleak_house +$ sudo gem install bleak_house Then setup your application for profiling. Then add the following at the bottom of config/environment.rb: @@ -638,7 +638,7 @@ require 'bleak_house' if ENV['BLEAK_HOUSE'] Start a server instance with BleakHouse integration: -RAILS_ENV=production BLEAK_HOUSE=1 ruby-bleak-house rails server +$ RAILS_ENV=production BLEAK_HOUSE=1 ruby-bleak-house rails server Make sure to run a couple hundred requests to get better data samples, then press +CTRL-C+. The server will stop and Bleak House will produce a dumpfile in +/tmp+: diff --git a/railties/guides/source/generators.textile b/railties/guides/source/generators.textile index 3adbbfa7aa..41a96b487d 100644 --- a/railties/guides/source/generators.textile +++ b/railties/guides/source/generators.textile @@ -388,7 +388,7 @@ In the above template we specify that the application relies on the +rspec-rails Imagine that this template was in a file called +template.rb+. We can use it to modify the outcome of the +rails new+ command by using the +-m+ option and passing in the filename: - rails new thud -m template.rb +$ rails new thud -m template.rb This command will generate the +Thud+ application, and then apply the template to the generated output. @@ -396,7 +396,7 @@ This command will generate the +Thud+ application, and then apply the template t Templates don't have to be stored on the local system, the +-m+ option also supports online templates: - rails new thud -m https://gist.github.com/722911.txt +$ rails new thud -m https://gist.github.com/722911.txt Whilst the final section of this guide doesn't cover how to generate the most awesome template known to man, it will take you through the methods available at your disposal so that you can develop it yourself. These same methods are also available for generators. diff --git a/railties/guides/source/layouts_and_rendering.textile b/railties/guides/source/layouts_and_rendering.textile index 5bfbf97ea7..1548da0eb5 100644 --- a/railties/guides/source/layouts_and_rendering.textile +++ b/railties/guides/source/layouts_and_rendering.textile @@ -109,7 +109,7 @@ render :nothing => true If you look at the response for this using cURL, you will see the following: - $ curl -i 127.0.0.1:3000/books +$ curl -i 127.0.0.1:3000/books HTTP/1.1 200 OK Connection: close Date: Sun, 24 Jan 2010 09:25:18 GMT diff --git a/railties/guides/source/migrations.textile b/railties/guides/source/migrations.textile index 0d13fbc10a..21784c5ba3 100644 --- a/railties/guides/source/migrations.textile +++ b/railties/guides/source/migrations.textile @@ -109,7 +109,7 @@ h4. Creating a Model The model and scaffold generators will create migrations appropriate for adding a new model. This migration will already contain instructions for creating the relevant table. If you tell Rails what columns you want then statements for adding those will also be created. For example, running -rails generate model Product name:string description:text +$ rails generate model Product name:string description:text will create a migration that looks like this @@ -139,7 +139,7 @@ h4. Creating a Standalone Migration If you are creating migrations for other purposes (for example to add a column to an existing table) then you can use the migration generator: -rails generate migration AddPartNumberToProducts +$ rails generate migration AddPartNumberToProducts This will create an empty but appropriately named migration: @@ -157,7 +157,7 @@ end If the migration name is of the form "AddXXXToYYY" or "RemoveXXXFromYYY" and is followed by a list of column names and types then a migration containing the appropriate +add_column+ and +remove_column+ statements will be created. -rails generate migration AddPartNumberToProducts part_number:string +$ rails generate migration AddPartNumberToProducts part_number:string will generate @@ -177,7 +177,7 @@ end Similarly, -rails generate migration RemovePartNumberFromProducts part_number:string +$ rails generate migration RemovePartNumberFromProducts part_number:string generates @@ -197,7 +197,7 @@ end You are not limited to one magically generated column, for example -rails generate migration AddDetailsToProducts part_number:string price:decimal +$ rails generate migration AddDetailsToProducts part_number:string price:decimal generates @@ -383,7 +383,7 @@ If you specify a target version, Active Record will run the required migrations version is the numerical prefix on the migration's filename. For example to migrate to version 20080906120000 run -rake db:migrate VERSION=20080906120000 +$ rake db:migrate VERSION=20080906120000 If this is greater than the current version (i.e. it is migrating upwards) this will run the +up+ method on all migrations up to and including 20080906120000, if migrating downwards this will run the +down+ method on all the migrations down to, but not including, 20080906120000. @@ -393,13 +393,13 @@ h4. Rolling Back A common task is to rollback the last migration, for example if you made a mistake in it and wish to correct it. Rather than tracking down the version number associated with the previous migration you can run -rake db:rollback +$ rake db:rollback This will run the +down+ method from the latest migration. If you need to undo several migrations you can provide a +STEP+ parameter: -rake db:rollback STEP=3 +$ rake db:rollback STEP=3 will run the +down+ method from the last 3 migrations. @@ -407,7 +407,7 @@ will run the +down+ method from the last 3 migrations. The +db:migrate:redo+ task is a shortcut for doing a rollback and then migrating back up again. As with the +db:rollback+ task you can use the +STEP+ parameter if you need to go more than one version back, for example -rake db:migrate:redo STEP=3 +$ rake db:migrate:redo STEP=3 Neither of these Rake tasks do anything you could not do with +db:migrate+, they are simply more convenient since you do not need to explicitly specify the version to migrate to. @@ -421,7 +421,7 @@ h4. Being Specific If you need to run a specific migration up or down the +db:migrate:up+ and +db:migrate:down+ tasks will do that. Just specify the appropriate version and the corresponding migration will have its +up+ or +down+ method invoked, for example -rake db:migrate:up VERSION=20080906120000 +$ rake db:migrate:up VERSION=20080906120000 will run the +up+ method from the 20080906120000 migration. These tasks check whether the migration has already run, so for example +db:migrate:up VERSION=20080906120000+ will do nothing if Active Record believes that 20080906120000 has already been run. diff --git a/railties/guides/source/performance_testing.textile b/railties/guides/source/performance_testing.textile index cd0a8fa384..32eebe863c 100644 --- a/railties/guides/source/performance_testing.textile +++ b/railties/guides/source/performance_testing.textile @@ -37,7 +37,7 @@ h4. Generating Performance Tests Rails provides a generator called +test_unit:performance+ for creating new performance tests: -rails generate test_unit:performance homepage +$ rails generate test_unit:performance homepage This generates +homepage_test.rb+ in the +test/performance+ directory: diff --git a/railties/guides/source/plugins.textile b/railties/guides/source/plugins.textile index 2135c0da4e..daca50ee9e 100644 --- a/railties/guides/source/plugins.textile +++ b/railties/guides/source/plugins.textile @@ -31,7 +31,7 @@ Rails currently ships with a generator to generate a plugin within a Rails appli how this generator works. - rails generate plugin --help +$ rails generate plugin --help This generator places the plugin into the vendor/plugins directory. @@ -214,18 +214,18 @@ We can easily generate these models in our "dummy" Rails application by running test/dummy directory: - cd test/dummy - rails generate model Hickwall last_squak:string - rails generate model Wickwall last_squak:string last_tweet:string +$ cd test/dummy +$ rails generate model Hickwall last_squak:string +$ rails generate model Wickwall last_squak:string last_tweet:string Now you can create the necessary database tables in your testing database by navigating to your dummy app and migrating the database. First - cd test/dummy - rake db:migrate - rake db:test:prepare +$ cd test/dummy +$ rake db:migrate +$ rake db:test:prepare While you are here, change the Hickwall and Wickwall models so that they know that they are supposed to act @@ -424,9 +424,9 @@ 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. - cd my_app - rails console - String.instance_methods.sort +$ cd my_app +$ rails console +$ String.instance_methods.sort You can also remove the .gemspec, Gemfile and Gemfile.lock files as they will no longer be needed. @@ -447,7 +447,7 @@ Once your README is solid, go through and add rdoc comments to all of the method Once your comments are good to go, navigate to your plugin directory and run: -rake rdoc +$ rake rdoc !!!!!!!!!!!!!! Make sure these still make sense. Add any references that you see fit. !!!!!!!!!!!!! -- cgit v1.2.3 From 7112cf5e021d8da7c4e073a4e2d2a4afb10671ec Mon Sep 17 00:00:00 2001 From: Josh Kalderimis Date: Sun, 27 Feb 2011 22:58:07 +0100 Subject: Updated the AS guides with some information on the difference between Date.today and Date.current. --- railties/guides/source/active_support_core_extensions.textile | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) (limited to 'railties/guides') diff --git a/railties/guides/source/active_support_core_extensions.textile b/railties/guides/source/active_support_core_extensions.textile index 788c243d2a..e0b1bf6e83 100644 --- a/railties/guides/source/active_support_core_extensions.textile +++ b/railties/guides/source/active_support_core_extensions.textile @@ -2791,6 +2791,8 @@ h5. +Date.current+ Active Support defines +Date.current+ to be today in the current time zone. That's like +Date.today+, except that it honors the user time zone, if defined. It also defines +Date.yesterday+ and +Date.tomorrow+, and the instance predicates +past?+, +today?+, and +future?+, all of them relative to +Date.current+. +When making Date comparisons using methods which honor the user time zone, make sure to use +Date.current+ and not +Date.today+. There are cases where the user time zone might be in the future compared to the system time zone, which +Date.today+ uses by default. This means +Date.today+ may equal +Date.yesterday+. + h5. Named dates h6. +prev_year+, +next_year+ @@ -3105,7 +3107,7 @@ h5. Named Datetimes h6. +DateTime.current+ -Active Support defines +DateTime.current+ to be like +Time.now.to_datetime+, except that it honors the user time zone, if defined. It also defines instance predicates +past?+, and +future?+ relative to +DateTime.current+. +Active Support defines +DateTime.current+ to be like +Time.now.to_datetime+, except that it honors the user time zone, if defined. It also defines +DateTime.yesterday+ and +DateTime.tomorrow+, and the instance predicates +past?+, and +future?+ relative to +DateTime.current+. h5. Other Extensions @@ -3282,6 +3284,12 @@ t.advance(:seconds => 1) * If +since+ or +ago+ jump to a time that can't be expressed with +Time+ a +DateTime+ object is returned instead. +h5. +Time.current+ + +Active Support defines +Time.current+ to be today in the current time zone. That's like +Time.now+, except that it honors the user time zone, if defined. It also defines +Time.yesterday+ and +Time.tomorrow+, and the instance predicates +past?+, +today?+, and +future?+, all of them relative to +Time.current+. + +When making Time comparisons using methods which honor the user time zone, make sure to use +Time.current+ and not +Time.now+. There are cases where the user time zone might be in the future compared to the system time zone, which +Time.today+ uses by default. This means +Time.now+ may equal +Time.yesterday+. + h4. Time Constructors Active Support defines +Time.current+ to be +Time.zone.now+ if there's a user time zone defined, with fallback to +Time.now+: -- cgit v1.2.3