From 6e76595b4cfc6ce1b5d1728c5e0bbec5a7b12835 Mon Sep 17 00:00:00 2001 From: Jason Lee Date: Thu, 5 Apr 2012 13:33:12 +0800 Subject: [PATCH 01/11] =?UTF-8?q?Action=20Mailer=20guides=20=E7=BF=BB?= =?UTF-8?q?=E8=AF=91=E4=BA=86=E5=89=8D=E9=9D=A2=E4=B8=80=E9=83=A8=E5=88=86?= =?UTF-8?q?=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- source/CN/action_mailer_basics.textile | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/source/CN/action_mailer_basics.textile b/source/CN/action_mailer_basics.textile index c277f76..204ddc5 100644 --- a/source/CN/action_mailer_basics.textile +++ b/source/CN/action_mailer_basics.textile @@ -1,22 +1,22 @@ h2. Action Mailer Basics -This guide should provide you with all you need to get started in sending and receiving emails from and to your application, and many internals of Action Mailer. It also covers how to test your mailers. +本教程将告诉你如何让你的应用程序可以发送和接收邮件,还有 Action Mailer 的一些内部原理。 同时也包括如何编写 Mailer 的测试。 endprologue. -WARNING. This Guide is based on Rails 3.0. Some of the code shown here will not work in earlier versions of Rails. +警告. 本教程是基于 Rails 3.0 , 一些代码可能无法在旧版本的 Rails 中运行。 -h3. Introduction +h3. 简介 -Action Mailer allows you to send emails from your application using a mailer model and views. So, in Rails, emails are used by creating mailers that inherit from +ActionMailer::Base+ and live in +app/mailers+. Those mailers have associated views that appear alongside controller views in +app/views+. +Action Mailer 让你的应用可以用一个 mailer 的 model 和 views 来发送邮件。所以,在 Rails 里面,邮件是通过一个继承至 +ActionMailer::Base+ 的 mailer 来创建的,并存放在 +app/mailers+ 目录下面。这些 mailer 将依靠在 +app/views+ 目录下面对应名称的 view 来生成。 -h3. Sending Emails +h3. 发送邮件 -This section will provide a step-by-step guide to creating a mailer and its views. +本节将一步一步的教你创建一个 mailer 和它对应的 views。 -h4. Walkthrough to Generating a Mailer +h4. 生成一个 Mailer -h5. Create the Mailer +h5. 创建 Mailer $ rails generate mailer UserMailer @@ -27,11 +27,11 @@ invoke test_unit create test/functional/user_mailer_test.rb -So we got the mailer, the views, and the tests. +现在就有了一个 mailer, 还有它的 view 和 test 文件. -h5. Edit the Mailer +h5. 修改 Mailer -+app/mailers/user_mailer.rb+ contains an empty mailer: ++app/mailers/user_mailer.rb+ 里面有个空的 mailer 类: class UserMailer < ActionMailer::Base @@ -39,7 +39,7 @@ class UserMailer < ActionMailer::Base end -Let's add a method called +welcome_email+, that will send an email to the user's registered email address: +让我们来添加一个叫 +welcome_email+ 的方法, 它将用于发送用户注册成功的邮件: class UserMailer < ActionMailer::Base @@ -48,7 +48,7 @@ class UserMailer < ActionMailer::Base def welcome_email(user) @user = user @url = "http://example.com/login" - mail(:to => user.email, :subject => "Welcome to My Awesome Site") + mail(:to => user.email, :subject => "欢迎来到某某网站") end end From b24414bd624e323d2134f9ae4929e854be7f7d0d Mon Sep 17 00:00:00 2001 From: fenprace Date: Sat, 7 Apr 2012 09:31:32 +0800 Subject: [PATCH 02/11] =?UTF-8?q?=E8=B0=83=E6=95=B4=E8=BE=9E=E6=8E=AA?= =?UTF-8?q?=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- source/CN/getting_started.textile | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/source/CN/getting_started.textile b/source/CN/getting_started.textile index c1b7e35..756dafa 100644 --- a/source/CN/getting_started.textile +++ b/source/CN/getting_started.textile @@ -9,19 +9,19 @@ h2. 与Rails的第一次接触 endprologue. -WARNING. 这个指导手册适用与 Rails 3.1,有些代码在 Rails 早期版本可能会不工作。 +WARNING. 这个指导手册适用与 Rails 3.1,有些代码在 Rails 早期版本可能无法正常运行。 h3. 手册假设 本指导设计给那些想大概的了解 Rails 应用创建的初学者。这里假设你对 Rails 没有任何预先的了解。要得到(本手册的)知识,你需要预先安装: -* "Ruby":http://www.ruby-lang.org/en/downloads version 1.8.7 或者更高 +* "Ruby":http://www.ruby-lang.org/en/downloads version 1.8.7 或者更高版本 -TIP: 注意 Ruby 1.8.7 p248 and p249 有 marshaling bugs 会与 Rails 3.0 发生冲突。Ruby 1.8.7 p248 and p249在 发行版 1.8.7-2010.02 已经得到解决。Ruby 1.9 前提下,Ruby 1.9.1 不能使用因为它在 Rails 3.0 上会出现 segfaults 错误,因此如果你希望使用 Rails 3 和 1.9.x 跳至 1.9.2 (就可以)安全地使用 Rails。 +TIP: 注意 Ruby 1.8.7 p248 和 p249 有 marshaling bugs ,会与 Rails 3.0 发生冲突。Ruby 1.8.7 p248 和 p249在 发行版 1.8.7-2010.02 已经得到解决。Ruby 1.9 下 Ruby 1.9.1 不能使用,因为它在 Rails 3.0 上会出现 segfaults 错误,因此如果你希望使用 Rails 3 和 1.9.x ,更新版本到 1.9.2 就可以安全地使用 Rails。 * "RubyGems":http://rubyforge.org/frs/?group_id=126 包管理系统 - ** 如果你想了解更多关于RubyGems,请阅读 "RubyGems User Guide":http://docs.rubygems.org/read/book/1 + ** 如果你想了解更多关于 RubyGems 的知识,请阅读 "RubyGems User Guide":http://docs.rubygems.org/read/book/1 * 安装 "SQLite3 Database":http://www.sqlite.org Rails是一个基于Ruby程序语言的web程序框架。如果你没有预先的学习ruby,你会发现直接的入门Rails学习很有跨度。这里有一些学习ruby的免费互联网资源。 @@ -41,7 +41,7 @@ Rails是一个值得骄傲的软件。它使得我们以最好的方式去做事 Rails 理念包含几个指导原则 * DRY - 不要自己重复——建议一次又一次编写同样的代码是一件坏事请。 -* 约定优于配置——意思是 Rails 假设对于你想做什么以及你想怎么做的事情,刻意的做很少的事情比编写无尽的配置文件更好 +* 约定优于配置——意思是 Rails 假设对于你想做什么以及你想怎么做的事情,刻意的做很少的事情比编写无尽的配置文件更好。 h4. MVC架构 From 34e9f2f34e15c5937400dc7878edfa62ce9b921e Mon Sep 17 00:00:00 2001 From: fenprace Date: Sat, 7 Apr 2012 09:33:35 +0800 Subject: [PATCH 03/11] =?UTF-8?q?=E8=BE=9E=E6=8E=AA=E8=B0=83=E6=95=B4?= =?UTF-8?q?=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- source/CN/getting_started.textile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source/CN/getting_started.textile b/source/CN/getting_started.textile index 756dafa..ada71e1 100644 --- a/source/CN/getting_started.textile +++ b/source/CN/getting_started.textile @@ -40,8 +40,8 @@ Rails是一个值得骄傲的软件。它使得我们以最好的方式去做事 Rails 理念包含几个指导原则 -* DRY - 不要自己重复——建议一次又一次编写同样的代码是一件坏事请。 -* 约定优于配置——意思是 Rails 假设对于你想做什么以及你想怎么做的事情,刻意的做很少的事情比编写无尽的配置文件更好。 +* DRY - 不要自己重复——建议一次又一次编写同样的代码是一件坏事请 +* 约定优于配置——意思是 Rails 假设对于你想做什么以及你想怎么做的事情,刻意的做很少的事情比编写无尽的配置文件更好 h4. MVC架构 From c071cd0a9e55b00f094b330efaade06e1178435f Mon Sep 17 00:00:00 2001 From: fenprace Date: Sat, 7 Apr 2012 09:48:33 +0800 Subject: [PATCH 04/11] =?UTF-8?q?=E8=BE=9E=E6=8E=AA=E8=B0=83=E6=95=B4?= =?UTF-8?q?=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- source/CN/getting_started.textile | 40 +++++++++++++++---------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/source/CN/getting_started.textile b/source/CN/getting_started.textile index ada71e1..5ae9220 100644 --- a/source/CN/getting_started.textile +++ b/source/CN/getting_started.textile @@ -50,56 +50,56 @@ Model,View,Controller架构是Rails的核心,通常称之为MVC。MVC 的 * 很容易使得代码保持 DRY # “Don’t Repeat Yourself” * 明确代码的不同之处使之跟容易维护 -h5. 模型 +h5. 模型( Models ) 模型代表了应用程序的信息(数据)和操纵这些数据的规则。在 Rails 中, models 主要用于管理数据表和相应的规则的互动。在大多数情况,在你数据库中的每个表都会和你的应用程序互动。你应用程序的逻辑业务将会集中放置在 models 中。 -h5. 视图 +h5. 视图( Views ) -View代表了应用程序的用户界面。在Rails中,Views通常是嵌入了执行演示数据任务的Ruby代码的HTML文件。Views完成了给web浏览器或者其他工具用于提出来自你的程序的请求提供数据。 +View代表了应用程序的用户界面。在 Rails 中,Views 通常是嵌入了执行演示数据任务的Ruby代码的HTML文件。Views完成了给web浏览器或者其他工具用于提出来自你的程序的请求提供数据。 -h5. 控制器 +h5. 控制器( Controllers ) -Controllers 提供了models和视图间的粘合。在 Rails 中,controllers 相应来自 web 浏览器请求的进程,向 models 询问数据以及传递数据给 views 用于呈现。 +Controllers 提供了 Models 和 Views 间的粘合。在 Rails 中,Controllers 响应来自 Web 浏览器请求的进程,向 Models 询问数据并将数据传递给 Views 呈现。 h3. Rails 的组件 -Rails关联着许多独立的组件。对这些组件在下面给出简要的解释。如果你是Rails的新人,当你阅读到这个部分,不要抛弃任何一个组件的描述,而且他们还会做进一步解释。例如,我们将会构造应用骨架,但是在这里,你不需要知道关于他们的更进一步的任何知识。 +Rails 关联着许多独立的组件。对这些组件在下面给出简要的解释。如果你是 Rails 的新人,当你阅读到这个部分时,不要忽视任何一个组件的描述,但也没有必要了解的过于深入。例如,我们会构造应用骨架,但你不需要了解有关构造应用骨架的深层知识。 -* Action Pack活动组 - ** Action Controller 活动控制 - ** Action Dispatch 活动传输 - ** Action View 活动视图 -* Action Mailer 活动信封 -* Active Model -* Active Record +* Action Pack + ** Action Controller + ** Action Dispatch + ** Action View +* Action Mailer +* Active Model +* Active Record * Active Resource * Active Support * Railties h4. Action Pack -Action Pack是一个单独的包它包含了 Action Controller, Action View and Action Dispatch(传输调度)。是MVC的VC部分。 +Action Pack是一个单独的包它包含了 Action Controller, Action View and Action Dispatch(传输调度)。是 MVC 的 VC 部分。 h5. Action Controller -Action Controller是在Rails中管理控制的组件。 The Action Controller框架进程收到Rails应用程序的请求,提取参数,以及调度他们到具有相应义务的动作。这些服务是由 Action Controller包含了会话管理部分,模板渲染(翻译),重定向部分。 +Action Controller 是在 Rails 中管理控制的组件。 The Action Controller 框架进程收到 Rails 应用程序的请求,提取参数,以及调度他们到具有相应义务的动作。这些服务是由 Action Controller 提供,包含会话管理、模板渲染、重定向功能。 h5. Action Dispatch -Action Dispatch处理了你的和其他部分的应用程序的路由——这些web请求以及一些你所期望的调度。Rack applications 是更高级的主题它涵盖在一个叫做 "Rails on Rack":http://guides.rubyonrails.org/rails_on_rack.html 的教程中。 +Action Dispatch处理了你和其他部分的应用程序的路由——一些Web请求以及你的配置。Rack applications 是更高级的模块,你可以到 "Rails on Rack":http://guides.rubyonrails.org/rails_on_rack.html 了解它。 h5. Action Mailer -Action Mailer 是一个营造 E-mail 服务的框架。你可以使用 Action Mailer 去发送、接收 email 以及发送一些简单的计划文本或者基于灵活模板的复杂的多重的电子邮件。 +Action Mailer 是一个营造 E-mail 服务的框架。你可以使用 Action Mailer 去发送、接收 Email 。 h5. Active Model -Active Model 提供了 Action Pack gem 服务和 Object Relationship Mapping gems 之间的接口定义,比如Active记录。Active Model 允许 Rails 在 Active Record 部分采用其他 ORM 框架如果你的应用程序需要。 +Active Model 提供了 Action Pack gem 服务和 Object Relationship Mapping gems 之间的接口定义,比如 Active 记录。Active Model 允许 Rails 在 Active Record 部分采用其他 ORM 框架如果你的应用程序需要。 h5. Active Record -Active Record 是一个 Rails 应用程序的 models 根本。它提供独立的数据库,基于 CRUD 功能,先进(高级)的查找能力,和与另一个 models 关联的能力,几乎所有其他服务。 +Active Record 是一个 Rails 应用程序的 Models 根本。它提供有 CRUD 功能独立的数据库,有高级的查找、与另一个 Models 关联的能力,支持几乎所有数据库服务。 h5. Active Resource @@ -107,7 +107,7 @@ Active Resource提供一个管理目标业务和 RESTful web 服务之间连接 h5. Active Support -Active Support 是一个广泛收集实用工具类和标准的 Ruby 库的扩展,它们由的核心代码和您的应用程序(决定)。 +Active Support 是一个广泛收集实用工具类和标准的 Ruby 库的扩展,它们由的核心代码和您的应用程序决定。 h5. Railties From e2fe901599b8cc06c488df88b9043bd232cc4a56 Mon Sep 17 00:00:00 2001 From: ichord Date: Sat, 7 Apr 2012 23:08:52 +0800 Subject: [PATCH 05/11] translate rails configurations --- README.markdown | 2 + source/CN/configuring.textile | 757 +--------------------------------- source/documents_CN.yaml | 4 +- 3 files changed, 21 insertions(+), 742 deletions(-) diff --git a/README.markdown b/README.markdown index ec2638e..586cfc1 100644 --- a/README.markdown +++ b/README.markdown @@ -1,6 +1,8 @@ # Ruby on Rails Guides 中文指南 如果你也想为 Ruby on Rails 社区出一份力就从这里开始吧! + +http://www.railschina.org/ ## Rails Guides 中文 diff --git a/source/CN/configuring.textile b/source/CN/configuring.textile index cf0d8f1..4061c1a 100644 --- a/source/CN/configuring.textile +++ b/source/CN/configuring.textile @@ -1,762 +1,37 @@ -h2. Configuring Rails Applications +h2. 配置 Rails 应用程序 -This guide covers the configuration and initialization features available to Rails applications. By referring to this guide, you will be able to: +这个指南覆盖了Rails应用可以使用的配置和初始化设置.通过浏览这个指南,你将能: -* Adjust the behavior of your Rails applications -* Add additional code to be run at application start time +* 控制Rails应用的行为 +* 添加在程序启动时运行的代码 -endprologue. +h3. 初始化代码的为止 -h3. Locations for Initialization Code - -Rails offers four standard spots to place initialization code: +Rails 提供四个标准的位置防止初始化代码 * +config/application.rb+ -* Environment-specific configuration files -* Initializers -* After-initializers +* 运行环境相关的配置文件 +* 各初始化文件 +* 初始化后运行文件 -h3. Running Code Before Rails +h3. 先于Rails运行代码 -In the rare event that your application needs to run some code before Rails itself is loaded, put it above the call to +require 'rails/all'+ in +config/application.rb+. +有时候你需要在 Rails 加载自己之前运行代码, 将调入代码放在 +config/application.rb+ 文件的 +require 'rails/all'+ 之上. -h3. Configuring Rails Components +h3. 配置 Rails 组件 -In general, the work of configuring Rails means configuring the components of Rails, as well as configuring Rails itself. The configuration file +config/application.rb+ and environment-specific configuration files (such as +config/environments/production.rb+) allow you to specify the various settings that you want to pass down to all of the components. +一般而言, 配置Rails的工作其实就是配置Rails的组件, 就像配置Rails本身一样. 配置文件+config/application.rb+ 和运行环境相关的配置文件(比如 +config/environments/production.br+) 可以让你设定一些你想传递给所有组件的设置. -For example, the default +config/application.rb+ file includes this setting: +例如, 缺省的 +config/application.rb+ 文件包括这个设置: config.filter_parameters += [:password] -This is a setting for Rails itself. If you want to pass settings to individual Rails components, you can do so via the same +config+ object in +config/application.rb+: +这是给Rails本身的设置. 如果你想向单独的Rails组件传递设置, 你同样可以在+config/application.rb+文件里通过同一个+config+对象做一样的操作. config.active_record.observers = [:hotel_observer, :review_observer] -Rails will use that particular setting to configure Active Record. - -h4. Rails General Configuration - -These configuration methods are to be called on a +Rails::Railtie+ object, such as a subclass of +Rails::Engine+ or +Rails::Application+. - -* +config.after_initialize+ takes a block which will be run _after_ Rails has finished initializing the application. That includes the initialization of the framework itself, engines, and all the application's initializers in +config/initializers+. Note that this block _will_ be run for rake tasks. Useful for configuring values set up by other initializers: - - -config.after_initialize do - ActionView::Base.sanitized_allowed_tags.delete 'div' -end - - -* +config.allow_concurrency+ should be true to allow concurrent (threadsafe) action processing. 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, or when you want to work around the concurrency constraints builtin in browsers using different domain aliases. Shorter version of +config.action_controller.asset_host+. - -* +config.asset_path+ lets you decorate asset paths. This can be a callable, a string, or be +nil+ which is the default. For example, the normal path for +blog.js+ would be +/javascripts/blog.js+, let that absolute path be +path+. If +config.asset_path+ is a callable, Rails calls it when generating asset paths passing +path+ as argument. If +config.asset_path+ is a string, it is expected to be a +sprintf+ format string with a +%s+ where +path+ will get inserted. In either case, Rails outputs the decorated path. Shorter version of +config.action_controller.asset_path+. - - -config.asset_path = proc { |path| "/blog/public#{path}" } - - -NOTE. The +config.asset_path+ configuration is ignored if the asset pipeline is enabled, which is the default. - -* +config.autoload_once_paths+ accepts an array of paths from which Rails will autoload constants that won't be wiped per request. Relevant if +config.cache_classes+ is false, which is the case in development mode by default. Otherwise, all autoloading happens only once. All elements of this array must also be in +autoload_paths+. Default is an empty array. - -* +config.autoload_paths+ accepts an array of paths from which Rails will autoload constants. Default is all directories under +app+. - -* +config.cache_classes+ controls whether or not application classes and modules should be reloaded on each request. Defaults to false in development mode, and true in test and production modes. 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 one of the symbols +:memory_store+, +:file_store+, +:mem_cache_store+, or an object that implements the cache API. Defaults to +:file_store+ if the directory +tmp/cache+ exists, and to +:memory_store+ otherwise. - -* +config.colorize_logging+ specifies whether or not to use ANSI color codes when logging information. Defaults to true. - -* +config.consider_all_requests_local+ is a flag. If true then any error will cause detailed debugging information to be dumped in the HTTP response, and the +Rails::Info+ controller will show the application runtime context in +/rails/info/properties+. True by default in development and test environments, and false in production mode. 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.dependency_loading+ is a flag that allows you to disable constant autoloading setting it to false. It only has effect if +config.cache_classes+ is true, which it is by default in production mode. This flag is set to false by +config.threadsafe!+. - -* +config.eager_load_paths+ accepts an array of paths from which Rails will eager load on boot if cache classes is enabled. Defaults to every folder in the +app+ directory of the application. - -* +config.encoding+ sets up the application-wide encoding. Defaults to UTF-8. - -* +config.exceptions_app+ sets the exceptions application invoked by the ShowException middleware when an exception happens. Defaults to +ActionDispatch::PublicExceptions.new(Rails.public_path)+. - -* +config.file_watcher+ the class used to detect file updates in the filesystem when +config.reload_classes_only_on_change+ is true. Must conform to +ActiveSupport::FileUpdateChecker+ API. - -* +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.force_ssl+ forces all requests to be under HTTPS protocol by using +ActionDispatch::SSL+ middleware. - -* +config.log_level+ defines the verbosity of the Rails logger. This option defaults to +:debug+ for all modes except production, where it defaults to +:info+. - -* +config.log_tags+ accepts a list of methods that respond to +request+ object. This makes it easy to tag log lines with debug information like subdomain and request id -- both very helpful in debugging multi-user production applications. - -* +config.logger+ accepts a logger conforming to the interface of Log4r or the default Ruby +Logger+ class. Defaults to an instance of +ActiveSupport::BufferedLogger+, with auto flushing off in production mode. - -* +config.middleware+ allows you to configure the application's middleware. This is covered in depth in the "Configuring Middleware":#configuring-middleware section below. - -* +config.preload_frameworks+ enables or disables preloading all frameworks at startup. Enabled by +config.threadsafe!+. Defaults to +nil+, so is disabled. - -* +config.reload_classes_only_on_change+ enables or disables reloading of classes only when tracked files change. By default tracks everything on autoload paths and is set to true. If +config.cache_classes+ is true, this option is ignored. - -* +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. Applications get +config.secret_token+ initialized to a random key in +config/initializers/secret_token.rb+. - -* +config.serve_static_assets+ configures Rails itself to serve static assets. Defaults to true, but in the production environment is turned off as the server software (e.g. Nginx or Apache) used to run the application should serve static assets instead. Unlike the default setting set this to true when running (absolutely not recommended!) or testing your app in production mode using WEBrick. Otherwise you won´t be able use page caching and requests for files that exist regularly under the public directory will anyway hit your Rails app. - -* +config.session_store+ is usually set up in +config/initializers/session_store.rb+ and specifies what class to use to store the session. Possible values are +:cookie_store+ which is the default, +:mem_cache_store+, and +:disabled+. The last one tells Rails not to deal with sessions. Custom session stores can also be specified: - - -config.session_store :my_custom_store - - -This custom store must be defined as +ActionDispatch::Session::MyCustomStore+. In addition to symbols, they can also be objects implementing a certain API, like +ActiveRecord::SessionStore+, in which case no special namespace is required. - -* +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 disables warnings when a certain set of methods are invoked on +nil+ and it does not respond to them. Defaults to true in development and test environments. - -* +config.console+ allows you to set class that will be used as console you run +rails console+. It's best to run it in +console+ block: - - -console do - # this block is called only when running console, - # so we can safely require pry here - require "pry" - config.console = Pry -end - - -h4. Configuring Assets - -Rails 3.1, by default, is set up to use the +sprockets+ gem to manage assets within an application. This gem concatenates and compresses assets in order to make serving them much less painful. - -* +config.assets.enabled+ a flag that controls whether the asset pipeline is enabled. It is explicitly initialized in +config/application.rb+. - -* +config.assets.compress+ a flag that enables the compression of compiled assets. It is explicitly set to true in +config/production.rb+. - -* +config.assets.css_compressor+ defines the CSS compressor to use. It is set by default by +sass-rails+. The unique alternative value at the moment is +:yui+, which uses the +yui-compressor+ gem. - -* +config.assets.js_compressor+ defines the JavaScript compressor to use. Possible values are +:closure+, +:uglifier+ and +:yui+ which require the use of the +closure-compiler+, +uglifier+ or +yui-compressor+ gems respectively. - -* +config.assets.paths+ contains the paths which are used to look for assets. Appending paths to this configuration option will cause those paths to be used in the search for assets. - -* +config.assets.precompile+ allows you to specify additional assets (other than +application.css+ and +application.js+) which are to be precompiled when +rake assets:precompile+ is run. - -* +config.assets.prefix+ defines the prefix where assets are served from. Defaults to +/assets+. - -* +config.assets.digest+ enables the use of MD5 fingerprints in asset names. Set to +true+ by default in +production.rb+. - -* +config.assets.debug+ disables the concatenation and compression of assets. Set to +false+ by default in +development.rb+. - -* +config.assets.manifest+ defines the full path to be used for the asset precompiler's manifest file. Defaults to using +config.assets.prefix+. - -* +config.assets.cache_store+ defines the cache store that Sprockets will use. The default is the Rails file store. - -* +config.assets.version+ is an option string that is used in MD5 hash generation. This can be changed to force all files to be recompiled. - -* +config.assets.compile+ is a boolean that can be used to turn on live Sprockets compilation in production. - -* +config.assets.logger+ accepts a logger conforming to the interface of Log4r or the default Ruby +Logger+ class. Defaults to the same configured at +config.logger+. Setting +config.assets.logger+ to false will turn off served assets logging. - -h4. Configuring Generators - -Rails 3 allows you to alter what generators are used with the +config.generators+ method. This method takes a block: - - -config.generators do |g| - g.orm :active_record - g.test_framework :test_unit -end - - -The full set of methods that can be used in this block are as follows: - -* +assets+ allows to create assets on generating a scaffold. Defaults to +true+. -* +force_plural+ allows pluralized model names. Defaults to +false+. -* +helper+ defines whether or not to generate helpers. Defaults to +true+. -* +integration_tool+ defines which integration tool to use. Defaults to +nil+. -* +javascripts+ turns on the hook for javascripts in generators. Used in Rails for when the +scaffold+ generator is ran. Defaults to +true+. -* +javascript_engine+ configures the engine to be used (for eg. coffee) when generating assets. Defaults to +nil+. -* +orm+ defines which orm to use. Defaults to +false+ and will use Active Record by default. -* +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+. -* +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. Defaults to +true+. -* +stylesheet_engine+ configures the stylesheet engine (for eg. sass) to be used when generating assets. Defaults to +:css+. -* +test_framework+ defines which test framework to use. Defaults to +false+ and will use Test::Unit by default. -* +template_engine+ defines which template engine to use, such as ERB or Haml. Defaults to +:erb+. - -h4. Configuring Middleware - -Every Rails application comes with a standard set of middleware which it uses in this order in the development environment: - -* +ActionDispatch::SSL+ forces every request to be under HTTPS protocol. Will be available if +config.force_ssl+ is set to +true+. Options passed to this can be configured by using +config.ssl_options+. -* +ActionDispatch::Static+ is used to serve static assets. Disabled if +config.serve_static_assets+ is +true+. -* +Rack::Lock+ wraps the app in mutex so it can only be called by a single thread at a time. Only enabled if +config.action_controller.allow_concurrency+ is set to +false+, which it is by default. -* +ActiveSupport::Cache::Strategy::LocalCache+ serves as a basic memory backed cache. This cache is not thread safe and is intended only for serving as a temporary memory cache for a single thread. -* +Rack::Runtime+ sets an +X-Runtime+ header, containing the time (in seconds) taken to execute the request. -* +Rails::Rack::Logger+ notifies 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::RequestId+ makes a unique X-Request-Id header available to the response and enables the +ActionDispatch::Request#uuid+ method. -* +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+ 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 any INSERT or UPDATE takes place then the cache is cleaned. -* +ActionDispatch::Cookies+ sets cookies for the request. -* +ActionDispatch::Session::CookieStore+ is responsible for storing the session in cookies. An alternate middleware can be used for this by changing the +config.action_controller.session_store+ to an alternate value. Additionally, options passed to this can be configured by using +config.action_controller.session_options+. -* +ActionDispatch::Flash+ sets up the +flash+ keys. Only available if +config.action_controller.session_store+ is set to a value. -* +ActionDispatch::ParamsParser+ parses out parameters from the request into +params+. -* +Rack::MethodOverride+ allows the method to be overridden if +params[:_method]+ is set. This is the middleware which supports the PATCH, PUT, and DELETE HTTP method types. -* +ActionDispatch::Head+ converts HEAD requests to GET requests and serves them as so. -* +ActionDispatch::BestStandardsSupport+ enables "best standards support" so that IE8 renders some elements correctly. - -Besides these usual middleware, you can add your own by using the +config.middleware.use+ method: - - -config.middleware.use Magical::Unicorns - - -This will put the +Magical::Unicorns+ middleware on the end of the stack. You can use +insert_before+ if you wish to add a middleware before another. - - -config.middleware.insert_before ActionDispatch::Head, Magical::Unicorns - - -There's also +insert_after+ which will insert a middleware after another: - - -config.middleware.insert_after ActionDispatch::Head, Magical::Unicorns - - -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 - - -In addition to these methods to handle the stack, if your application is going to be used as an API endpoint only, the middleware stack can be configured like this: - - -config.middleware.http_only! - - -By doing this, Rails will create a smaller middleware stack, by not adding some middlewares that are usually useful for browser access only, such as Cookies, Session and Flash, BestStandardsSupport, and MethodOverride. You can always add any of them later manually if you want. Refer to the "API App docs":api_app.html for more info on how to setup your application for API only apps. - -h4. Configuring i18n - -* +config.i18n.default_locale+ sets the default locale of an application used for i18n. Defaults to +:en+. - -* +config.i18n.load_path+ sets the path Rails uses to look for locale files. Defaults to +config/locales/*.{yml,rb}+. - -h4. Configuring Active Record - -config.active_record includes a variety of configuration options: - -* +config.active_record.logger+ accepts a logger conforming to the interface of Log4r or the default Ruby Logger class, which is then passed on to any new database connections made. You can retrieve this logger by calling +logger+ on either an Active Record model class or an Active Record model instance. Set to +nil+ to disable logging. - -* +config.active_record.primary_key_prefix_type+ lets you adjust the naming for primary key columns. By default, Rails assumes that primary key columns are named +id+ (and this configuration option doesn't need to be set.) There are two other choices: -** +:table_name+ would make the primary key for the Customer class +customerid+ -** +:table_name_with_underscore+ would make the primary key for the Customer class +customer_id+ - -* +config.active_record.table_name_prefix+ lets you set a global string to be prepended to table names. If you set this to +northwest_+, then the Customer class will look for +northwest_customers+ as its table. The default is an empty string. - -* +config.active_record.table_name_suffix+ lets you set a global string to be appended to table names. If you set this to +_northwest+, then the Customer class will look for +customers_northwest+ as its table. The default is an empty string. - -* +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 Customer 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 +:utc+ for Rails, although Active Record 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. - -* +config.active_record.timestamped_migrations+ controls whether migrations are numbered with serial integers or with timestamps. The default is true, to use timestamps, which are preferred if there are multiple developers working on the same application. - -* +config.active_record.lock_optimistically+ controls whether Active Record will use optimistic locking and is true by default. - -* +config.active_record.whitelist_attributes+ will create an empty whitelist of attributes available for mass-assignment security for all models in your app. - -* +config.active_record.auto_explain_threshold_in_seconds+ configures the threshold for automatic EXPLAINs (+nil+ disables this feature). Queries exceeding the threshold get their query plan logged. Default is 0.5 in development mode. - -* +config.active_record.dependent_restrict_raises+ will control the behavior when an object with a :dependent => :restrict association is deleted. Setting this to false will prevent +DeleteRestrictionError+ from being raised and instead will add an error on the model object. Defaults to false in the development mode. - -* +config.active_record.mass_assignment_sanitizer+ will determine the strictness of the mass assignment sanitization within Rails. Defaults to +:strict+. In this mode, mass assigning any non-+attr_accessible+ attribute in a +create+ or +update_attributes+ call will raise an exception. Setting this option to +:logger+ will only print to the log file when an attribute is being assigned and will not raise an exception. - -The MySQL adapter adds one additional configuration option: - -* +ActiveRecord::ConnectionAdapters::MysqlAdapter.emulate_booleans+ controls whether Active Record will consider all +tinyint(1)+ columns in a MySQL database to be booleans and is true by default. - -The schema dumper adds one additional configuration option: - -* +ActiveRecord::SchemaDumper.ignore_tables+ accepts an array of tables that should _not_ be included in any generated schema file. This setting is ignored unless +config.active_record.schema_format == :ruby+. - -h4. Configuring Action Controller - -config.action_controller includes a number of configuration settings: - -* +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+ 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_extension+ configures the extension used for cached pages saved to +page_cache_directory+. Defaults to +.html+. - -* +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". - -* +config.action_controller.logger+ accepts a logger conforming to the interface of Log4r or the default Ruby Logger class, which is then used to log information from Action Controller. Set to +nil+ to disable logging. - -* +config.action_controller.request_forgery_protection_token+ sets the token parameter name for RequestForgery. Calling +protect_from_forgery+ sets it to +:authenticity_token+ by default. - -* +config.action_controller.allow_forgery_protection+ enables or disables CSRF protection. By default this is false in test mode and true in all other modes. - -* +config.action_controller.relative_url_root+ can be used to tell Rails that you are deploying to a subdirectory. The default is +ENV['RAILS_RELATIVE_URL_ROOT']+. - -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_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+. - -The Active Record session store can also be configured: - -* +ActiveRecord::SessionStore::Session.table_name+ sets the name of the table used to store sessions. Defaults to +sessions+. - -* +ActiveRecord::SessionStore::Session.primary_key+ sets the name of the ID column used in the sessions table. Defaults to +session_id+. - -* +ActiveRecord::SessionStore::Session.data_column_name+ sets the name of the column which stores marshaled session data. Defaults to +data+. - -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 six on +ActionView::Base+: - - -* +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(
#{html_tag}
).html_safe } -
- -* +config.action_view.default_form_builder+ tells Rails which form builder to use by default. The default is +ActionView::Helpers::FormBuilder+. - -* +config.action_view.logger+ accepts a logger conforming to the interface of Log4r or the default Ruby Logger class, which is then used to log information from Action View. Set to +nil+ to disable logging. - -* +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+ 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 => %w(jquery jquery_ujs) } - - -However, you may add to this by defining others: - - -config.action_view.javascript_expansions[:prototype] = ['prototype', 'effects', 'dragdrop', 'controls'] - - -And can reference in the view with the following code: - - -<%= javascript_include_tag :prototype %> - - -* +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: - - -<%= stylesheet_link_tag :special %> - - -* +config.action_view.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+: - -* +config.action_mailer.logger+ accepts a logger conforming to the interface of Log4r or the default Ruby Logger class, which is then used to log information from Action Mailer. Set to +nil+ to disable logging. - -* +config.action_mailer.smtp_settings+ allows detailed configuration for the +:smtp+ delivery method. It accepts a hash of options, which can include any of these options: -** +: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+. - -* +config.action_mailer.sendmail_settings+ allows detailed configuration for the +sendmail+ delivery method. It accepts a hash of options, which can include any of these options: -** +:location+ - The location of the sendmail executable. Defaults to +/usr/sbin/sendmail+. -** +:arguments+ - The command line arguments. Defaults to +-i -t+. - -* +config.action_mailer.raise_delivery_errors+ specifies whether to raise an error if email delivery cannot be completed. It defaults to true. - -* +config.action_mailer.delivery_method+ defines the delivery method. The allowed values are +:smtp+ (default), +:sendmail+, and +:test+. - -* +config.action_mailer.perform_deliveries+ specifies whether mail will actually be delivered and is true by default. It can be convenient to set it to false for testing. - -* +config.action_mailer.default+ configures Action Mailer defaults. These default to: - -:mime_version => "1.0", -:charset => "UTF-8", -:content_type => "text/plain", -:parts_order => [ "text/plain", "text/enriched", "text/html" ] - - -* +config.action_mailer.observers+ registers observers which will be notified when mail is delivered. - -config.action_mailer.observers = ["MailObserver"] - - -* +config.action_mailer.interceptors+ registers interceptors which will be called before mail is sent. - -config.action_mailer.interceptors = ["MailInterceptor"] - - -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+. - -* +ActiveSupport::BufferedLogger.silencer+ is set to +false+ to disable the ability to silence logging in a block. The default is +true+. - -* +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+. - -h4. Configuring a Database - -Just about every Rails application will interact with a database. The database to use is specified in a configuration file called +config/database.yml+. If you open this file in a new Rails application, you'll see a default database configured to use SQLite3. The file contains sections for three different environments in which Rails can run by default: - -* The +development+ environment is used on your development/local computer as you interact manually with the application. -* The +test+ environment is used when running automated tests. -* The +production+ environment is used when you deploy your application for the world to use. - -TIP: You don't have to update the database configurations manually. If you look at the options of the application generator, you will see that one of the options is named --database. This option allows you to choose an adapter from a list of the 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. Detailed examples of the common database connections are below. - -h5. Configuring an SQLite3 Database - -Rails comes with built-in support for "SQLite3":http://www.sqlite.org, which is a lightweight serverless database application. While a busy production environment may overload SQLite, it works well for development and testing. Rails defaults to using an SQLite database when creating a new project, but you can always change it later. - -Here's the section of the default configuration file (config/database.yml) with connection information for the development environment: - - -development: - adapter: sqlite3 - database: db/development.sqlite3 - pool: 5 - timeout: 5000 - - -NOTE: Rails uses an SQLite3 database for data storage by default because it is a zero configuration database that just works. Rails also supports MySQL and PostgreSQL "out of the box", and has plugins for many database systems. If you are using a database in a production environment Rails most likely has an adapter for it. - -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: - - -development: - adapter: mysql2 - encoding: utf8 - database: blog_development - pool: 5 - username: root - password: - socket: /tmp/mysql.sock - - -If your development computer's MySQL installation includes a root user with an empty password, this configuration should work for you. Otherwise, change the username and password in the +development+ section as appropriate. - -h5. Configuring a PostgreSQL Database - -If you choose to use PostgreSQL, your +config/database.yml+ will be customized to use PostgreSQL databases: - - -development: - adapter: postgresql - encoding: unicode - database: blog_development - pool: 5 - username: blog - password: - - -h5. Configuring an SQLite3 Database for JRuby Platform - -If you choose to use SQLite3 and are using JRuby, your +config/database.yml+ will look a little different. Here's the development section: - - -development: - adapter: jdbcsqlite3 - database: db/development.sqlite3 - - -h5. Configuring a MySQL Database for JRuby Platform - -If you choose to use MySQL and are using JRuby, your +config/database.yml+ will look a little different. Here's the development section: - - -development: - adapter: jdbcmysql - database: blog_development - username: root - password: - - -h5. Configuring a PostgreSQL Database for JRuby Platform - -If you choose to use PostgreSQL and are using JRuby, your +config/database.yml+ will look a little different. Here's the development section: - - -development: - adapter: jdbcpostgresql - encoding: unicode - database: blog_development - username: blog - password: - - -Change the username and password in the +development+ section as appropriate. - -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_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. - -* +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 in your application, Rails turns to loading initializers. An initializer is any Ruby file 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 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 the 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. More importantly, will run upon every request in +development+, but only once (during boot-up) in +production+ and +test+. - -* +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+ environment. - -* +after_initialize+: Run directly after the initialization of the application, but before the application initializers are run. - -To define an event for these hooks, use the block syntax within a +Rails::Application+, +Rails::Railtie+ or +Rails::Engine+ subclass: - - -module YourApp - class Application < Rails::Application - config.before_initialize do - # initialization code goes here - end - end -end - - -Alternatively, you can also do it through the +config+ method on the +Rails.application+ object: - - -Rails.application.config.before_initialize do - # initialization code goes here -end - - -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. - -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 - - -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. - -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. - -The block argument of the +initializer+ method is the instance of the application itself, and so we can access the configuration on it by using the +config+ method as done in the example. - -Because +Rails::Application+ inherits from +Rails::Railtie+ (indirectly), you can use the +initializer+ method in +config/application.rb+ to define initializers for the application. - -h4. Initializers - -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). - -*+load_environment_hook+* -Serves as a placeholder so that +:load_environment_config+ can be defined to run before it. - -*+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. - -*+preload_frameworks+* Loads 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. - -*+initialize_logger+* Initializes the logger (an +ActiveSupport::BufferedLogger+ object) for the application and makes it accessible at +Rails.logger+, provided that no initializer inserted before this point has defined +Rails.logger+. - -*+initialize_cache+* If +Rails.cache+ isn't set yet, 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. - -*+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. - -*+initialize_dependency_mechanism+* If +config.cache_classes+ is true, configures +ActiveSupport::Dependencies.mechanism+ to +require+ dependencies rather than +load+ them. - -*+bootstrap_hook+* Runs all configured +before_initialize+ blocks. - -*+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+* Requires +active_support/whiny_nil+ if +config.whiny_nils+ is 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 - - -And: - - -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 - - -*+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 on the +config.time_zone+ setting, which defaults to "UTC". - -*+action_dispatch.configure+* Configures the +ActionDispatch::Http::URL.tld_length+ to be set to the value of +config.action_dispatch.tld_length+. - -*+action_view.cache_asset_ids+* Sets +ActionView::Helpers::AssetTagHelper::AssetPaths.cache_asset_ids+ to +false+ when Active Support loads, but only if +config.cache_classes+ is too. - -*+action_view.javascript_expansions+* Registers the expansions set up by +config.action_view.javascript_expansions+ and +config.action_view.stylesheet_expansions+ to be recognized by Action View and therefore usable in the views. - -*+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. - -*+action_controller.logger+* Sets +ActionController::Base.logger+ -- if it's not already set -- to +Rails.logger+. - -*+action_controller.initialize_framework_caches+* Sets +ActionController::Base.cache_store+ -- if it's not already set -- to +Rails.cache+. - -*+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. - -*+action_controller.compile_config_methods+* Initializes methods for the config settings specified so that they are quicker to access. - -*+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+. - -*+active_record.logger+* Sets +ActiveRecord::Base.logger+ -- if it's not already set -- to +Rails.logger+. - -*+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. - -*+active_record.initialize_database+* Loads the database configuration (by default) from +config/database.yml+ and establishes a connection for the current environment. - -*+active_record.log_runtime+* Includes +ActiveRecord::Railties::ControllerRuntime+ which is responsible for reporting the time taken by Active Record calls for the request back to the logger. - -*+active_record.set_dispatch_hooks+* Resets all reloadable connections to the database if +config.cache_classes+ is set to +false+. - -*+action_mailer.logger+* Sets +ActionMailer::Base.logger+ -- if it's not already set -- to +Rails.logger+. - -*+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. - -*+action_mailer.compile_config_methods+* Initializes methods for the config settings specified so that they are quicker to access. - -*+set_load_path+* This initializer runs before +bootstrap_hook+. Adds the +vendor+, +lib+, all directories of +app+ and any paths specified by +config.load_paths+ to +$LOAD_PATH+. - -*+set_autoload_paths+* This initializer runs before +bootstrap_hook+. Adds all sub-directories of +app+ and paths specified by +config.autoload_paths+ to +ActiveSupport::Dependencies.autoload_paths+. - -*+add_routing_paths+* Loads (by default) all +config/routes.rb+ files (in the application and railties, including engines) and sets up the routes for the application. - -*+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. - -*+add_view_paths+* Adds the directory +app/views+ from the application, railties and engines to the lookup path for view files for the application. - -*+load_environment_config+* Loads the +config/environments+ file for the current environment. - -*+append_asset_paths+* Finds asset paths for the application and all attached railties and keeps a track of the available directories in +config.static_asset_paths+. - -*+prepend_helpers_path+* Adds the directory +app/helpers+ from the application, railties and engines to the lookup path for helpers for the application. - -*+load_config_initializers+* Loads all Ruby files from +config/initializers+ in the application, railties and engines. The files in this directory can be used to hold configuration settings that should be made after all of the frameworks are loaded. - -*+engines_blank_point+* Provides a point-in-initialization to hook into if you wish to do anything before engines are loaded. After this point, all railtie and engine initializers are ran. - -*+add_generator_templates+* Finds templates for generators at +lib/templates+ for the application, railities and engines and adds these to the +config.generators.templates+ setting, which will make the templates available for all generators to reference. - -*+ensure_autoload_once_paths_as_subset+* Ensures that the +config.autoload_once_paths+ only contains paths from +config.autoload_paths+. If it contains extra paths, then an exception will be raised. - -*+add_to_prepare_blocks+* The block for every +config.to_prepare+ call in the application, a railtie or engine is added to the +to_prepare+ callbacks for Action Dispatch which will be ran per request in development, or before the first request in production. - -*+add_builtin_route+* If the application is running under the development environment then this will append the route for +rails/info/properties+ to the application routes. This route provides the detailed information such as Rails and Ruby version for +public/index.html+ in a default Rails application. - -*+build_middleware_stack+* Builds the middleware stack for the application, returning an object which has a +call+ method which takes a Rack environment object for the request. - -*+eager_load!+* If +config.cache_classes+ is true, runs the +config.before_eager_load+ hooks and then calls +eager_load!+ which will load all the Ruby files from +config.eager_load_paths+. - -*+finisher_hook+* Provides a hook for after the initialization of process of the application is complete, as well as running all the +config.after_initialize+ blocks for the application, railties and engines. - -*+set_routes_reloader+* Configures Action Dispatch to reload the routes file using +ActionDispatch::Callbacks.to_prepare+. - -*+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. Database pooling - -Active Record database connections are managed by +ActiveRecord::ConnectionAdapters::ConnectionPool+ which ensures that a connection pool synchronizes the amount of thread access to a limited number of database connections. This limit defaults to 5 and can be configured in +database.yml+. - - -development: - adapter: sqlite3 - database: db/development.sqlite3 - pool: 5 - timeout: 5000 - - -Since the connection pooling is handled inside of ActiveRecord by default, all application servers (Thin, mongrel, Unicorn etc.) should behave the same. Initially, the database connection pool is empty and it will create additional connections as the demand for them increases, until it reaches the connection pool limit. - -Any one request will check out a connection the first time it requires access to the database, after which it will check the connection back in, at the end of the request, meaning that the additional connection slot will be available again for the next request in the queue. - -NOTE. If you have enabled +Rails.threadsafe!+ mode then there could be a chance that several threads may be accessing multiple connections simultaneously. So depending on your current request load, you could very well have multiple threads contending for a limited amount of connections. +Rails 将会使用那些特定的设置来配置Active Record. diff --git a/source/documents_CN.yaml b/source/documents_CN.yaml index c43c9d8..ca9a67b 100644 --- a/source/documents_CN.yaml +++ b/source/documents_CN.yaml @@ -87,7 +87,9 @@ - name: Configuring Rails Applications url: configuring.html - description: This guide covers the basic configuration settings for a Rails application. + work_in_progress: true + contributor: ichord + description: 这个指南覆盖Rails应用的所有基本配置. - name: Rails Command Line Tools and Rake Tasks url: command_line.html From d19798972bed35f0411394223a2e19bbb0a78419 Mon Sep 17 00:00:00 2001 From: ichord Date: Sat, 7 Apr 2012 23:13:12 +0800 Subject: [PATCH 06/11] add untranslate part --- source/CN/configuring.textile | 723 ++++++++++++++++++++++++++++++++++ 1 file changed, 723 insertions(+) diff --git a/source/CN/configuring.textile b/source/CN/configuring.textile index 4061c1a..a66b680 100644 --- a/source/CN/configuring.textile +++ b/source/CN/configuring.textile @@ -35,3 +35,726 @@ config.active_record.observers = [:hotel_observer, :review_observer] Rails 将会使用那些特定的设置来配置Active Record. + +h4. Rails General Configuration + +These configuration methods are to be called on a +Rails::Railtie+ object, such as a subclass of +Rails::Engine+ or +Rails::Application+. + +* +config.after_initialize+ takes a block which will be run _after_ Rails has finished initializing the application. That includes the initialization of the framework itself, engines, and all the application's initializers in +config/initializers+. Note that this block _will_ be run for rake tasks. Useful for configuring values set up by other initializers: + + +config.after_initialize do + ActionView::Base.sanitized_allowed_tags.delete 'div' +end + + +* +config.allow_concurrency+ should be true to allow concurrent (threadsafe) action processing. 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, or when you want to work around the concurrency constraints builtin in browsers using different domain aliases. Shorter version of +config.action_controller.asset_host+. + +* +config.asset_path+ lets you decorate asset paths. This can be a callable, a string, or be +nil+ which is the default. For example, the normal path for +blog.js+ would be +/javascripts/blog.js+, let that absolute path be +path+. If +config.asset_path+ is a callable, Rails calls it when generating asset paths passing +path+ as argument. If +config.asset_path+ is a string, it is expected to be a +sprintf+ format string with a +%s+ where +path+ will get inserted. In either case, Rails outputs the decorated path. Shorter version of +config.action_controller.asset_path+. + + +config.asset_path = proc { |path| "/blog/public#{path}" } + + +NOTE. The +config.asset_path+ configuration is ignored if the asset pipeline is enabled, which is the default. + +* +config.autoload_once_paths+ accepts an array of paths from which Rails will autoload constants that won't be wiped per request. Relevant if +config.cache_classes+ is false, which is the case in development mode by default. Otherwise, all autoloading happens only once. All elements of this array must also be in +autoload_paths+. Default is an empty array. + +* +config.autoload_paths+ accepts an array of paths from which Rails will autoload constants. Default is all directories under +app+. + +* +config.cache_classes+ controls whether or not application classes and modules should be reloaded on each request. Defaults to false in development mode, and true in test and production modes. 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 one of the symbols +:memory_store+, +:file_store+, +:mem_cache_store+, or an object that implements the cache API. Defaults to +:file_store+ if the directory +tmp/cache+ exists, and to +:memory_store+ otherwise. + +* +config.colorize_logging+ specifies whether or not to use ANSI color codes when logging information. Defaults to true. + +* +config.consider_all_requests_local+ is a flag. If true then any error will cause detailed debugging information to be dumped in the HTTP response, and the +Rails::Info+ controller will show the application runtime context in +/rails/info/properties+. True by default in development and test environments, and false in production mode. 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.dependency_loading+ is a flag that allows you to disable constant autoloading setting it to false. It only has effect if +config.cache_classes+ is true, which it is by default in production mode. This flag is set to false by +config.threadsafe!+. + +* +config.eager_load_paths+ accepts an array of paths from which Rails will eager load on boot if cache classes is enabled. Defaults to every folder in the +app+ directory of the application. + +* +config.encoding+ sets up the application-wide encoding. Defaults to UTF-8. + +* +config.exceptions_app+ sets the exceptions application invoked by the ShowException middleware when an exception happens. Defaults to +ActionDispatch::PublicExceptions.new(Rails.public_path)+. + +* +config.file_watcher+ the class used to detect file updates in the filesystem when +config.reload_classes_only_on_change+ is true. Must conform to +ActiveSupport::FileUpdateChecker+ API. + +* +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.force_ssl+ forces all requests to be under HTTPS protocol by using +ActionDispatch::SSL+ middleware. + +* +config.log_level+ defines the verbosity of the Rails logger. This option defaults to +:debug+ for all modes except production, where it defaults to +:info+. + +* +config.log_tags+ accepts a list of methods that respond to +request+ object. This makes it easy to tag log lines with debug information like subdomain and request id -- both very helpful in debugging multi-user production applications. + +* +config.logger+ accepts a logger conforming to the interface of Log4r or the default Ruby +Logger+ class. Defaults to an instance of +ActiveSupport::BufferedLogger+, with auto flushing off in production mode. + +* +config.middleware+ allows you to configure the application's middleware. This is covered in depth in the "Configuring Middleware":#configuring-middleware section below. + +* +config.preload_frameworks+ enables or disables preloading all frameworks at startup. Enabled by +config.threadsafe!+. Defaults to +nil+, so is disabled. + +* +config.reload_classes_only_on_change+ enables or disables reloading of classes only when tracked files change. By default tracks everything on autoload paths and is set to true. If +config.cache_classes+ is true, this option is ignored. + +* +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. Applications get +config.secret_token+ initialized to a random key in +config/initializers/secret_token.rb+. + +* +config.serve_static_assets+ configures Rails itself to serve static assets. Defaults to true, but in the production environment is turned off as the server software (e.g. Nginx or Apache) used to run the application should serve static assets instead. Unlike the default setting set this to true when running (absolutely not recommended!) or testing your app in production mode using WEBrick. Otherwise you won´t be able use page caching and requests for files that exist regularly under the public directory will anyway hit your Rails app. + +* +config.session_store+ is usually set up in +config/initializers/session_store.rb+ and specifies what class to use to store the session. Possible values are +:cookie_store+ which is the default, +:mem_cache_store+, and +:disabled+. The last one tells Rails not to deal with sessions. Custom session stores can also be specified: + + +config.session_store :my_custom_store + + +This custom store must be defined as +ActionDispatch::Session::MyCustomStore+. In addition to symbols, they can also be objects implementing a certain API, like +ActiveRecord::SessionStore+, in which case no special namespace is required. + +* +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 disables warnings when a certain set of methods are invoked on +nil+ and it does not respond to them. Defaults to true in development and test environments. + +* +config.console+ allows you to set class that will be used as console you run +rails console+. It's best to run it in +console+ block: + + +console do + # this block is called only when running console, + # so we can safely require pry here + require "pry" + config.console = Pry +end + + +h4. Configuring Assets + +Rails 3.1, by default, is set up to use the +sprockets+ gem to manage assets within an application. This gem concatenates and compresses assets in order to make serving them much less painful. + +* +config.assets.enabled+ a flag that controls whether the asset pipeline is enabled. It is explicitly initialized in +config/application.rb+. + +* +config.assets.compress+ a flag that enables the compression of compiled assets. It is explicitly set to true in +config/production.rb+. + +* +config.assets.css_compressor+ defines the CSS compressor to use. It is set by default by +sass-rails+. The unique alternative value at the moment is +:yui+, which uses the +yui-compressor+ gem. + +* +config.assets.js_compressor+ defines the JavaScript compressor to use. Possible values are +:closure+, +:uglifier+ and +:yui+ which require the use of the +closure-compiler+, +uglifier+ or +yui-compressor+ gems respectively. + +* +config.assets.paths+ contains the paths which are used to look for assets. Appending paths to this configuration option will cause those paths to be used in the search for assets. + +* +config.assets.precompile+ allows you to specify additional assets (other than +application.css+ and +application.js+) which are to be precompiled when +rake assets:precompile+ is run. + +* +config.assets.prefix+ defines the prefix where assets are served from. Defaults to +/assets+. + +* +config.assets.digest+ enables the use of MD5 fingerprints in asset names. Set to +true+ by default in +production.rb+. + +* +config.assets.debug+ disables the concatenation and compression of assets. Set to +false+ by default in +development.rb+. + +* +config.assets.manifest+ defines the full path to be used for the asset precompiler's manifest file. Defaults to using +config.assets.prefix+. + +* +config.assets.cache_store+ defines the cache store that Sprockets will use. The default is the Rails file store. + +* +config.assets.version+ is an option string that is used in MD5 hash generation. This can be changed to force all files to be recompiled. + +* +config.assets.compile+ is a boolean that can be used to turn on live Sprockets compilation in production. + +* +config.assets.logger+ accepts a logger conforming to the interface of Log4r or the default Ruby +Logger+ class. Defaults to the same configured at +config.logger+. Setting +config.assets.logger+ to false will turn off served assets logging. + +h4. Configuring Generators + +Rails 3 allows you to alter what generators are used with the +config.generators+ method. This method takes a block: + + +config.generators do |g| + g.orm :active_record + g.test_framework :test_unit +end + + +The full set of methods that can be used in this block are as follows: + +* +assets+ allows to create assets on generating a scaffold. Defaults to +true+. +* +force_plural+ allows pluralized model names. Defaults to +false+. +* +helper+ defines whether or not to generate helpers. Defaults to +true+. +* +integration_tool+ defines which integration tool to use. Defaults to +nil+. +* +javascripts+ turns on the hook for javascripts in generators. Used in Rails for when the +scaffold+ generator is ran. Defaults to +true+. +* +javascript_engine+ configures the engine to be used (for eg. coffee) when generating assets. Defaults to +nil+. +* +orm+ defines which orm to use. Defaults to +false+ and will use Active Record by default. +* +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+. +* +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. Defaults to +true+. +* +stylesheet_engine+ configures the stylesheet engine (for eg. sass) to be used when generating assets. Defaults to +:css+. +* +test_framework+ defines which test framework to use. Defaults to +false+ and will use Test::Unit by default. +* +template_engine+ defines which template engine to use, such as ERB or Haml. Defaults to +:erb+. + +h4. Configuring Middleware + +Every Rails application comes with a standard set of middleware which it uses in this order in the development environment: + +* +ActionDispatch::SSL+ forces every request to be under HTTPS protocol. Will be available if +config.force_ssl+ is set to +true+. Options passed to this can be configured by using +config.ssl_options+. +* +ActionDispatch::Static+ is used to serve static assets. Disabled if +config.serve_static_assets+ is +true+. +* +Rack::Lock+ wraps the app in mutex so it can only be called by a single thread at a time. Only enabled if +config.action_controller.allow_concurrency+ is set to +false+, which it is by default. +* +ActiveSupport::Cache::Strategy::LocalCache+ serves as a basic memory backed cache. This cache is not thread safe and is intended only for serving as a temporary memory cache for a single thread. +* +Rack::Runtime+ sets an +X-Runtime+ header, containing the time (in seconds) taken to execute the request. +* +Rails::Rack::Logger+ notifies 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::RequestId+ makes a unique X-Request-Id header available to the response and enables the +ActionDispatch::Request#uuid+ method. +* +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+ 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 any INSERT or UPDATE takes place then the cache is cleaned. +* +ActionDispatch::Cookies+ sets cookies for the request. +* +ActionDispatch::Session::CookieStore+ is responsible for storing the session in cookies. An alternate middleware can be used for this by changing the +config.action_controller.session_store+ to an alternate value. Additionally, options passed to this can be configured by using +config.action_controller.session_options+. +* +ActionDispatch::Flash+ sets up the +flash+ keys. Only available if +config.action_controller.session_store+ is set to a value. +* +ActionDispatch::ParamsParser+ parses out parameters from the request into +params+. +* +Rack::MethodOverride+ allows the method to be overridden if +params[:_method]+ is set. This is the middleware which supports the PATCH, PUT, and DELETE HTTP method types. +* +ActionDispatch::Head+ converts HEAD requests to GET requests and serves them as so. +* +ActionDispatch::BestStandardsSupport+ enables "best standards support" so that IE8 renders some elements correctly. + +Besides these usual middleware, you can add your own by using the +config.middleware.use+ method: + + +config.middleware.use Magical::Unicorns + + +This will put the +Magical::Unicorns+ middleware on the end of the stack. You can use +insert_before+ if you wish to add a middleware before another. + + +config.middleware.insert_before ActionDispatch::Head, Magical::Unicorns + + +There's also +insert_after+ which will insert a middleware after another: + + +config.middleware.insert_after ActionDispatch::Head, Magical::Unicorns + + +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 + + +In addition to these methods to handle the stack, if your application is going to be used as an API endpoint only, the middleware stack can be configured like this: + + +config.middleware.http_only! + + +By doing this, Rails will create a smaller middleware stack, by not adding some middlewares that are usually useful for browser access only, such as Cookies, Session and Flash, BestStandardsSupport, and MethodOverride. You can always add any of them later manually if you want. Refer to the "API App docs":api_app.html for more info on how to setup your application for API only apps. + +h4. Configuring i18n + +* +config.i18n.default_locale+ sets the default locale of an application used for i18n. Defaults to +:en+. + +* +config.i18n.load_path+ sets the path Rails uses to look for locale files. Defaults to +config/locales/*.{yml,rb}+. + +h4. Configuring Active Record + +config.active_record includes a variety of configuration options: + +* +config.active_record.logger+ accepts a logger conforming to the interface of Log4r or the default Ruby Logger class, which is then passed on to any new database connections made. You can retrieve this logger by calling +logger+ on either an Active Record model class or an Active Record model instance. Set to +nil+ to disable logging. + +* +config.active_record.primary_key_prefix_type+ lets you adjust the naming for primary key columns. By default, Rails assumes that primary key columns are named +id+ (and this configuration option doesn't need to be set.) There are two other choices: +** +:table_name+ would make the primary key for the Customer class +customerid+ +** +:table_name_with_underscore+ would make the primary key for the Customer class +customer_id+ + +* +config.active_record.table_name_prefix+ lets you set a global string to be prepended to table names. If you set this to +northwest_+, then the Customer class will look for +northwest_customers+ as its table. The default is an empty string. + +* +config.active_record.table_name_suffix+ lets you set a global string to be appended to table names. If you set this to +_northwest+, then the Customer class will look for +customers_northwest+ as its table. The default is an empty string. + +* +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 Customer 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 +:utc+ for Rails, although Active Record 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. + +* +config.active_record.timestamped_migrations+ controls whether migrations are numbered with serial integers or with timestamps. The default is true, to use timestamps, which are preferred if there are multiple developers working on the same application. + +* +config.active_record.lock_optimistically+ controls whether Active Record will use optimistic locking and is true by default. + +* +config.active_record.whitelist_attributes+ will create an empty whitelist of attributes available for mass-assignment security for all models in your app. + +* +config.active_record.auto_explain_threshold_in_seconds+ configures the threshold for automatic EXPLAINs (+nil+ disables this feature). Queries exceeding the threshold get their query plan logged. Default is 0.5 in development mode. + +* +config.active_record.dependent_restrict_raises+ will control the behavior when an object with a :dependent => :restrict association is deleted. Setting this to false will prevent +DeleteRestrictionError+ from being raised and instead will add an error on the model object. Defaults to false in the development mode. + +* +config.active_record.mass_assignment_sanitizer+ will determine the strictness of the mass assignment sanitization within Rails. Defaults to +:strict+. In this mode, mass assigning any non-+attr_accessible+ attribute in a +create+ or +update_attributes+ call will raise an exception. Setting this option to +:logger+ will only print to the log file when an attribute is being assigned and will not raise an exception. + +The MySQL adapter adds one additional configuration option: + +* +ActiveRecord::ConnectionAdapters::MysqlAdapter.emulate_booleans+ controls whether Active Record will consider all +tinyint(1)+ columns in a MySQL database to be booleans and is true by default. + +The schema dumper adds one additional configuration option: + +* +ActiveRecord::SchemaDumper.ignore_tables+ accepts an array of tables that should _not_ be included in any generated schema file. This setting is ignored unless +config.active_record.schema_format == :ruby+. + +h4. Configuring Action Controller + +config.action_controller includes a number of configuration settings: + +* +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+ 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_extension+ configures the extension used for cached pages saved to +page_cache_directory+. Defaults to +.html+. + +* +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". + +* +config.action_controller.logger+ accepts a logger conforming to the interface of Log4r or the default Ruby Logger class, which is then used to log information from Action Controller. Set to +nil+ to disable logging. + +* +config.action_controller.request_forgery_protection_token+ sets the token parameter name for RequestForgery. Calling +protect_from_forgery+ sets it to +:authenticity_token+ by default. + +* +config.action_controller.allow_forgery_protection+ enables or disables CSRF protection. By default this is false in test mode and true in all other modes. + +* +config.action_controller.relative_url_root+ can be used to tell Rails that you are deploying to a subdirectory. The default is +ENV['RAILS_RELATIVE_URL_ROOT']+. + +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_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+. + +The Active Record session store can also be configured: + +* +ActiveRecord::SessionStore::Session.table_name+ sets the name of the table used to store sessions. Defaults to +sessions+. + +* +ActiveRecord::SessionStore::Session.primary_key+ sets the name of the ID column used in the sessions table. Defaults to +session_id+. + +* +ActiveRecord::SessionStore::Session.data_column_name+ sets the name of the column which stores marshaled session data. Defaults to +data+. + +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 six on +ActionView::Base+: + + +* +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(
#{html_tag}
).html_safe } +
+ +* +config.action_view.default_form_builder+ tells Rails which form builder to use by default. The default is +ActionView::Helpers::FormBuilder+. + +* +config.action_view.logger+ accepts a logger conforming to the interface of Log4r or the default Ruby Logger class, which is then used to log information from Action View. Set to +nil+ to disable logging. + +* +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+ 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 => %w(jquery jquery_ujs) } + + +However, you may add to this by defining others: + + +config.action_view.javascript_expansions[:prototype] = ['prototype', 'effects', 'dragdrop', 'controls'] + + +And can reference in the view with the following code: + + +<%= javascript_include_tag :prototype %> + + +* +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: + + +<%= stylesheet_link_tag :special %> + + +* +config.action_view.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+: + +* +config.action_mailer.logger+ accepts a logger conforming to the interface of Log4r or the default Ruby Logger class, which is then used to log information from Action Mailer. Set to +nil+ to disable logging. + +* +config.action_mailer.smtp_settings+ allows detailed configuration for the +:smtp+ delivery method. It accepts a hash of options, which can include any of these options: +** +: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+. + +* +config.action_mailer.sendmail_settings+ allows detailed configuration for the +sendmail+ delivery method. It accepts a hash of options, which can include any of these options: +** +:location+ - The location of the sendmail executable. Defaults to +/usr/sbin/sendmail+. +** +:arguments+ - The command line arguments. Defaults to +-i -t+. + +* +config.action_mailer.raise_delivery_errors+ specifies whether to raise an error if email delivery cannot be completed. It defaults to true. + +* +config.action_mailer.delivery_method+ defines the delivery method. The allowed values are +:smtp+ (default), +:sendmail+, and +:test+. + +* +config.action_mailer.perform_deliveries+ specifies whether mail will actually be delivered and is true by default. It can be convenient to set it to false for testing. + +* +config.action_mailer.default+ configures Action Mailer defaults. These default to: + +:mime_version => "1.0", +:charset => "UTF-8", +:content_type => "text/plain", +:parts_order => [ "text/plain", "text/enriched", "text/html" ] + + +* +config.action_mailer.observers+ registers observers which will be notified when mail is delivered. + +config.action_mailer.observers = ["MailObserver"] + + +* +config.action_mailer.interceptors+ registers interceptors which will be called before mail is sent. + +config.action_mailer.interceptors = ["MailInterceptor"] + + +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+. + +* +ActiveSupport::BufferedLogger.silencer+ is set to +false+ to disable the ability to silence logging in a block. The default is +true+. + +* +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+. + +h4. Configuring a Database + +Just about every Rails application will interact with a database. The database to use is specified in a configuration file called +config/database.yml+. If you open this file in a new Rails application, you'll see a default database configured to use SQLite3. The file contains sections for three different environments in which Rails can run by default: + +* The +development+ environment is used on your development/local computer as you interact manually with the application. +* The +test+ environment is used when running automated tests. +* The +production+ environment is used when you deploy your application for the world to use. + +TIP: You don't have to update the database configurations manually. If you look at the options of the application generator, you will see that one of the options is named --database. This option allows you to choose an adapter from a list of the 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. Detailed examples of the common database connections are below. + +h5. Configuring an SQLite3 Database + +Rails comes with built-in support for "SQLite3":http://www.sqlite.org, which is a lightweight serverless database application. While a busy production environment may overload SQLite, it works well for development and testing. Rails defaults to using an SQLite database when creating a new project, but you can always change it later. + +Here's the section of the default configuration file (config/database.yml) with connection information for the development environment: + + +development: + adapter: sqlite3 + database: db/development.sqlite3 + pool: 5 + timeout: 5000 + + +NOTE: Rails uses an SQLite3 database for data storage by default because it is a zero configuration database that just works. Rails also supports MySQL and PostgreSQL "out of the box", and has plugins for many database systems. If you are using a database in a production environment Rails most likely has an adapter for it. + +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: + + +development: + adapter: mysql2 + encoding: utf8 + database: blog_development + pool: 5 + username: root + password: + socket: /tmp/mysql.sock + + +If your development computer's MySQL installation includes a root user with an empty password, this configuration should work for you. Otherwise, change the username and password in the +development+ section as appropriate. + +h5. Configuring a PostgreSQL Database + +If you choose to use PostgreSQL, your +config/database.yml+ will be customized to use PostgreSQL databases: + + +development: + adapter: postgresql + encoding: unicode + database: blog_development + pool: 5 + username: blog + password: + + +h5. Configuring an SQLite3 Database for JRuby Platform + +If you choose to use SQLite3 and are using JRuby, your +config/database.yml+ will look a little different. Here's the development section: + + +development: + adapter: jdbcsqlite3 + database: db/development.sqlite3 + + +h5. Configuring a MySQL Database for JRuby Platform + +If you choose to use MySQL and are using JRuby, your +config/database.yml+ will look a little different. Here's the development section: + + +development: + adapter: jdbcmysql + database: blog_development + username: root + password: + + +h5. Configuring a PostgreSQL Database for JRuby Platform + +If you choose to use PostgreSQL and are using JRuby, your +config/database.yml+ will look a little different. Here's the development section: + + +development: + adapter: jdbcpostgresql + encoding: unicode + database: blog_development + username: blog + password: + + +Change the username and password in the +development+ section as appropriate. + +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_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. + +* +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 in your application, Rails turns to loading initializers. An initializer is any Ruby file 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 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 the 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. More importantly, will run upon every request in +development+, but only once (during boot-up) in +production+ and +test+. + +* +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+ environment. + +* +after_initialize+: Run directly after the initialization of the application, but before the application initializers are run. + +To define an event for these hooks, use the block syntax within a +Rails::Application+, +Rails::Railtie+ or +Rails::Engine+ subclass: + + +module YourApp + class Application < Rails::Application + config.before_initialize do + # initialization code goes here + end + end +end + + +Alternatively, you can also do it through the +config+ method on the +Rails.application+ object: + + +Rails.application.config.before_initialize do + # initialization code goes here +end + + +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. + +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 + + +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. + +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. + +The block argument of the +initializer+ method is the instance of the application itself, and so we can access the configuration on it by using the +config+ method as done in the example. + +Because +Rails::Application+ inherits from +Rails::Railtie+ (indirectly), you can use the +initializer+ method in +config/application.rb+ to define initializers for the application. + +h4. Initializers + +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). + +*+load_environment_hook+* +Serves as a placeholder so that +:load_environment_config+ can be defined to run before it. + +*+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. + +*+preload_frameworks+* Loads 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. + +*+initialize_logger+* Initializes the logger (an +ActiveSupport::BufferedLogger+ object) for the application and makes it accessible at +Rails.logger+, provided that no initializer inserted before this point has defined +Rails.logger+. + +*+initialize_cache+* If +Rails.cache+ isn't set yet, 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. + +*+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. + +*+initialize_dependency_mechanism+* If +config.cache_classes+ is true, configures +ActiveSupport::Dependencies.mechanism+ to +require+ dependencies rather than +load+ them. + +*+bootstrap_hook+* Runs all configured +before_initialize+ blocks. + +*+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+* Requires +active_support/whiny_nil+ if +config.whiny_nils+ is 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 + + +And: + + +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 + + +*+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 on the +config.time_zone+ setting, which defaults to "UTC". + +*+action_dispatch.configure+* Configures the +ActionDispatch::Http::URL.tld_length+ to be set to the value of +config.action_dispatch.tld_length+. + +*+action_view.cache_asset_ids+* Sets +ActionView::Helpers::AssetTagHelper::AssetPaths.cache_asset_ids+ to +false+ when Active Support loads, but only if +config.cache_classes+ is too. + +*+action_view.javascript_expansions+* Registers the expansions set up by +config.action_view.javascript_expansions+ and +config.action_view.stylesheet_expansions+ to be recognized by Action View and therefore usable in the views. + +*+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. + +*+action_controller.logger+* Sets +ActionController::Base.logger+ -- if it's not already set -- to +Rails.logger+. + +*+action_controller.initialize_framework_caches+* Sets +ActionController::Base.cache_store+ -- if it's not already set -- to +Rails.cache+. + +*+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. + +*+action_controller.compile_config_methods+* Initializes methods for the config settings specified so that they are quicker to access. + +*+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+. + +*+active_record.logger+* Sets +ActiveRecord::Base.logger+ -- if it's not already set -- to +Rails.logger+. + +*+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. + +*+active_record.initialize_database+* Loads the database configuration (by default) from +config/database.yml+ and establishes a connection for the current environment. + +*+active_record.log_runtime+* Includes +ActiveRecord::Railties::ControllerRuntime+ which is responsible for reporting the time taken by Active Record calls for the request back to the logger. + +*+active_record.set_dispatch_hooks+* Resets all reloadable connections to the database if +config.cache_classes+ is set to +false+. + +*+action_mailer.logger+* Sets +ActionMailer::Base.logger+ -- if it's not already set -- to +Rails.logger+. + +*+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. + +*+action_mailer.compile_config_methods+* Initializes methods for the config settings specified so that they are quicker to access. + +*+set_load_path+* This initializer runs before +bootstrap_hook+. Adds the +vendor+, +lib+, all directories of +app+ and any paths specified by +config.load_paths+ to +$LOAD_PATH+. + +*+set_autoload_paths+* This initializer runs before +bootstrap_hook+. Adds all sub-directories of +app+ and paths specified by +config.autoload_paths+ to +ActiveSupport::Dependencies.autoload_paths+. + +*+add_routing_paths+* Loads (by default) all +config/routes.rb+ files (in the application and railties, including engines) and sets up the routes for the application. + +*+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. + +*+add_view_paths+* Adds the directory +app/views+ from the application, railties and engines to the lookup path for view files for the application. + +*+load_environment_config+* Loads the +config/environments+ file for the current environment. + +*+append_asset_paths+* Finds asset paths for the application and all attached railties and keeps a track of the available directories in +config.static_asset_paths+. + +*+prepend_helpers_path+* Adds the directory +app/helpers+ from the application, railties and engines to the lookup path for helpers for the application. + +*+load_config_initializers+* Loads all Ruby files from +config/initializers+ in the application, railties and engines. The files in this directory can be used to hold configuration settings that should be made after all of the frameworks are loaded. + +*+engines_blank_point+* Provides a point-in-initialization to hook into if you wish to do anything before engines are loaded. After this point, all railtie and engine initializers are ran. + +*+add_generator_templates+* Finds templates for generators at +lib/templates+ for the application, railities and engines and adds these to the +config.generators.templates+ setting, which will make the templates available for all generators to reference. + +*+ensure_autoload_once_paths_as_subset+* Ensures that the +config.autoload_once_paths+ only contains paths from +config.autoload_paths+. If it contains extra paths, then an exception will be raised. + +*+add_to_prepare_blocks+* The block for every +config.to_prepare+ call in the application, a railtie or engine is added to the +to_prepare+ callbacks for Action Dispatch which will be ran per request in development, or before the first request in production. + +*+add_builtin_route+* If the application is running under the development environment then this will append the route for +rails/info/properties+ to the application routes. This route provides the detailed information such as Rails and Ruby version for +public/index.html+ in a default Rails application. + +*+build_middleware_stack+* Builds the middleware stack for the application, returning an object which has a +call+ method which takes a Rack environment object for the request. + +*+eager_load!+* If +config.cache_classes+ is true, runs the +config.before_eager_load+ hooks and then calls +eager_load!+ which will load all the Ruby files from +config.eager_load_paths+. + +*+finisher_hook+* Provides a hook for after the initialization of process of the application is complete, as well as running all the +config.after_initialize+ blocks for the application, railties and engines. + +*+set_routes_reloader+* Configures Action Dispatch to reload the routes file using +ActionDispatch::Callbacks.to_prepare+. + +*+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. Database pooling + +Active Record database connections are managed by +ActiveRecord::ConnectionAdapters::ConnectionPool+ which ensures that a connection pool synchronizes the amount of thread access to a limited number of database connections. This limit defaults to 5 and can be configured in +database.yml+. + + +development: + adapter: sqlite3 + database: db/development.sqlite3 + pool: 5 + timeout: 5000 + + +Since the connection pooling is handled inside of ActiveRecord by default, all application servers (Thin, mongrel, Unicorn etc.) should behave the same. Initially, the database connection pool is empty and it will create additional connections as the demand for them increases, until it reaches the connection pool limit. + +Any one request will check out a connection the first time it requires access to the database, after which it will check the connection back in, at the end of the request, meaning that the additional connection slot will be available again for the next request in the queue. + +NOTE. If you have enabled +Rails.threadsafe!+ mode then there could be a chance that several threads may be accessing multiple connections simultaneously. So depending on your current request load, you could very well have multiple threads contending for a limited amount of connections. From 08edbf3f5b71e2b7d932e72ec15a4bf0c9dfcb78 Mon Sep 17 00:00:00 2001 From: Tassandar Date: Mon, 9 Apr 2012 15:24:51 +0800 Subject: [PATCH 07/11] update to 3.2.3 EN --- config/deploy.rb | 4 +- source/EN/active_record_querying.textile | 72 ++++++---- .../EN/api_documentation_guidelines.textile | 16 ++- source/EN/asset_pipeline.textile | 6 +- source/EN/association_basics.textile | 4 +- source/EN/caching_with_rails.textile | 20 +-- source/EN/command_line.textile | 6 + source/EN/configuring.textile | 13 +- .../EN/contributing_to_ruby_on_rails.textile | 2 +- source/EN/engines.textile | 81 ++++++------ source/EN/getting_started.textile | 16 +-- source/EN/i18n.textile | 26 +++- source/EN/kindle/KINDLE.md | 26 ++++ source/EN/kindle/copyright.html.erb | 1 + source/EN/kindle/layout.html.erb | 27 ++++ source/EN/kindle/rails_guides.opf.erb | 52 ++++++++ source/EN/kindle/toc.html.erb | 24 ++++ source/EN/kindle/toc.ncx.erb | 64 +++++++++ source/EN/kindle/welcome.html.erb | 5 + source/EN/layouts_and_rendering.textile | 14 +- source/EN/migrations.textile | 17 ++- source/EN/rails_on_rack.textile | 123 ++++++++++++------ source/EN/routing.textile | 11 ++ .../ruby_on_rails_guides_guidelines.textile | 2 +- source/EN/testing.textile | 40 +++++- 25 files changed, 522 insertions(+), 150 deletions(-) create mode 100644 source/EN/kindle/KINDLE.md create mode 100644 source/EN/kindle/copyright.html.erb create mode 100644 source/EN/kindle/layout.html.erb create mode 100644 source/EN/kindle/rails_guides.opf.erb create mode 100644 source/EN/kindle/toc.html.erb create mode 100644 source/EN/kindle/toc.ncx.erb create mode 100644 source/EN/kindle/welcome.html.erb diff --git a/config/deploy.rb b/config/deploy.rb index 6e028cf..16039b4 100644 --- a/config/deploy.rb +++ b/config/deploy.rb @@ -1,8 +1,8 @@ set :application, "RailsGuides" -set :domain, "railschina.org" +set :domain, "www.railschina.org" set :use_sudo, false set :user, "ruby" -set :version, "v3.2.2" +set :version, "v3.2.3" set :repository, "./output" set :scm, :none diff --git a/source/EN/active_record_querying.textile b/source/EN/active_record_querying.textile index 8e23a57..de55401 100644 --- a/source/EN/active_record_querying.textile +++ b/source/EN/active_record_querying.textile @@ -133,6 +133,24 @@ SELECT * FROM clients ORDER BY clients.id DESC LIMIT 1 Model.last returns +nil+ if no matching record is found. No exception will be raised. +h5. +find_by+ + +Model.find_by finds the first record matching some conditions. For example: + + +Client.find_by first_name: 'Lifo' +# => # + +Client.find_by first_name: 'Jon' +# => nil + + +It is equivalent to writing: + + +Client.where(first_name: 'Lifo').first + + h5(#first_1). +first!+ Model.first! finds the first record. For example: @@ -167,6 +185,24 @@ SELECT * FROM clients ORDER BY clients.id DESC LIMIT 1 Model.last! raises +RecordNotFound+ if no matching record is found. +h5(#find_by_1). +find_by!+ + +Model.find_by! finds the first record matching some conditions. It raises +RecordNotFound+ if no matching record is found. For example: + + +Client.find_by! first_name: 'Lifo' +# => # + +Client.find_by! first_name: 'Jon' +# => RecordNotFound + + +It is equivalent to writing: + + +Client.where(first_name: 'Lifo').first! + + h4. Retrieving Multiple Objects h5. Using Multiple Primary Keys @@ -659,7 +695,7 @@ Optimistic locking allows multiple users to access the same record for edits, an Optimistic locking column -In order to use optimistic locking, the table needs to have a column called +lock_version+. Each time the record is updated, Active Record increments the +lock_version+ column. If an update request is made with a lower value in the +lock_version+ field than is currently in the +lock_version+ column in the database, the update request will fail with an +ActiveRecord::StaleObjectError+. Example: +In order to use optimistic locking, the table needs to have a column called +lock_version+ of type integer. Each time the record is updated, Active Record increments the +lock_version+ column. If an update request is made with a lower value in the +lock_version+ field than is currently in the +lock_version+ column in the database, the update request will fail with an +ActiveRecord::StaleObjectError+. Example: c1 = Client.find(1) @@ -943,21 +979,23 @@ If, in the case of this +includes+ query, there were no comments for any posts, 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+. All scope methods will return an +ActiveRecord::Relation+ object which will allow for further methods (such as other scopes) to be called on it. +Scoping allows you to specify commonly-used 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: +To define a simple scope, we use the +scope+ method inside the class, passing the query that we'd like run when this scope is called: class Post < ActiveRecord::Base - scope :published, where(:published => true) + scope :published, -> { where(published: true) } end -Just like before, these methods are also chainable: +This is exactly the same as defining a class method, and which you use is a matter of personal preference: class Post < ActiveRecord::Base - scope :published, where(:published => true).joins(:category) + def self.published + where(published: true) + end end @@ -965,8 +1003,8 @@ 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)) + scope :published, -> { where(:published => true) } + scope :published_and_commented, -> { published.where("comments_count > 0") } end @@ -983,25 +1021,13 @@ category = Category.first 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 :created_before_now, 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: +Your scope can take arguments: class Post < ActiveRecord::Base - scope :created_before, lambda { |time| where("created_at < ?", time) } + scope :created_before, ->(time) { where("created_at < ?", time) } end @@ -1048,7 +1074,7 @@ If we wish for a scope to be applied across all queries to the model we can use class Client < ActiveRecord::Base - default_scope where("removed_at IS NULL") + default_scope { where("removed_at IS NULL") } end diff --git a/source/EN/api_documentation_guidelines.textile b/source/EN/api_documentation_guidelines.textile index 14dddea..c6aa1f0 100644 --- a/source/EN/api_documentation_guidelines.textile +++ b/source/EN/api_documentation_guidelines.textile @@ -1,4 +1,4 @@ - h2. API Documentation Guidelines +h2. API Documentation Guidelines This guide documents the Ruby on Rails API documentation guidelines. @@ -133,6 +133,20 @@ h4. Regular Font When "true" and "false" are English words rather than Ruby keywords use a regular font: + +# Runs all the validations within the specified context. Returns true if no errors are found, +# false otherwise. +# +# If the argument is false (default is +nil+), the context is set to :create if +# new_record? is true, and to :update if it is not. +# +# Validations with no :on option will run no matter the context. Validations with +# some :on option will only run in the specified context. +def valid?(context = nil) + ... +end + + h3. Description Lists In lists of options, parameters, etc. use a hyphen between the item and its description (reads better than a colon because normally options are symbols): diff --git a/source/EN/asset_pipeline.textile b/source/EN/asset_pipeline.textile index b1b1d21..982c4aa 100644 --- a/source/EN/asset_pipeline.textile +++ b/source/EN/asset_pipeline.textile @@ -409,7 +409,9 @@ cannot see application objects or methods. *Heroku requires this to be false.* WARNING: If you set +config.assets.initialize_on_precompile+ to false, be sure to test +rake assets:precompile+ locally before deploying. It may expose bugs where your assets reference application objects or methods, since those are still -in scope in development mode regardless of the value of this flag. +in scope in development mode regardless of the value of this flag. Changing this flag also affects +engines. Engines can define assets for precompilation as well. Since the complete environment is not loaded, +engines (or other gems) will not be loaded, which can cause missing assets. Capistrano (v2.8.0 and above) includes a recipe to handle this in deployment. Add the following line to +Capfile+: @@ -671,7 +673,7 @@ config.assets.compile = false # Generate digests for assets URLs. config.assets.digest = true -# Defaults to Rails.root.join("public/assets") +# Defaults to nil and saved in location specified by config.assets.prefix # config.assets.manifest = YOUR_PATH # Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added) diff --git a/source/EN/association_basics.textile b/source/EN/association_basics.textile index 493b7c3..8ddc56b 100644 --- a/source/EN/association_basics.textile +++ b/source/EN/association_basics.textile @@ -342,9 +342,9 @@ In designing a data model, you will sometimes find a model that should have a re class Employee < ActiveRecord::Base - has_many :subordinates, :class_name => "Employee" - belongs_to :manager, :class_name => "Employee", + has_many :subordinates, :class_name => "Employee", :foreign_key => "manager_id" + belongs_to :manager, :class_name => "Employee" end diff --git a/source/EN/caching_with_rails.textile b/source/EN/caching_with_rails.textile index e2c6c7a..12bc32f 100644 --- a/source/EN/caching_with_rails.textile +++ b/source/EN/caching_with_rails.textile @@ -92,7 +92,7 @@ INFO: Page caching runs in an after filter. Thus, invalid requests won't generat h4. Action Caching -One of the issues with Page Caching is that you cannot use it for pages that require to restrict access somehow. This is where Action Caching comes in. Action Caching works like Page Caching except for the fact that the incoming web request does go from the webserver to the Rails stack and Action Pack so that before filters can be run on it before the cache is served. This allows authentication and other restriction to be run while still serving the result of the output from a cached copy. +Page Caching cannot be used for actions that have before filters - for example, pages that require authentication. This is where Action Caching comes in. Action Caching works like Page Caching except the incoming web request hits the Rails stack so that before filters can be run on it before the cache is served. This allows authentication and other restrictions to be run while still serving the result of the output from a cached copy. Clearing the cache works in a similar way to Page Caching, except you use +expire_action+ instead of +expire_page+. @@ -257,7 +257,9 @@ However, it's important to note that query caches are created at the start of an 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 provides different stores for the cached data created by action and fragment caches. + +TIP: Page caches are always stored on disk. h4. Configuration @@ -267,7 +269,7 @@ You can set up your application's default cache store by calling +config.cache_s config.cache_store = :memory_store -Alternatively, you can call +ActionController::Base.cache_store+ outside of a configuration block. +NOTE: Alternatively, you can call +ActionController::Base.cache_store+ outside of a configuration block. You can access the cache by calling +Rails.cache+. @@ -294,7 +296,7 @@ h4. ActiveSupport::Cache::MemoryStore 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 = :memory_store, :size => 64.megabytes +config.cache_store = :memory_store, :size => 64.megabytes 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. @@ -306,7 +308,7 @@ 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 = :file_store, "/path/to/cache/directory" +config.cache_store = :file_store, "/path/to/cache/directory" 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. @@ -322,7 +324,7 @@ When initializing the cache, you need to specify the addresses for all memcached 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 = :mem_cache_store, "cache-1.example.com", "cache-2.example.com" +config.cache_store = :mem_cache_store, "cache-1.example.com", "cache-2.example.com" h4. ActiveSupport::Cache::EhcacheStore @@ -330,7 +332,7 @@ h4. ActiveSupport::Cache::EhcacheStore If you are using JRuby you can use Terracotta's Ehcache as the cache store for your application. Ehcache is an open source Java cache that also offers an enterprise version with increased scalability, management, and commercial support. You must first install the jruby-ehcache-rails3 gem (version 1.1.0 or later) to use this cache store. -ActionController::Base.cache_store = :ehcache_store +config.cache_store = :ehcache_store When initializing the cache, you may use the +:ehcache_config+ option to specify the Ehcache config file to use (where the default is "ehcache.xml" in your Rails config directory), and the :cache_name option to provide a custom name for your cache (the default is rails_cache). @@ -359,7 +361,7 @@ h4. ActiveSupport::Cache::NullStore This cache store implementation is meant to be used only in development or test environments and it never stores anything. This can be very useful in development when you have code that interacts directly with +Rails.cache+, but caching may interfere with being able to see the results of code changes. With this cache store, all +fetch+ and +read+ operations will result in a miss. -ActionController::Base.cache_store = :null_store +config.cache_store = :null_store h4. Custom Cache Stores @@ -369,7 +371,7 @@ You can create your own custom cache store by simply extending +ActiveSupport::C To use a custom cache store, simple set the cache store to a new instance of the class. -ActionController::Base.cache_store = MyCacheStore.new +config.cache_store = MyCacheStore.new h4. Cache Keys diff --git a/source/EN/command_line.textile b/source/EN/command_line.textile index 463c2b1..858ce47 100644 --- a/source/EN/command_line.textile +++ b/source/EN/command_line.textile @@ -278,6 +278,12 @@ The +console+ command lets you interact with your Rails application from the com You can also use the alias "c" to invoke the console: rails c. +You can specify the environment in which the +console+ command should operate using the +-e+ switch. + + +$ rails console -e staging + + If you wish to test out some code without changing any data, you can do that by invoking +rails console --sandbox+. diff --git a/source/EN/configuring.textile b/source/EN/configuring.textile index cf0d8f1..717654d 100644 --- a/source/EN/configuring.textile +++ b/source/EN/configuring.textile @@ -354,8 +354,7 @@ h4. Configuring Action Dispatch h4. Configuring Action View -There are only a few configuration options for Action View, starting with six on +ActionView::Base+: - +config.action_view includes a small number of configuration settings: * +config.action_view.field_error_proc+ provides an HTML generator for displaying errors that come from Active Record. The default is @@ -395,6 +394,16 @@ And can reference in the view with the following code: * +config.action_view.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. +* +config.action_view.embed_authenticity_token_in_remote_forms+ allows you to set the default behavior for +authenticity_token+ in forms with +:remote => true+. By default it's set to false, which means that remote forms will not include +authenticity_token+, which is helpful when you're fragment-caching the form. Remote forms get the authenticity from the +meta+ tag, so embedding is unnecessary unless you support browsers without JavaScript. In such case you can either pass +:authenticity_token => true+ as a form option or set this config setting to +true+ + +* +config.action_view.prefix_partial_path_with_controller_namespace+ determines whether or not partials are looked up from a subdirectory in templates rendered from namespaced controllers. For example, consider a controller named +Admin::PostsController+ which renders this template: + + +<%= render @post %> + + +The default setting is +true+, which uses the partial at +/admin/posts/_post.erb+. Setting the value to +false+ would render +/posts/_post.erb+, which is the same behavior as rendering from a non-namespaced controller such as +PostsController+. + h4. Configuring Action Mailer There are a number of settings available on +config.action_mailer+: diff --git a/source/EN/contributing_to_ruby_on_rails.textile b/source/EN/contributing_to_ruby_on_rails.textile index d0dbb15..fbb3483 100644 --- a/source/EN/contributing_to_ruby_on_rails.textile +++ b/source/EN/contributing_to_ruby_on_rails.textile @@ -42,7 +42,7 @@ 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. +* "Everyday Git":http://schacon.github.com/git/everyday.html will teach you just enough about git to get by. * The "PeepCode screencast":https://peepcode.com/products/git on git ($9) is easier to follow. * "GitHub":http://help.github.com offers links to a variety of git resources. * "Pro Git":http://progit.org/book/ is an entire book about git with a Creative Commons license. diff --git a/source/EN/engines.textile b/source/EN/engines.textile index 6ae9504..36210ae 100644 --- a/source/EN/engines.textile +++ b/source/EN/engines.textile @@ -16,7 +16,7 @@ Engines can be considered miniature applications that provide functionality to t Therefore, engines and applications can be thought of almost the same thing, just with very minor differences, as you'll see throughout this guide. Engines and applications also share a common structure. -Engines are also closely related to plugins where the two share a common +lib+ directory structure and are both generated using the +rails plugin new+ generator. The difference being that an engine is considered a "full plugin" by Rails -- as indicated by the +--full+ option that's passed to the generator command -- but this guide will refer to them simply as "engines" throughout. An engine *can* be a plugin, and a plugin *can* be an engine. +Engines are also closely related to plugins where the two share a common +lib+ directory structure and are both generated using the +rails plugin new+ generator. The difference being that an engine is considered a "full plugin" by Rails as indicated by the +--full+ option that's passed to the generator command, but this guide will refer to them simply as "engines" throughout. An engine *can* be a plugin, and a plugin *can* be an engine. The engine that will be created in this guide will be called "blorgh". The engine will provide blogging functionality to its host applications, allowing for new posts and comments to be created. At the beginning of this guide, you will be working solely within the engine itself, but in later sections you'll see how to hook it into an application. @@ -51,7 +51,7 @@ h5. Critical files At the root of this brand new engine's directory, lives a +blorgh.gemspec+ file. When you include the engine into the application later on, you will do so with this line in a Rails application's +Gemfile+: - gem 'blorgh', :path => "vendor/engines/blorgh" +gem 'blorgh', :path => "vendor/engines/blorgh" By specifying it as a gem within the +Gemfile+, Bundler will load it as such, parsing this +blorgh.gemspec+ file and requiring a file within the +lib+ directory called +lib/blorgh.rb+. This file requires the +blorgh/engine.rb+ file (located at +lib/blorgh/engine.rb+) and defines a base module called +Blorgh+. @@ -77,7 +77,7 @@ end By inheriting from the +Rails::Engine+ class, this gem notifies Rails that there's an engine at the specified path, and will correctly mount the engine inside the application, performing tasks such as adding the +app+ directory of the engine to the load path for models, mailers, controllers and views. -The +isolate_namespace+ method here deserves special notice. This call is responsible for isolating the controllers, models, routes and other things into their own namespace, away from similar components inside hte application. Without this, there is a possibility that the engine's components could "leak" into the application, causing unwanted disruption, or that important engine components could be overriden by similarly named things within the application. One of the examples of such conflicts are helpers. Without calling +isolate_namespace+, engine's helpers would be included in application's controllers. +The +isolate_namespace+ method here deserves special notice. This call is responsible for isolating the controllers, models, routes and other things into their own namespace, away from similar components inside the application. Without this, there is a possibility that the engine's components could "leak" into the application, causing unwanted disruption, or that important engine components could be overridden by similarly named things within the application. One of the examples of such conflicts are helpers. Without calling +isolate_namespace+, engine's helpers would be included in application's controllers. NOTE: It is *highly* recommended that the +isolate_namespace+ line be left within the +Engine+ class definition. Without it, classes generated in an engine *may* conflict with an application. @@ -115,7 +115,6 @@ The +test+ directory is where tests for the engine will go. To test the engine, Rails.application.routes.draw do - mount Blorgh::Engine => "/blorgh" end @@ -126,7 +125,7 @@ Also in the test directory is the +test/integration+ directory, where integratio h3. Providing engine functionality -The engine that this guide covers will provide posting and commenting functionality and follows a similar thread to the "Getting Started Guide":getting-started.html, with some new twists. +The engine that this guide covers will provide posting and commenting functionality and follows a similar thread to the "Getting Started Guide":getting_started.html, with some new twists. h4. Generating a post resource @@ -179,7 +178,6 @@ After that, a line for the resource is inserted into the +config/routes.rb+ file Blorgh::Engine.routes.draw do resources :posts - end @@ -219,17 +217,13 @@ By default, the scaffold styling is not applied to the engine as the engine's la <%= stylesheet_link_tag "scaffold" %> -You can see what the engine has so far by running +rake db:migrate+ at the root of our engine to run the migration generated by the scaffold generator, and then running +rails server+. When you open +http://localhost:3000/blorgh/posts+ you will see the default scaffold that has been generated. - -!images/engines_scaffold.png(Blank engine scaffold)! - -Click around! You've just generated your first engine's first functions. +You can see what the engine has so far by running +rake db:migrate+ at the root of our engine to run the migration generated by the scaffold generator, and then running +rails server+ in +test/dummy+. When you open +http://localhost:3000/blorgh/posts+ you will see the default scaffold that has been generated. Click around! You've just generated your first engine's first functions. If you'd rather play around in the console, +rails console+ will also work just like a Rails application. Remember: the +Post+ model is namespaced, so to reference it you must call it as +Blorgh::Post+. - >> Blorgh::Post.find(1) - => # +>> Blorgh::Post.find(1) +=> # One final thing is that the +posts+ resource for this engine should be the root of the engine. Whenever someone goes to the root path where the engine is mounted, they should be shown a list of posts. This can be made to happen if this line is inserted into the +config/routes.rb+ file inside the engine: @@ -263,7 +257,7 @@ create test/fixtures/blorgh/comments.yml This generator call will generate just the necessary model files it needs, namespacing the files under a +blorgh+ directory and creating a model class called +Blorgh::Comment+. -To show the comments on a post, edit +app/views/posts/show.html.erb+ and add this line before the "Edit" link: +To show the comments on a post, edit +app/views/blorgh/posts/show.html.erb+ and add this line before the "Edit" link:

