diff options
author | Xavier Noria <fxn@hashref.com> | 2010-12-05 10:33:50 +0100 |
---|---|---|
committer | Xavier Noria <fxn@hashref.com> | 2010-12-05 10:33:50 +0100 |
commit | 48386d245bc169d3a36e5f305927bd968b108fea (patch) | |
tree | 9156d3535c42e7f56af6e69fbbd5164ccb4fcc95 /railties/guides/source | |
parent | b696dd70db651c6cb4a096dd0d5762416acd9917 (diff) | |
parent | e1d0d5ae81d2b02eebb1afbfb79edf0a2da2d48e (diff) | |
download | rails-48386d245bc169d3a36e5f305927bd968b108fea.tar.gz rails-48386d245bc169d3a36e5f305927bd968b108fea.tar.bz2 rails-48386d245bc169d3a36e5f305927bd968b108fea.zip |
Merge branch 'master' of git://github.com/lifo/docrails
Diffstat (limited to 'railties/guides/source')
-rw-r--r-- | railties/guides/source/active_record_querying.textile | 62 | ||||
-rw-r--r-- | railties/guides/source/association_basics.textile | 4 | ||||
-rw-r--r-- | railties/guides/source/configuring.textile | 302 | ||||
-rw-r--r-- | railties/guides/source/contributing_to_rails.textile | 2 | ||||
-rw-r--r-- | railties/guides/source/generators.textile | 257 | ||||
-rw-r--r-- | railties/guides/source/i18n.textile | 2 | ||||
-rw-r--r-- | railties/guides/source/security.textile | 2 |
7 files changed, 543 insertions, 88 deletions
diff --git a/railties/guides/source/active_record_querying.textile b/railties/guides/source/active_record_querying.textile index 328439fdb8..e41b5fb606 100644 --- a/railties/guides/source/active_record_querying.textile +++ b/railties/guides/source/active_record_querying.textile @@ -65,6 +65,7 @@ The methods are: * +lock+ * +readonly+ * +from+ +* +having+ All of the above methods return an instance of <tt>ActiveRecord::Relation</tt>. @@ -103,7 +104,7 @@ h5. +first+ <ruby> client = Client.first -=> #<Client id: 1, first_name: => "Lifo"> +=> #<Client id: 1, first_name: "Lifo"> </ruby> SQL equivalent of the above is: @@ -120,7 +121,7 @@ h5. +last+ <ruby> client = Client.last -=> #<Client id: 221, first_name: => "Russel"> +=> #<Client id: 221, first_name: "Russel"> </ruby> SQL equivalent of the above is: @@ -231,7 +232,7 @@ WARNING: Building your own conditions as pure strings can leave you vulnerable t h4. Array Conditions -Now what if that number could vary, say as an argument from somewhere, or perhaps from the user's level status somewhere? The find then becomes something like: +Now what if that number could vary, say as an argument from somewhere? The find then becomes something like: <ruby> Client.where("orders_count = ?", params[:orders]) @@ -279,62 +280,15 @@ h5(#array-range_conditions). Range Conditions If you're looking for a range inside of a table (for example, users created in a certain timeframe) you can use the conditions option coupled with the +IN+ SQL statement for this. If you had two dates coming in from a controller you could do something like this to look for a range: <ruby> -Client.where("created_at IN (?)", - (params[:start_date].to_date)..(params[:end_date].to_date)) +Client.where(:created_at => (params[:start_date].to_date)..(params[:end_date].to_date)) </ruby> -This would generate the proper query which is great for small ranges but not so good for larger ranges. For example if you pass in a range of date objects spanning a year that's 365 (or possibly 366, depending on the year) strings it will attempt to match your field against. +This query will generate something similar to the following SQL: <sql> -SELECT * FROM users WHERE (created_at IN - ('2007-12-31','2008-01-01','2008-01-02','2008-01-03','2008-01-04','2008-01-05', - '2008-01-06','2008-01-07','2008-01-08','2008-01-09','2008-01-10','2008-01-11', - '2008-01-12','2008-01-13','2008-01-14','2008-01-15','2008-01-16','2008-01-17', - '2008-01-18','2008-01-19','2008-01-20','2008-01-21','2008-01-22','2008-01-23',... - ‘2008-12-15','2008-12-16','2008-12-17','2008-12-18','2008-12-19','2008-12-20', - '2008-12-21','2008-12-22','2008-12-23','2008-12-24','2008-12-25','2008-12-26', - '2008-12-27','2008-12-28','2008-12-29','2008-12-30','2008-12-31')) + SELECT "clients".* FROM "clients" WHERE ("clients"."created_at" BETWEEN '2010-09-29' AND '2010-11-30') </sql> -h5. Time and Date Conditions - -Things can get *really* messy if you pass in Time objects as it will attempt to compare your field to *every second* in that range: - -<ruby> -Client.where("created_at IN (?)", - (params[:start_date].to_date.to_time)..(params[:end_date].to_date.to_time)) -</ruby> - -<sql> -SELECT * FROM users WHERE (created_at IN - ('2007-12-01 00:00:00', '2007-12-01 00:00:01' ... - '2007-12-01 23:59:59', '2007-12-02 00:00:00')) -</sql> - -This could possibly cause your database server to raise an unexpected error, for example MySQL will throw back this error: - -<shell> -Got a packet bigger than 'max_allowed_packet' bytes: _query_ -</shell> - -Where _query_ is the actual query used to get that error. - -In this example it would be better to use greater-than and less-than operators in SQL, like so: - -<ruby> -Client.where( - "created_at > ? AND created_at < ?", params[:start_date], params[:end_date]) -</ruby> - -You can also use the greater-than-or-equal-to and less-than-or-equal-to like this: - -<ruby> -Client.where( - "created_at >= ? AND created_at <= ?", params[:start_date], params[:end_date]) -</ruby> - -Just like in Ruby. If you want a shorter syntax be sure to check out the "Hash Conditions":#hash-conditions section later on in the guide. - h4. Hash Conditions Active Record also allows you to pass in hash conditions which can increase the readability of your conditions syntax. With hash conditions, you pass in a hash with keys of the fields you want conditionalised and the values of how you want to conditionalise them: @@ -385,7 +339,7 @@ SELECT * FROM clients WHERE (clients.orders_count IN (1,3,5)) h4. Ordering -To retrieve records from the database in a specific order, you can specify the +:order+ option to the +find+ call. +To retrieve records from the database in a specific order, you can use the +order+ method. For example, if you're getting a set of records and want to order them in ascending order by the +created_at+ field in your table: diff --git a/railties/guides/source/association_basics.textile b/railties/guides/source/association_basics.textile index 14bbe907f3..62abc40c81 100644 --- a/railties/guides/source/association_basics.textile +++ b/railties/guides/source/association_basics.textile @@ -550,6 +550,8 @@ build_customer create_customer </ruby> +NOTE: When initializing a new +has_one+ or +belongs_to+ association you must use the +build_+ prefix to build the association, rather than the +association.build+ method that would be used for +has_many+ or +has_and_belongs_to_many+ associations. To create one, use the +create_+ prefix. + h6(#belongs_to-association). <tt><em>association</em>(force_reload = false)</tt> The <tt><em>association</em></tt> method returns the associated object, if any. If no associated object is found, it returns +nil+. @@ -817,6 +819,8 @@ build_account create_account </ruby> +NOTE: When initializing a new +has_one+ or +belongs_to+ association you must use the +build_+ prefix to build the association, rather than the +association.build+ method that would be used for +has_many+ or +has_and_belongs_to_many+ associations. To create one, use the +create_+ prefix. + h6(#has_one-association). <tt><em>association</em>(force_reload = false)</tt> The <tt><em>association</em></tt> method returns the associated object, if any. If no associated object is found, it returns +nil+. diff --git a/railties/guides/source/configuring.textile b/railties/guides/source/configuring.textile index ca78cc0e6d..afafabd1e9 100644 --- a/railties/guides/source/configuring.textile +++ b/railties/guides/source/configuring.textile @@ -47,40 +47,64 @@ h4. Rails General Configuration end </ruby> -* +config.app_generators+ alternate name for +config.generators+. See the "Configuring Generators" section below for how to use this. +* +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!+. + +* +config.asset_host+ sets the host for the assets. Useful when CDNs are used for hosting assets rather than the application server itself. Shorter version of +config.action_controller.asset_host+. + +* +config.asset_path+ takes a block which configures where assets can be found. Shorter version of +config.action_controller.asset_path+. + +<ruby> + config.asset_path = proc { |asset_path| "assets/#{asset_path}" } +</ruby> * +config.autoload_once_paths+ accepts an array of paths from which Rails will automatically load from only once. All elements of this array must also be in +autoload_paths+. * +config.autoload_paths+ accepts an array of additional paths to prepend to the load path. By default, all app, lib, vendor and mock paths are included in this list. -* +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. +* +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.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. +* +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+ (true by default) specifies whether or not to use ANSI color codes when logging information. +* +config.colorize_logging+ specifies whether or not to use ANSI color codes when logging information. Defaults to _true_. -* +config.dependency_loading+ enables or disables dependency loading during the request cycle. Setting dependency_loading to _true_ will allow new classes to be loaded during a request and setting it to _false_ will disable this behavior. +* +config.consider_all_requests_local+ is generally set to +true+ during development and +false+ during production; if it is set to +true+, then any error will cause detailed debugging information to be dumped in the HTTP response. For finer-grained control, set this to +false+ and implement +local_request?+ in controllers to specify which requests should provide debugging information on errors. + +* +config.controller_paths+ configures where Rails can find controllers for this application. + +* +config.dependency_loading+ enables or disables dependency loading during the request cycle. Setting dependency_loading to _true_ will allow new classes to be loaded during a request and setting it to _false_ will disable this behavior. Can also be enabled with +threadsafe!+. * +config.eager_load_paths+ accepts an array of paths from which Rails will eager load on boot if cache classes is enabled. All elements of this array must also be in +load_paths+. +* +config.encoding+ sets up the application-wide encoding. Defaults to UTF-8. + +* +config.filter_parameters+ used for filtering out the parameters that you don't want shown in the logs, such as passwords or credit card numbers. + +* +config.helper_paths+ configures where Rails can find helpers for this application. + * +config.log_level+ defines the verbosity of the Rails logger. In production mode, this defaults to +:info+. In development mode, it defaults to +:debug+. * +config.log_path+ overrides the path to the log file to use. Defaults to +log/#{environment}.log+ (e.g. log/development.log or log/production.log). -* +config.middleware+ allows you to configure the application's middleware. This is covered in depth in the "Configuring Middleware" section below. - * +config.logger+ accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, which is then used to log information from Action Controller. Set to nil to disable logging. +* +config.middleware+ allows you to configure the application's middleware. This is covered in depth in the "Configuring Middleware" section below. + * +config.plugins+ accepts the list of plugins to load. If this is set to nil, all plugins will be loaded. If this is set to [], no plugins will be loaded. Otherwise, plugins will be loaded in the order specified. -* +config.preload_frameworks+ enables or disables preloading all frameworks at startup. +* +config.preload_frameworks+ enables or disables preloading all frameworks at startup. Can also be enabled with +threadsafe!+. Defaults to +nil+, so is disabled. * +config.reload_plugins+ enables or disables plugin reloading. * +config.root+ configures the root path of the application. +* +config.secret_token+ used for specifying a key which allows sessions for the application to be verified against a known secure key to prevent tampering. + * +config.serve_static_assets+ configures Rails to serve static assets. Defaults to _true_, but in the production environment is turned off. The server software used to run the application should be used to serve the assets instead. +* +config.threadsafe!+ enables +allow_concurrency+, +cache_classes+, +dependency_loading+ and +preload_frameworks+ to make the application threadsafe. + +WARNING: Threadsafe operation is incompatible with the normal workings of development mode Rails. In particular, automatic dependency loading and class reloading are automatically disabled when you call +config.threadsafe!+. + * +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_. @@ -198,15 +222,15 @@ h4. Configuring Action Controller <tt>config.action_controller</tt> includes a number of configuration settings: -* +config.action_controller.asset_host+ provides a string that is prepended to all of the URL-generating helpers in +AssetHelper+. This is designed to allow moving all javascript, CSS, and image files to a separate asset host. +* +config.action_controller.asset_host+ sets the host for the assets. Useful when CDNs are used for hosting assets rather than the application server itself. -* +config.action_controller.asset_path+ allows you to override the default asset path generation by providing your own instructions. +* +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.consider_all_requests_local+ is generally set to +true+ during development and +false+ during production; if it is set to +true+, then any error will cause detailed debugging information to be dumped in the HTTP response. For finer-grained control, set this to +false+ and implement +local_request?+ to specify which requests should provide debugging information on errors. +* +config.action_controller.page_cache_directory+ should be the document root for the web server and is set using <tt>Base.page_cache_directory = "/document/root"</tt>. For Rails, this directory has already been set to Rails.public_path (which is usually set to <tt>Rails.root + "/public"</tt>). Changing this setting can be useful to avoid naming conflicts with files in <tt>public/</tt>, but doing so will likely require configuring your web server to look in the new location for cached files. -* +config.action_controller.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. Instead, you should simply call +config.threadsafe!+ inside your +production.rb+ file, which makes all the necessary adjustments. +* +config.action_controller.page_cache_extension+ configures the extension used for cached pages saved to +page_cache_directory+. Defaults to +.html+ -WARNING: Threadsafe operation is incompatible with the normal workings of development mode Rails. In particular, automatic dependency loading and class reloading are automatically disabled when you call +config.threadsafe!+. +* +config.action_controller.perform_caching+ configures whether the application should perform caching or not. Set to _false_ in development mode, _true_ in production. * +config.action_controller.default_charset+ specifies the default character set for all renders. The default is "utf-8". @@ -236,6 +260,14 @@ h4. Configuring Action Dispatch * +config.action_dispatch.session_store+ sets the name of the store for session data. The default is +:cookie_store+; other valid options include +:active_record_store+, +:mem_cache_store+ or the name of your own custom class. +* +config.action_dispatch.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.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. + h4. Configuring Action View There are only a few configuration options for Action View, starting with four on +ActionView::Base+: @@ -250,6 +282,32 @@ 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: + +<ruby> + config.action_view.javascript_expansions = { :defaults => ['prototype', 'effects', 'dragdrop', 'controls', 'rails'] } +</ruby> + +However, you may add to this by defining others: + +<ruby> + config.action_view.javascript_expansions[:jquery] = ["jquery", "jquery-ui"] +</ruby> + +Then this can be referenced in the view with the following code: + +<ruby> + <%= javascript_include_tag :jquery %> +</ruby> + +* +config.action_view.stylesheet_expansions+ works in much the same way as +javascript_expansions+, but has no default key. Keys defined for this hash can be referenced in the view like such: + +<ruby> + <%= stylesheet_link_tag :special %> +</ruby> + +* +ActionView::Helpers::AssetTagHelper::AssetPaths.cache_asset_ids+ With the cache enabled, the asset tag helper methods will make fewer expensive file system calls (the default implementation checks the file system timestamp). However this prevents you from modifying any asset files while the server is running. + h4. Configuring Action Mailer There are a number of settings available on +config.action_mailer+: @@ -292,6 +350,8 @@ h4. Configuring Active Support There are a few configuration options available in Active Support: +* +config.active_support.bare+ enables or disables the loading of +active_support/all+ when booting Rails. Defaults to +nil+, which means +active_support/all+ is loaded. + * +config.active_support.escape_html_entities_in_json+ enables or disables the escaping of HTML entities in JSON serialization. Defaults to +true+. * +config.active_support.use_standard_json_time_format+ enables or disables serializing dates to ISO 8601 format. Defaults to +false+. @@ -302,41 +362,223 @@ There are a few configuration options available in Active Support: * +ActiveSupport::Logger.silencer+ is set to +false+ to disable the ability to silence logging in a block. The default is +true+. -h3. Using Initializers +h3. Rails Environment Settings -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 and plugins are loaded. +Some parts of Rails can also be configured externally by supplying environment variables. The following environment variables are recognized by various parts of Rails: -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. +* +ENV['RAILS_ENV']+ defines the Rails environment (production, development, test, and so on) that Rails will run under. -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+. +* +ENV['RAILS_RELATIVE_URL_ROOT']+ is used by the routing code to recognize URLs when you deploy your application to a subdirectory. -h3. Using an After-Initializer +* +ENV["RAILS_ASSET_ID"]+ will override the default cache-busting timestamps that Rails generates for downloadable assets. + +* +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. Initialization events + +Rails has 5 initialization events which can be hooked into (listed in order that they are ran): + +* +before_configuration+: This is run as soon as the application constant inherits from +Rails::Application+. The +config+ calls are evaluated before this happens. +* +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. +* +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. +* +after_initialize+: Run directly after the initialization of the application, but before the application initializers are run. + + +WARNING: Some parts of your application, notably observers and routing, are not yet set up at the point where the +after_initialize+ block is called. -After-initializers are run (as you might guess) after any initializers are loaded. You can supply an +after_initialize+ block (or an array of such blocks) by setting up +config.after_initialize+ in any of the Rails configuration files: +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: <ruby> -config.after_initialize do - SomeClass.init -end + initializer "active_support.initialize_whiny_nils" do |app| + require 'active_support/whiny_nil' if app.config.whiny_nils + end </ruby> -WARNING: Some parts of your application, notably observers and routing, are not yet set up at the point where the +after_initialize+ block is called. +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_. -h3. Rails Environment Settings +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. -Some parts of Rails can also be configured externally by supplying environment variables. The following environment variables are recognized by various parts of Rails: +WARNING: You may put your initializer before or after any other initializer in the chain, as long as it is logical. Say you have 4 initializers called "one" through "four" (defined in that order) and you define "four" to go _before_ "four" but _after_ "three", that just isn't logical and Rails will not be able to determine your initializer order. -* +ENV['RAILS_ENV']+ defines the Rails environment (production, development, test, and so on) that Rails will run under. +The block's argument of the +initialize+ is the instance of the application itself, and so we can access the configuration on it by using the +config+ method as this initializer does. -* +ENV['RAILS_RELATIVE_URL_ROOT']+ is used by the routing code to recognize URLs when you deploy your application to a subdirectory. +Because +Rails::Application+ inherits from +Rails::Railtie+ (indirectly), you can use the +initializer+ method in +config/application.rb+ to define initializers for the application. -* +ENV["RAILS_ASSET_ID"]+ will override the default cache-busting timestamps that Rails generates for downloadable assets. +Below is a comprehensive list of all the initializers found in Rails in the order that they are defined (and therefore run in, unless otherwise stated). -* +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. +h4. +load_environment_hook+ + +Serves as a placeholder so that +:load_environment_config+ can be defined to run before it. + +h4. +load_active_support+ + +Requires +active_support/dependencies+ which sets up the basis for Active Support. Optionally requires +active_support/all+ if +config.active_support.bare+ is un-truthful, which is the default. + +h4. +preload_frameworks+ + +Will load all autoload dependencies of Rails automatically if +config.preload_frameworks+ is +true+ or "truthful". By default this configuration option is disabled. In Rails, when internal classes are referenced for the first time they are autoloaded. +:preload_frameworks+ loads all of this at once on initialization. + +h4. +initialize_logger+ + +Initializes the logger (an +ActiveSupport::BufferedLogger+ object) for the application and makes it accessible at +Rails.logger+, providing that there's no initializer inserted before this point that has defined +Rails.logger+. + +h4. +initialize_cache+ + +If +RAILS_CACHE+ isn't yet set, initializes the cache by referencing the value in +config.cache_store+ and stores the outcome as +RAILS_CACHE+. If this object responds to the +middleware+ method, its middleware is inserted before +Rack::Runtime+ in the middleware stack. + +h4. +set_clear_dependencies_hook+ + +Provides a hook for +active_record.set_dispatch_hooks+ to use, which will run before this initializer. + +This initializer -- which runs only if +cache_classes+ is set to +false+ -- uses +ActionDispatch::Callbacks.after+ to remove the constants which have been referenced during the request from the object space so that they will be reloaded during the following request. + +h4. +initialize_dependency_mechanism+ + +If +config.cache_classes+ is set to +true+, configures +ActiveSupport::Dependencies.mechanism+ to +require+ dependencies rather than +load+ them. + +h4. +bootstrap_hook+ + +Runs all configured +before_initialize+ blocks. + +h4. +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. + +h4. +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: + +<text> + Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id +</text> + +And: + +<text> + 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.each +</text> + +h4. +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. + +h4. +active_support.initialize_time_zone+ + +Sets the default time zone for the application based off the +config.time_zone+ setting, which defaults to "UTC". + +h4. +action_dispatch.configure+ + +Configures the +ActionDispatch::Http::URL.tld_length+ to be set to the value of +config.action_dispatch.tld_length+. + +h4. +action_view.cache_asset_ids+ + +Will set +ActionView::Helpers::AssetTagHelper::AssetPaths.cache_asset_ids+ to +false+ when Active Support loads, but only if +config.cache_classes+ is too. + +h4. +action_view.javascript_expansions+ + +Registers the expansions set up by +config.action_view.javascript_expansions+ and +config.action_view.stylesheet_expansions+ to be recognised by Action View and therefore usable in the views. + +h4. +action_view.set_configs+ + +Sets up Action View by using the settings in +config.action_view+ by +send+'ing the method names as setters to +ActionView::Base+ and passing the values through. + +h4. +action_controller.logger+ + +Sets +ActionController::Base.logger+ -- if it's not already set -- to +Rails.logger+. + +h4. +action_controller.initialize_framework_caches+ + +Sets +ActionController::Base.cache_store+ -- if it's not already set -- to +RAILS_CACHE+. + +h4. +action_controller.set_configs+ + +Sets up Action Controller by using the settings in +config.action_controller+ by +send+'ing the method names as setters to +ActionController::Base+ and passing the values through. + +h4. +action_controller.compile_config_methods+ + +Initializes methods for the config settings specified so that they are quicker to access. + +h4. +active_record.initialize_timezone+ + +Sets +ActiveRecord::Base.time_zone_aware_attributes+ to true, as well as setting +ActiveRecord::Base.default_timezone+ to UTC. When attributes are read from the database, they will be converted into the time zone specified by +Time.zone+. + +h4. +active_record.logger+ + +Sets +ActiveRecord::Base.logger+ -- if it's not already set -- to +Rails.logger+. + +h4. +active_record.set_configs+ + +Sets up Active Record by using the settings in +config.active_record+ by +send+'ing the method names as setters to +ActiveRecord::Base+ and passing the values through. + +h4. +active_record.initialize_database+ + +Loads the database configuration (by default) from +config/database.yml+ and establishes a connection for the current environment. + +h4. +active_record.log_runtime+ + +Includes +ActiveRecord::Railties::ControllerRuntime+ which is responsible for reporting the length of time Active Record calls took for the request back to the logger. + +h4. +active_record.set_dispatch_hooks+ + +If +config.cache_classes+ is set to false, all reloadable connections to the database will be reset. + +h4. +action_mailer.logger+ + +Sets +ActionMailer::Base.logger+ -- if it's not already set -- to +Rails.logger+. + +h4. +action_mailer.set_configs+ + +Sets up Action Mailer by using the settings in +config.action_mailer+ by +send+'ing the method names as setters to +ActionMailer::Base+ and passing the values through. + +h4. +action_mailer.compile_config_methods+ + +Initializes methods for the config settings specified so that they are quicker to access. + +h4. +active_resource.set_configs+ + +Sets up Active Resource by using the settings in +config.active_resource+ by +send+'ing the method names as setters to +ActiveResource::Base+ and passing the values through. + +h4. +set_load_path+ + +This initializer runs before +bootstrap_hook+. Adds the +vendor+, +lib+, all directories of +app+ and any paths specified by +config.load_paths+ to +$LOAD_PATH+. + +h4. +set_autoload_path+ + +This initializer runs before +bootstrap_hook+. Adds all sub-directories of +app+ and paths specified by +config.autoload_paths+ to +ActiveSupport::Dependencies.autoload_paths+. + +h4. +add_routing_paths+ + +Loads (by default) all +config/routes.rb+ files (in the application and railties, including engines) and sets up the routes for the application. + +h4. +add_locales+ + +Adds the files in +config/locales+ (from the application, railties and engines) to +I18n.load_path+, making available the translations in these files. + +h4. +add_view_paths+ + +Adds the directory +app/views+ from the application, railties and engines to the lookup path for view files for the application. + +h4. +load_environment_config+ + + + +h4. Initializer files + +After loading the framework and any gems and plugins in your application, Rails turns to loading initialization code from +config/initializers+. The files in this directory can be used to hold configuration settings that should be made after all of the frameworks and plugins are loaded. + +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. Changelog -* November 26, 2010: Removed all config settings not available in Rails 3 (Ryan Bigg) +* December 3, 2010: Added initialization events for Rails 3 ("Ryan Bigg":http://ryanbigg.com) +* November 26, 2010: Removed all config settings not available in Rails 3 ("Ryan Bigg":http://ryanbigg.com) * August 13, 2009: Updated with config syntax and added general configuration options by "John Pignata" * January 3, 2009: First reasonably complete draft by "Mike Gunderloy":credits.html#mgunderloy * November 5, 2008: Rough outline by "Mike Gunderloy":credits.html#mgunderloy diff --git a/railties/guides/source/contributing_to_rails.textile b/railties/guides/source/contributing_to_rails.textile index ccb9db5eee..1a1f4e9858 100644 --- a/railties/guides/source/contributing_to_rails.textile +++ b/railties/guides/source/contributing_to_rails.textile @@ -132,7 +132,7 @@ You can now run tests as you did for +sqlite3+: rake test_mysql </shell> -You can also replace +myqsl+ 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. +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. diff --git a/railties/guides/source/generators.textile b/railties/guides/source/generators.textile index 99c34ed30f..a0d744333f 100644 --- a/railties/guides/source/generators.textile +++ b/railties/guides/source/generators.textile @@ -1,4 +1,4 @@ -h2. Creating and Customizing Rails Generators +h2. Creating and Customizing Rails Generators & Templates Rails generators are an essential tool if you plan to improve your workflow. With this guide you will learn how to create generators and customize existing ones. @@ -10,6 +10,7 @@ In this guide you will: * Customize your scaffold by creating new generators * Customize your scaffold by changing generator templates * Learn how to use fallbacks to avoid overwriting a huge set of generators +* Learn how to create an application template endprologue. @@ -45,6 +46,8 @@ class InitializerGenerator < Rails::Generators::Base end </ruby> +NOTE: +create_file+ is a method provided by +Thor::Actions+ and the documentation for it and its brethren can be found at "rdoc.info":http://rdoc.info/github/wycats/thor/master/Thor/Actions. + Our new generator is quite simple: it inherits from +Rails::Generators::Base+ and has one method definition. Each public method in the generator is executed when a generator is invoked. Finally, we invoke the +create_file+ method that will create a file at the given destination with the given content. If you are familiar with the Rails Application Templates API, you'll feel right at home with the new generators API. To invoke our new generator, we just need to do: @@ -131,6 +134,8 @@ $ rails generate initializer core_extensions We can see that now a initializer named core_extensions was created at +config/initializers/core_extensions.rb+ with the contents of our template. That means that +copy_file+ copied a file in our source root to the destination path we gave. The method +file_name+ is automatically created when we inherit from +Rails::Generators::NamedBase+. +The methods that are available for generators are covered in the "final section":#generator_methods of this guide. + h3. Generators Lookup When you run +rails generate initializer core_extensions+ Rails requires these files in turn until one is found: @@ -361,8 +366,258 @@ $ rails generate scaffold Comment body:text Fallbacks allow your generators to have a single responsibility, increasing code reuse and reducing the amount of duplication. +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". + +<ruby> + 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 +</ruby> + +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. + +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: + +<shell> + rails new thud -m template.rb +</shell> + +This command will generate the +Thud+ application, and then apply the template to the generated output. + +Templates don't have to be stored on the local system, the +-m+ option also supports online templates: + +<shell> + rails new thud -m https://gist.github.com/722911 +</shell> + +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. + +h3. Generator methods + +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 + +h4. +plugin+ + ++plugin+ will install a plugin into the current application. + +<ruby> + plugin("dynamic-form", :git => "git://github.com/rails/dynamic-form.git") +</ruby> + +Available options are: + +* +:git+ - Takes the path to the git repository where this plugin can be found. +* +:branch+ - The name of the branch of the git repository where the plugin is found. +* +:submodule+ - Set to +true+ for the plugin to be installed as a submodule. Defaults to +false+. +* +:svn+ - Takes the path to the svn repository where this plugin can be found. +* +:revision+ - The revision of the plugin in an SVN repository. + +h4. +gem+ + +Specifies a gem dependency of the application. + +<ruby> + gem("rspec", :group => "test", :version => "2.1.0") + gem("devise", "1.1.5") +</ruby> + +Available options are: + +* +:group+ - The group in the +Gemfile+ where this gem should go. +* +:version+ - The version string of the gem you want to use. Can also be specified as the second argument to the method. +* +:git+ - The URL to the git repository for this gem. + +Any additional options passed to this method are put on the end of the line: + +<ruby> + gem("devise", :git => "git://github.com/plataformatec/devise", :branch => "master") +</ruby> + +The above code will put the following line into +Gemfile+: + +<ruby> + gem "devise", :git => "git://github.com/plataformatec/devise", :branch => "master" +</ruby> + + +h4. +add_source+ + +Adds a specified source to +Gemfile+: + +<ruby> + add_source "http://gems.github.com" +</ruby> + +h4. +application+ + +Adds a line to +config/application.rb+ directly after the application class definition. + +<ruby> + application "config.asset_host = 'http://example.com'" +</ruby> + +This method can also take a block: + +<ruby> + application do + "config.asset_host = 'http://example.com'" + end + end +</ruby> + +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: + +<ruby> + application(nil, :env => "development") do + "config.asset_host = 'http://localhost:3000'" + end +</ruby> + +h4. +git+ + +Runs the specified git command: + +<ruby> + git :init + git :add => "." + git :commit => "-m First commit!" + git :add => "onefile.rb", :rm => "badfile.cxx" +</ruby> + +The values of the hash here being the arguments or options passed to the specific git command. As per the final example shown here, multiple git commands can be specified at a time, but the order of their running is not guaranteed to be the same as the order that they were specified in. + +h4. +vendor+ + +Places a file into +vendor+ which contains the specified code. + +<ruby> + vendor("sekrit.rb", '#top secret stuff') +</ruby> + +This method also takes a block: + +<ruby> + vendor("seeds.rb") do + "puts 'in ur app, seeding ur database'" + end +</ruby> + +h4. +lib+ + +Places a file into +lib+ which contains the specified code. + +<ruby> + lib("special.rb", 'p Rails.root') +</ruby> + +This method also takes a block: + +<ruby> + lib("super_special.rb") do + puts "Super special!" + end +</ruby> + +h4. +rakefile+ + +Creates a Rake file in the +lib/tasks+ directory of the application. + +<ruby> + rakefile("test.rake", 'hello there') +</ruby> + +This method also takes a block: + +<ruby> + rakefile("test.rake") do + %Q{ + task :rock => :environment do + puts "Rockin'" + end + } + end +</ruby> + +h4. +initializer+ + +Creates an initializer in the +config/initializers+ directory of the application: + +<ruby> + initializer("begin.rb", "puts 'this is the beginning'") +</ruby> + +This method also takes a block: + +<ruby> + initializer("begin.rb") do + puts "Almost done!" + end +</ruby> + +h4. +generate+ + +Runs the specified generator where the first argument is the generator name and the remaining arguments are passed directly to the generator. + +<ruby> + generate("scaffold", "forums title:string description:text") +</ruby> + + +h4. +rake+ + +Runs the specified Rake task. + +<ruby> + rake("db:migrate") +</ruby> + +Available options are: + +* +:env+ - Specifies the environment in which to run this rake task. +* +:sudo+ - Whether or not to run this task using +sudo+. Defaults to +false+. + +h4. +capify!+ + +Runs the +capify+ command from Capistrano at the root of the application which generates Capistrano configuration. + +<ruby> + capify! +</ruby> + +h4. +route+ + +Adds text to the +config/routes.rb+ file: + +<ruby> + route("resources :people") +</ruby> + +h4. +readme+ + +Output the contents of a file in the template's +source_path+, usually a README. + +<ruby> + readme("README") +</ruby> + h3. Changelog +* December 1, 2010: Documenting the available methods and options for generators and templates by "Ryan Bigg":http://ryanbigg.com +* December 1, 2010: Addition of Rails application templates by "Ryan Bigg":http://ryanbigg.com + * August 23, 2010: Edit pass by "Xavier Noria":credits.html#fxn * April 30, 2010: Reviewed by José Valim diff --git a/railties/guides/source/i18n.textile b/railties/guides/source/i18n.textile index 25c24ac7d7..8a39bdf3c1 100644 --- a/railties/guides/source/i18n.textile +++ b/railties/guides/source/i18n.textile @@ -830,7 +830,7 @@ In other contexts you might want to change this behaviour, though. E.g. the defa <ruby> module I18n - def just_raise_that_exception(*args) + def self.just_raise_that_exception(*args) raise args.first end end diff --git a/railties/guides/source/security.textile b/railties/guides/source/security.textile index 5b24d8c8e3..528c8861d4 100644 --- a/railties/guides/source/security.textile +++ b/railties/guides/source/security.textile @@ -166,7 +166,7 @@ end The section about session fixation introduced the problem of maintained sessions. An attacker maintaining a session every five minutes can keep the session alive forever, although you are expiring sessions. A simple solution for this would be to add a created_at column to the sessions table. Now you can delete sessions that were created a long time ago. Use this line in the sweep method above: <ruby> -delete_all "updated_at < '#{time.to_s(:db)}' OR +delete_all "updated_at < '#{time.ago.to_s(:db)}' OR created_at < '#{2.days.ago.to_s(:db)}'" </ruby> |