1.2 Startup and Application Settings
Load Path:
$ rails console $ LOAD_PATH
Whenever you start a process to handle requests with Rails (such as with rails server), one of the firstthings that happens is that config/boot.rb
is loaded.
There are three files involved in setting up the entire Rails stack:
boot.rb
: sets up Bundler and load paths
application.rb
: loads rails gems, gems for the specified Rail.env, and configures the application
environment.rb
: runs all initializers
All three are run when you need the whole Rails environment loaded. That’s what’s done by runner, console,server, etc.
1.2.1 application.rb
The file config/application.rb
is the home to your Rails application settings, and it’s the only file required at the top of config/environment.rb
.
You also have the ability to easily cherry-pick only the components needed by your application.
# To pick the frameworks you want, remove 'require "rails/all"'
# and list the framework frailties that you want:
# require "active_model/railtie"
# require "active_record/railtie"
# require "action_controller/railtie"
# require "action_mailer/railtie"
# require "action_view/railtie"
# require "sprockets/railtie"
# require "rails/test_unit/railtie"
1.2.1.1 Load Path Modifications
By default, Rails looks for code in a number of standard directories such as app/models
and app/controllers
referred to collectively as the load path.
# Custom directories with classes and modules you want to be autoloadable
# config.autoload_paths+=%W(#{config.root}/extras)
config.autoload_paths+=%W(#{config.root}/app/presenters)
Note that
config.root
refers to the root directory of your Rails application. the%W
functions as a whitespace-delimited array literal and is used quite often in
the Rails codebase for convenience.
1.2.1.2 Time Zones
The default time zone for Rails 4 applications is UTC.
# Set Time.zone default to the specified zone and make Active Record auto-converttothiszone.
# Run "rake -D time" for a list of tasks for finding time zone names.
config.time_zone='CentralTime(US&Canada)'
1.2.1.3 Localisation
Rails features localization support via locale files. The default locale is :en
.
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
1.2.1.4 Generator Default Settings
Rails generator scripts make certain assumptions about your tool chain. Setting the correct values here meanshaving to type less parameters on the command line. For instance, to use Spec
without fixtures and Hamlas the template engine, our settings would look like:
# Configure generators values. Many other options are available,
# be sure to check the documentation.
config.generators do |g|
g.template_engine :haml
g.test_framework :rspec, fixture: false
end
Note that Rubygems such as rspec-rails, haml-rails, and factory_girl_rails handle this for you automatically.
1.2.2 Initializers
Rails 2 introduced the concept of breaking out configuration settings into their own small ruby files under the config/initializers
directory, where they are automatically loaded at startup. You can add configuration settings for your own application by adding ruby files to the initializers directory.
1.2.2.1 Backtrace Silencers
Rails has a mechanism forreducing the size of backtraces by eliminating lines that don’t really add anything to your debugging.
1.2.2.2 Filter Parameter Logging
When a request is made to your application, by default Rails logs details such as the request path, HTTPmethod, IP Address, and parameters. If an attacker somehow gained access to your logs, they may be able toview sensitive information, like passwords and credit card numbers.
1.2.2.3 Inflections
Rails has a class named Inflector
whose responsibility is to transform strings (words) from singular to plural,class names to table names, modularized class names to ones without, and class names to foreign keys, etc.
The default inflections for pluralization and singularization of uncountable words are kept in an interestingfile inside the ActiveSupport gem, named inflections.rb
.
Most of the time the Inflector
class does a decent job of figuring out the pluralized table name for a given class, but occasionally it won’t. This is one of the first stumbling blocks for many new Rails users, but it is not necessary to panic. With a little ad hoc testing beforehand, it’s easy to find out how Inflector will react to certain words. We just need to use the Rails console
, which by the way is one of the best things about working in Rails.
$ rails console
>> ActiveSupport::Inflector.pluralize "project"
=> "projects"
>> ActiveSupport::Inflector.pluralize "virus"
=> "viri"
>> "pensum".pluralize # Inflector features are mixed into String by default
=>"pensums"
1.2.2.4 Custom MEME Types
Rails supports a standard set of MIME types (/, text/html, text/plain, text/javascript, text/css, text/calendar,text/csv, application/xml, application/rss+xml, application/atom+xml, application/x-yaml, multipart/form-data, application/x-www-form-urlencoded, application/json)
Short name | respond_to symbol |
Aliases and Explanations |
---|---|---|
text/html | :html, :xhtml | application/xhtml+xml |
text/plain | :text, :txt | |
text/javascript | :js | application/javascript, application/x-javascript |
text/css | :css | Cascading style sheets |
text/calendar | :ics | iCalendar format for sharing meeting requests and tasks |
text/csv | :csv | Comma-separated values |
application/xml | :xml | text/xml, application/x-xml |
application/rss+xml | :rss | Really Simple Syndication format for web feeds |
application/atom+xml | :atom | Atom Syndication Format for web feeds |
application/x-yaml | :yaml | text/yaml - The human-readable data serialization format |
application/x-www-form- urlencoded | :url_encoded_form | The default content type of HTML forms |
multipart/form-data | :multipart_form | Used for HTML forms that contain files, non-ASCII data, and binary data |
application/json | :json | text/x-json, application/jsonrequest - JavaScript Object Notation |
If your application needs to respond to other MIME types, you can register them in the mime_types.rb
initializer.
1.2.2.5 Secret Token
Certain types of hacking involve modifying the contents of cookies without the server knowing about it.By digitally signing all cookies sent to the browser, Rails can detect whether they were tampered with. The secret_token.rb
initializer contains the secret key base, randomly generated along with your app, which isused to sign cookies.
In Rails 4 , the file is
secrets.yml
inconfig/
1.2.2.6 Session Store
As of Rails 4, session cookies are encrypted by default using the new encrypted cookie store. The session- store.rb
initializer configures the session store of the application, by setting its session store type and key.
The session cookies are signed using thesecret_key_base
set in the secret_token.rb
initializer. If you are really paranoid, you can change the secret key in secret_token.rb
or run rake secret
to generate a new one automatically.
1.2.2.7 Wrap Parameters
The wrap_parameters.rb
initializer configures your application to work with JavaScript MVC frameworks, such as Backbone.js out of the box.
When submitting JSON parameters to a controller, Rails will wrap the parameters into a nested hash, with
the controller’s name being set as the key. To illustrate, consider the following JSON:
{ "title": "The Rails 4 Way"}
If a client submitted the above JSON to a controller named ArticlesController
, Rails would nest the params hash under the key “article”. This ensures the setting of model attributes from request parameters is consistent with the convention used when submitting from Rails form helpers.
{"title": "The Rails 4 Way", "article" => {"title" :"The Rails 4 Way"}}
1.2.3 Additional Configuration
There are additional options, which you can add in additional initializer files.
1.2.3.1 Log-Level Override
# Force all environments to use the same logger level
# (by default production uses :info, the others :debug)
config.log_level=:debug
1.2.3.2 Schema Dumper
Every time you run tests, Rails dumps the schema of your development database and copies it to the test database using an auto generated schema.rb script. It looks very similar to an Active Record migration script; in fact, it uses the same API.
You might find it necessary to revert to the older style of dumping the schema using SQL, if you’re doing things that are incompatible with the schema dumper code (see the comment).
Use SQL instead of Active Record's schema dumper when creating the
test database.This is necessary if your schema can't be completely
dumped by the schema dumper,for example,if you have constraints
or db-specific column types
config.active_record.schema_format=:sql
The value of the RAILS_ENV
environment variable dictates which additional environ-ment settings are loaded