Comments

@@ -355,11 +349,11 @@ end This is the final part required to get the new comment form working. Displaying the comments however, is not quite right yet. If you were to create a comment right now you would see this error: - - Missing partial blorgh/comments/comment with {:handlers=>[:erb, :builder], :formats=>[:html], :locale=>[:en, :en]}. Searched in: - * "/Users/ryan/Sites/side_projects/blorgh/test/dummy/app/views" - * "/Users/ryan/Sites/side_projects/blorgh/app/views" - + +Missing partial blorgh/comments/comment with {:handlers=>[:erb, :builder], :formats=>[:html], :locale=>[:en, :en]}. Searched in: + * "/Users/ryan/Sites/side_projects/blorgh/test/dummy/app/views" + * "/Users/ryan/Sites/side_projects/blorgh/app/views" + The engine is unable to find the partial required for rendering the comments. Rails has looked firstly in the application's (+test/dummy+) +app/views+ directory and then in the engine's +app/views+ directory. When it can't find it, it will throw this error. The engine knows to look for +blorgh/comments/comment+ because the model object it is receiving is from the +Blorgh::Comment+ class. @@ -511,11 +505,11 @@ $ rake blorgh:install:migrations Notice here that only _one_ migration was copied over here. This is because the first two migrations were copied over the first time this command was run. - - NOTE: Migration [timestamp]_create_blorgh_posts.rb from blorgh has been skipped. Migration with the same name already exists. - NOTE: Migration [timestamp]_create_blorgh_comments.rb from blorgh has been skipped. Migration with the same name already exists. - Copied migration [timestamp]_add_author_id_to_blorgh_posts.rb from blorgh - + +NOTE Migration [timestamp]_create_blorgh_posts.rb from blorgh has been skipped. Migration with the same name already exists. +NOTE Migration [timestamp]_create_blorgh_comments.rb from blorgh has been skipped. Migration with the same name already exists. +Copied migration [timestamp]_add_author_id_to_blorgh_posts.rb from blorgh + Run this migration using this command: @@ -536,9 +530,9 @@ Finally, the author's name should be displayed on the post's page. Add this code By outputting +@post.author+ using the +<%=+ tag the +to_s+ method will be called on the object. By default, this will look quite ugly: - + # - + This is undesirable and it would be much better to have the user's name there. To do this, add a +to_s+ method to the +User+ class within the application: @@ -581,9 +575,9 @@ self.author = Blorgh.user_class.constantize.find_or_create_by_name(author_name) To save having to call +constantize+ on the +user_class+ result all the time, you could instead just override the +user_class+ getter method inside the +Blorgh+ module in the +lib/blorgh.rb+ file to always call +constantize+ on the saved value before returning the result: - def self.user_class - @@user_class.constantize - end +def self.user_class + @@user_class.constantize +end This would then turn the above code for +self.author=+ into this: @@ -663,10 +657,6 @@ Try this now by creating a new file at +app/views/blorgh/posts/index.html.erb+ a <% end %>
-Rather than looking like the default scaffold, the page will now look like this: - -!images/engines_post_override.png(Engine scaffold overriden)! - h4. Routes Routes inside an engine are, by default, isolated from the application. This is done by the +isolate_namespace+ call inside the +Engine+ class. This essentially means that the application and its engines can have identically named routes, and that they will not clash. @@ -674,9 +664,9 @@ Routes inside an engine are, by default, isolated from the application. This is Routes inside an engine are drawn on the +Engine+ class within +config/routes.rb+, like this: - Blorgh::Engine.routes.draw do - resources :posts - end +Blorgh::Engine.routes.draw do + resources :posts +end By having isolated routes such as this, if you wish to link to an area of an engine from within an application, you will need to use the engine's routing proxy method. Calls to normal routing methods such as +posts_path+ may end up going to undesired locations if both the application and the engine both have such a helper defined. @@ -717,11 +707,26 @@ Imagine that you did have an asset located at +app/assets/stylesheets/blorgh/sty You can also specify these assets as dependencies of other assets using the Asset Pipeline require statements in processed files: - + /* *= require blorgh/style */ - + + +h4. Separate Assets & Precompiling + +There are some situations where your engine's assets not required by the host application. For example, say that you've created +an admin functionality that only exists for your engine. In this case, the host application doesn't need to require +admin.css+ +or +admin.js+. Only the gem's admin layout needs these assets. It doesn't make sense for the host app to include +"blorg/admin.css"+ in it's stylesheets. In this situation, you should explicitly define these assets for precompilation. +This tells sprockets to add you engine assets when +rake assets:precompile+ is ran. + +You can define assets for precompilation in +engine.rb+ + + +initializer do |app| + app.config.assets.precompile += %w(admin.css admin.js) +end + For more information, read the "Asset Pipeline guide":http://guides.rubyonrails.org/asset_pipeline.html diff --git a/source/EN/getting_started.textile b/source/EN/getting_started.textile index fdae21c..59b12b4 100644 --- a/source/EN/getting_started.textile +++ b/source/EN/getting_started.textile @@ -73,7 +73,7 @@ h3. Creating a New Rails Project The best way to use this guide is to follow each step as it happens, no code or step needed to make this example application has been left out, so you can -literally follow along step by step. You can get the complete code "here":https://github.com/lifo/docrails/tree/master/railties/guides/code/getting_started. +literally follow along step by step. You can get the complete code "here":https://github.com/lifo/docrails/tree/master/guides/code/getting_started. By following along with this guide, you'll create a Rails project called blog, a (very) simple weblog. Before you can start building the application, you need to @@ -119,10 +119,10 @@ After you create the blog application, switch to its folder to continue work dir $ cd blog
-The +rails new blog+ command we ran above created a folder in your working directory called blog. The blog directory has a number of auto-generated folders that make up the structure of a Rails application. Most of the work in this tutorial will happen in the app/ folder, but here's a basic rundown on the function of each of the files and folders that Rails created by default: +The +rails new blog+ command we ran above created a folder in your working directory called blog. The blog directory has a number of auto-generated files and folders that make up the structure of a Rails application. Most of the work in this tutorial will happen in the app/ folder, but here's a basic rundown on the function of each of the files and folders that Rails created by default: |_.File/Folder|_.Purpose| -|app/|Contains the controllers, models, views and assets for your application. You'll focus on this folder for the remainder of this guide.| +|app/|Contains the controllers, models, views, helpers, mailers and assets for your application. You'll focus on this folder for the remainder of this guide.| |config/|Configure your application's runtime rules, routes, database, and more. This is covered in more detail in "Configuring Rails Applications":configuring.html| |config.ru|Rack configuration for Rack based servers used to start the application.| |db/|Contains your current database schema, as well as the database migrations.| @@ -152,11 +152,11 @@ $ rails server TIP: Compiling CoffeeScript to JavaScript requires a JavaScript runtime and the absence of a runtime will give you an +execjs+ error. Usually Mac OS X and Windows come with a JavaScript runtime installed. Rails adds the +therubyracer+ gem to Gemfile in a commented line for new apps and you can uncomment if you need it. +therubyrhino+ is the recommended runtime for JRuby users and is added by default to Gemfile in apps generated under JRuby. You can investigate about all the supported runtimes at "ExecJS":https://github.com/sstephenson/execjs#readme. -This will fire up an instance of a webserver built into Ruby called WEBrick by default. To see your application in action, open a browser window and navigate to "http://localhost:3000":http://localhost:3000. You should see Rails' default information page: +This will fire up an instance of a webserver built into Ruby called WEBrick by default. To see your application in action, open a browser window and navigate to "http://localhost:3000":http://localhost:3000. You should see the Rails default information page: !images/rails_welcome.png(Welcome Aboard screenshot)! -TIP: To stop the web server, hit Ctrl+C in the terminal window where it's running. In development mode, Rails does not generally require you to stop the server; changes you make in files will be automatically picked up by the server. +TIP: To stop the web server, hit Ctrl+C in the terminal window where it's running. In development mode, Rails does not generally require you to restart the server; changes you make in files will be automatically picked up by the server. The "Welcome Aboard" page is the _smoke test_ for a new Rails application: it makes sure that you have your software configured correctly enough to serve a page. You can also click on the _About your application’s environment_ link to see a summary of your application's environment. @@ -284,13 +284,13 @@ Missing template posts/new, application/new with {:locale=>[:en], :formats=>[:ht That's quite a lot of text! Let's quickly go through and understand what each part of it does. -The first part identifies what template is missing. In this case, it's the +posts/new+ template. Rails will first look for this template. If it can't find it, then it will attempt to load a template called +application/new+. It looks for one here because the +PostsController+ inherits from +ApplicationController+. +The first part identifies what template is missing. In this case, it's the +posts/new+ template. Rails will first look for this template. If not found, then it will attempt to load a template called +application/new+. It looks for one here because the +PostsController+ inherits from +ApplicationController+. -The next part of the message contains a hash. The +:locale+ key in this hash simply indicates what spoken language template should be retrieved. By default, this is the English -- or "en" -- template. The next key, +:formats+ shows what formats of template Rails is after. The default is +:html+, and so Rails is looking for an HTML template. The final key, +:handlers+, is telling us what _template handlers_ could be used to render our template. +:erb+ is most commonly used for HTML templates, +:builder+ is used for XML templates, and +:coffee+ uses CoffeeScript to build JavaScript templates. +The next part of the message contains a hash. The +:locale+ key in this hash simply indicates what spoken language template should be retrieved. By default, this is the English -- or "en" -- template. The next key, +:formats+ specifies the format of template to be served in response . The default format is +:html+, and so Rails is looking for an HTML template. The final key, +:handlers+, is telling us what _template handlers_ could be used to render our template. +:erb+ is most commonly used for HTML templates, +:builder+ is used for XML templates, and +:coffee+ uses CoffeeScript to build JavaScript templates. The final part of this message tells us where Rails has looked for the templates. Templates within a basic Rails application like this are kept in a single location, but in more complex applications it could be many different paths. -The simplest template that would work in this case would be one located at +app/views/posts/new.html.erb+. The extension of this file name is key: the first extension is the _format_ of the template, and the second extension is the _handler_ that will be used. Rails is attempting to find a template called +posts/new+ within +app/views+ for the application. The format for this template can only be +html+ and the handler must be one of +erb+, +builder+ or +coffee+. Because you want to create a new HTML form, you will be using the +ERB+ language. Therefore the file should be called +posts/new.html.erb+ and be located inside the +app/views+ directory of the application. +The simplest template that would work in this case would be one located at +app/views/posts/new.html.erb+. The extension of this file name is key: the first extension is the _format_ of the template, and the second extension is the _handler_ that will be used. Rails is attempting to find a template called +posts/new+ within +app/views+ for the application. The format for this template can only be +html+ and the handler must be one of +erb+, +builder+ or +coffee+. Because you want to create a new HTML form, you will be using the +ERB+ language. Therefore the file should be called +posts/new.html.erb+ and needs to be located inside the +app/views+ directory of the application. Go ahead now and create a new file at +app/views/posts/new.html.erb+ and write this content in it: diff --git a/source/EN/i18n.textile b/source/EN/i18n.textile index 320f1e9..6179694 100644 --- a/source/EN/i18n.textile +++ b/source/EN/i18n.textile @@ -866,19 +866,35 @@ The I18n API will catch all of these exceptions when they are thrown in the back The reason for this is that during development you'd usually want your views to still render even though a translation is missing. -In other contexts you might want to change this behaviour, though. E.g. the default exception handling does not allow to catch missing translations during automated tests easily. For this purpose a different exception handler can be specified. The specified exception handler must be a method on the I18n module: +In other contexts you might want to change this behaviour, though. E.g. the default exception handling does not allow to catch missing translations during automated tests easily. For this purpose a different exception handler can be specified. The specified exception handler must be a method on the I18n module or a class with +#call+ method: module I18n - def self.just_raise_that_exception(*args) - raise args.first + class JustRaiseExceptionHandler < ExceptionHandler + def call(exception, locale, key, options) + if exception.is_a?(MissingTranslation) + raise exception.to_exception + else + super + end + end end end -I18n.exception_handler = :just_raise_that_exception +I18n.exception_handler = I18n::JustRaiseExceptionHandler.new -This would re-raise all caught exceptions including +MissingTranslationData+. +This would re-raise only the +MissingTranslationData+ exception, passing all other input to the default exception handler. + +However, if you are using +I18n::Backend::Pluralization+ this handler will also raise +I18n::MissingTranslationData: translation missing: en.i18n.plural.rule+ exception that should normally be ignored to fall back to the default pluralization rule for English locale. To avoid this you may use additional check for translation key: + + +if exception.is_a?(MissingTranslation) && key.to_s != 'i18n.plural.rule' + raise exception.to_exception +else + super +end + Another example where the default behaviour is less desirable is the Rails TranslationHelper which provides the method +#t+ (as well as +#translate+). When a +MissingTranslationData+ exception occurs in this context, the helper wraps the message into a span with the CSS class +translation_missing+. diff --git a/source/EN/kindle/KINDLE.md b/source/EN/kindle/KINDLE.md new file mode 100644 index 0000000..a7d9a4e --- /dev/null +++ b/source/EN/kindle/KINDLE.md @@ -0,0 +1,26 @@ +# Rails Guides on the Kindle + + +## Synopsis + + 1. Obtain `kindlegen` from the link below and put the binary in your path + 2. Run `KINDLE=1 rake generate_guides` to generate the guides and compile the `.mobi` file + 3. Copy `output/kindle/rails_guides.mobi` to your Kindle + +## Resources + + * [StackOverflow: Kindle Periodical Format](http://stackoverflow.com/questions/5379565/kindle-periodical-format) + * Example Periodical [.ncx](https://gist.github.com/808c971ed087b839d462) and [.opf](https://gist.github.com/d6349aa8488eca2ee6d0) + * [Kindle Publishing guidelines](http://kindlegen.s3.amazonaws.com/AmazonKindlePublishingGuidelines.pdf) + * [KindleGen & Kindle Previewer](http://www.amazon.com/gp/feature.html?ie=UTF8&docId=1000234621) + +## TODO + +### Post release + + * Integrate generated Kindle document in to published HTML guides + * Tweak heading styles (most docs use h3/h4/h5, which end up being smaller than the text under it) + * Tweak table styles (smaller text? Many of the tables are unusable on a Kindle in portrait mode) + * Have the HTML/XML TOC 'drill down' into the TOCs of the individual guides + * `.epub` generation. + diff --git a/source/EN/kindle/copyright.html.erb b/source/EN/kindle/copyright.html.erb new file mode 100644 index 0000000..bd51d87 --- /dev/null +++ b/source/EN/kindle/copyright.html.erb @@ -0,0 +1 @@ +<%= render 'license' %> \ No newline at end of file diff --git a/source/EN/kindle/layout.html.erb b/source/EN/kindle/layout.html.erb new file mode 100644 index 0000000..f0a2862 --- /dev/null +++ b/source/EN/kindle/layout.html.erb @@ -0,0 +1,27 @@ + + + + + + +<%= yield(:page_title) || 'Ruby on Rails Guides' %> + + + + + + + <% if content_for? :header_section %> + <%= yield :header_section %> +
+ <% end %> + + <% if content_for? :index_section %> + <%= yield :index_section %> +
+ <% end %> + + <%= yield.html_safe %> + + diff --git a/source/EN/kindle/rails_guides.opf.erb b/source/EN/kindle/rails_guides.opf.erb new file mode 100644 index 0000000..4e07664 --- /dev/null +++ b/source/EN/kindle/rails_guides.opf.erb @@ -0,0 +1,52 @@ + + + + + + + + Ruby on Rails Guides (<%= @version %>) + + en-us + Ruby on Rails + Ruby on Rails + Reference + <%= Time.now.strftime('%Y-%m-%d') %> + + These guides are designed to make you immediately productive with Rails, and to help you understand how all of the pieces fit together. + + + + + + + + + <% documents_flat.each do |document| %> + + <% end %> + + <% %w{toc.html credits.html welcome.html copyright.html}.each do |url| %> + + <% end %> + + + + + + + + + + + + <% documents_flat.each do |document| %> + + <% end %> + + + + + + + diff --git a/source/EN/kindle/toc.html.erb b/source/EN/kindle/toc.html.erb new file mode 100644 index 0000000..e013797 --- /dev/null +++ b/source/EN/kindle/toc.html.erb @@ -0,0 +1,24 @@ +<% content_for :page_title do %> +Ruby on Rails Guides +<% end %> + +

