diff options
Diffstat (limited to 'railties/guides/source')
-rw-r--r-- | railties/guides/source/action_controller_overview.textile | 2 | ||||
-rw-r--r-- | railties/guides/source/action_mailer_basics.textile | 25 | ||||
-rw-r--r-- | railties/guides/source/active_record_querying.textile | 56 | ||||
-rw-r--r-- | railties/guides/source/asset_pipeline.textile | 283 | ||||
-rw-r--r-- | railties/guides/source/command_line.textile | 2 | ||||
-rw-r--r-- | railties/guides/source/debugging_rails_applications.textile | 26 | ||||
-rw-r--r-- | railties/guides/source/form_helpers.textile | 2 | ||||
-rw-r--r-- | railties/guides/source/migrations.textile | 2 | ||||
-rw-r--r-- | railties/guides/source/plugins.textile | 2 | ||||
-rw-r--r-- | railties/guides/source/security.textile | 10 |
10 files changed, 349 insertions, 61 deletions
diff --git a/railties/guides/source/action_controller_overview.textile b/railties/guides/source/action_controller_overview.textile index 891bae3d5e..073e3bddcf 100644 --- a/railties/guides/source/action_controller_overview.textile +++ b/railties/guides/source/action_controller_overview.textile @@ -802,7 +802,7 @@ class DinnerController end </ruby> -Just like the filter, you could also passing +:only+ and +:except+ to enforce the secure connection only to specific actions +Just like the filter, you could also passing +:only+ and +:except+ to enforce the secure connection only to specific actions. <ruby> class DinnerController diff --git a/railties/guides/source/action_mailer_basics.textile b/railties/guides/source/action_mailer_basics.textile index e1ff49cd60..2eaee158ff 100644 --- a/railties/guides/source/action_mailer_basics.textile +++ b/railties/guides/source/action_mailer_basics.textile @@ -284,16 +284,37 @@ class UserMailer < ActionMailer::Base @user = user @url = "http://example.com/login" mail(:to => user.email, + :subject => "Welcome to My Awesome Site", + :template_path => 'notifications', + :template_name => 'another') + end + end + +end +</ruby> + +In this case it will look for templates at +app/views/notifications+ with name +another+. + +If you want more flexibility you can also pass a block and render specific templates or even render inline or text without using a template file: + +<ruby> +class UserMailer < ActionMailer::Base + default :from => "notifications@example.com" + + def welcome_email(user) + @user = user + @url = "http://example.com/login" + mail(:to => user.email, :subject => "Welcome to My Awesome Site") do |format| format.html { render 'another_template' } - format.text { render 'another_template' } + format.text { render :text => 'Render text' } end end end </ruby> -Will render 'another_template.text.erb' and 'another_template.html.erb'. The render command is the same one used inside of Action Controller, so you can use all the same options, such as <tt>:text</tt> etc. +This will render the template 'another_template.html.erb' for the HTML part and use the rendered text for the text part. The render command is the same one used inside of Action Controller, so you can use all the same options, such as <tt>:text</tt>, <tt>:inline</tt> etc. h4. Action Mailer Layouts diff --git a/railties/guides/source/active_record_querying.textile b/railties/guides/source/active_record_querying.textile index e3871a3c34..082f9eda7d 100644 --- a/railties/guides/source/active_record_querying.textile +++ b/railties/guides/source/active_record_querying.textile @@ -256,7 +256,7 @@ The above will yield the supplied block with +1000+ invoices every time. h3. Conditions -The +find+ method allows you to specify conditions to limit the records returned, representing the +WHERE+-part of the SQL statement. Conditions can either be specified as a string, array, or hash. +The +where+ method allows you to specify conditions to limit the records returned, representing the +WHERE+-part of the SQL statement. Conditions can either be specified as a string, array, or hash. h4. Pure String Conditions @@ -466,7 +466,7 @@ To apply a +GROUP BY+ clause to the SQL fired by the finder, you can specify the For example, if you want to find a collection of the dates orders were created on: <ruby> -Order.group("date(created_at)").order("created_at") +Order.select("date(created_at) as ordered_date, sum(price) as total_price").group("date(created_at)") </ruby> And this will give you a single +Order+ object for each date where there are orders in the database. @@ -474,7 +474,7 @@ And this will give you a single +Order+ object for each date where there are ord The SQL that would be executed would be something like this: <sql> -SELECT * FROM orders GROUP BY date(created_at) ORDER BY created_at +SELECT date(created_at) as ordered_date, sum(price) as total_price FROM orders GROUP BY date(created_at) </sql> h3. Having @@ -484,16 +484,16 @@ SQL uses the +HAVING+ clause to specify conditions on the +GROUP BY+ fields. You For example: <ruby> -Order.group("date(created_at)").having("created_at < ?", 1.month.ago) +Order.select("date(created_at) as ordered_date, sum(price) as total_price").group("date(created_at)").having("sum(price) > ?", 100) </ruby> The SQL that would be executed would be something like this: <sql> -SELECT * FROM orders GROUP BY date(created_at) HAVING created_at < '2011-04-27' +SELECT date(created_at) as ordered_date, sum(price) as total_price FROM orders GROUP BY date(created_at) HAVING sum(price) > 100 </sql> -This will return single order objects for each day, but only those that are at least one month old. +This will return single order objects for each day, but only those that are ordered more than $100 in a day. h3. Overriding Conditions @@ -965,6 +965,47 @@ Using a class method is the preferred way to accept arguments for scopes. These category.posts.1_week_before(time) </ruby> +h4. Working with scopes + +Where a relational object is required, the +scoped+ method may come in handy. This will return an +ActiveRecord::Relation+ object which can have further scoping applied to it afterwards. A place where this may come in handy is on associations + +<ruby> +client = Client.find_by_first_name("Ryan") +orders = client.orders.scoped +</ruby> + +With this new +orders+ object, we are able to ascertain that this object can have more scopes applied to it. For instance, if we wanted to return orders only in the last 30 days at a later point. + +<ruby> +orders.where("created_at > ?", 30.days.ago) +</ruby> + +h4. Applying a default scope + +If we wish for a scope to be applied across all queries to the model we can use the +default_scope+ method within the model itself. + +<ruby> +class Client < ActiveRecord::Base + default_scope where("removed_at IS NULL") +end +</ruby> + +When queries are executed on this model, the SQL query will now look something like this: + +<sql> +SELECT * FROM clients WHERE removed_at IS NULL +</sql> + +h4. Removing all scoping + +If we wish to remove scoping for any reason we can use the +unscoped+ method. This is especially useful if a +default_scope+ is specified in the model and should not be applied for this particular query. + +<ruby> +Client.unscoped.all +</ruby> + +This method removes all scoping and will do a normal query on the table. + h3. Dynamic Finders For every field (also known as an attribute) you define in your table, Active Record provides a finder method. If you have a field called +first_name+ on your +Client+ model for example, you get +find_by_first_name+ and +find_all_by_first_name+ for free from Active Record. If you have a +locked+ field on the +Client+ model, you also get +find_by_locked+ and +find_all_by_locked+ methods. @@ -1146,7 +1187,8 @@ For options, please see the parent section, "Calculations":#calculations. h3. Changelog -* December 23 2010: Add documentation for the +scope+ method. "Ryan Bigg":http://ryanbigg.com +* June 26 2011: Added documentation for the +scoped+, +unscoped+ and +default+ methods. "Ryan Bigg":credits.html#radar +* December 23 2010: Add documentation for the +scope+ method. "Ryan Bigg":credits.html#radar * April 7, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com * February 3, 2010: Update to Rails 3 by "James Miller":credits.html#bensie * February 7, 2009: Second version by "Pratik":credits.html#lifo diff --git a/railties/guides/source/asset_pipeline.textile b/railties/guides/source/asset_pipeline.textile index 78683b743c..563c1c79ae 100644 --- a/railties/guides/source/asset_pipeline.textile +++ b/railties/guides/source/asset_pipeline.textile @@ -13,15 +13,82 @@ endprologue. h3. What Is The Asset Pipeline? -With Rails 3.1 comes a new feature known as the asset pipeline. The asset pipeline provides features that have usually been implemented by external gems, such as "Jammit":http://documentcloud.github.com/jammit and "Sprockets.":http://getsprockets.org These gems are popular for being able to serve concatenated or compressed versions of the assets of an application, such as Cascade Style Sheets (CSS) or JavaScript (JS) files so that the number of requests made to the server are reduced, making the page load faster. Rails 3.1 includes the Sprockets gem. +The asset pipeline provides a framework to concatenate and minify or compress Javascript and CSS assets. It also adds the ability to write these assets in other languages such as CoffeeScript, SCSS and ERB. + +Prior to Rails 3.1 these features were added through third-party Ruby libraries such as Jammit and Sprockets. Rails 3.1 includes the +sprockets-rails+ gem, which depends on the +sprockets+ gem, by default. + +By having this as a core feature of Rails, all developers can benefit from the power of having their assets pre-processed, compressed and minified by one central library, Sprockets. This is part of Rails' "Fast by default" strategy as outlined by DHH in his 2011 keynote at Railsconf. + +In new Rails 3.1 application the asset pipeline is enable by default. It can be disabled in +application.rb+ by putting this line inside the +Application+ class definition: + +<plain> + config.assets.enabled = false +</plain> + +It is recommended that you use the defaults for all new apps. + + +h4. Main Features + +The first is to concatenate of assets. This is important in a production environment to reduce the number of requests that a client browser has to make to render a web page. While Rails already has a feature to concatenate these types of asset--by placing +:cache => true+ at the end of tags such as +javascript_include_tag+ and +stylesheet_link_tag+--, many people do not use it. + +The default behavior in Rails 3.1 and onward is to concatenate all files into one master file each for JS and CSS, however you can separate files or groups of files if required (see below). In production an MD5 fingerprint is inserted into each filename. + +The second feature of the pipeline is to minify or compress. For CSS this usually involves removing whitespace and comments. For Javascript more complex processes can be applied. + +You can choose from a set of built in options or specify your own. + +The third feature is the ability to code these assets using another language, or language extension. These include SCSS or Sass for CSS, CoffeeScript for Javascript, and ERB for both. + +h4. What is fingerprinting and why should I care? + +Fingerprinting is a technique where the filenames of content that is static or infrequently updated is altered to be unique to the content contained in the file. + +When a filename is unique and based on its content, http headers can be set to encourage caches everywhere (at ISPs, in browsers) to keep there own copy of the content. When the content is updated, the fingerprint will change and the remote clients will request the new file. This is generally known as _cachebusting_. + +The most effective technique is to insert a hash of the content into the name, usually at the end. For example a CSS file +global.css+ is hashed and the filename is updated to incorporate the hash. + +<plain> +global.css => global-908e25f4bf641868d8683022a5b62f54.css +</plain> + +This is the strategy adopted by the Rails asset pipeline. + +Rails old strategy was to append a query string to every asset linked with a built-in helper. In the source the generated code looked like this: + +<plain> +/stylesheets/global.css?1309495796 +</plain> + +This has several disadvantages: + +1. Not all caches will cache content with a query string + +"Steve Souders recommends":http://www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/, "...avoiding a querystring for cacheable resources". He found that in these case 5-20% of requests will not be cached. + +2. The filename can change between nodes in multi-server environments. + +The query string in Rails is based on the files mtime (mtime is the file modification time). When assets are deployed to a cluster, there is no guarantee that the timestamps will be the same, resulting in different values being used depending on which server handles the request. + +The other problems is that when static assets are deployed with each new release of code, the mtime of *all* these files changes, forcing all remote clients to fetch them again, even when the content of those assets has not changed. + +Fingerprinting avoids all these problems be ensuring filenames are consistent based on the content. + +More reading: + +* "Optimize caching":http://code.google.com/speed/page-speed/docs/caching.html +* "Revving Filenames: don’t use querystring":http://www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/ + h3. How to Use the Asset Pipeline -In previous versions of Rails, all assets lived under the +public+ directory in directories such as +images+, +javascripts+ and +stylesheets+. With the asset pipeline, the preferred location for these assets is now the +app/assets+ directory. Files in this directory will be served by the Sprockets middleware included in the sprockets gem. +In previous versions of Rails, all assets were located in subdirectories of +public+ such as +images+, +javascripts+ and +stylesheets+. With the asset pipeline, the preferred location for these assets is now the +app/assets+ directory. Files in this directory will be served by the Sprockets middleware included in the sprockets gem. + +This is not to say that assets can (or should) no longer be placed in +public+. They still can be and will be served as static files by the application or web server. You would only use +app/assets+ if you wish your files to undergo some pre-processing before they are served. -This is not to say that assets can (or should) no longer be placed in +public+. They still can be, they will just be served by the application or the web server which is running the application and served just like normal files. You would only use +app/assets+ if you wish your files to undergo some pre-processing before they are served. +When a scaffold or controller is generated for the application, Rails will also generate a JavaScript file (or CoffeeScript if the +coffee-script+ gem is in the +Gemfile+) and a Cascading Style Sheet file (or SCSS if +sass-rails+ is in the +Gemfile+) file for that controller. -When a scaffold or controller is generated for the application, Rails will also generate a JavaScript file (or CoffeeScript if the +coffee-script+ gem is in the +Gemfile+) and a Cascade Style Sheet file (or SCSS if +sass-rails+ is in the +Gemfile+) file for that controller. For example, if a +ProjectsController+ is generated, there will be a new file at +app/assets/javascripts/projects.js.coffee+ and another at +app/assets/stylesheets/projects.css.scss+. You should put any JavaScript or CSS unique to a controller inside their respective asset files. +For example, if a +ProjectsController+ is generated, there will be a new file at +app/assets/javascripts/projects.js.coffee+ and another at +app/assets/stylesheets/projects.css.scss+. You should put any JavaScript or CSS unique to a controller inside their respective asset files, as these files can then be loaded just for these controllers with lines such as +<%= javascript_include_tag params[:controller] %>+ or +<%= stylesheet_link_tag params[:controller] %>+. h4. Asset Organization @@ -31,29 +98,34 @@ Assets can be placed inside an application in one of three locations: +app/asset +lib/assets+ is for your own libraries' code that doesn't really fit into the scope of the application or those libraries which are shared across applications. -+vendor/assets+ is for assets that are owned by outside entities, such as code for JavaScript plugins. ++vendor/assets+ is for assets that are owned by outside entities, such as code for JavaScript plugins. -Any subdirectory that exists within these three locations will be added to the search path for Sprockets (visible by calling +Rails.application.config.assets.paths+ in a console). When an asset is requested, these paths will be looked through to see if they contain an asset matching the name specified. Once an asset has been found, it's processed by Sprockets and then served up. +All subdirectories that exists within these three locations will be added to the search path for Sprockets (visible by calling +Rails.application.config.assets.paths+ in a console). When an asset is requested, these paths will be looked through to see if they contain an asset matching the name specified. Once an asset has been found, it's processed by Sprockets and served. -h4. External Assets +h4. Coding links to Assets -Assets can also come from external sources such as engines. A good example of this is the +jquery-rails+ gem which comes with Rails as the standard JavaScript library gem. This gem contains an engine class which inherits from +Rails::Engine+. By doing this, Rails is informed that the directory for this gem may contain assets and the +app/assets+, +lib/assets+ and +vendor/assets+ directories of this engine are added to the search path of Sprockets. - -h4. Serving Assets - -To serve assets, we can use the same tags that we are generally familiar with: +To access assets, we can use the same tags that we are generally familiar with: <erb> <%= image_tag "rails.png" %> </erb> -Providing that assets are enabled within our application (+config.assets.enabled+ in your environment is set to +true+), this file will be served by Sprockets unless a file at +public/assets/rails.png+ exists, in which case that file will be served. Otherwise, Sprockets will look through the available paths until it finds a file that matches the name and then will serve it, first looking in the application's assets directories and then falling back to the various engines of the application. +Providing that assets are enabled within our application (+config.assets.enabled+ in the current environment's file is not set to +false+), this file will be served by Sprockets unless a file at +public/assets/rails.png+ exists, in which case that file will be served. Alternatively, a file with an MD5 hash after its name such as +public/assets/rails-af27b6a414e6da00003503148be9b409.png+ will also be picked up by Sprockets. How these hashes are generated is covered in the "Production Assets":#production_assets section later on in this guide. + +Otherwise, Sprockets will look through the available paths until it finds a file that matches the name and then will serve it, first looking in the application's assets directories and then falling back to the various engines of the application. + +Sprockets does not add any new methods to require your assets, we still use the familiar +javascript_include_tag+ and +stylesheet_link_tag+. -Sprockets does not add any new methods to require your assets, we still use the familiar +javascript_include_tag+ and +stylesheet_link_tag+. You can use it to include from the normal public directory or the assets directory. +<erb> + <%= stylesheet_link_tag "application" %> + <%= javascript_include_tag "application" %> +</erb> + +These helpers (when the pipeline is on) are providing links to the compiled manifest with the specified name (or names). h4. Manifest Files and Directives -Sprockets allows some assets to be manifest files. These manifest files require what's known as _directives_, which instruct Sprockets which files to require in order to build a single CSS or JavaScript file. With these directives, Sprockets will load the files specified, process them if necessary, concatenate them into one single file and then compress them (if +Rails.application.config.assets.compress+ is set to +true+). By serving one file rather than many, a page's load time can be greatly reduced. +Sprockets uses manifest files to determine which assets to include and serve. These manifest files contain _directives_ - instructions that tell Sprockets which files to require in order to build a single CSS or JavaScript file. With these directives, Sprockets will load the files specified, process them if necessary, concatenate them into one single file and then compress them (if +Rails.application.config.assets.compress+ is set to +true+). By serving one file rather than many, a page's load time is greatly reduced. For example, in the default Rails application there's a +app/assets/javascripts/application.js+ file which contains the following lines: @@ -63,7 +135,7 @@ For example, in the default Rails application there's a +app/assets/javascripts/ //= require_tree . </plain> -In JavaScript files, directives begin with +//=+. In this case, the following file is using the +require+ directive and the +require_tree+ directive. The +require+ directive tells Sprockets that we would like to require a file called +jquery.js+ that is available somewhere in the search path for Sprockets. By default, this is located inside the +vendor/assets/javascripts+ directory contained within the +jquery-rails+ gem. An identical event takes place for the +jquery_ujs+ require specified here also. +In JavaScript files, directives begin with +//=+. In this case, the following file is using the +require+ directive and the +require_tree+ directive. The +require+ directive tells Sprockets that we would like to require a file called +jquery.js+ that is available somewhere in the search path for Sprockets. By default, this is located inside the +vendor/assets/javascripts+ directory contained within the +jquery-rails+ gem. An identical event takes place for the +jquery_ujs+ require The +require_tree .+ directive tells Sprockets to include _all_ JavaScript files in this directory into the output. Only a path relative to the file can be specified. @@ -76,31 +148,188 @@ There's also a default +app/assets/stylesheets/application.css+ file which conta */ </plain> -The directives that work in the JavaScript files will also work in stylesheets, obviously requiring stylesheets rather than JavaScript files. The +require_tree+ directive here works the same way as the JavaScript one, requiring all stylesheets from the current directory. +The directives that work in the JavaScript files will also work in stylesheets, obviously including stylesheets rather than JavaScript files. The +require_tree+ directive here works the same way as the JavaScript one, requiring all stylesheets from the current directory. In this example +require_self+ is used. This will put the CSS contained within the file (if any) at the top of any other CSS in this file unless +require_self+ is specified after another +require+ directive. +You can have as many manifest files as you need. For example the +admin.css+ and +admin.js+ manifest could contain the JS and CSS files that are used for the admin section of an application. + +For some assets (like CSS) the compiled order is important. You can specify individual files and they will be compiled in the order specified: + +<plain> +/* ... +*= require reset +*= require layout +*= require chrome +*/ +</plain> + + h4. Preprocessing -Based on the extensions of the assets, Sprockets will do preprocessing on the files. With the default gemset that comes with Rails, when a controller or a scaffold is generated, a CoffeeScript file and a SCSS file will be generated in place of a regular JavaScript and CSS file. The example used before was a controller called "projects", which generated an +app/assets/javascripts/projects.js.coffee+ and a +app/assets/stylesheets/projects.css.scss+ file. +The file extensions used on an asset will determine what preprocssing will be applied. When a controller or a scaffold is generated with the default Rails gemset, a CoffeeScript file and a SCSS file will be generated in place of a regular JavaScript and CSS file. The example used before was a controller called "projects", which generated an +app/assets/javascripts/projects.js.coffee+ and a +app/assets/stylesheets/projects.css.scss+ file. When these files are requested, they will be processed by the processors provided by the +coffee-script+ and +sass-rails+ gems and then sent back to the browser as JavaScript and CSS respectively. -In addition to this single layer of pre-processing, we can also put on additional extensions to the end of the file in order for them to be processed using other languages first. For example, we could call our stylesheet +app/assets/stylesheets/projects.css.scss.erb+ it would first be processed as ERB, then SCSS and finally served as CSS. We could also do this with our JavaScript file, calling it +app/assets/javascripts/projects.js.coffee.erb+. +Additional layers of pre-processing can be requested by adding other extensions. These should be used in the order the processing should be applied. For example, a stylesheet called +app/assets/stylesheets/projects.css.scss.erb+ would first be processed as ERB, then SCSS and finally served as CSS. The same applies to a JavaScript file - +app/assets/javascripts/projects.js.coffee.erb+ would be process as ERB, CoffeeScript and served as JavaScript. Keep in mind that the order of these pre-processors is important. For example, if we called our JavaScript file +app/assets/javascripts/projects.js.erb.coffee+ then it would be processed with the CoffeeScript interpreter first, which wouldn't understand ERB and therefore we would run into problems. -h4. Compressing Assets +h3. In Development + +TODO: Talk about: Rack::Cache's caching (used in dev and production. The only difference is hashing and headers). + +In the development environment assets are compiled and cached on the first request after the server is started. Sprockets sets a +must-validate+ cache-control http header to reduce request overhead on subsequent requests - on these the browser gets a 304 (not-modified) response. + +If any of the files in the manifest have changed between requests, the server will respond with a new compiled file. + +h4. Debugging Assets + +You can put +?debug_assets=true+ or +?debug_assets=1+ at the end of a URL and Sprockets will expand the lines which load the assets. For example, if we had an +app/assets/javascripts/application.js+ file containing these lines: + +<plain> +//= require "projects" +//= require "tickets" +</plain> + +By default, this would only render this line when used with +<%= javascript_include_tag "application" %>+ in a view or layout: + +<html> + <script src='/assets/application.js'></script> +</html> + +When the +debug_assets+ parameter is set, this line will be expanded out into three separate lines, separating out the combined file into their parts. + +<html> + <script src='/assets/application.js'></script> + <script src='/assets/projects.js'></script> + <script src='/assets/tickets.js'></script> +</html> + +This allows the individual parts of an asset to be rendered and debugged separately. + +h3. In Production + +In the production environment, assets are served slightly differently. + +On the first request the assets are compiled and cached as described above, however the manifest names are altered to include an MD5 hash. Files names typically will look like these: + +<plain> +/assets/application-908e25f4bf641868d8683022a5b62f54.js +/assets/application-4dd5b109ee3439da54f5bdfd78a80473.css +</plain> + +The MD5 is generated from the contents of the compiled files, and is included in the http +Content-MD5+ header. + +Sprockets also sets the +Cache-Control+ http header to +max-age=31536000+. This signals all caches between your server and the client browser that this content (the file served) can be cached for 1 year. The effect of this is to reduce the number of requests for this asset from your server; the asset has a good chance of being in the local browser cache or some intermediate cache. + +This behavior is controlled by the setting of +config.action_controller.perform_caching+ setting in Rails (which is +true+ for production, +false+ for everything else). This value is propagated to Sprockets during initialization for use when action_controller is not available. + +TODO: +describe each and the differences between: + * Sass-rails's handy +image_url+ helpers + * ERB pre-processing and +asset_path+ + +h4. Precompiling assets + +Even though assets are served by Rack::Cache with far-future headers, in high traffic sites this may not be fast enough. + +Rails comes bundled with a rake task to compile the manifests to files on disc. These are located in the +public/assets+ directory where they will be served by your web server instead of the Rails application. + +TODO: Add section about image assets + +The rake task is: + +<erb> +rake assets:precompile +</erb> + +TODO: explain where to use this with Capistrano + +TODO: talk about the +config.assets.precompile+ option and the default matcher for files: + +<erb> +[ /\w+\.(?!js|css).+/, "application.js", "application.css" ] +</erb> + + +Sprockets also creates a "gzip":http://en.wikipedia.org/wiki/Gzip (.gz) of your assets. This prevents your server from contently compressing your assets for each request. You must configure your server to use gzip compression and serve the compressed assets that will be stored in the public/assets folder. The following are some configuration blocks that you can use for common servers. +NGINX & Apache examples? + + + +h3. Customizing The Pipeline + +h4. CSS + +There is currently one option for processing CSS - SCSS. This Gem extends the CSS syntax and offers minification. + +The following line will enable SCSS in you project. + +<erb> +config.assets.css_compressor = :scss +</erb> + +This option is for compression only and does not relate to the SCSS language extensions that apply when using the +.scss+ file extension on CSS assets. + +h4. Javascript + +There are three options available to process javascript - uglifier, closure and yui. + +The default Gemfile includes "uglifier":https://github.com/lautis/uglifier. This gem wraps "UglifierJS":https://github.com/mishoo/UglifyJS (written for NodeJS) in Ruby. It compress your code by removing white spaces and other magical things like changing your if and else statements to ternary operators when possible. + +TODO: Add detail about the other two + +The following line will invoke uglifier for Javascript compression. + +<erb> +config.assets.js_compressor = :uglifier +</erb> + + + +h4. Using your own compressor + +The compressor config settings for CSS and Javascript will also take an Object. + +This object must have a +compress+ method that takes a string as the sole argument and it must return a string. + +<erb> +class Transformer + def compress(string) + do_something_returning_a_string(string) + end +end +</erb> + +To enable this pass a +new+ Object to the config option in +application.rb+: + +<erb> +config.assets.css_compressor = Transformer.new +</erb> + + +h4. Changing the _assets_ path + +The public path that Sprockets uses by default is +/assets+. + +This can be changed to something else: + +<erb> +config.assets.prefix = "/some_other_path" +</erb> + +This is a handy option if you have any existing project (pre Rails 3.1) that already uses this path. + -The default Gemfile also includes the "uglifier":https://github.com/lautis/uglifier gem. This gem wraps "UglifierJS":https://github.com/mishoo/UglifyJS (written for NodeJS) in Ruby. It compress your code by removing white spaces and other magical things like changing your if and else statements to ternary operators when possible. +h3. Adding Assets to Your Gems -Sprockets also turns on "Gzip":http://en.wikipedia.org/wiki/Gzip (.gz) when possible (by checking the user's headers). Gzip is a file compression technique, much like the ever so popular "zip" file, except it's more open source friendly. Gzip should not modify the contents of the file, but simply the size of the file. +Assets can also come from external sources in the form of gems. -h4. Adding Assets to Your Gems +A good example of this is the +jquery-rails+ gem which comes with Rails as the standard JavaScript library gem. This gem contains an engine class which inherits from +Rails::Engine+. By doing this, Rails is informed that the directory for this gem may contain assets and the +app/assets+, +lib/assets+ and +vendor/assets+ directories of this engine are added to the search path of Sprockets. -To include your assets inside of a gem, simple package it in +lib/assets+ as you would in +app/assets+. You should append or prepend the name of your gem though, this should help avoid name conflicts with other gems or the user's application. +h3. Making Your Library or Gem a Pre-Processor -h4. Making Your Library or Gem a Pre-Processor +"You should be able to register [your gems] on Tilt and Sprockets will find them." - Josh +Tilt: https://github.com/rtomayko/tilt -"You should be able to register [your gems] on Tilt and Sprockets will find them." - Josh -Tilt: https://github.com/rtomayko/tilt
\ No newline at end of file diff --git a/railties/guides/source/command_line.textile b/railties/guides/source/command_line.textile index b0edc1017d..9e3b25d794 100644 --- a/railties/guides/source/command_line.textile +++ b/railties/guides/source/command_line.textile @@ -507,7 +507,7 @@ We had to create the *gitapp* directory and initialize an empty git repository b <shell> $ cat config/database.yml -# PostgreSQL. Versions 7.4 and 8.x are supported. +# PostgreSQL. Versions 8.2 and up are supported. # # Install the ruby-postgres driver: # gem install ruby-postgres diff --git a/railties/guides/source/debugging_rails_applications.textile b/railties/guides/source/debugging_rails_applications.textile index 6f028805d6..f5bee52b5a 100644 --- a/railties/guides/source/debugging_rails_applications.textile +++ b/railties/guides/source/debugging_rails_applications.textile @@ -127,7 +127,7 @@ When something is logged it's printed into the corresponding log if the log leve The available log levels are: +:debug+, +:info+, +:warn+, +:error+, and +:fatal+, corresponding to the log level numbers from 0 up to 4 respectively. To change the default log level, use <ruby> -config.log_level = Logger::WARN # In any environment initializer, or +config.log_level = :warn # In any environment initializer, or Rails.logger.level = 0 # at any time </ruby> @@ -480,11 +480,7 @@ class Author < ActiveRecord::Base def find_recent_comments(limit = 10) debugger - @recent_comments ||= comments.find( - :all, - :conditions => ["created_at > ?", 1.week.ago], - :limit => limit - ) + @recent_comments ||= comments.where("created_at > ?", 1.week.ago).limit(limit) end end </ruby> @@ -493,7 +489,7 @@ TIP: You can use ruby-debug while using +rails console+. Just remember to +requi <shell> $ rails console -Loading development environment (Rails 2.1.0) +Loading development environment (Rails 3.1.0) >> require "ruby-debug" => [] >> author = Author.first @@ -507,15 +503,15 @@ With the code stopped, take a look around: <shell> (rdb:1) list -[6, 15] in /PathTo/project/app/models/author.rb +[2, 9] in /PathTo/project/app/models/author.rb + 2 has_one :editorial + 3 has_many :comments + 4 + 5 def find_recent_comments(limit = 10) 6 debugger - 7 @recent_comments ||= comments.find( - 8 :all, - 9 :conditions => ["created_at > ?", 1.week.ago], - 10 :limit => limit -=> 11 ) - 12 end - 13 end +=> 7 @recent_comments ||= comments.where("created_at > ?", 1.week.ago).limit(limit) + 8 end + 9 end </shell> You are at the end of the line, but... was this line executed? You can inspect the instance variables. diff --git a/railties/guides/source/form_helpers.textile b/railties/guides/source/form_helpers.textile index 4314d00f2e..9051ede9dd 100644 --- a/railties/guides/source/form_helpers.textile +++ b/railties/guides/source/form_helpers.textile @@ -589,7 +589,7 @@ def upload end </ruby> -Once a file has been uploaded, there are a multitude of potential tasks, ranging from where to store the files (on disk, Amazon S3, etc) and associating them with models to resizing image files and generating thumbnails. The intricacies of this are beyond the scope of this guide, but there are several plugins designed to assist with these. Two of the better known ones are "Attachment-Fu":https://github.com/technoweenie/attachment_fu and "Paperclip":http://www.thoughtbot.com/projects/paperclip. +Once a file has been uploaded, there are a multitude of potential tasks, ranging from where to store the files (on disk, Amazon S3, etc) and associating them with models to resizing image files and generating thumbnails. The intricacies of this are beyond the scope of this guide, but there are several libraries designed to assist with these. Two of the better known ones are "CarrierWave":https://github.com/jnicklas/carrierwave and "Paperclip":http://www.thoughtbot.com/projects/paperclip. NOTE: If the user has not selected a file the corresponding parameter will be an empty string. diff --git a/railties/guides/source/migrations.textile b/railties/guides/source/migrations.textile index f17f686d47..dbbf8f3b51 100644 --- a/railties/guides/source/migrations.textile +++ b/railties/guides/source/migrations.textile @@ -344,7 +344,7 @@ The +change+ method removes the need to write both +up+ and +down+ methods in th * +add_column+ * +add_index+ -* +add_timestamp+ +* +add_timestamps+ * +create_table+ * +remove_timestamps+ * +rename_column+ diff --git a/railties/guides/source/plugins.textile b/railties/guides/source/plugins.textile index 2eb71e49c4..79bbe495bd 100644 --- a/railties/guides/source/plugins.textile +++ b/railties/guides/source/plugins.textile @@ -37,7 +37,7 @@ Use the +rails generate plugin+ command in your Rails root directory directory. See usage and options by asking for help: <shell> -$ rails generate plugin new --help +$ rails generate plugin --help </shell> h4. Or generate a gemified plugin. diff --git a/railties/guides/source/security.textile b/railties/guides/source/security.textile index 412ded1d0b..908f3f125a 100644 --- a/railties/guides/source/security.textile +++ b/railties/guides/source/security.textile @@ -649,7 +649,7 @@ h5(#sql-injection-introduction). Introduction SQL injection attacks aim at influencing database queries by manipulating web application parameters. A popular goal of SQL injection attacks is to bypass authorization. Another goal is to carry out data manipulation or reading arbitrary data. Here is an example of how not to use user input data in a query: <ruby> -Project.all(:conditions => "name = '#{params[:name]}'") +Project.where("name = '#{params[:name]}'") </ruby> This could be in a search action and the user may enter a project's name that he wants to find. If a malicious user enters ' OR 1 --, the resulting SQL query will be: @@ -681,7 +681,7 @@ h5. Unauthorized Reading The UNION statement connects two SQL queries and returns the data in one set. An attacker can use it to read arbitrary data from the database. Let's take the example from above: <ruby> -Project.all(:conditions => "name = '#{params[:name]}'") +Project.where("name = '#{params[:name]}'") </ruby> And now let's inject another query using the UNION statement: @@ -703,18 +703,18 @@ Also, the second query renames some columns with the AS statement so that the we h5(#sql-injection-countermeasures). Countermeasures -Ruby on Rails has a built-in filter for special SQL characters, which will escape ' , " , NULL character and line breaks. <em class="highlight">Using +Model.find(id)+ or +Model.find_by_some thing(something)+ automatically applies this countermeasure</em>. But in SQL fragments, especially <em class="highlight">in conditions fragments (+:conditions => "..."+), the +connection.execute()+ or +Model.find_by_sql()+ methods, it has to be applied manually</em>. +Ruby on Rails has a built-in filter for special SQL characters, which will escape ' , " , NULL character and line breaks. <em class="highlight">Using +Model.find(id)+ or +Model.find_by_some thing(something)+ automatically applies this countermeasure</em>. But in SQL fragments, especially <em class="highlight">in conditions fragments (+where("...")+), the +connection.execute()+ or +Model.find_by_sql()+ methods, it has to be applied manually</em>. Instead of passing a string to the conditions option, you can pass an array to sanitize tainted strings like this: <ruby> -Model.first(:conditions => ["login = ? AND password = ?", entered_user_name, entered_password]) +Model.where("login = ? AND password = ?", entered_user_name, entered_password).first </ruby> As you can see, the first part of the array is an SQL fragment with question marks. The sanitized versions of the variables in the second part of the array replace the question marks. Or you can pass a hash for the same result: <ruby> -Model.first(:conditions => {:login => entered_user_name, :password => entered_password}) +Model.where(:login => entered_user_name, :password => entered_password).first </ruby> The array or hash form is only available in model instances. You can try +sanitize_sql()+ elsewhere. _(highlight)Make it a habit to think about the security consequences when using an external string in SQL_. |