Table of Contents

+
+ +<% documents_by_section.each_with_index do |section, i| %> +

<%= "#{i + 1}." %> <%= section['name'] %>

+
    + <% section['documents'].each do |document| %> +
  • + <%= document['name'] %> + <% if document['work_in_progress']%>(WIP)<% end %> +
  • + <% end %> +
+<% end %> +
+
diff --git a/source/EN/kindle/toc.ncx.erb b/source/EN/kindle/toc.ncx.erb new file mode 100644 index 0000000..2c6d8e3 --- /dev/null +++ b/source/EN/kindle/toc.ncx.erb @@ -0,0 +1,64 @@ + + + + + + + + + + +Ruby on Rails Guides +docrails + + + + Table of Contents + + + + + + Introduction + + + + + + Welcome + + + + + Credits + + + + Copyright & License + + + + + <% play_order = 4 %> + <% documents_by_section.each_with_index do |section, section_no| %> + + + <%= section['name'] %> + + + + <% section['documents'].each_with_index do |document, document_no| %> + + + <%= document['name'] %> + + + + <% end %> + + <% end %> + + + + diff --git a/source/EN/kindle/welcome.html.erb b/source/EN/kindle/welcome.html.erb new file mode 100644 index 0000000..e30704c --- /dev/null +++ b/source/EN/kindle/welcome.html.erb @@ -0,0 +1,5 @@ +<%= render 'welcome' %> + +

Kindle Edition

+ +The Kindle Edition of the Rails Guides should be considered a work in progress. Feedback is really welcome, please see the "Feedback" section at the end of each guide for instructions. diff --git a/source/EN/layouts_and_rendering.textile b/source/EN/layouts_and_rendering.textile index 4b4f9f3..7c7fc70 100644 --- a/source/EN/layouts_and_rendering.textile +++ b/source/EN/layouts_and_rendering.textile @@ -1134,13 +1134,6 @@ In Rails 3.0, there is also a shorthand for this. Assuming +@products+ is a coll 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: -In the event that the collection is empty, +render+ will return nil, so it should be fairly simple to provide alternative content. - - -

Products

-<%= render(@products) || 'There are no products available.' %> -
- * +index.html.erb+ @@ -1162,6 +1155,13 @@ In the event that the collection is empty, +render+ will return nil, so it shoul In this case, Rails will use the customer or employee partials as appropriate for each member of the collection. +In the event that the collection is empty, +render+ will return nil, so it should be fairly simple to provide alternative content. + + +

Products

+<%= render(@products) || 'There are no products available.' %> +
+ h5. Local Variables To use a custom local variable name within the partial, specify the +:as+ option in the call to the partial: diff --git a/source/EN/migrations.textile b/source/EN/migrations.textile index c11f8e2..f663496 100644 --- a/source/EN/migrations.textile +++ b/source/EN/migrations.textile @@ -51,7 +51,7 @@ end This migration adds a table called +products+ with a string column called +name+ and a text column called +description+. A primary key column called +id+ will -also be added, however since this is the default we do not need to ask for this. +also be added, however since this is the default we do not need to explicitly specify it. The timestamp columns +created_at+ and +updated_at+ which Active Record populates automatically will also be added. Reversing this migration is as simple as dropping the table. @@ -65,7 +65,7 @@ class AddReceiveNewsletterToUsers < ActiveRecord::Migration change_table :users do |t| t.boolean :receive_newsletter, :default => false end - User.update_all ["receive_newsletter = ?", true] + User.update_all :receive_newsletter => true end def down @@ -497,7 +497,7 @@ and h4. Using the +change+ Method The +change+ method removes the need to write both +up+ and +down+ methods in -those cases that Rails know how to revert the changes automatically. Currently, +those cases that Rails knows how to revert the changes automatically. Currently, the +change+ method supports only these migration definitions: * +add_column+ @@ -635,10 +635,9 @@ example, $ rake db:migrate:up VERSION=20080906120000 -will run the +up+ method from the 20080906120000 migration. These tasks still -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. +will run the +up+ method from the 20080906120000 migration. This task will first +check whether the migration is already performed and will do nothing if Active Record believes +that it has already been run. h4. Changing the output of running migrations @@ -728,7 +727,7 @@ class AddFlagToProduct < ActiveRecord::Migration def change add_column :products, :flag, :boolean Product.all.each do |product| - product.update_attributes!(:flag => 'false') + product.update_attributes!(:flag => false) end end end @@ -804,7 +803,7 @@ class AddFlagToProduct < ActiveRecord::Migration end def change - add_column :products, :flag, :integer + add_column :products, :flag, :boolean Product.reset_column_information Product.all.each do |product| product.update_attributes!(:flag => false) diff --git a/source/EN/rails_on_rack.textile b/source/EN/rails_on_rack.textile index 9526526..ff86227 100644 --- a/source/EN/rails_on_rack.textile +++ b/source/EN/rails_on_rack.textile @@ -91,13 +91,15 @@ For a freshly generated Rails application, this might produce something like: use ActionDispatch::Static use Rack::Lock -use ActiveSupport::Cache::Strategy::LocalCache +use # use Rack::Runtime +use Rack::MethodOverride +use ActionDispatch::RequestId use Rails::Rack::Logger use ActionDispatch::ShowExceptions use ActionDispatch::DebugExceptions use ActionDispatch::RemoteIp -use Rack::Sendfile +use ActionDispatch::Reloader use ActionDispatch::Callbacks use ActiveRecord::ConnectionAdapters::ConnectionManagement use ActiveRecord::QueryCache @@ -105,8 +107,9 @@ use ActionDispatch::Cookies use ActionDispatch::Session::CookieStore use ActionDispatch::Flash use ActionDispatch::ParamsParser -use Rack::MethodOverride use ActionDispatch::Head +use Rack::ConditionalGet +use Rack::ETag use ActionDispatch::BestStandardsSupport run Blog::Application.routes @@ -145,62 +148,104 @@ You can swap an existing middleware in the middleware stack using +config.middle # config/application.rb -# Replace ActionController::Failsafe with Lifo::Failsafe -config.middleware.swap ActionController::Failsafe, Lifo::Failsafe +# Replace ActionDispatch::ShowExceptions with Lifo::ShowExceptions +config.middleware.swap ActionDispatch::ShowExceptions, Lifo::ShowExceptions h5. Middleware Stack is an Array The middleware stack behaves just like a normal +Array+. You can use any +Array+ methods to insert, reorder, or remove items from the stack. Methods described in the section above are just convenience methods. -For example, the following removes the middleware matching the supplied class name: +Append following lines to your application configuration: -config.middleware.delete(middleware) +# config/application.rb +config.middleware.delete "Rack::Lock" +And now if you inspect the middleware stack, you'll find that +Rack::Lock+ will not be part of it. + + +$ rake middleware +(in /Users/lifo/Rails/blog) +use ActionDispatch::Static +use # +use Rack::Runtime +... +run Myapp::Application.routes + + h4. Internal Middleware Stack -Much of Action Controller's functionality is implemented as Middlewares. The following table explains the purpose of each of them: +Much of Action Controller's functionality is implemented as Middlewares. The following list explains the purpose of each of them: -|_.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+|Enables the Active Record query cache.| -|+ActionDispatch::Session::CookieStore+|Uses the cookie based session store.| -|+ActionDispatch::Session::CacheStore+|Uses the Rails cache based session store.| -|+ActionDispatch::Session::MemCacheStore+|Uses the memcached based session store.| -|+ActiveRecord::SessionStore+|Uses the database based session store.| -|+Rack::MethodOverride+|Sets HTTP method based on +_method+ parameter or env["HTTP_X_HTTP_METHOD_OVERRIDE"].| -|+Rack::Head+|Discards the response body if the client sends a +HEAD+ request.| + *+ActionDispatch::Static+* +* Used to serve static assets. Disabled if config.serve_static_assets is true. -TIP: It's possible to use any of the above middlewares in your custom Rack stack. + *+Rack::Lock+* +* Sets env["rack.multithread"] flag to +true+ and wraps the application within a Mutex. -h4. Customizing Internal Middleware Stack + *+ActiveSupport::Cache::Strategy::LocalCache::Middleware+* +* Used for memory caching. This cache is not thread safe. -It's possible to replace the entire middleware stack with a custom stack using ActionController::Dispatcher.middleware=. + *+Rack::Runtime+* +* Sets an X-Runtime header, containing the time (in seconds) taken to execute the request. -Put the following in an initializer: + *+Rack::MethodOverride+* +* Allows the method to be overridden if params[:_method] is set. This is the middleware which supports the PUT and DELETE HTTP method types. - -# config/initializers/stack.rb -ActionController::Dispatcher.middleware = ActionController::MiddlewareStack.new do |m| - m.use ActionController::Failsafe - m.use ActiveRecord::QueryCache - m.use Rack::Head -end - + *+ActionDispatch::RequestId+* +* Makes a unique +X-Request-Id+ header available to the response and enables the ActionDispatch::Request#uuid method. -And now inspecting the middleware stack: + *+Rails::Rack::Logger+* +* Notifies the logs that the request has began. After request is complete, flushes all the logs. - -$ rake middleware -(in /Users/lifo/Rails/blog) -use ActionController::Failsafe -use ActiveRecord::QueryCache -use Rack::Head -run ActionController::Dispatcher.new - + *+ActionDispatch::ShowExceptions+* +* Rescues any exception returned by the application and calls an exceptions app that will wrap it in a format for the end user. + + *+ActionDispatch::DebugExceptions+* +* Responsible for logging exceptions and showing a debugging page in case the request is local. + + *+ActionDispatch::RemoteIp+* +* Checks for IP spoofing attacks. + + *+ActionDispatch::Reloader+* +* Provides prepare and cleanup callbacks, intended to assist with code reloading during development. + + *+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+* +* Enables the Active Record query cache. + + *+ActionDispatch::Cookies+* +* Sets cookies for the request. + + *+ActionDispatch::Session::CookieStore+* +* Responsible for storing the session in cookies. + + *+ActionDispatch::Flash+* +* Sets up the flash keys. Only available if config.action_controller.session_store is set to a value. + + *+ActionDispatch::ParamsParser+* +* Parses out parameters from the request into params. + + *+ActionDispatch::Head+* +* Converts HEAD requests to +GET+ requests and serves them as so. + + *+Rack::ConditionalGet+* +* Adds support for "Conditional +GET+" so that server responds with nothing if page wasn't changed. + + *+Rack::ETag+* +* Adds ETag header on all String bodies. ETags are used to validate cache. + + *+ActionDispatch::BestStandardsSupport+* +* Enables “best standards support” so that IE8 renders some elements correctly. + +TIP: It's possible to use any of the above middlewares in your custom Rack stack. h4. Using Rack Builder diff --git a/source/EN/routing.textile b/source/EN/routing.textile index e93b128..75f4e82 100644 --- a/source/EN/routing.textile +++ b/source/EN/routing.textile @@ -535,6 +535,17 @@ TwitterClone::Application.routes.draw do end +You can also specify constraints as a lambda: + + +TwitterClone::Application.routes.draw do + match "*path" => "blacklist#index", + :constraints => lambda { |request| Blacklist.retrieve_ips.include?(request.remote_ip) } +end + + +Both the +matches?+ method and the lambda gets the +request+ object as an argument. + h4. Route Globbing Route globbing is a way to specify that a particular parameter should be matched to all the remaining parts of a route. For example diff --git a/source/EN/ruby_on_rails_guides_guidelines.textile b/source/EN/ruby_on_rails_guides_guidelines.textile index f7d1ed8..f3e934d 100644 --- a/source/EN/ruby_on_rails_guides_guidelines.textile +++ b/source/EN/ruby_on_rails_guides_guidelines.textile @@ -44,7 +44,7 @@ h3. HTML Guides h4. Generation -To generate all the guides, just +cd+ into the +guides+ directory and execute: +To generate all the guides, just +cd+ into the *+guides+* directory and execute: bundle exec rake generate_guides diff --git a/source/EN/testing.textile b/source/EN/testing.textile index c367f53..d35be6a 100644 --- a/source/EN/testing.textile +++ b/source/EN/testing.textile @@ -412,7 +412,7 @@ NOTE: +assert_valid(record)+ has been deprecated. Please use +assert(record.vali |+assert_no_difference(expressions, message = nil, &block)+ |Asserts that the numeric result of evaluating an expression is not changed before and after invoking the passed in block.| |+assert_recognizes(expected_options, path, extras={}, message=nil)+ |Asserts that the routing of the given path was handled correctly and that the parsed options (given in the expected_options hash) match path. Basically, it asserts that Rails recognizes the route given by expected_options.| |+assert_generates(expected_path, options, defaults={}, extras = {}, message=nil)+ |Asserts that the provided options can be used to generate the provided path. This is the inverse of assert_recognizes. The extras parameter is used to tell the request the names and values of additional request parameters that would be in a query string. The message parameter allows you to specify a custom error message for assertion failures.| -|+assert_response(type, message = nil)+ |Asserts that the response comes with a specific status code. You can specify +:success+ to indicate 200, +:redirect+ to indicate 300-399, +:missing+ to indicate 404, or +:error+ to match the 500-599 range| +|+assert_response(type, message = nil)+ |Asserts that the response comes with a specific status code. You can specify +:success+ to indicate 200-299, +:redirect+ to indicate 300-399, +:missing+ to indicate 404, or +:error+ to match the 500-599 range| |+assert_redirected_to(options = {}, message=nil)+ |Assert that the redirection options passed in match those of the redirect called in the latest action. This match can be partial, such that +assert_redirected_to(:controller => "weblog")+ will also match the redirection of +redirect_to(:controller => "weblog", :action => "show")+ and so on.| |+assert_template(expected = nil, message=nil)+ |Asserts that the request was rendered with the appropriate template file.| @@ -524,6 +524,44 @@ You also have access to three instance variables in your functional tests: * +@request+ - The request * +@response+ - The response +h4. Testing Templates and Layouts + +If you want to make sure that the response rendered the correct template and layout, you can use the +assert_template+ +method: + + +test "index should render correct template and layout" do + get :index + assert_template :index + assert_template :layout => "layouts/application" +end + + +Note that you cannot test for template and layout at the same time, with one call to +assert_template+ method. +Also, for the +layout+ test, you can give a regular expression instead of a string, but using the string, makes +things clearer. On the other hand, you have to include the "layouts" directory name even if you save your layout +file in this standard layout directory. Hence, + + +assert_template :layout => "application" + + +will not work. + +If your view renders any partial, when asserting for the layout, you have to assert for the partial at the same time. +Otherwise, assertion will fail. + +Hence: + + +test "new should render correct layout" do + get :new + assert_template :layout => "layouts/application", :partial => "_form" +end + + +is the correct way to assert for the layout when the view renders a partial with name +_form+. Omitting the +:partial+ key in your +assert_template+ call will complain. + h4. A Fuller Functional Test Example Here's another example that uses +flash+, +assert_redirected_to+, and +assert_difference+: From 44f24c43d1935480fa0cb8107f5b4b7f06c79e95 Mon Sep 17 00:00:00 2001 From: Tassandar Date: Mon, 9 Apr 2012 15:31:46 +0800 Subject: [PATCH 08/11] =?UTF-8?q?=E4=BF=AE=E6=94=B9=20README?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.markdown | 1 - 1 file changed, 1 deletion(-) diff --git a/README.markdown b/README.markdown index 586cfc1..f255422 100644 --- a/README.markdown +++ b/README.markdown @@ -39,7 +39,6 @@ Rails Guides 中文用了一些关键字来让你的文章生成更加便捷。 * [textile 语法](http://redcloth.org/textile) -**由于 markdown 没有提供设置 id 的内建语法,生成的目录无法产生链接,我会尽快修复**。 ##### 概要 From 76139d2b2ed4d67d34cda2d3acde6e7ee1e93939 Mon Sep 17 00:00:00 2001 From: tassandar Date: Thu, 12 Apr 2012 16:30:32 +0800 Subject: [PATCH 09/11] =?UTF-8?q?=E6=B5=8B=E8=AF=95=E6=89=8B=E5=86=8C?= =?UTF-8?q?=E7=BF=BB=E8=AF=91=E5=AE=8C=E6=88=90=EF=BC=8C=E4=BF=AE=E6=94=B9?= =?UTF-8?q?=E4=BA=86=E9=83=A8=E5=88=86=E9=93=BE=E6=8E=A5=E5=86=85=E5=AE=B9?= =?UTF-8?q?=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 2 +- source/CN/_feedback.html.erb | 6 +- source/CN/_welcome.html.erb | 4 +- source/CN/performance_testing.textile | 481 ++++---------------------- 4 files changed, 71 insertions(+), 422 deletions(-) diff --git a/.gitignore b/.gitignore index 076f422..9128f32 100644 --- a/.gitignore +++ b/.gitignore @@ -5,4 +5,4 @@ tags .lock /.git* /.gitignore - +/rails-guides/source/CN/google6a3b64c272ed36b0.html diff --git a/source/CN/_feedback.html.erb b/source/CN/_feedback.html.erb index 9a2c292..f68c178 100644 --- a/source/CN/_feedback.html.erb +++ b/source/CN/_feedback.html.erb @@ -3,11 +3,11 @@ 你也可以为 Rails Guides 中文做出贡献.

- 如果你发现了任何翻译上的错误或者不足.请到<%= link_to 'GitHub帐号','http://github.com/RubyChinaTranslation/rails-guides-china'%> clone 并且 fork 一份进行更正提交,我们会很快做出回应。 + 如果你发现了任何翻译上的错误或者不足.请到<%= link_to 'GitHub帐号','https://github.com/ruby-china/rails-guides/'%> clone 并且 fork 一份进行更正提交,我们会很快做出回应。 如果你发现了任何代码上的bug或者不足,你可以到<%= link_to 'docrails', 'https://github.com/lifo/docrails' %> 进行反馈与更正。 - 如果你发现了某一篇文章已经过时了并且并没有做出相应的提示,你也同样可以在<%= link_to '这里','http://github.com/rubychinatranslation/rails-guides-china/issues' %>上发起一个请求来提醒我们。 + 如果你发现了某一篇文章已经过时了并且并没有做出相应的提示,你也同样可以在<%= link_to '这里','https://github.com/ruby-china/rails-guides/issues' %>上发起一个请求来提醒我们。

-

如果对rails有什么建议的话去这里<%= link_to 'open an issue for rails', 'https://github.com/rails/rails/issues'%>.

+

如果对rails有什么建议的话去这里<%= link_to 'open an issue for rails', 'https://github.com/rails/rails/issues/'%>.

当然你不管你有什么想要说的都可以发到 <%= link_to 'ruby china社区','http://ruby-china.org' %> 讨论或者<%= mail_to "cool.zhikai@gmail.com","mail我"%>.欢迎加入到Ruby on Rails 社区!

diff --git a/source/CN/_welcome.html.erb b/source/CN/_welcome.html.erb index 3082231..dce2c22 100644 --- a/source/CN/_welcome.html.erb +++ b/source/CN/_welcome.html.erb @@ -5,7 +5,7 @@ 这是一个 Edge Guides, 基於 master 分支.

- 如果你需要的是一个稳定版的文档,你可以参见 这里 + 如果你需要的是一个稳定版的文档,你可以参见 这里

<% else %>

@@ -17,5 +17,5 @@ 你能在这里找到官方的原版 Rails Guide .

- Ruby on Rails Guides 中文需要热心的你,加入翻译或者建议. + Ruby on Rails Guides 中文需要热心的你,加入翻译或者建议.

diff --git a/source/CN/performance_testing.textile b/source/CN/performance_testing.textile index 958b13c..fa89a09 100644 --- a/source/CN/performance_testing.textile +++ b/source/CN/performance_testing.textile @@ -1,22 +1,23 @@ -h2. Performance Testing Rails Applications +h2. Rails 应用中的性能测试 -This guide covers the various ways of performance testing a Ruby on Rails application. By referring to this guide, you will be able to: +这篇文章介绍了几种在 Ruby on Rails 应用中进行性能测试的方法。通过阅读这篇文章,你可以 * Understand the various types of benchmarking and profiling metrics -* Generate performance and benchmarking tests -* Install and use a GC-patched Ruby binary to measure memory usage and object allocation -* Understand the benchmarking information provided by Rails inside the log files +* 生成一个 benchmark 性能测试。 +* 安装使用 Ruby的扩展GC类库来测试你的内存使用和分配情况。 +* 通过 Rails 内置的日志功能来了解 benchmarking 信息。 * Learn about various tools facilitating benchmarking and profiling -Performance testing is an integral part of the development cycle. It is very important that you don't make your end users wait for too long before the page is completely loaded. Ensuring a pleasant browsing experience for end users and cutting the cost of unnecessary hardware is important for any non-trivial web application. +在开发中,性能测试是一个循序渐进的过程。让你的用户能够很快的完成加载并看到你的产品是非常重要的。确保用户在各类浏览器上的体验,降低硬件上不必要的消耗是每一个 web 程序都必须要做到的。 endprologue. -h3. Performance Test Cases +h3. 性能测试案例 -Rails performance tests are a special type of integration tests, designed for benchmarking and profiling the test code. With performance tests, you can determine where your application's memory or speed problems are coming from, and get a more in-depth picture of those problems. +Rails 性能测试是包括基准测试,夹具测试在内的一系列集成测试。用上了性能测试,你可以发现你的应用程序中存在的内存或者速度问题,对存在的问题进行更深入的检测。 + +在这里我们新建一个 Rails 应用程序, +test/performance/browsing_test.rb+ ,在这个文件里写入一个测试的例子: -In a freshly generated Rails application, +test/performance/browsing_test.rb+ contains an example of a performance test: require 'test_helper' @@ -30,17 +31,17 @@ class BrowsingTest < ActionDispatch::PerformanceTest end -This example is a simple performance test case for profiling a GET request to the application's homepage. +这是一个简单的性能测试例子,它会为你生成一个 GET 请求的性能测试夹具(profiling). -h4. Generating Performance Tests +h4. 生成一个性能测试 -Rails provides a generator called +performance_test+ for creating new performance tests: +Rails 提供了一个 +performance_test+ 生成器来新建一个性能测试 $ rails generate performance_test homepage -This generates +homepage_test.rb+ in the +test/performance+ directory: +这里生成的 +performance_test.rb+ 在 +test/performance+ 目录中: require 'test_helper' @@ -54,9 +55,10 @@ class HomepageTest < ActionDispatch::PerformanceTest end -h4. Examples +h4. 例子 + +现在假设你的应用程序有这些 controller 和 model : -Let's assume your application has the following controller and model: # routes.rb @@ -95,11 +97,12 @@ class Post < ActiveRecord::Base end -h5. Controller Example +h5. 控制器测试范例 + +因为性能测试本质上是一种特殊的集成测试(integration test) ,你可以在测试中使用 +get+ 和 +post+ 方法。 -Because performance tests are a special kind of integration test, you can use the +get+ and +post+ methods in them. +下面分别是 +HomeController#dashboard+ 和 +PostsController#create+ 的测试: -Here's the performance test for +HomeController#dashboard+ and +PostsController#create+: require 'test_helper' @@ -121,93 +124,76 @@ class PostPerformanceTest < ActionDispatch::PerformanceTest end -You can find more details about the +get+ and +post+ methods in the "Testing Rails Applications":testing.html guide. - -h5. Model Example - -Even though the performance tests are integration tests and hence closer to the request/response cycle by nature, you can still performance test pure model code. - -Performance test for +Post+ model: - - -require 'test_helper' -require 'rails/performance_test_help' - -class PostModelTest < ActionDispatch::PerformanceTest - def test_creation - Post.create :body => 'still fooling you', :cost => '100' - end - - def test_slow_method - # Using posts(:awesome) fixture - posts(:awesome).slow_method - end -end - +你可以在"Testing Rails Applications":testing.html这篇文章中找到 +get+ 和 +post+ 的更多细节。 -h4. Modes +h4. 模式 -Performance tests can be run in two modes: Benchmarking and Profiling. +性能测试可以运行于两种测试中: 基准模式 (Benchmarking)和 夹具模式(Profiling) -h5. Benchmarking +h5. 基准模式 -Benchmarking makes it easy to quickly gather a few metrics about each test run. By default, each test case is run *4 times* in benchmarking mode. +基准测试能让我们迅速获取每个测试运行的数据。默认情况下,每一个测试都会在基准模式下运行 *四 次*。 -To run performance tests in benchmarking mode: +你可以这样来启动一个 基准测试。 $ rake test:benchmark -h5. Profiling +h5. 夹具测试 + +夹具(Profiling)能让你借助一个模具(profiler)更深入的分析你的每一个测试,根据你的Ruby解释器,这个测试模具可能会是本地的(ruby , JRuby的话)或者不是远程的(MRI,用在了 RubyProf上)。默认情况下,每一个测试用例会在夹具模式下被运行一次。 -Profiling allows you to make an in-depth analysis of each of your tests by using an external profiler. Depending on your Ruby interpreter, this profiler can be native (Rubinius, JRuby) or not (MRI, which uses RubyProf). By default, each test case is run *once* in profiling mode. +我们可以这样运行一个 夹具测试: -To run performance tests in profiling mode: $ rake test:profile -h4. Metrics +h4. 数据(Metrics) -Benchmarking and profiling run performance tests and give you multiple metrics. The availability of each metric is determined by the interpreter being used—none of them support all metrics—and by the mode in use. A brief description of each metric and their availability across interpreters/modes is given below. +夹具测试和性能测试会得到几组数据,每个数据的产生都取决于计算机的硬件,模式,解释器的使用————这意味着你需要综合的看待他们。应该尽量对每一组数据都做出一个简短描述并记录下当前运行的环境。 -h5. Wall Time +h5. 真实时间(Wall Time) -Wall time measures the real world time elapsed during the test run. It is affected by any other processes concurrently running on the system. +Wall Time 记录了你在跑测试的时候花了多少时间,这个时间会被计算机系统上的其他进程影响。 -h5. Process Time +h5. 处理时间(Process Time) -Process time measures the time taken by the process. It is unaffected by any other processes running concurrently on the same system. Hence, process time is likely to be constant for any given performance test, irrespective of the machine load. +Process Time 记录了 CPU 花在单个进程上的时间,这个数据并不会被同系统上的其他进程所影响。也正是因此,Process Time 通常对于同一个性能测试来说会是一个常数————如果忽略机器的载入时间的话。 -h5. CPU Time -Similar to process time, but leverages the more accurate CPU clock counter available on the Pentium and PowerPC platforms. +h5. CPU时间(CPU Time) -h5. User Time +与 process time 相似, 但是 CPU Time 运用了 更加精准的 CPU 时钟计数器,该功能只在奔腾和PowerPC平台上有效. -User time measures the amount of time the CPU spent in user-mode, i.e. within the process. This is not affected by other processes and by the time it possibly spends blocked. +h5. 用户时间(User Time) -h5. Memory +User Time 计算了CPU花在 用户态下的时间总和。它不会被其他处理器所影响,但是可能会被 “阻止”(blocked)的状态影响。 -Memory measures the amount of memory used for the performance test case. +TIP: 译者注: "用户态"http://zh.wikipedia.org/wiki/%E7%94%A8%E6%88%B7%E6%80%81(user mode)在计算机结构指两项类似的概念。在CPU的设计中,用户态指非特权状态。在此状态下,执行的代码被硬件限定,不能进行某些操作,比如写入其他进程的存储空间,以防止给操作系统带来安全隐患。在操作系统的设计中,用户态也类似,指非特权的执行状态。内核禁止此状态下的代码进行潜在危险的操作,比如写入系统配置文件、杀掉其他用户的进程、重启系统等。 -h5. Objects +h5. 内存 -Objects measures the number of objects allocated for the performance test case. +计算在性能测试用例中所占用的内存 -h5. GC Runs +h5. 对象 -GC Runs measures the number of times GC was invoked for the performance test case. +对象(Objects)计算了性能测试中被分配了的对象总数。 -h5. GC Time +h5. GC 状态 -GC Time measures the amount of time spent in GC for the performance test case. +GC 状态 (GC Runs)计算了在性能测试中GC被调用的次数 -h5. Metric Availability +h5. GC 时间 + +GC Time 计算了在性能测试GC所花费的总时间。 + +h5. 数据失礼 + +h6. 基准测试 -h6(#benchmarking_1). Benchmarking |_.Interpreter|_.Wall Time|_.Process Time|_.CPU Time|_.User Time|_.Memory|_.Objects|_.GC Runs|_.GC Time| |_.MRI | yes | yes | yes | no | yes | yes | yes | yes | @@ -215,7 +201,7 @@ h6(#benchmarking_1). Benchmarking |_.Rubinius | yes | no | no | no | yes | yes | yes | yes | |_.JRuby | yes | no | no | yes | yes | yes | yes | yes | -h6(#profiling_1). Profiling +h6. 夹具 |_.Interpreter|_.Wall Time|_.Process Time|_.CPU Time|_.User Time|_.Memory|_.Objects|_.GC Runs|_.GC Time| |_.MRI | yes | yes | no | no | yes | yes | yes | yes | @@ -223,19 +209,19 @@ h6(#profiling_1). Profiling |_.Rubinius | yes | no | no | no | no | no | no | no | |_.JRuby | yes | no | no | no | no | no | no | no | -NOTE: To profile under JRuby you'll need to run +export JRUBY_OPTS="-Xlaunch.inproc=false --profile.api"+ *before* the performance tests. +NOTE: 要在JRuby下面运行这个测试你可能需要在运行测试前运行 +export JRUBY_OPTS="-Xlaunch.inproc=false --profile.api" . -h4. Understanding the Output +h4. 输出 -Performance tests generate different outputs inside +tmp/performance+ directory depending on their mode and metric. +性能测试会根据你的模式在+tmp/performance+文件夹里面输出几个不同的测试结果。 -h5(#output-benchmarking). Benchmarking +h5. 基准测试 -In benchmarking mode, performance tests generate two types of outputs. +在基准模式中,性能测试会产生两种输出。 -h6(#output-command-line). Command Line +h6. 命令行 -This is the primary form of output in benchmarking mode. Example: +这是一个基准测试所产生输出示例: BrowsingTest#test_homepage (31 ms warmup) @@ -246,9 +232,9 @@ BrowsingTest#test_homepage (31 ms warmup) gc_time: 19 ms -h6. CSV Files +h6. CSV 文件 -Performance test results are also appended to +.csv+ files inside +tmp/performance+. For example, running the default +BrowsingTest#test_homepage+ will generate following five files: +性能测试的输出结果同样可以输出到 +tmp/performance+ 下面的 +.csv+ 文件。举例来说,运行+BrowsingTest#test_homepage+ 将会生成以下5个文件: * BrowsingTest#test_homepage_gc_runs.csv * BrowsingTest#test_homepage_gc_time.csv @@ -256,342 +242,5 @@ Performance test results are also appended to +.csv+ files inside +tmp/performan * BrowsingTest#test_homepage_objects.csv * BrowsingTest#test_homepage_wall_time.csv -As the results are appended to these files each time the performance tests are run in benchmarking mode, you can collect data over a period of time. This can be very helpful in analyzing the effects of code changes. - -Sample output of +BrowsingTest#test_homepage_wall_time.csv+: - - -measurement,created_at,app,rails,ruby,platform -0.00738224999999992,2009-01-08T03:40:29Z,,3.0.0,ruby-1.8.7.249,x86_64-linux -0.00755874999999984,2009-01-08T03:46:18Z,,3.0.0,ruby-1.8.7.249,x86_64-linux -0.00762099999999993,2009-01-08T03:49:25Z,,3.0.0,ruby-1.8.7.249,x86_64-linux -0.00603075000000008,2009-01-08T04:03:29Z,,3.0.0,ruby-1.8.7.249,x86_64-linux -0.00619899999999995,2009-01-08T04:03:53Z,,3.0.0,ruby-1.8.7.249,x86_64-linux -0.00755449999999991,2009-01-08T04:04:55Z,,3.0.0,ruby-1.8.7.249,x86_64-linux -0.00595999999999997,2009-01-08T04:05:06Z,,3.0.0,ruby-1.8.7.249,x86_64-linux -0.00740450000000004,2009-01-09T03:54:47Z,,3.0.0,ruby-1.8.7.249,x86_64-linux -0.00603150000000008,2009-01-09T03:54:57Z,,3.0.0,ruby-1.8.7.249,x86_64-linux -0.00771250000000012,2009-01-09T15:46:03Z,,3.0.0,ruby-1.8.7.249,x86_64-linux - - -h5(#output-profiling). Profiling - -In profiling mode, performance tests can generate multiple types of outputs. The command line output is always presented but support for the others is dependent on the interpreter in use. A brief description of each type and their availability across interpreters is given below. - -h6. Command Line - -This is a very basic form of output in profiling mode: - - -BrowsingTest#test_homepage (58 ms warmup) - process_time: 63 ms - memory: 832.13 KB - objects: 7,882 - - -h6. Flat - -Flat output shows the metric—time, memory, etc—measure in each method. "Check Ruby-Prof documentation for a better explanation":http://ruby-prof.rubyforge.org/files/examples/flat_txt.html. - -h6. Graph - -Graph output shows the metric measure in each method, which methods call it and which methods it calls. "Check Ruby-Prof documentation for a better explanation":http://ruby-prof.rubyforge.org/files/examples/graph_txt.html. - -h6. Tree - -Tree output is profiling information in calltree format for use by "kcachegrind":http://kcachegrind.sourceforge.net/html/Home.html and similar tools. - -h6. Output Availability - -|_. |_.Flat|_.Graph|_.Tree| -|_.MRI | yes | yes | yes | -|_.REE | yes | yes | yes | -|_.Rubinius | yes | yes | no | -|_.JRuby | yes | yes | no | - -h4. Tuning Test Runs - -Test runs can be tuned by setting the +profile_options+ class variable on your test class. - - -require 'test_helper' -require 'rails/performance_test_help' - -# Profiling results for each test method are written to tmp/performance. -class BrowsingTest < ActionDispatch::PerformanceTest - self.profile_options = { :runs => 5, - :metrics => [:wall_time, :memory] } - - def test_homepage - get '/' - end -end - - -In this example, the test would run 5 times and measure wall time and memory. There are a few configurable options: - -|_.Option |_.Description|_.Default|_.Mode| -|+:runs+ |Number of runs.|Benchmarking: 4, Profiling: 1|Both| -|+:output+ |Directory to use when writing the results.|+tmp/performance+|Both| -|+:metrics+ |Metrics to use.|See below.|Both| -|+:formats+ |Formats to output to.|See below.|Profiling| - -Metrics and formats have different defaults depending on the interpreter in use. - -|_.Interpreter|_.Mode|_.Default metrics|_.Default formats| -|/2.MRI/REE |Benchmarking|+[:wall_time, :memory, :objects, :gc_runs, :gc_time]+|N/A| -|Profiling |+[:process_time, :memory, :objects]+|+[:flat, :graph_html, :call_tree, :call_stack]+| -|/2.Rubinius|Benchmarking|+[:wall_time, :memory, :objects, :gc_runs, :gc_time]+|N/A| -|Profiling |+[:wall_time]+|+[:flat, :graph]+| -|/2.JRuby |Benchmarking|+[:wall_time, :user_time, :memory, :gc_runs, :gc_time]+|N/A| -|Profiling |+[:wall_time]+|+[:flat, :graph]+| - -As you've probably noticed by now, metrics and formats are specified using a symbol array with each name "underscored.":http://api.rubyonrails.org/classes/String.html#method-i-underscore - -h4. Performance Test Environment - -Performance tests are run in the +test+ environment. But running performance tests will set the following configuration parameters: - - -ActionController::Base.perform_caching = true -ActiveSupport::Dependencies.mechanism = :require -Rails.logger.level = ActiveSupport::BufferedLogger::INFO - - -As +ActionController::Base.perform_caching+ is set to +true+, performance tests will behave much as they do in the +production+ environment. - -h4. Installing GC-Patched MRI - -To get the best from Rails' performance tests under MRI, you'll need to build a special Ruby binary with some super powers. - -The recommended patches for each MRI version are: - -|_.Version|_.Patch| -|1.8.6|ruby186gc| -|1.8.7|ruby187gc| -|1.9.2 and above|gcdata| - -All of these can be found on "RVM's _patches_ directory":https://github.com/wayneeseguin/rvm/tree/master/patches/ruby under each specific interpreter version. - -Concerning the installation itself, you can either do this easily by using "RVM":http://rvm.beginrescueend.com or you can build everything from source, which is a little bit harder. - -h5. Install Using RVM - -The process of installing a patched Ruby interpreter is very easy if you let RVM do the hard work. All of the following RVM commands will provide you with a patched Ruby interpreter: - - -$ rvm install 1.9.2-p180 --patch gcdata -$ rvm install 1.8.7 --patch ruby187gc -$ rvm install 1.9.2-p180 --patch ~/Downloads/downloaded_gcdata_patch.patch - - -You can even keep your regular interpreter by assigning a name to the patched one: - - -$ rvm install 1.9.2-p180 --patch gcdata --name gcdata -$ rvm use 1.9.2-p180 # your regular ruby -$ rvm use 1.9.2-p180-gcdata # your patched ruby - - -And it's done! You have installed a patched Ruby interpreter. - -h5. Install From Source - -This process is a bit more complicated, but straightforward nonetheless. If you've never compiled a Ruby binary before, follow these steps to build a Ruby binary inside your home directory. - -h6. Download and Extract - - -$ mkdir rubygc -$ wget -$ tar -xzvf -$ cd - - -h6. Apply the Patch - - -$ curl http://github.com/wayneeseguin/rvm/raw/master/patches/ruby/1.9.2/p180/gcdata.patch | patch -p0 # if you're on 1.9.2! -$ curl http://github.com/wayneeseguin/rvm/raw/master/patches/ruby/1.8.7/ruby187gc.patch | patch -p0 # if you're on 1.8.7! - - -h6. 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. - - -$ ./configure --prefix=//rubygc -$ make && make install - - -h6. Prepare Aliases - -For convenience, add the following lines in your +~/.profile+: - - -alias gcruby='~/rubygc/bin/ruby' -alias gcrake='~/rubygc/bin/rake' -alias gcgem='~/rubygc/bin/gem' -alias gcirb='~/rubygc/bin/irb' -alias gcrails='~/rubygc/bin/rails' - - -Don't forget to use your aliases from now on. - -h6. Install RubyGems (1.8 only!) - -Download "RubyGems":http://rubyforge.org/projects/rubygems and install it from source. Rubygem's README file should have necessary installation instructions. Please note that this step isn't necessary if you've installed Ruby 1.9 and above. - -h4. Using Ruby-Prof on MRI and REE - -Add Ruby-Prof to your applications' Gemfile if you want to benchmark/profile under MRI or REE: - - -gem 'ruby-prof', :git => 'git://github.com/wycats/ruby-prof.git' - - -Now run +bundle install+ and you're ready to go. - -h3. Command Line Tools - -Writing performance test cases could be an overkill when you are looking for one time tests. Rails ships with two command line tools that enable quick and dirty performance testing: - -h4. +benchmarker+ - -Usage: - - -Usage: rails benchmarker 'Ruby.code' 'Ruby.more_code' ... [OPTS] - -r, --runs N Number of runs. - Default: 4 - -o, --output PATH Directory to use when writing the results. - Default: tmp/performance - -m, --metrics a,b,c Metrics to use. - Default: wall_time,memory,objects,gc_runs,gc_time - - -Example: - - -$ rails benchmarker 'Item.all' 'CouchItem.all' --runs 3 --metrics wall_time,memory - - -h4. +profiler+ - -Usage: - - -Usage: rails profiler 'Ruby.code' 'Ruby.more_code' ... [OPTS] - -r, --runs N Number of runs. - Default: 1 - -o, --output PATH Directory to use when writing the results. - Default: tmp/performance - --metrics a,b,c Metrics to use. - Default: process_time,memory,objects - -m, --formats x,y,z Formats to output to. - Default: flat,graph_html,call_tree - - -Example: - - -$ rails profiler 'Item.all' 'CouchItem.all' --runs 2 --metrics process_time --formats flat - - -NOTE: Metrics and formats vary from interpreter to interpreter. Pass +--help+ to each tool to see the defaults for your interpreter. - -h3. Helper Methods - -Rails provides various helper methods inside Active Record, Action Controller and Action View to measure the time taken by a given piece of code. The method is called +benchmark()+ in all the three components. - -h4. Model - - -Project.benchmark("Creating project") do - project = Project.create("name" => "stuff") - project.create_manager("name" => "David") - project.milestones << Milestone.all -end - - -This benchmarks the code enclosed in the +Project.benchmark("Creating project") do...end+ block and prints the result to the log file: - - -Creating project (185.3ms) - - -Please refer to the "API docs":http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M001336 for additional options to +benchmark()+ - -h4. Controller - -Similarly, you could use this helper method inside "controllers":http://api.rubyonrails.org/classes/ActionController/Benchmarking/ClassMethods.html#M000715 - - -def process_projects - self.class.benchmark("Processing projects") do - Project.process(params[:project_ids]) - Project.update_cached_projects - end -end - - -NOTE: +benchmark+ is a class method inside controllers - -h4. View - -And in "views":http://api.rubyonrails.org/classes/ActionController/Benchmarking/ClassMethods.html#M000715: - - -<% benchmark("Showing projects partial") do %> - <%= render @projects %> -<% end %> - - -h3. Request Logging - -Rails log files contain very useful information about the time taken to serve each request. Here's a typical log file entry: - - -Processing ItemsController#index (for 127.0.0.1 at 2009-01-08 03:06:39) [GET] -Rendering template within layouts/items -Rendering items/index -Completed in 5ms (View: 2, DB: 0) | 200 OK [http://0.0.0.0/items] - - -For this section, we're only interested in the last line: - - -Completed in 5ms (View: 2, DB: 0) | 200 OK [http://0.0.0.0/items] - - -This data is fairly straightforward to understand. Rails uses millisecond(ms) as the metric to measure the time taken. The complete request spent 5 ms inside Rails, out of which 2 ms were spent rendering views and none was spent communication with the database. It's safe to assume that the remaining 3 ms were spent inside the controller. - -Michael Koziarski has an "interesting blog post":http://www.therailsway.com/2009/1/6/requests-per-second explaining the importance of using milliseconds as the metric. - -h3. Useful Links - -h4. Rails Plugins and Gems - -* "Rails Analyzer":http://rails-analyzer.rubyforge.org -* "Palmist":http://www.flyingmachinestudios.com/programming/announcing-palmist -* "Rails Footnotes":https://github.com/josevalim/rails-footnotes/tree/master -* "Query Reviewer":https://github.com/dsboulder/query_reviewer/tree/master - -h4. Generic Tools - -* "httperf":http://www.hpl.hp.com/research/linux/httperf/ -* "ab":http://httpd.apache.org/docs/2.2/programs/ab.html -* "JMeter":http://jakarta.apache.org/jmeter/ -* "kcachegrind":http://kcachegrind.sourceforge.net/html/Home.html - -h4. Tutorials and Documentation - -* "ruby-prof API Documentation":http://ruby-prof.rubyforge.org -* "Request Profiling Railscast":http://railscasts.com/episodes/98-request-profiling - Outdated, but useful for understanding call graphs - -h3. Commercial Products -Rails has been lucky to have a few companies dedicated to Rails-specific performance tools. A couple of those are: -* "New Relic":http://www.newrelic.com -* "Scout":http://scoutapp.com From 1138c1ff5edc6aea1a12f17190d16006f135b6be Mon Sep 17 00:00:00 2001 From: Tassandar Date: Fri, 13 Apr 2012 13:07:25 +0800 Subject: [PATCH 10/11] =?UTF-8?q?=E5=8A=A0=E5=85=A5=E5=9B=BE=E6=A0=87,?= =?UTF-8?q?=E4=BF=AE=E6=94=B9configuring.textile?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- assets/images/icons/favicon.ico | Bin 0 -> 24718 bytes source/CN/configuring.textile | 2 + source/CN/layout.html.erb | 3 +- source/CN/performance_testing_cn.textile | 246 ----------------------- source/documents_CN.yaml | 2 +- 5 files changed, 5 insertions(+), 248 deletions(-) create mode 100644 assets/images/icons/favicon.ico delete mode 100644 source/CN/performance_testing_cn.textile diff --git a/assets/images/icons/favicon.ico b/assets/images/icons/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..4080e36a5d0feec17ffbbc100aef0fd4387234a5 GIT binary patch literal 24718 zcmdSAWl$bL7bZHm26uP27k76Eu0eyl2Y0vN?hrz7hY;M|A!u+765Qc^m+#vjxAxZF zf48=3duqDt=|0^v({uXtGpEh~02BZV{3k&H6o48W0LcCq{ZDL!0stBBb^l5KX{W~n zfE$ee2YUzr01-U^#HgvreLyBcesB4pATO=)Uj9c40}*xOr3FWRKCkfO}ll*-L6z1|89|6FZ4gi9~0pR()D)<-xzHk7*i75aGW&r@cOJ2LW zFaSW$swr#9^xYjU>SF;N?E2uRpN_3lQbQr0$Yb$mbDRqBV>9f}8G*T^N z;m;%EE}|3urfwcj!<|3{N~HwV(r{JLaaGfDmk=|3!)I)w;;pCRZle=yW)Ns)5UgVn ztKrx9K_^&3&RxYW*k`6TDo&4&Ehc&{;EhgN09Tsq-g3eIX8zE%#wPHm+= zL#06r{q^GX+uhB#w>R+H%iHtw&B6Xuux~bHF5}c$SI6@dtd#T{7BcNJ zXhlk?xu*QX4!XKd=H}jBUtS;Xp03YVvT|mk!^Nt!OGd zs)3oej)l9H5mZCVIv!}6MkAO<%kzVU?|5Vc41v6Y!N1coJEY|sxcM761?xHZe#%P? z`{`%X2v20>4JD*p?d|S&b=QG-n)$?9_(hwzM7mAYdd$_*=tN6|WUBdP&-ZrU-d=AH z_qVI6h8>+-gvDAV#eYglCen)}Q*ot$#5ZRb&o;JRU!LC};8*b5>)Xqqm1Voa#}+=3 zW;VfQI{s!_zARqFxOaVH;H%Uy`6;j6Ca2SFYCG=!Wz_pi=SS@(27zXJ{$_fCY8vhx zrG3?RrKj}JP|?)h)2{qq(*FyRU>0O{y$eH`DalD^LoM-^zXK!}d3|>PKpXha2{qze zZt*TatRO9+MX&&c0d)a>ADoJshL(<=fsu)sg%t`KU}NV1adL6<@bd8s2nq?q03xDd z;u4Zl(lWBLa`Fm_uz-^CM-^2ybq!4|Z5>@be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4n+k03qX4B g28oSv=HnS0xOv{W2>`s+D9n3GG5YlX@#gaX0J%g%qW}N^ literal 0 HcmV?d00001 diff --git a/source/CN/configuring.textile b/source/CN/configuring.textile index a66b680..04453d0 100644 --- a/source/CN/configuring.textile +++ b/source/CN/configuring.textile @@ -5,6 +5,8 @@ h2. 配置 Rails 应用程序 * 控制Rails应用的行为 * 添加在程序启动时运行的代码 +endprologue. + h3. 初始化代码的为止 Rails 提供四个标准的位置防止初始化代码 diff --git a/source/CN/layout.html.erb b/source/CN/layout.html.erb index a5de46a..b7979f4 100644 --- a/source/CN/layout.html.erb +++ b/source/CN/layout.html.erb @@ -9,7 +9,8 @@ - + + diff --git a/source/CN/performance_testing_cn.textile b/source/CN/performance_testing_cn.textile deleted file mode 100644 index fa89a09..0000000 --- a/source/CN/performance_testing_cn.textile +++ /dev/null @@ -1,246 +0,0 @@ -h2. Rails 应用中的性能测试 - -这篇文章介绍了几种在 Ruby on Rails 应用中进行性能测试的方法。通过阅读这篇文章,你可以 - -* Understand the various types of benchmarking and profiling metrics -* 生成一个 benchmark 性能测试。 -* 安装使用 Ruby的扩展GC类库来测试你的内存使用和分配情况。 -* 通过 Rails 内置的日志功能来了解 benchmarking 信息。 -* Learn about various tools facilitating benchmarking and profiling - -在开发中,性能测试是一个循序渐进的过程。让你的用户能够很快的完成加载并看到你的产品是非常重要的。确保用户在各类浏览器上的体验,降低硬件上不必要的消耗是每一个 web 程序都必须要做到的。 - -endprologue. - -h3. 性能测试案例 - -Rails 性能测试是包括基准测试,夹具测试在内的一系列集成测试。用上了性能测试,你可以发现你的应用程序中存在的内存或者速度问题,对存在的问题进行更深入的检测。 - -在这里我们新建一个 Rails 应用程序, +test/performance/browsing_test.rb+ ,在这个文件里写入一个测试的例子: - - - -require 'test_helper' -require 'rails/performance_test_help' - -# Profiling results for each test method are written to tmp/performance. -class BrowsingTest < ActionDispatch::PerformanceTest - def test_homepage - get '/' - end -end - - -这是一个简单的性能测试例子,它会为你生成一个 GET 请求的性能测试夹具(profiling). - -h4. 生成一个性能测试 - -Rails 提供了一个 +performance_test+ 生成器来新建一个性能测试 - - -$ rails generate performance_test homepage - - -这里生成的 +performance_test.rb+ 在 +test/performance+ 目录中: - - -require 'test_helper' -require 'rails/performance_test_help' - -class HomepageTest < ActionDispatch::PerformanceTest - # Replace this with your real tests. - def test_homepage - get '/' - end -end - - -h4. 例子 - -现在假设你的应用程序有这些 controller 和 model : - - - -# routes.rb -root :to => 'home#index' -resources :posts - -# home_controller.rb -class HomeController < ApplicationController - def dashboard - @users = User.last_ten.includes(:avatars) - @posts = Post.all_today - end -end - -# posts_controller.rb -class PostsController < ApplicationController - def create - @post = Post.create(params[:post]) - redirect_to(@post) - end -end - -# post.rb -class Post < ActiveRecord::Base - before_save :recalculate_costly_stats - - def slow_method - # I fire gallzilion queries sleeping all around - end - - private - - def recalculate_costly_stats - # CPU heavy calculations - end -end - - -h5. 控制器测试范例 - -因为性能测试本质上是一种特殊的集成测试(integration test) ,你可以在测试中使用 +get+ 和 +post+ 方法。 - -下面分别是 +HomeController#dashboard+ 和 +PostsController#create+ 的测试: - - - -require 'test_helper' -require 'rails/performance_test_help' - -class PostPerformanceTest < ActionDispatch::PerformanceTest - def setup - # Application requires logged-in user - login_as(:lifo) - end - - def test_homepage - get '/dashboard' - end - - def test_creating_new_post - post '/posts', :post => { :body => 'lifo is fooling you' } - end -end - - -你可以在"Testing Rails Applications":testing.html这篇文章中找到 +get+ 和 +post+ 的更多细节。 - -h4. 模式 - -性能测试可以运行于两种测试中: 基准模式 (Benchmarking)和 夹具模式(Profiling) - -h5. 基准模式 - -基准测试能让我们迅速获取每个测试运行的数据。默认情况下,每一个测试都会在基准模式下运行 *四 次*。 - -你可以这样来启动一个 基准测试。 - - -$ rake test:benchmark - - -h5. 夹具测试 - -夹具(Profiling)能让你借助一个模具(profiler)更深入的分析你的每一个测试,根据你的Ruby解释器,这个测试模具可能会是本地的(ruby , JRuby的话)或者不是远程的(MRI,用在了 RubyProf上)。默认情况下,每一个测试用例会在夹具模式下被运行一次。 - -我们可以这样运行一个 夹具测试: - - - -$ rake test:profile - - -h4. 数据(Metrics) - -夹具测试和性能测试会得到几组数据,每个数据的产生都取决于计算机的硬件,模式,解释器的使用————这意味着你需要综合的看待他们。应该尽量对每一组数据都做出一个简短描述并记录下当前运行的环境。 - -h5. 真实时间(Wall Time) - -Wall Time 记录了你在跑测试的时候花了多少时间,这个时间会被计算机系统上的其他进程影响。 - -h5. 处理时间(Process Time) - -Process Time 记录了 CPU 花在单个进程上的时间,这个数据并不会被同系统上的其他进程所影响。也正是因此,Process Time 通常对于同一个性能测试来说会是一个常数————如果忽略机器的载入时间的话。 - - -h5. CPU时间(CPU Time) - -与 process time 相似, 但是 CPU Time 运用了 更加精准的 CPU 时钟计数器,该功能只在奔腾和PowerPC平台上有效. - -h5. 用户时间(User Time) - -User Time 计算了CPU花在 用户态下的时间总和。它不会被其他处理器所影响,但是可能会被 “阻止”(blocked)的状态影响。 - -TIP: 译者注: "用户态"http://zh.wikipedia.org/wiki/%E7%94%A8%E6%88%B7%E6%80%81(user mode)在计算机结构指两项类似的概念。在CPU的设计中,用户态指非特权状态。在此状态下,执行的代码被硬件限定,不能进行某些操作,比如写入其他进程的存储空间,以防止给操作系统带来安全隐患。在操作系统的设计中,用户态也类似,指非特权的执行状态。内核禁止此状态下的代码进行潜在危险的操作,比如写入系统配置文件、杀掉其他用户的进程、重启系统等。 - -h5. 内存 - -计算在性能测试用例中所占用的内存 - -h5. 对象 - -对象(Objects)计算了性能测试中被分配了的对象总数。 - -h5. GC 状态 - -GC 状态 (GC Runs)计算了在性能测试中GC被调用的次数 - -h5. GC 时间 - -GC Time 计算了在性能测试GC所花费的总时间。 - -h5. 数据失礼 - -h6. 基准测试 - - -|_.Interpreter|_.Wall Time|_.Process Time|_.CPU Time|_.User Time|_.Memory|_.Objects|_.GC Runs|_.GC Time| -|_.MRI | yes | yes | yes | no | yes | yes | yes | yes | -|_.REE | yes | yes | yes | no | yes | yes | yes | yes | -|_.Rubinius | yes | no | no | no | yes | yes | yes | yes | -|_.JRuby | yes | no | no | yes | yes | yes | yes | yes | - -h6. 夹具 - -|_.Interpreter|_.Wall Time|_.Process Time|_.CPU Time|_.User Time|_.Memory|_.Objects|_.GC Runs|_.GC Time| -|_.MRI | yes | yes | no | no | yes | yes | yes | yes | -|_.REE | yes | yes | no | no | yes | yes | yes | yes | -|_.Rubinius | yes | no | no | no | no | no | no | no | -|_.JRuby | yes | no | no | no | no | no | no | no | - -NOTE: 要在JRuby下面运行这个测试你可能需要在运行测试前运行 +export JRUBY_OPTS="-Xlaunch.inproc=false --profile.api" . - -h4. 输出 - -性能测试会根据你的模式在+tmp/performance+文件夹里面输出几个不同的测试结果。 - -h5. 基准测试 - -在基准模式中,性能测试会产生两种输出。 - -h6. 命令行 - -这是一个基准测试所产生输出示例: - - -BrowsingTest#test_homepage (31 ms warmup) - wall_time: 6 ms - memory: 437.27 KB - objects: 5,514 - gc_runs: 0 - gc_time: 19 ms - - -h6. CSV 文件 - -性能测试的输出结果同样可以输出到 +tmp/performance+ 下面的 +.csv+ 文件。举例来说,运行+BrowsingTest#test_homepage+ 将会生成以下5个文件: - -* BrowsingTest#test_homepage_gc_runs.csv -* BrowsingTest#test_homepage_gc_time.csv -* BrowsingTest#test_homepage_memory.csv -* BrowsingTest#test_homepage_objects.csv -* BrowsingTest#test_homepage_wall_time.csv - - - diff --git a/source/documents_CN.yaml b/source/documents_CN.yaml index ca9a67b..a0a4312 100644 --- a/source/documents_CN.yaml +++ b/source/documents_CN.yaml @@ -83,7 +83,7 @@ url: performance_testing.html work_in_progress: true contributor: Tassandar - description: 这份文章介绍了几种对一个 Ruby on Rails 应用的测试方法。 + description: 这份文章介绍了几种对一个 Ruby on Rails 应用进行性能测试的方法。 - name: Configuring Rails Applications url: configuring.html From af94f4fa2d23f303284e9fa372950f06ef094879 Mon Sep 17 00:00:00 2001 From: Tassandar Date: Fri, 13 Apr 2012 19:09:46 +0800 Subject: [PATCH 11/11] =?UTF-8?q?=E4=BF=AE=E6=94=B9README?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.markdown | 227 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 225 insertions(+), 2 deletions(-) diff --git a/README.markdown b/README.markdown index f255422..179729f 100644 --- a/README.markdown +++ b/README.markdown @@ -87,8 +87,225 @@ xxx包括以下关键字: work_in_progress: true #如果加入这一栏说明你正在更新或者对他进行写作 contributor: ME #这里可以写上你的 github 帐号名 description: 这里是描述 - -##### 生成 + +#### 翻译约定 +**请大家加入意见** + +* 专有名词保持大写:HTML, HAML, SASS, REST...等等。 + +* 英文及数字夹在中文之间显得薄弱的关系,之间保留 1 格的空格:大家都来翻译 Rails 指南吧,Rails 目前版本为 3.2.2。 + +* 代码与文字之间保留1格:`` `rvm` 是 Ruby 的版本管控工具。`` + +由于没有照字母顺序排序的关系,建议你使用浏览器的搜索(`ctrl+F`, `cmd+F`)来寻找名词。 + +**请大家加入名词** + +##### 约定翻译的名词: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
原文中文
class类别
object对象
instance实例
instantiate实例化
instance variable实例变量
local variable局域变数
inherit继承
interface接口
library函式库
server服务器
database数据库
(database)table数据表
code代码
command-line命令行
terminal终端机
method方法
application应用程序、应用
framework框架
template模版
layout版型
request请求
timestamp时间戳章
form表单
array数组
iterate迭代
escaped逸出
tag标签
attribute属性
routing路由
collection集合
macro
+ +##### 保留不译的名词: + +... 基本上 Rails、Ruby 有的特有名词,除了计算机科学中常见的词儿以外,在不造成读者困扰的情况下,尽量保持原汁原味。 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
原文说明
ActiveXXX比如 ActiveRecord
resource资源
partial片段的 view
schema资料库纲要
migration资料库迁移
REST
helper辅助的 Ruby 代码
scaffold鹰架
mock行为驱动测试用词
stub行为驱动测试用词
param参数
Rake任务
Cucumber不是小黄瓜
validator验证器
+ + + + +#### 生成 使用命令 @@ -138,3 +355,9 @@ https://github.com/lifo/docrails ![Creative Commons License](http://i.creativecommons.org/l/by-nc-sa/2.5/cn/88x31.png) 有什么问题可以联系我. + + + + + +