diff options
Diffstat (limited to 'railties')
272 files changed, 23425 insertions, 8692 deletions
diff --git a/railties/CHANGELOG b/railties/CHANGELOG index fc1ec340c7..75f1df44e7 100644 --- a/railties/CHANGELOG +++ b/railties/CHANGELOG @@ -1,7 +1,38 @@ -*Rails 3.0.0 [release candidate] (July 26th, 2010)* +*Rails 3.1.0 (unreleased)* -* Application generation: --skip-testunit and --skip-activerecord become --skip-test-unit - and --skip-active-record respectively. [fxn] +* Added `rails plugin new` command which generates rails plugin with gemspec, tests and dummy application for testing [Piotr Sarnacki] + +* Added -j parameter with jquery/prototype as options. Now you can create your apps with jQuery using `rails new myapp -j jquery`. The default is still Prototype. [siong1987] + +* Added Rack::Etag and Rack::ConditionalGet to the default middleware stack [José Valim] + +* Added Rack::Cache to the default middleware stack [Yehuda Katz and Carl Lerche] + +* Engine is now rack application [Piotr Sarnacki] + +* Added middleware stack to Engine [Piotr Sarnacki] + +* Engine can now load plugins [Piotr Sarnacki] + +* Engine can load its own environment file [Piotr Sarnacki] + +* Added helpers to call engines' route helpers from application and vice versa [Piotr Sarnacki] + +* Task for copying plugins' and engines' migrations to application's db/migrate directory [Piotr Sarnacki] + +* Changed ActionDispatch::Static to allow handling multiple directories [Piotr Sarnacki] + +* Added isolate_namespace() method to Engine, which sets Engine as isolated [Piotr Sarnacki] + +* Include all helpers from plugins and shared engines in application [Piotr Sarnacki] + +*Rails 3.0.1 (October 15, 2010)* + +* No Changes, just a version bump. + +*Rails 3.0.0 (August 29, 2010)* + +* Application generation: --skip-testunit and --skip-activerecord become --skip-test-unit and --skip-active-record respectively. [fxn] * Added console to Rails::Railtie as a hook called just after console starts. [José Valim] @@ -15,19 +46,10 @@ * Made the rails command work even when you're in a subdirectory [Chad Fowler] - -*Rails 3.0.0 [beta 4] (June 8th, 2010)* - * Removed Rails Metal [Yehuda Katz, José Valim]. - -*Rails 3.0.0 [beta 3] (April 13th, 2010)* - * Renamed config.cookie_secret to config.secret_token and pass it as env key. [José Valim] - -*Rails 3.0.0 [beta 2] (April 1st, 2010)* - * Session store configuration has changed [Yehuda Katz, Carl Lerche] config.session_store :cookie_store, {:key => "..."} @@ -39,14 +61,12 @@ * Added config.generators.templates to provide alternative paths for the generators to look for templates [José Valim] -*Rails 3.0.0 [beta 1] (February 4, 2010)* - * Added "rake about" as a replacement for script/about [DHH] * Removed all the default commands in script/* and replaced them with script/rails and a rails command that'll act the same when run from within the app [DHH]. Example: ./script/generate scaffold post title:string can now be called as rails g scaffold post title:string - + Run rails --help inside an app for more help. * Removed config/initializers/new_rails_defaults.rb as all frameworks now follow the settings from it [DHH] @@ -68,7 +88,7 @@ cookies.permanent.signed[:remember_me] = current_user.id # => Set-Cookie: discount=BAhU--848956038e692d7046deab32b7131856ab20e14e; path=/; expires=Sun, 16-Dec-2029 03:24:16 GMT - + ...to use the signed cookies, you need to set a secret to ActionController::Base.cookie_verifier_secret (automatically done in config/initializers/cookie_verification_secret.rb for new Rails applications). * Added config/initializers/cookie_verification_secret.rb with an auto-generated secret for using ActionController::Base#cookies.signed [DHH] @@ -101,42 +121,42 @@ * Add "-m/--template" option to Rails generator to apply a template to the generated application. [Jeremy McAnally] This has been extracted from rg - http://github.com/jeremymcanally/rg - + Example: - + # template.rb - + # Install plugins from git or svn plugin "will-paginate", :git => "git://github.com/mislav/will_paginate.git" plugin "old-restful-auth", :svn => "http://svn.techno-weenie.net/projects/plugins/restful_authentication/" - + # Add gems to environment.rb gem "jeremymcanally-context" gem "bluecloth" - + # Vendor file. Data in a string or... vendor("borrowed.rb", <<CODE def helpful_method do_something_helpful_here end CODE - + # ...file data from block return value. # #initializer creates a new initializer file initializer("crypto.rb") do salt = "--#{Time.now}--#{rand}--#{srand(Time.now.to_i)}" - + "SPECIAL_SALT = '#{salt}'" end - + Usage: - + To use a template, provide a file path or URL: - + 1. Using a local file : rails <application name> -m /path/to/my/template.rb - + 2. Or directly from a URL : rails <application name> --template=http://gist.github.com/31208.txt @@ -235,7 +255,7 @@ rake gems:unpack # unpacks all gems rake gems:unpack GEM=mygem # unpacks only the gem 'mygem' - + rake gems:build # builds all unpacked gems rake gems:build GEM=mygem # builds only the gem 'mygem' @@ -246,16 +266,16 @@ * Allow files in plugins to be reloaded like the rest of the application. [Rick Olson] Enables or disables plugin reloading. - + config.reload_plugins = true - + You can get around this setting per plugin. If #reload_plugins? == false (DEFAULT), add this to your plugin's init.rb to make it reloadable: - + Dependencies.load_once_paths.delete lib_path - + If #reload_plugins? == true, add this to your plugin's init.rb to only load it once: - + Dependencies.load_once_paths << lib_path * Small tweak to allow plugins to specify gem dependencies. [Rick Olson] @@ -280,13 +300,13 @@ config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net" config.gem "aws-s3", :lib => "aws/s3" end - + # List required gems. rake gems - + # Install all required gems: rake gems:install - + # Unpack specified gem to vendor/gems/gem_name-x.x.x rake gems:unpack GEM=bj @@ -473,9 +493,9 @@ databases on localhost. #9753 [Trevor Wennblom] For example: ruby script/generation migration AddSomeStuffToCustomers first_name:string last_name:string - + or - + ruby script/generation migration RemoveSomeStuffFromCustomers first_name:string last_name:string * Add ActiveResource to Rails::Info. Closes #8741 [Chris Kampmeier] @@ -535,13 +555,13 @@ databases on localhost. #9753 [Trevor Wennblom] * Removed breakpointer and Binding.of_caller in favor of relying on ruby-debug by Kent Sibilev since the breakpointer has been broken since Ruby 1.8.4 and will not be coming back [David Heinemeier Hansson] To use the new debugger, start your server with script/server --debugger and insert a call to 'debugger' - (instead of 'breakpoint') where you want to jump into the debugger. - + (instead of 'breakpoint') where you want to jump into the debugger. + BACKWARDS INCOMPATIBILITY NOTE: You must remove the default line 12 from config/environments/development.rb: - + config.breakpoint_server = true - - This configuration option is no longer available. Rails will fail to start in development mode as long as + + This configuration option is no longer available. Rails will fail to start in development mode as long as that's still present. * Resource scaffolding returns the created entity.to_xml. [Jeremy Kemper] @@ -553,7 +573,7 @@ databases on localhost. #9753 [Trevor Wennblom] * Include Active Resource instead of Action Web Service [David Heinemeier Hansson] You can add AWS back with this in config/environment.rb: config.load_paths += %W( #{RAILS_ROOT}/vendor/rails/actionwebservice/lib ) - + ...or just gem 'actionwebservice' * Give generate scaffold a more descriptive database message. Closes #7316 [Jeremy McAnally] @@ -566,7 +586,7 @@ databases on localhost. #9753 [Trevor Wennblom] * Windows: include MinGW in RUBY_PLATFORM check. #2982 [okkez000@gmail.com, Kaspar Schiess] -* Split out the basic plugin locator functionality into an abstract super class. Add a FileSystemLocator to do the job of checking the plugin_paths for plugins. Add plugin_locators configuration option which will iterate over the set of plugin locators and load each of the plugin loaders they return. Rename locater everywhere to locator. [Marcel Molina Jr.] +* Split out the basic plugin locator functionality into an abstract super class. Add a FileSystemLocator to do the job of checking the plugin_paths for plugins. Add plugin_locators configuration option which will iterate over the set of plugin locators and load each of the plugin loaders they return. Rename locater everywhere to locator. [Marcel Molina Jr.] * Split plugin location and loading out of the initializer and into a new Plugin namespace, which includes Plugin::Locater and Plugin::Loader. The loader class that is used can be customized using the config.plugin_loader option. Those monkey patching the plugin loading subsystem take note, the internals changing here will likely break your modifications. The good news is that it should be substantially easier to hook into the plugin locating and loading process now. [Marcel Molina Jr.] @@ -602,7 +622,7 @@ databases on localhost. #9753 [Trevor Wennblom] * Ensure plugins are in the Dependencies.load_once_paths collection by default. [Rick Olson] If you really want your plugins to reload, add this to the very top of init.rb: - + Dependencies.load_once_paths.delete(lib_path) * Allow config.to_prepare to work, make the dispatcher safe to 're require'. [Michael Koziarski, Nicholas Seckar] @@ -724,9 +744,9 @@ databases on localhost. #9753 [Trevor Wennblom] * Remove the uncanny default of adding all app/models/*/ directories to the load path. This change will break application which expect the current behavior. As documented in initializer.rb, the workaround is: - + config.autoload_paths += Dir[RAILS_ROOT + '/app/models/*/'] - + References #6031. [Nicholas Seckar] * Update to script.aculo.us 1.6.3 [Thomas Fuchs] @@ -811,10 +831,10 @@ References #6031. [Nicholas Seckar] 0002 def show 0003-> breakpoint 0004 end - 0005 + 0005 0006 def index 0007 end - 0008 + 0008 => "/path/to/rails/root/app/controllers/top_controller.rb" irb(#<TopController:0x40822a68>):004:0> show_call_stack 3 @@ -905,7 +925,7 @@ References #6031. [Nicholas Seckar] * Ensure plugins are in the Dependencies.load_once_paths collection by default. [Rick Olson] If you really want your plugins to reload, add this to the very top of init.rb: - + Dependencies.load_once_paths.delete(lib_path) * Fix scaffold_resource generator so it respects the --pretend argument when creating the routes file. Closes #6852 [fearoffish] @@ -1011,9 +1031,9 @@ References #6031. [Nicholas Seckar] * Remove the uncanny default of adding all app/models/*/ directories to the load path. This change will break application which expect the current behavior. As documented in initializer.rb, the workaround is: - + config.autoload_paths += Dir[RAILS_ROOT + '/app/models/*/'] - + References #6031. [Nicholas Seckar] * Update to script.aculo.us 1.6.3 [Thomas Fuchs] @@ -1094,10 +1114,10 @@ References #6031. [Nicholas Seckar] 0002 def show 0003-> breakpoint 0004 end - 0005 + 0005 0006 def index 0007 end - 0008 + 0008 => "/path/to/rails/root/app/controllers/top_controller.rb" irb(#<TopController:0x40822a68>):004:0> show_call_stack 3 @@ -1332,7 +1352,7 @@ References #6031. [Nicholas Seckar] * Changed the default session configuration to place sessions in tmp/sessions, if that directory is available, instead of /tmp (this essentially means a goodbye to 9/10 White Screen of Death errors and should have web hosting firms around the world cheering) [David Heinemeier Hansson] -* Added tmp/sessions, tmp/cache, and tmp/sockets as default directories in the Rails skeleton [David Heinemeier Hansson] +* Added tmp/sessions, tmp/cache, and tmp/sockets as default directories in the Rails skeleton [David Heinemeier Hansson] * Added that script/generate model will now automatically create a migration file for the model created. This can be turned off by calling the generator with --skip-migration [David Heinemeier Hansson] @@ -1711,7 +1731,7 @@ References #6031. [Nicholas Seckar] # runs the one statement 10 times script/benchmarker 10 'Person.expensive_method(10)' - + # pits the two statements against each other with 50 runs each script/benchmarker 50 'Person.expensive_method(10)' 'Person.cheap_method(10)' @@ -1751,18 +1771,18 @@ References #6031. [Nicholas Seckar] * Changed .htaccess to allow dispatch.* to be called from a sub-directory as part of the push with Action Pack to make Rails work on non-vhost setups #826 [Nicholas Seckar/Tobias Lütke] * Added script/runner which can be used to run code inside the environment by eval'ing the first parameter. Examples: - + ./script/runner 'ReminderService.deliver' ./script/runner 'Mailer.receive(STDIN.read)' - + This makes it easier to do CRON and postfix scripts without actually making a script just to trigger 1 line of code. * Fixed webrick_server cookie handling to allow multiple cookes to be set at once #800, #813 [dave@cherryville.org] * Fixed the Rakefile's interaction with postgresql to: - 1. Use PGPASSWORD and PGHOST in the environment to fix prompting for - passwords when connecting to a remote db and local socket connections. + 1. Use PGPASSWORD and PGHOST in the environment to fix prompting for + passwords when connecting to a remote db and local socket connections. 2. Add a '-x' flag to pg_dump which stops it dumping privileges #807 [rasputnik] 3. Quote the user name and use template0 when dumping so the functions doesn't get dumped too #855 [pburleson] 4. Use the port if available #875 [madrobby] @@ -1825,10 +1845,10 @@ References #6031. [Nicholas Seckar] Controller: components/list/items_controller.rb (holds a List::ItemsController class with uses_component_template_root called) - + Model : components/list/item.rb (namespace is still shared, so an Item model in app/models will take precedence) - + Views : components/list/items/show.rhtml @@ -1921,11 +1941,11 @@ References #6031. [Nicholas Seckar] * Fixed dependency management to happen in a unified fashion for Active Record and Action Pack using the new Dependencies module. This means that the environment options needs to change from: - + Before in development.rb: ActionController::Base.reload_dependencies = true ActiveRecord::Base.reload_associations = true - + Now in development.rb: Dependencies.mechanism = :load @@ -1979,41 +1999,41 @@ References #6031. [Nicholas Seckar] * Added breakpoint support through the script/breakpointer client. This means that you can break out of execution at any point in the code, investigate and change the model, AND then resume execution! Example: - + class WeblogController < ActionController::Base def index @posts = Post.find_all breakpoint "Breaking out from the list" end end - - So the controller will accept the action, run the first line, then present you with a IRB prompt in the breakpointer window. + + So the controller will accept the action, run the first line, then present you with a IRB prompt in the breakpointer window. Here you can do things like: - + Executing breakpoint "Breaking out from the list" at .../webrick_server.rb:16 in 'breakpoint' >> @posts.inspect - => "[#<Post:0x14a6be8 @attributes={\"title\"=>nil, \"body\"=>nil, \"id\"=>\"1\"}>, + => "[#<Post:0x14a6be8 @attributes={\"title\"=>nil, \"body\"=>nil, \"id\"=>\"1\"}>, #<Post:0x14a6620 @attributes={\"title\"=>\"Rails you know!\", \"body\"=>\"Only ten..\", \"id\"=>\"2\"}>]" >> @posts.first.title = "hello from a breakpoint" => "hello from a breakpoint" ...and even better is that you can examine how your runtime objects actually work: - >> f = @posts.first + >> f = @posts.first => #<Post:0x13630c4 @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}> >> f. Display all 152 possibilities? (y or n) - + Finally, when you're ready to resume execution, you press CTRL-D * Changed environments to be configurable through an environment variable. By default, the environment is "development", but you can change that and set your own by configuring the Apache vhost with a string like (mod_env must be available on the server): - + SetEnv RAILS_ENV production - + ...if you're using WEBrick, you can pick the environment to use with the command-line parameters -e/--environment, like this: - + ruby public/dispatcher.servlet -e production * Added a new default environment called "development", which leaves the production environment to be tuned exclusively for that. @@ -2028,11 +2048,11 @@ References #6031. [Nicholas Seckar] app/controllers/account_controller.rb # URL: /account/ app/controllers/admin/account_controller.rb # URL: /admin/account/ - + NOTE: You need to update your public/.htaccess with the new rules to pick it up -* Added reloading for associations and dependencies under cached environments like FastCGI and mod_ruby. This makes it possible to use - those environments for development. This is turned on by default, but can be turned off with +* Added reloading for associations and dependencies under cached environments like FastCGI and mod_ruby. This makes it possible to use + those environments for development. This is turned on by default, but can be turned off with ActiveRecord::Base.reload_associations = false and ActionController::Base.reload_dependencies = false in production environments. * Added support for sub-directories in app/models. So now you can have something like Basecamp with: @@ -2041,7 +2061,7 @@ References #6031. [Nicholas Seckar] app/models/project app/models/participants app/models/settings - + It's poor man's namespacing, but only for file-system organization. You still require files just like before. Nothing changes inside the files themselves. @@ -2061,7 +2081,7 @@ References #6031. [Nicholas Seckar] @david.projects << @new_project breakpoint "Let's have a closer look at @david" end - + You need to install dev-utils yourself for this to work ("gem install dev-util"). * Added shared generator behavior so future upgrades should be possible without manually copying over files [Jeremy Kemper] @@ -2120,7 +2140,7 @@ References #6031. [Nicholas Seckar] *0.7.0* -* Added an optional second argument to the new_model script that allows the programmer to specify the table name, +* Added an optional second argument to the new_model script that allows the programmer to specify the table name, which will used to generate a custom table_name method in the model and will also be used in the creation of fixtures. [Kevin Radloff] @@ -2134,8 +2154,8 @@ References #6031. [Nicholas Seckar] * create_fixtures in both the functional and unit test helper now turns off the log during fixture generation and can generate more than one fixture at a time. Which makes it possible for assignments like: - - @people, @projects, @project_access, @companies, @accounts = + + @people, @projects, @project_access, @companies, @accounts = create_fixtures "people", "projects", "project_access", "companies", "accounts" * Upgraded to Action Pack 0.8.5 (locally-scoped variables, partials, advanced send_file) @@ -2147,7 +2167,7 @@ References #6031. [Nicholas Seckar] * No longer specifies a template for rdoc, so it'll use whatever is default (you can change it in the rakefile) -* The new_model generator will now use the same rules for plural wordings as Active Record +* The new_model generator will now use the same rules for plural wordings as Active Record (so Category will give categories, not categorys) [Kevin Radloff] * dispatch.fcgi now sets FCGI_PURE_RUBY to true to ensure that it's the Ruby version that's loaded [danp] @@ -2173,13 +2193,13 @@ References #6031. [Nicholas Seckar] * Added environments that can be included from any script to get the full Active Record and Action Controller context running. This can be used by maintenance scripts or to interact with the model through IRB. Example: - + require 'config/environments/production' - + for account in Account.find_all account.recalculate_interests end - + A short migration script for an account model that had it's interest calculation strategy changed. * Accessing the index of a controller with "/weblog" will now redirect to "/weblog/" (only on Apache, not WEBrick) @@ -2202,7 +2222,7 @@ References #6031. [Nicholas Seckar] * Added lib in root as a place to store app specific libraries -* Added lib and vendor to load_path, so anything store within can be loaded directly. +* Added lib and vendor to load_path, so anything store within can be loaded directly. Hence lib/redcloth.rb can be loaded with require "redcloth" * Upgraded to Action Pack 0.7.8 (lots of fixes) @@ -2216,7 +2236,7 @@ References #6031. [Nicholas Seckar] * Updated the generated template stubs to valid XHTML files -* Ensure that controllers generated are capitalized, so "new_controller TodoLists" +* Ensure that controllers generated are capitalized, so "new_controller TodoLists" gives the same as "new_controller Todolists" and "new_controller todolists". diff --git a/railties/MIT-LICENSE b/railties/MIT-LICENSE index 86bcb23b7c..c73d1af096 100644 --- a/railties/MIT-LICENSE +++ b/railties/MIT-LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2004-2010 David Heinemeier Hansson +Copyright (c) 2004-2011 David Heinemeier Hansson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the diff --git a/railties/README.rdoc b/railties/README.rdoc index a1718a7d96..0457227473 100644 --- a/railties/README.rdoc +++ b/railties/README.rdoc @@ -4,7 +4,7 @@ Railties is responsible to glue all frameworks together. Overall, it: * handles all the bootstrapping process for a Rails application; -* manager rails command line interface; +* manages rails command line interface; * provides Rails generators core; @@ -15,7 +15,7 @@ The latest version of Railties can be installed with Rubygems: * gem install railties -Documentation can be found at +Documentation can be found at * http://api.rubyonrails.org @@ -23,3 +23,4 @@ Documentation can be found at == License Railties is released under the MIT license. + diff --git a/railties/Rakefile b/railties/Rakefile index 8e78d2ff4a..26fa0bf6a5 100644..100755 --- a/railties/Rakefile +++ b/railties/Rakefile @@ -1,8 +1,5 @@ -gem 'rdoc', '>= 2.5.9' -require 'rdoc' -require 'rake' +#!/usr/bin/env rake require 'rake/testtask' -require 'rdoc/task' require 'rake/gempackagetask' require 'date' @@ -21,7 +18,7 @@ namespace :test do Dir["test/#{dir}/*_test.rb"].each do |file| next true if file.include?("fixtures") ruby = File.join(*RbConfig::CONFIG.values_at('bindir', 'RUBY_INSTALL_NAME')) - system(ruby, '-Itest', "-I#{File.dirname(__FILE__)}/../activesupport/lib", file) + sh(ruby, '-Itest', "-I#{File.dirname(__FILE__)}/../activesupport/lib", file) end end end @@ -48,8 +45,9 @@ task :generate_guides do ruby "guides/rails_guides.rb" end -task :update_prototype_ujs do - system "curl http://github.com/rails/prototype-ujs/raw/master/src/rails.js > lib/rails/generators/rails/app/templates/public/javascripts/rails.js" +task :update_ujs do + system "curl https://github.com/rails/prototype-ujs/raw/master/src/rails.js > lib/rails/generators/rails/app/templates/public/javascripts/prototype_ujs.js" + system "curl https://github.com/rails/jquery-ujs/raw/master/src/rails.js > lib/rails/generators/rails/app/templates/public/javascripts/jquery_ujs.js" end # Validate guides ------------------------------------------------------------------------- @@ -58,19 +56,6 @@ task :validate_guides do ruby "guides/w3c_validator.rb" end -# Generate documentation ------------------------------------------------------------------ - -RDoc::Task.new { |rdoc| - rdoc.rdoc_dir = 'doc' - rdoc.title = "Railties -- Gluing the Engine to the Rails" - rdoc.options << '-f' << 'horo' - rdoc.options << '--main' << 'README.rdoc' - rdoc.options << '--charset' << 'utf-8' - rdoc.rdoc_files.include('README.rdoc', 'CHANGELOG') - rdoc.rdoc_files.include('lib/**/*.rb') - rdoc.rdoc_files.exclude('lib/rails/generators/**/templates/*') -} - # Generate GEM ---------------------------------------------------------------------------- spec = eval(File.read('railties.gemspec')) diff --git a/railties/guides/assets/javascripts/code_highlighter.js b/railties/guides/assets/javascripts/code_highlighter.js deleted file mode 100644 index ce983dad52..0000000000 --- a/railties/guides/assets/javascripts/code_highlighter.js +++ /dev/null @@ -1,188 +0,0 @@ -/* Unobtrustive Code Highlighter By Dan Webb 11/2005 - Version: 0.4 - - Usage: - Add a script tag for this script and any stylesets you need to use - to the page in question, add correct class names to CODE elements, - define CSS styles for elements. That's it! - - Known to work on: - IE 5.5+ PC - Firefox/Mozilla PC/Mac - Opera 7.23 + PC - Safari 2 - - Known to degrade gracefully on: - IE5.0 PC - - Note: IE5.0 fails due to the use of lookahead in some stylesets. To avoid script errors - in older browsers use expressions that use lookahead in string format when defining stylesets. - - This script is inspired by star-light by entirely cunning Dean Edwards - http://dean.edwards.name/star-light/. -*/ - -// replace callback support for safari. -if ("a".replace(/a/, function() {return "b"}) != "b") (function(){ - var default_replace = String.prototype.replace; - String.prototype.replace = function(search,replace){ - // replace is not function - if(typeof replace != "function"){ - return default_replace.apply(this,arguments) - } - var str = "" + this; - var callback = replace; - // search string is not RegExp - if(!(search instanceof RegExp)){ - var idx = str.indexOf(search); - return ( - idx == -1 ? str : - default_replace.apply(str,[search,callback(search, idx, str)]) - ) - } - var reg = search; - var result = []; - var lastidx = reg.lastIndex; - var re; - while((re = reg.exec(str)) != null){ - var idx = re.index; - var args = re.concat(idx, str); - result.push( - str.slice(lastidx,idx), - callback.apply(null,args).toString() - ); - if(!reg.global){ - lastidx += RegExp.lastMatch.length; - break - }else{ - lastidx = reg.lastIndex; - } - } - result.push(str.slice(lastidx)); - return result.join("") - } -})(); - -var CodeHighlighter = { styleSets : new Array }; - -CodeHighlighter.addStyle = function(name, rules) { - // using push test to disallow older browsers from adding styleSets - if ([].push) this.styleSets.push({ - name : name, - rules : rules, - ignoreCase : arguments[2] || false - }) - - function setEvent() { - // set highlighter to run on load (use LowPro if present) - if (typeof Event != 'undefined' && typeof Event.onReady == 'function') - return Event.onReady(CodeHighlighter.init.bind(CodeHighlighter)); - - var old = window.onload; - - if (typeof window.onload != 'function') { - window.onload = function() { CodeHighlighter.init() }; - } else { - window.onload = function() { - old(); - CodeHighlighter.init(); - } - } - } - - // only set the event when the first style is added - if (this.styleSets.length==1) setEvent(); -} - -CodeHighlighter.init = function() { - if (!document.getElementsByTagName) return; - if ("a".replace(/a/, function() {return "b"}) != "b") return; // throw out Safari versions that don't support replace function - // throw out older browsers - - var codeEls = document.getElementsByTagName("CODE"); - // collect array of all pre elements - codeEls.filter = function(f) { - var a = new Array; - for (var i = 0; i < this.length; i++) if (f(this[i])) a[a.length] = this[i]; - return a; - } - - var rules = new Array; - rules.toString = function() { - // joins regexes into one big parallel regex - var exps = new Array; - for (var i = 0; i < this.length; i++) exps.push(this[i].exp); - return exps.join("|"); - } - - function addRule(className, rule) { - // add a replace rule - var exp = (typeof rule.exp != "string")?String(rule.exp).substr(1, String(rule.exp).length-2):rule.exp; - // converts regex rules to strings and chops of the slashes - rules.push({ - className : className, - exp : "(" + exp + ")", - length : (exp.match(/(^|[^\\])\([^?]/g) || "").length + 1, // number of subexps in rule - replacement : rule.replacement || null - }); - } - - function parse(text, ignoreCase) { - // main text parsing and replacement - return text.replace(new RegExp(rules, (ignoreCase)?"gi":"g"), function() { - var i = 0, j = 1, rule; - while (rule = rules[i++]) { - if (arguments[j]) { - // if no custom replacement defined do the simple replacement - if (!rule.replacement) return "<span class=\"" + rule.className + "\">" + arguments[0] + "</span>"; - else { - // replace $0 with the className then do normal replaces - var str = rule.replacement.replace("$0", rule.className); - for (var k = 1; k <= rule.length - 1; k++) str = str.replace("$" + k, arguments[j + k]); - return str; - } - } else j+= rule.length; - } - }); - } - - function highlightCode(styleSet) { - // clear rules array - var parsed, clsRx = new RegExp("(\\s|^)" + styleSet.name + "(\\s|$)"); - rules.length = 0; - - // get stylable elements by filtering out all code elements without the correct className - var stylableEls = codeEls.filter(function(item) { return clsRx.test(item.className) }); - - // add style rules to parser - for (var className in styleSet.rules) addRule(className, styleSet.rules[className]); - - - // replace for all elements - for (var i = 0; i < stylableEls.length; i++) { - // EVIL hack to fix IE whitespace badness if it's inside a <pre> - if (/MSIE/.test(navigator.appVersion) && stylableEls[i].parentNode.nodeName == 'PRE') { - stylableEls[i] = stylableEls[i].parentNode; - - parsed = stylableEls[i].innerHTML.replace(/(<code[^>]*>)([^<]*)<\/code>/i, function() { - return arguments[1] + parse(arguments[2], styleSet.ignoreCase) + "</code>" - }); - parsed = parsed.replace(/\n( *)/g, function() { - var spaces = ""; - for (var i = 0; i < arguments[1].length; i++) spaces+= " "; - return "\n" + spaces; - }); - parsed = parsed.replace(/\t/g, " "); - parsed = parsed.replace(/\n(<\/\w+>)?/g, "<br />$1").replace(/<br \/>[\n\r\s]*<br \/>/g, "<p><br></p>"); - - } else parsed = parse(stylableEls[i].innerHTML, styleSet.ignoreCase); - - stylableEls[i].innerHTML = parsed; - } - } - - // run highlighter on all stylesets - for (var i=0; i < this.styleSets.length; i++) { - highlightCode(this.styleSets[i]); - } -} diff --git a/railties/guides/assets/javascripts/highlighters.js b/railties/guides/assets/javascripts/highlighters.js deleted file mode 100644 index 4f5f0779d7..0000000000 --- a/railties/guides/assets/javascripts/highlighters.js +++ /dev/null @@ -1,90 +0,0 @@ -CodeHighlighter.addStyle("css", { - comment : { - exp : /\/\*[^*]*\*+([^\/][^*]*\*+)*\// - }, - keywords : { - exp : /@\w[\w\s]*/ - }, - selectors : { - exp : "([\\w-:\\[.#][^{};>]*)(?={)" - }, - properties : { - exp : "([\\w-]+)(?=\\s*:)" - }, - units : { - exp : /([0-9])(em|en|px|%|pt)\b/, - replacement : "$1<span class=\"$0\">$2</span>" - }, - urls : { - exp : /url\([^\)]*\)/ - } - }); - -CodeHighlighter.addStyle("ruby",{ - comment : { - exp : /#[^\n]+/ - }, - brackets : { - exp : /\(|\)/ - }, - string : { - exp : /'[^']*'|"[^"]*"/ - }, - keywords : { - exp : /\b(do|end|self|class|def|if|module|yield|then|else|for|until|unless|while|elsif|case|when|break|retry|redo|rescue|require|raise)\b/ - }, - /* Added by Shelly Fisher (shelly@agileevolved.com) */ - symbol : { - exp : /([^:])(:[A-Za-z0-9_!?]+)/ - }, - ivar : { - exp : /\@[A-Za-z0-9_!?]+/ - } -}); - -CodeHighlighter.addStyle("html", { - comment : { - exp: /<!\s*(--([^-]|[\r\n]|-[^-])*--\s*)>/ - }, - tag : { - exp: /(<\/?)([a-zA-Z1-9]+\s?)/, - replacement: "$1<span class=\"$0\">$2</span>" - }, - string : { - exp : /'[^']*'|"[^"]*"/ - }, - attribute : { - exp: /\b([a-zA-Z-:]+)(=)/, - replacement: "<span class=\"$0\">$1</span>$2" - }, - doctype : { - exp: /<!DOCTYPE([^&]|&[^g]|&g[^t])*>/ - } -}); - -CodeHighlighter.addStyle("javascript",{ - comment : { - exp : /(\/\/[^\n]*(\n|$))|(\/\*[^*]*\*+([^\/][^*]*\*+)*\/)/ - }, - brackets : { - exp : /\(|\)/ - }, - string : { - exp : /'[^']*'|"[^"]*"/ - }, - keywords : { - exp : /\b(arguments|break|case|continue|default|delete|do|else|false|for|function|if|in|instanceof|new|null|return|switch|this|true|typeof|var|void|while|with)\b/ - }, - global : { - exp : /\b(toString|valueOf|window|element|prototype|constructor|document|escape|unescape|parseInt|parseFloat|setTimeout|clearTimeout|setInterval|clearInterval|NaN|isNaN|Infinity)\b/ - } -}); - -CodeHighlighter.addStyle("yaml", { - keyword : { - exp : /\/\*[^*]*\*+([^\/][^*]*\*+)*\// - }, - value : { - exp : /@\w[\w\s]*/ - }, -}); diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushAS3.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushAS3.js new file mode 100644 index 0000000000..8aa3ed2732 --- /dev/null +++ b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushAS3.js @@ -0,0 +1,59 @@ +/** + * SyntaxHighlighter + * http://alexgorbatchev.com/SyntaxHighlighter + * + * SyntaxHighlighter is donationware. If you are using it, please donate. + * http://alexgorbatchev.com/SyntaxHighlighter/donate.html + * + * @version + * 3.0.83 (July 02 2010) + * + * @copyright + * Copyright (C) 2004-2010 Alex Gorbatchev. + * + * @license + * Dual licensed under the MIT and GPL licenses. + */ +;(function() +{ + // CommonJS + typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null; + + function Brush() + { + // Created by Peter Atoria @ http://iAtoria.com + + var inits = 'class interface function package'; + + var keywords = '-Infinity ...rest Array as AS3 Boolean break case catch const continue Date decodeURI ' + + 'decodeURIComponent default delete do dynamic each else encodeURI encodeURIComponent escape ' + + 'extends false final finally flash_proxy for get if implements import in include Infinity ' + + 'instanceof int internal is isFinite isNaN isXMLName label namespace NaN native new null ' + + 'Null Number Object object_proxy override parseFloat parseInt private protected public ' + + 'return set static String super switch this throw true try typeof uint undefined unescape ' + + 'use void while with' + ; + + this.regexList = [ + { regex: SyntaxHighlighter.regexLib.singleLineCComments, css: 'comments' }, // one line comments + { regex: SyntaxHighlighter.regexLib.multiLineCComments, css: 'comments' }, // multiline comments + { regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, // double quoted strings + { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // single quoted strings + { regex: /\b([\d]+(\.[\d]+)?|0x[a-f0-9]+)\b/gi, css: 'value' }, // numbers + { regex: new RegExp(this.getKeywords(inits), 'gm'), css: 'color3' }, // initializations + { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' }, // keywords + { regex: new RegExp('var', 'gm'), css: 'variable' }, // variable + { regex: new RegExp('trace', 'gm'), css: 'color1' } // trace + ]; + + this.forHtmlScript(SyntaxHighlighter.regexLib.scriptScriptTags); + }; + + Brush.prototype = new SyntaxHighlighter.Highlighter(); + Brush.aliases = ['actionscript3', 'as3']; + + SyntaxHighlighter.brushes.AS3 = Brush; + + // CommonJS + typeof(exports) != 'undefined' ? exports.Brush = Brush : null; +})(); diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushAppleScript.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushAppleScript.js new file mode 100644 index 0000000000..d40bbd7dd2 --- /dev/null +++ b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushAppleScript.js @@ -0,0 +1,75 @@ +/** + * SyntaxHighlighter + * http://alexgorbatchev.com/SyntaxHighlighter + * + * SyntaxHighlighter is donationware. If you are using it, please donate. + * http://alexgorbatchev.com/SyntaxHighlighter/donate.html + * + * @version + * 3.0.83 (July 02 2010) + * + * @copyright + * Copyright (C) 2004-2010 Alex Gorbatchev. + * + * @license + * Dual licensed under the MIT and GPL licenses. + */ +;(function() +{ + // CommonJS + typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null; + + function Brush() + { + // AppleScript brush by David Chambers + // http://davidchambersdesign.com/ + var keywords = 'after before beginning continue copy each end every from return get global in local named of set some that the then times to where whose with without'; + var ordinals = 'first second third fourth fifth sixth seventh eighth ninth tenth last front back middle'; + var specials = 'activate add alias AppleScript ask attachment boolean class constant delete duplicate empty exists false id integer list make message modal modified new no paragraph pi properties quit real record remove rest result reveal reverse run running save string true word yes'; + + this.regexList = [ + + { regex: /(--|#).*$/gm, + css: 'comments' }, + + { regex: /\(\*(?:[\s\S]*?\(\*[\s\S]*?\*\))*[\s\S]*?\*\)/gm, // support nested comments + css: 'comments' }, + + { regex: /"[\s\S]*?"/gm, + css: 'string' }, + + { regex: /(?:,|:|¬|'s\b|\(|\)|\{|\}|«|\b\w*»)/g, + css: 'color1' }, + + { regex: /(-)?(\d)+(\.(\d)?)?(E\+(\d)+)?/g, // numbers + css: 'color1' }, + + { regex: /(?:&(amp;|gt;|lt;)?|=|� |>|<|≥|>=|≤|<=|\*|\+|-|\/|÷|\^)/g, + css: 'color2' }, + + { regex: /\b(?:and|as|div|mod|not|or|return(?!\s&)(ing)?|equals|(is(n't| not)? )?equal( to)?|does(n't| not) equal|(is(n't| not)? )?(greater|less) than( or equal( to)?)?|(comes|does(n't| not) come) (after|before)|is(n't| not)?( in)? (back|front) of|is(n't| not)? behind|is(n't| not)?( (in|contained by))?|does(n't| not) contain|contain(s)?|(start|begin|end)(s)? with|((but|end) )?(consider|ignor)ing|prop(erty)?|(a )?ref(erence)?( to)?|repeat (until|while|with)|((end|exit) )?repeat|((else|end) )?if|else|(end )?(script|tell|try)|(on )?error|(put )?into|(of )?(it|me)|its|my|with (timeout( of)?|transaction)|end (timeout|transaction))\b/g, + css: 'keyword' }, + + { regex: /\b\d+(st|nd|rd|th)\b/g, // ordinals + css: 'keyword' }, + + { regex: /\b(?:about|above|against|around|at|below|beneath|beside|between|by|(apart|aside) from|(instead|out) of|into|on(to)?|over|since|thr(ough|u)|under)\b/g, + css: 'color3' }, + + { regex: /\b(?:adding folder items to|after receiving|choose( ((remote )?application|color|folder|from list|URL))?|clipboard info|set the clipboard to|(the )?clipboard|entire contents|display(ing| (alert|dialog|mode))?|document( (edited|file|nib name))?|file( (name|type))?|(info )?for|giving up after|(name )?extension|quoted form|return(ed)?|second(?! item)(s)?|list (disks|folder)|text item(s| delimiters)?|(Unicode )?text|(disk )?item(s)?|((current|list) )?view|((container|key) )?window|with (data|icon( (caution|note|stop))?|parameter(s)?|prompt|properties|seed|title)|case|diacriticals|hyphens|numeric strings|punctuation|white space|folder creation|application(s( folder)?| (processes|scripts position|support))?|((desktop )?(pictures )?|(documents|downloads|favorites|home|keychain|library|movies|music|public|scripts|sites|system|users|utilities|workflows) )folder|desktop|Folder Action scripts|font(s| panel)?|help|internet plugins|modem scripts|(system )?preferences|printer descriptions|scripting (additions|components)|shared (documents|libraries)|startup (disk|items)|temporary items|trash|on server|in AppleTalk zone|((as|long|short) )?user name|user (ID|locale)|(with )?password|in (bundle( with identifier)?|directory)|(close|open for) access|read|write( permission)?|(g|s)et eof|using( delimiters)?|starting at|default (answer|button|color|country code|entr(y|ies)|identifiers|items|name|location|script editor)|hidden( answer)?|open(ed| (location|untitled))?|error (handling|reporting)|(do( shell)?|load|run|store) script|administrator privileges|altering line endings|get volume settings|(alert|boot|input|mount|output|set) volume|output muted|(fax|random )?number|round(ing)?|up|down|toward zero|to nearest|as taught in school|system (attribute|info)|((AppleScript( Studio)?|system) )?version|(home )?directory|(IPv4|primary Ethernet) address|CPU (type|speed)|physical memory|time (stamp|to GMT)|replacing|ASCII (character|number)|localized string|from table|offset|summarize|beep|delay|say|(empty|multiple) selections allowed|(of|preferred) type|invisibles|showing( package contents)?|editable URL|(File|FTP|News|Media|Web) [Ss]ervers|Telnet hosts|Directory services|Remote applications|waiting until completion|saving( (in|to))?|path (for|to( (((current|frontmost) )?application|resource))?)|POSIX (file|path)|(background|RGB) color|(OK|cancel) button name|cancel button|button(s)?|cubic ((centi)?met(re|er)s|yards|feet|inches)|square ((kilo)?met(re|er)s|miles|yards|feet)|(centi|kilo)?met(re|er)s|miles|yards|feet|inches|lit(re|er)s|gallons|quarts|(kilo)?grams|ounces|pounds|degrees (Celsius|Fahrenheit|Kelvin)|print( (dialog|settings))?|clos(e(able)?|ing)|(de)?miniaturized|miniaturizable|zoom(ed|able)|attribute run|action (method|property|title)|phone|email|((start|end)ing|home) page|((birth|creation|current|custom|modification) )?date|((((phonetic )?(first|last|middle))|computer|host|maiden|related) |nick)?name|aim|icq|jabber|msn|yahoo|address(es)?|save addressbook|should enable action|city|country( code)?|formatte(r|d address)|(palette )?label|state|street|zip|AIM [Hh]andle(s)?|my card|select(ion| all)?|unsaved|(alpha )?value|entr(y|ies)|group|(ICQ|Jabber|MSN) handle|person|people|company|department|icon image|job title|note|organization|suffix|vcard|url|copies|collating|pages (across|down)|request print time|target( printer)?|((GUI Scripting|Script menu) )?enabled|show Computer scripts|(de)?activated|awake from nib|became (key|main)|call method|of (class|object)|center|clicked toolbar item|closed|for document|exposed|(can )?hide|idle|keyboard (down|up)|event( (number|type))?|launch(ed)?|load (image|movie|nib|sound)|owner|log|mouse (down|dragged|entered|exited|moved|up)|move|column|localization|resource|script|register|drag (info|types)|resigned (active|key|main)|resiz(e(d)?|able)|right mouse (down|dragged|up)|scroll wheel|(at )?index|should (close|open( untitled)?|quit( after last window closed)?|zoom)|((proposed|screen) )?bounds|show(n)?|behind|in front of|size (mode|to fit)|update(d| toolbar item)?|was (hidden|miniaturized)|will (become active|close|finish launching|hide|miniaturize|move|open|quit|(resign )?active|((maximum|minimum|proposed) )?size|show|zoom)|bundle|data source|movie|pasteboard|sound|tool(bar| tip)|(color|open|save) panel|coordinate system|frontmost|main( (bundle|menu|window))?|((services|(excluded from )?windows) )?menu|((executable|frameworks|resource|scripts|shared (frameworks|support)) )?path|(selected item )?identifier|data|content(s| view)?|character(s)?|click count|(command|control|option|shift) key down|context|delta (x|y|z)|key( code)?|location|pressure|unmodified characters|types|(first )?responder|playing|(allowed|selectable) identifiers|allows customization|(auto saves )?configuration|visible|image( name)?|menu form representation|tag|user(-| )defaults|associated file name|(auto|needs) display|current field editor|floating|has (resize indicator|shadow)|hides when deactivated|level|minimized (image|title)|opaque|position|release when closed|sheet|title(d)?)\b/g, + css: 'color3' }, + + { regex: new RegExp(this.getKeywords(specials), 'gm'), css: 'color3' }, + { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' }, + { regex: new RegExp(this.getKeywords(ordinals), 'gm'), css: 'keyword' } + ]; + }; + + Brush.prototype = new SyntaxHighlighter.Highlighter(); + Brush.aliases = ['applescript']; + + SyntaxHighlighter.brushes.AppleScript = Brush; + + // CommonJS + typeof(exports) != 'undefined' ? exports.Brush = Brush : null; +})(); diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushBash.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushBash.js new file mode 100644 index 0000000000..8c296969ff --- /dev/null +++ b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushBash.js @@ -0,0 +1,59 @@ +/** + * SyntaxHighlighter + * http://alexgorbatchev.com/SyntaxHighlighter + * + * SyntaxHighlighter is donationware. If you are using it, please donate. + * http://alexgorbatchev.com/SyntaxHighlighter/donate.html + * + * @version + * 3.0.83 (July 02 2010) + * + * @copyright + * Copyright (C) 2004-2010 Alex Gorbatchev. + * + * @license + * Dual licensed under the MIT and GPL licenses. + */ +;(function() +{ + // CommonJS + typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null; + + function Brush() + { + var keywords = 'if fi then elif else for do done until while break continue case function return in eq ne ge le'; + var commands = 'alias apropos awk basename bash bc bg builtin bzip2 cal cat cd cfdisk chgrp chmod chown chroot' + + 'cksum clear cmp comm command cp cron crontab csplit cut date dc dd ddrescue declare df ' + + 'diff diff3 dig dir dircolors dirname dirs du echo egrep eject enable env ethtool eval ' + + 'exec exit expand export expr false fdformat fdisk fg fgrep file find fmt fold format ' + + 'free fsck ftp gawk getopts grep groups gzip hash head history hostname id ifconfig ' + + 'import install join kill less let ln local locate logname logout look lpc lpr lprint ' + + 'lprintd lprintq lprm ls lsof make man mkdir mkfifo mkisofs mknod more mount mtools ' + + 'mv netstat nice nl nohup nslookup open op passwd paste pathchk ping popd pr printcap ' + + 'printenv printf ps pushd pwd quota quotacheck quotactl ram rcp read readonly renice ' + + 'remsync rm rmdir rsync screen scp sdiff sed select seq set sftp shift shopt shutdown ' + + 'sleep sort source split ssh strace su sudo sum symlink sync tail tar tee test time ' + + 'times touch top traceroute trap tr true tsort tty type ulimit umask umount unalias ' + + 'uname unexpand uniq units unset unshar useradd usermod users uuencode uudecode v vdir ' + + 'vi watch wc whereis which who whoami Wget xargs yes' + ; + + this.regexList = [ + { regex: /^#!.*$/gm, css: 'preprocessor bold' }, + { regex: /\/[\w-\/]+/gm, css: 'plain' }, + { regex: SyntaxHighlighter.regexLib.singleLinePerlComments, css: 'comments' }, // one line comments + { regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, // double quoted strings + { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // single quoted strings + { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' }, // keywords + { regex: new RegExp(this.getKeywords(commands), 'gm'), css: 'functions' } // commands + ]; + } + + Brush.prototype = new SyntaxHighlighter.Highlighter(); + Brush.aliases = ['bash', 'shell']; + + SyntaxHighlighter.brushes.Bash = Brush; + + // CommonJS + typeof(exports) != 'undefined' ? exports.Brush = Brush : null; +})(); diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushCSharp.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushCSharp.js new file mode 100644 index 0000000000..079214efe1 --- /dev/null +++ b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushCSharp.js @@ -0,0 +1,65 @@ +/** + * SyntaxHighlighter + * http://alexgorbatchev.com/SyntaxHighlighter + * + * SyntaxHighlighter is donationware. If you are using it, please donate. + * http://alexgorbatchev.com/SyntaxHighlighter/donate.html + * + * @version + * 3.0.83 (July 02 2010) + * + * @copyright + * Copyright (C) 2004-2010 Alex Gorbatchev. + * + * @license + * Dual licensed under the MIT and GPL licenses. + */ +;(function() +{ + // CommonJS + typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null; + + function Brush() + { + var keywords = 'abstract as base bool break byte case catch char checked class const ' + + 'continue decimal default delegate do double else enum event explicit ' + + 'extern false finally fixed float for foreach get goto if implicit in int ' + + 'interface internal is lock long namespace new null object operator out ' + + 'override params private protected public readonly ref return sbyte sealed set ' + + 'short sizeof stackalloc static string struct switch this throw true try ' + + 'typeof uint ulong unchecked unsafe ushort using virtual void while'; + + function fixComments(match, regexInfo) + { + var css = (match[0].indexOf("///") == 0) + ? 'color1' + : 'comments' + ; + + return [new SyntaxHighlighter.Match(match[0], match.index, css)]; + } + + this.regexList = [ + { regex: SyntaxHighlighter.regexLib.singleLineCComments, func : fixComments }, // one line comments + { regex: SyntaxHighlighter.regexLib.multiLineCComments, css: 'comments' }, // multiline comments + { regex: /@"(?:[^"]|"")*"/g, css: 'string' }, // @-quoted strings + { regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, // strings + { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // strings + { regex: /^\s*#.*/gm, css: 'preprocessor' }, // preprocessor tags like #region and #endregion + { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' }, // c# keyword + { regex: /\bpartial(?=\s+(?:class|interface|struct)\b)/g, css: 'keyword' }, // contextual keyword: 'partial' + { regex: /\byield(?=\s+(?:return|break)\b)/g, css: 'keyword' } // contextual keyword: 'yield' + ]; + + this.forHtmlScript(SyntaxHighlighter.regexLib.aspScriptTags); + }; + + Brush.prototype = new SyntaxHighlighter.Highlighter(); + Brush.aliases = ['c#', 'c-sharp', 'csharp']; + + SyntaxHighlighter.brushes.CSharp = Brush; + + // CommonJS + typeof(exports) != 'undefined' ? exports.Brush = Brush : null; +})(); + diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushColdFusion.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushColdFusion.js new file mode 100644 index 0000000000..627dbb9b76 --- /dev/null +++ b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushColdFusion.js @@ -0,0 +1,100 @@ +/** + * SyntaxHighlighter + * http://alexgorbatchev.com/SyntaxHighlighter + * + * SyntaxHighlighter is donationware. If you are using it, please donate. + * http://alexgorbatchev.com/SyntaxHighlighter/donate.html + * + * @version + * 3.0.83 (July 02 2010) + * + * @copyright + * Copyright (C) 2004-2010 Alex Gorbatchev. + * + * @license + * Dual licensed under the MIT and GPL licenses. + */ +;(function() +{ + // CommonJS + typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null; + + function Brush() + { + // Contributed by Jen + // http://www.jensbits.com/2009/05/14/coldfusion-brush-for-syntaxhighlighter-plus + + var funcs = 'Abs ACos AddSOAPRequestHeader AddSOAPResponseHeader AjaxLink AjaxOnLoad ArrayAppend ArrayAvg ArrayClear ArrayDeleteAt ' + + 'ArrayInsertAt ArrayIsDefined ArrayIsEmpty ArrayLen ArrayMax ArrayMin ArraySet ArraySort ArraySum ArraySwap ArrayToList ' + + 'Asc ASin Atn BinaryDecode BinaryEncode BitAnd BitMaskClear BitMaskRead BitMaskSet BitNot BitOr BitSHLN BitSHRN BitXor ' + + 'Ceiling CharsetDecode CharsetEncode Chr CJustify Compare CompareNoCase Cos CreateDate CreateDateTime CreateObject ' + + 'CreateODBCDate CreateODBCDateTime CreateODBCTime CreateTime CreateTimeSpan CreateUUID DateAdd DateCompare DateConvert ' + + 'DateDiff DateFormat DatePart Day DayOfWeek DayOfWeekAsString DayOfYear DaysInMonth DaysInYear DE DecimalFormat DecrementValue ' + + 'Decrypt DecryptBinary DeleteClientVariable DeserializeJSON DirectoryExists DollarFormat DotNetToCFType Duplicate Encrypt ' + + 'EncryptBinary Evaluate Exp ExpandPath FileClose FileCopy FileDelete FileExists FileIsEOF FileMove FileOpen FileRead ' + + 'FileReadBinary FileReadLine FileSetAccessMode FileSetAttribute FileSetLastModified FileWrite Find FindNoCase FindOneOf ' + + 'FirstDayOfMonth Fix FormatBaseN GenerateSecretKey GetAuthUser GetBaseTagData GetBaseTagList GetBaseTemplatePath ' + + 'GetClientVariablesList GetComponentMetaData GetContextRoot GetCurrentTemplatePath GetDirectoryFromPath GetEncoding ' + + 'GetException GetFileFromPath GetFileInfo GetFunctionList GetGatewayHelper GetHttpRequestData GetHttpTimeString ' + + 'GetK2ServerDocCount GetK2ServerDocCountLimit GetLocale GetLocaleDisplayName GetLocalHostIP GetMetaData GetMetricData ' + + 'GetPageContext GetPrinterInfo GetProfileSections GetProfileString GetReadableImageFormats GetSOAPRequest GetSOAPRequestHeader ' + + 'GetSOAPResponse GetSOAPResponseHeader GetTempDirectory GetTempFile GetTemplatePath GetTickCount GetTimeZoneInfo GetToken ' + + 'GetUserRoles GetWriteableImageFormats Hash Hour HTMLCodeFormat HTMLEditFormat IIf ImageAddBorder ImageBlur ImageClearRect ' + + 'ImageCopy ImageCrop ImageDrawArc ImageDrawBeveledRect ImageDrawCubicCurve ImageDrawLine ImageDrawLines ImageDrawOval ' + + 'ImageDrawPoint ImageDrawQuadraticCurve ImageDrawRect ImageDrawRoundRect ImageDrawText ImageFlip ImageGetBlob ImageGetBufferedImage ' + + 'ImageGetEXIFTag ImageGetHeight ImageGetIPTCTag ImageGetWidth ImageGrayscale ImageInfo ImageNegative ImageNew ImageOverlay ImagePaste ' + + 'ImageRead ImageReadBase64 ImageResize ImageRotate ImageRotateDrawingAxis ImageScaleToFit ImageSetAntialiasing ImageSetBackgroundColor ' + + 'ImageSetDrawingColor ImageSetDrawingStroke ImageSetDrawingTransparency ImageSharpen ImageShear ImageShearDrawingAxis ImageTranslate ' + + 'ImageTranslateDrawingAxis ImageWrite ImageWriteBase64 ImageXORDrawingMode IncrementValue InputBaseN Insert Int IsArray IsBinary ' + + 'IsBoolean IsCustomFunction IsDate IsDDX IsDebugMode IsDefined IsImage IsImageFile IsInstanceOf IsJSON IsLeapYear IsLocalHost ' + + 'IsNumeric IsNumericDate IsObject IsPDFFile IsPDFObject IsQuery IsSimpleValue IsSOAPRequest IsStruct IsUserInAnyRole IsUserInRole ' + + 'IsUserLoggedIn IsValid IsWDDX IsXML IsXmlAttribute IsXmlDoc IsXmlElem IsXmlNode IsXmlRoot JavaCast JSStringFormat LCase Left Len ' + + 'ListAppend ListChangeDelims ListContains ListContainsNoCase ListDeleteAt ListFind ListFindNoCase ListFirst ListGetAt ListInsertAt ' + + 'ListLast ListLen ListPrepend ListQualify ListRest ListSetAt ListSort ListToArray ListValueCount ListValueCountNoCase LJustify Log ' + + 'Log10 LSCurrencyFormat LSDateFormat LSEuroCurrencyFormat LSIsCurrency LSIsDate LSIsNumeric LSNumberFormat LSParseCurrency LSParseDateTime ' + + 'LSParseEuroCurrency LSParseNumber LSTimeFormat LTrim Max Mid Min Minute Month MonthAsString Now NumberFormat ParagraphFormat ParseDateTime ' + + 'Pi PrecisionEvaluate PreserveSingleQuotes Quarter QueryAddColumn QueryAddRow QueryConvertForGrid QueryNew QuerySetCell QuotedValueList Rand ' + + 'Randomize RandRange REFind REFindNoCase ReleaseComObject REMatch REMatchNoCase RemoveChars RepeatString Replace ReplaceList ReplaceNoCase ' + + 'REReplace REReplaceNoCase Reverse Right RJustify Round RTrim Second SendGatewayMessage SerializeJSON SetEncoding SetLocale SetProfileString ' + + 'SetVariable Sgn Sin Sleep SpanExcluding SpanIncluding Sqr StripCR StructAppend StructClear StructCopy StructCount StructDelete StructFind ' + + 'StructFindKey StructFindValue StructGet StructInsert StructIsEmpty StructKeyArray StructKeyExists StructKeyList StructKeyList StructNew ' + + 'StructSort StructUpdate Tan TimeFormat ToBase64 ToBinary ToScript ToString Trim UCase URLDecode URLEncodedFormat URLSessionFormat Val ' + + 'ValueList VerifyClient Week Wrap Wrap WriteOutput XmlChildPos XmlElemNew XmlFormat XmlGetNodeType XmlNew XmlParse XmlSearch XmlTransform ' + + 'XmlValidate Year YesNoFormat'; + + var keywords = 'cfabort cfajaximport cfajaxproxy cfapplet cfapplication cfargument cfassociate cfbreak cfcache cfcalendar ' + + 'cfcase cfcatch cfchart cfchartdata cfchartseries cfcol cfcollection cfcomponent cfcontent cfcookie cfdbinfo ' + + 'cfdefaultcase cfdirectory cfdiv cfdocument cfdocumentitem cfdocumentsection cfdump cfelse cfelseif cferror ' + + 'cfexchangecalendar cfexchangeconnection cfexchangecontact cfexchangefilter cfexchangemail cfexchangetask ' + + 'cfexecute cfexit cffeed cffile cfflush cfform cfformgroup cfformitem cfftp cffunction cfgrid cfgridcolumn ' + + 'cfgridrow cfgridupdate cfheader cfhtmlhead cfhttp cfhttpparam cfif cfimage cfimport cfinclude cfindex ' + + 'cfinput cfinsert cfinterface cfinvoke cfinvokeargument cflayout cflayoutarea cfldap cflocation cflock cflog ' + + 'cflogin cfloginuser cflogout cfloop cfmail cfmailparam cfmailpart cfmenu cfmenuitem cfmodule cfNTauthenticate ' + + 'cfobject cfobjectcache cfoutput cfparam cfpdf cfpdfform cfpdfformparam cfpdfparam cfpdfsubform cfpod cfpop ' + + 'cfpresentation cfpresentationslide cfpresenter cfprint cfprocessingdirective cfprocparam cfprocresult ' + + 'cfproperty cfquery cfqueryparam cfregistry cfreport cfreportparam cfrethrow cfreturn cfsavecontent cfschedule ' + + 'cfscript cfsearch cfselect cfset cfsetting cfsilent cfslider cfsprydataset cfstoredproc cfswitch cftable ' + + 'cftextarea cfthread cfthrow cftimer cftooltip cftrace cftransaction cftree cftreeitem cftry cfupdate cfwddx ' + + 'cfwindow cfxml cfzip cfzipparam'; + + var operators = 'all and any between cross in join like not null or outer some'; + + this.regexList = [ + { regex: new RegExp('--(.*)$', 'gm'), css: 'comments' }, // one line and multiline comments + { regex: SyntaxHighlighter.regexLib.xmlComments, css: 'comments' }, // single quoted strings + { regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, // double quoted strings + { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // single quoted strings + { regex: new RegExp(this.getKeywords(funcs), 'gmi'), css: 'functions' }, // functions + { regex: new RegExp(this.getKeywords(operators), 'gmi'), css: 'color1' }, // operators and such + { regex: new RegExp(this.getKeywords(keywords), 'gmi'), css: 'keyword' } // keyword + ]; + } + + Brush.prototype = new SyntaxHighlighter.Highlighter(); + Brush.aliases = ['coldfusion','cf']; + + SyntaxHighlighter.brushes.ColdFusion = Brush; + + // CommonJS + typeof(exports) != 'undefined' ? exports.Brush = Brush : null; +})(); diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushCpp.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushCpp.js new file mode 100644 index 0000000000..9f70d3aed6 --- /dev/null +++ b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushCpp.js @@ -0,0 +1,97 @@ +/** + * SyntaxHighlighter + * http://alexgorbatchev.com/SyntaxHighlighter + * + * SyntaxHighlighter is donationware. If you are using it, please donate. + * http://alexgorbatchev.com/SyntaxHighlighter/donate.html + * + * @version + * 3.0.83 (July 02 2010) + * + * @copyright + * Copyright (C) 2004-2010 Alex Gorbatchev. + * + * @license + * Dual licensed under the MIT and GPL licenses. + */ +;(function() +{ + // CommonJS + typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null; + + function Brush() + { + // Copyright 2006 Shin, YoungJin + + var datatypes = 'ATOM BOOL BOOLEAN BYTE CHAR COLORREF DWORD DWORDLONG DWORD_PTR ' + + 'DWORD32 DWORD64 FLOAT HACCEL HALF_PTR HANDLE HBITMAP HBRUSH ' + + 'HCOLORSPACE HCONV HCONVLIST HCURSOR HDC HDDEDATA HDESK HDROP HDWP ' + + 'HENHMETAFILE HFILE HFONT HGDIOBJ HGLOBAL HHOOK HICON HINSTANCE HKEY ' + + 'HKL HLOCAL HMENU HMETAFILE HMODULE HMONITOR HPALETTE HPEN HRESULT ' + + 'HRGN HRSRC HSZ HWINSTA HWND INT INT_PTR INT32 INT64 LANGID LCID LCTYPE ' + + 'LGRPID LONG LONGLONG LONG_PTR LONG32 LONG64 LPARAM LPBOOL LPBYTE LPCOLORREF ' + + 'LPCSTR LPCTSTR LPCVOID LPCWSTR LPDWORD LPHANDLE LPINT LPLONG LPSTR LPTSTR ' + + 'LPVOID LPWORD LPWSTR LRESULT PBOOL PBOOLEAN PBYTE PCHAR PCSTR PCTSTR PCWSTR ' + + 'PDWORDLONG PDWORD_PTR PDWORD32 PDWORD64 PFLOAT PHALF_PTR PHANDLE PHKEY PINT ' + + 'PINT_PTR PINT32 PINT64 PLCID PLONG PLONGLONG PLONG_PTR PLONG32 PLONG64 POINTER_32 ' + + 'POINTER_64 PSHORT PSIZE_T PSSIZE_T PSTR PTBYTE PTCHAR PTSTR PUCHAR PUHALF_PTR ' + + 'PUINT PUINT_PTR PUINT32 PUINT64 PULONG PULONGLONG PULONG_PTR PULONG32 PULONG64 ' + + 'PUSHORT PVOID PWCHAR PWORD PWSTR SC_HANDLE SC_LOCK SERVICE_STATUS_HANDLE SHORT ' + + 'SIZE_T SSIZE_T TBYTE TCHAR UCHAR UHALF_PTR UINT UINT_PTR UINT32 UINT64 ULONG ' + + 'ULONGLONG ULONG_PTR ULONG32 ULONG64 USHORT USN VOID WCHAR WORD WPARAM WPARAM WPARAM ' + + 'char bool short int __int32 __int64 __int8 __int16 long float double __wchar_t ' + + 'clock_t _complex _dev_t _diskfree_t div_t ldiv_t _exception _EXCEPTION_POINTERS ' + + 'FILE _finddata_t _finddatai64_t _wfinddata_t _wfinddatai64_t __finddata64_t ' + + '__wfinddata64_t _FPIEEE_RECORD fpos_t _HEAPINFO _HFILE lconv intptr_t ' + + 'jmp_buf mbstate_t _off_t _onexit_t _PNH ptrdiff_t _purecall_handler ' + + 'sig_atomic_t size_t _stat __stat64 _stati64 terminate_function ' + + 'time_t __time64_t _timeb __timeb64 tm uintptr_t _utimbuf ' + + 'va_list wchar_t wctrans_t wctype_t wint_t signed'; + + var keywords = 'break case catch class const __finally __exception __try ' + + 'const_cast continue private public protected __declspec ' + + 'default delete deprecated dllexport dllimport do dynamic_cast ' + + 'else enum explicit extern if for friend goto inline ' + + 'mutable naked namespace new noinline noreturn nothrow ' + + 'register reinterpret_cast return selectany ' + + 'sizeof static static_cast struct switch template this ' + + 'thread throw true false try typedef typeid typename union ' + + 'using uuid virtual void volatile whcar_t while'; + + var functions = 'assert isalnum isalpha iscntrl isdigit isgraph islower isprint' + + 'ispunct isspace isupper isxdigit tolower toupper errno localeconv ' + + 'setlocale acos asin atan atan2 ceil cos cosh exp fabs floor fmod ' + + 'frexp ldexp log log10 modf pow sin sinh sqrt tan tanh jmp_buf ' + + 'longjmp setjmp raise signal sig_atomic_t va_arg va_end va_start ' + + 'clearerr fclose feof ferror fflush fgetc fgetpos fgets fopen ' + + 'fprintf fputc fputs fread freopen fscanf fseek fsetpos ftell ' + + 'fwrite getc getchar gets perror printf putc putchar puts remove ' + + 'rename rewind scanf setbuf setvbuf sprintf sscanf tmpfile tmpnam ' + + 'ungetc vfprintf vprintf vsprintf abort abs atexit atof atoi atol ' + + 'bsearch calloc div exit free getenv labs ldiv malloc mblen mbstowcs ' + + 'mbtowc qsort rand realloc srand strtod strtol strtoul system ' + + 'wcstombs wctomb memchr memcmp memcpy memmove memset strcat strchr ' + + 'strcmp strcoll strcpy strcspn strerror strlen strncat strncmp ' + + 'strncpy strpbrk strrchr strspn strstr strtok strxfrm asctime ' + + 'clock ctime difftime gmtime localtime mktime strftime time'; + + this.regexList = [ + { regex: SyntaxHighlighter.regexLib.singleLineCComments, css: 'comments' }, // one line comments + { regex: SyntaxHighlighter.regexLib.multiLineCComments, css: 'comments' }, // multiline comments + { regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, // strings + { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // strings + { regex: /^ *#.*/gm, css: 'preprocessor' }, + { regex: new RegExp(this.getKeywords(datatypes), 'gm'), css: 'color1 bold' }, + { regex: new RegExp(this.getKeywords(functions), 'gm'), css: 'functions bold' }, + { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword bold' } + ]; + }; + + Brush.prototype = new SyntaxHighlighter.Highlighter(); + Brush.aliases = ['cpp', 'c']; + + SyntaxHighlighter.brushes.Cpp = Brush; + + // CommonJS + typeof(exports) != 'undefined' ? exports.Brush = Brush : null; +})(); diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushCss.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushCss.js new file mode 100644 index 0000000000..4297a9a648 --- /dev/null +++ b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushCss.js @@ -0,0 +1,91 @@ +/** + * SyntaxHighlighter + * http://alexgorbatchev.com/SyntaxHighlighter + * + * SyntaxHighlighter is donationware. If you are using it, please donate. + * http://alexgorbatchev.com/SyntaxHighlighter/donate.html + * + * @version + * 3.0.83 (July 02 2010) + * + * @copyright + * Copyright (C) 2004-2010 Alex Gorbatchev. + * + * @license + * Dual licensed under the MIT and GPL licenses. + */ +;(function() +{ + // CommonJS + typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null; + + function Brush() + { + function getKeywordsCSS(str) + { + return '\\b([a-z_]|)' + str.replace(/ /g, '(?=:)\\b|\\b([a-z_\\*]|\\*|)') + '(?=:)\\b'; + }; + + function getValuesCSS(str) + { + return '\\b' + str.replace(/ /g, '(?!-)(?!:)\\b|\\b()') + '\:\\b'; + }; + + var keywords = 'ascent azimuth background-attachment background-color background-image background-position ' + + 'background-repeat background baseline bbox border-collapse border-color border-spacing border-style border-top ' + + 'border-right border-bottom border-left border-top-color border-right-color border-bottom-color border-left-color ' + + 'border-top-style border-right-style border-bottom-style border-left-style border-top-width border-right-width ' + + 'border-bottom-width border-left-width border-width border bottom cap-height caption-side centerline clear clip color ' + + 'content counter-increment counter-reset cue-after cue-before cue cursor definition-src descent direction display ' + + 'elevation empty-cells float font-size-adjust font-family font-size font-stretch font-style font-variant font-weight font ' + + 'height left letter-spacing line-height list-style-image list-style-position list-style-type list-style margin-top ' + + 'margin-right margin-bottom margin-left margin marker-offset marks mathline max-height max-width min-height min-width orphans ' + + 'outline-color outline-style outline-width outline overflow padding-top padding-right padding-bottom padding-left padding page ' + + 'page-break-after page-break-before page-break-inside pause pause-after pause-before pitch pitch-range play-during position ' + + 'quotes right richness size slope src speak-header speak-numeral speak-punctuation speak speech-rate stemh stemv stress ' + + 'table-layout text-align top text-decoration text-indent text-shadow text-transform unicode-bidi unicode-range units-per-em ' + + 'vertical-align visibility voice-family volume white-space widows width widths word-spacing x-height z-index'; + + var values = 'above absolute all always aqua armenian attr aural auto avoid baseline behind below bidi-override black blink block blue bold bolder '+ + 'both bottom braille capitalize caption center center-left center-right circle close-quote code collapse compact condensed '+ + 'continuous counter counters crop cross crosshair cursive dashed decimal decimal-leading-zero default digits disc dotted double '+ + 'embed embossed e-resize expanded extra-condensed extra-expanded fantasy far-left far-right fast faster fixed format fuchsia '+ + 'gray green groove handheld hebrew help hidden hide high higher icon inline-table inline inset inside invert italic '+ + 'justify landscape large larger left-side left leftwards level lighter lime line-through list-item local loud lower-alpha '+ + 'lowercase lower-greek lower-latin lower-roman lower low ltr marker maroon medium message-box middle mix move narrower '+ + 'navy ne-resize no-close-quote none no-open-quote no-repeat normal nowrap n-resize nw-resize oblique olive once open-quote outset '+ + 'outside overline pointer portrait pre print projection purple red relative repeat repeat-x repeat-y rgb ridge right right-side '+ + 'rightwards rtl run-in screen scroll semi-condensed semi-expanded separate se-resize show silent silver slower slow '+ + 'small small-caps small-caption smaller soft solid speech spell-out square s-resize static status-bar sub super sw-resize '+ + 'table-caption table-cell table-column table-column-group table-footer-group table-header-group table-row table-row-group teal '+ + 'text-bottom text-top thick thin top transparent tty tv ultra-condensed ultra-expanded underline upper-alpha uppercase upper-latin '+ + 'upper-roman url visible wait white wider w-resize x-fast x-high x-large x-loud x-low x-slow x-small x-soft xx-large xx-small yellow'; + + var fonts = '[mM]onospace [tT]ahoma [vV]erdana [aA]rial [hH]elvetica [sS]ans-serif [sS]erif [cC]ourier mono sans serif'; + + this.regexList = [ + { regex: SyntaxHighlighter.regexLib.multiLineCComments, css: 'comments' }, // multiline comments + { regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, // double quoted strings + { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // single quoted strings + { regex: /\#[a-fA-F0-9]{3,6}/g, css: 'value' }, // html colors + { regex: /(-?\d+)(\.\d+)?(px|em|pt|\:|\%|)/g, css: 'value' }, // sizes + { regex: /!important/g, css: 'color3' }, // !important + { regex: new RegExp(getKeywordsCSS(keywords), 'gm'), css: 'keyword' }, // keywords + { regex: new RegExp(getValuesCSS(values), 'g'), css: 'value' }, // values + { regex: new RegExp(this.getKeywords(fonts), 'g'), css: 'color1' } // fonts + ]; + + this.forHtmlScript({ + left: /(<|<)\s*style.*?(>|>)/gi, + right: /(<|<)\/\s*style\s*(>|>)/gi + }); + }; + + Brush.prototype = new SyntaxHighlighter.Highlighter(); + Brush.aliases = ['css']; + + SyntaxHighlighter.brushes.CSS = Brush; + + // CommonJS + typeof(exports) != 'undefined' ? exports.Brush = Brush : null; +})(); diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushDelphi.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushDelphi.js new file mode 100644 index 0000000000..e1060d4468 --- /dev/null +++ b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushDelphi.js @@ -0,0 +1,55 @@ +/** + * SyntaxHighlighter + * http://alexgorbatchev.com/SyntaxHighlighter + * + * SyntaxHighlighter is donationware. If you are using it, please donate. + * http://alexgorbatchev.com/SyntaxHighlighter/donate.html + * + * @version + * 3.0.83 (July 02 2010) + * + * @copyright + * Copyright (C) 2004-2010 Alex Gorbatchev. + * + * @license + * Dual licensed under the MIT and GPL licenses. + */ +;(function() +{ + // CommonJS + typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null; + + function Brush() + { + var keywords = 'abs addr and ansichar ansistring array as asm begin boolean byte cardinal ' + + 'case char class comp const constructor currency destructor div do double ' + + 'downto else end except exports extended false file finalization finally ' + + 'for function goto if implementation in inherited int64 initialization ' + + 'integer interface is label library longint longword mod nil not object ' + + 'of on or packed pansichar pansistring pchar pcurrency pdatetime pextended ' + + 'pint64 pointer private procedure program property pshortstring pstring ' + + 'pvariant pwidechar pwidestring protected public published raise real real48 ' + + 'record repeat set shl shortint shortstring shr single smallint string then ' + + 'threadvar to true try type unit until uses val var varirnt while widechar ' + + 'widestring with word write writeln xor'; + + this.regexList = [ + { regex: /\(\*[\s\S]*?\*\)/gm, css: 'comments' }, // multiline comments (* *) + { regex: /{(?!\$)[\s\S]*?}/gm, css: 'comments' }, // multiline comments { } + { regex: SyntaxHighlighter.regexLib.singleLineCComments, css: 'comments' }, // one line + { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // strings + { regex: /\{\$[a-zA-Z]+ .+\}/g, css: 'color1' }, // compiler Directives and Region tags + { regex: /\b[\d\.]+\b/g, css: 'value' }, // numbers 12345 + { regex: /\$[a-zA-Z0-9]+\b/g, css: 'value' }, // numbers $F5D3 + { regex: new RegExp(this.getKeywords(keywords), 'gmi'), css: 'keyword' } // keyword + ]; + }; + + Brush.prototype = new SyntaxHighlighter.Highlighter(); + Brush.aliases = ['delphi', 'pascal', 'pas']; + + SyntaxHighlighter.brushes.Delphi = Brush; + + // CommonJS + typeof(exports) != 'undefined' ? exports.Brush = Brush : null; +})(); diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushDiff.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushDiff.js new file mode 100644 index 0000000000..e9b14fc580 --- /dev/null +++ b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushDiff.js @@ -0,0 +1,41 @@ +/** + * SyntaxHighlighter + * http://alexgorbatchev.com/SyntaxHighlighter + * + * SyntaxHighlighter is donationware. If you are using it, please donate. + * http://alexgorbatchev.com/SyntaxHighlighter/donate.html + * + * @version + * 3.0.83 (July 02 2010) + * + * @copyright + * Copyright (C) 2004-2010 Alex Gorbatchev. + * + * @license + * Dual licensed under the MIT and GPL licenses. + */ +;(function() +{ + // CommonJS + typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null; + + function Brush() + { + this.regexList = [ + { regex: /^\+\+\+.*$/gm, css: 'color2' }, + { regex: /^\-\-\-.*$/gm, css: 'color2' }, + { regex: /^\s.*$/gm, css: 'color1' }, + { regex: /^@@.*@@$/gm, css: 'variable' }, + { regex: /^\+[^\+]{1}.*$/gm, css: 'string' }, + { regex: /^\-[^\-]{1}.*$/gm, css: 'comments' } + ]; + }; + + Brush.prototype = new SyntaxHighlighter.Highlighter(); + Brush.aliases = ['diff', 'patch']; + + SyntaxHighlighter.brushes.Diff = Brush; + + // CommonJS + typeof(exports) != 'undefined' ? exports.Brush = Brush : null; +})(); diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushErlang.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushErlang.js new file mode 100644 index 0000000000..6ba7d9da87 --- /dev/null +++ b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushErlang.js @@ -0,0 +1,52 @@ +/** + * SyntaxHighlighter + * http://alexgorbatchev.com/SyntaxHighlighter + * + * SyntaxHighlighter is donationware. If you are using it, please donate. + * http://alexgorbatchev.com/SyntaxHighlighter/donate.html + * + * @version + * 3.0.83 (July 02 2010) + * + * @copyright + * Copyright (C) 2004-2010 Alex Gorbatchev. + * + * @license + * Dual licensed under the MIT and GPL licenses. + */ +;(function() +{ + // CommonJS + typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null; + + function Brush() + { + // Contributed by Jean-Lou Dupont + // http://jldupont.blogspot.com/2009/06/erlang-syntax-highlighter.html + + // According to: http://erlang.org/doc/reference_manual/introduction.html#1.5 + var keywords = 'after and andalso band begin bnot bor bsl bsr bxor '+ + 'case catch cond div end fun if let not of or orelse '+ + 'query receive rem try when xor'+ + // additional + ' module export import define'; + + this.regexList = [ + { regex: new RegExp("[A-Z][A-Za-z0-9_]+", 'g'), css: 'constants' }, + { regex: new RegExp("\\%.+", 'gm'), css: 'comments' }, + { regex: new RegExp("\\?[A-Za-z0-9_]+", 'g'), css: 'preprocessor' }, + { regex: new RegExp("[a-z0-9_]+:[a-z0-9_]+", 'g'), css: 'functions' }, + { regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, + { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, + { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' } + ]; + }; + + Brush.prototype = new SyntaxHighlighter.Highlighter(); + Brush.aliases = ['erl', 'erlang']; + + SyntaxHighlighter.brushes.Erland = Brush; + + // CommonJS + typeof(exports) != 'undefined' ? exports.Brush = Brush : null; +})(); diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushGroovy.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushGroovy.js new file mode 100644 index 0000000000..6ec5c18521 --- /dev/null +++ b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushGroovy.js @@ -0,0 +1,67 @@ +/** + * SyntaxHighlighter + * http://alexgorbatchev.com/SyntaxHighlighter + * + * SyntaxHighlighter is donationware. If you are using it, please donate. + * http://alexgorbatchev.com/SyntaxHighlighter/donate.html + * + * @version + * 3.0.83 (July 02 2010) + * + * @copyright + * Copyright (C) 2004-2010 Alex Gorbatchev. + * + * @license + * Dual licensed under the MIT and GPL licenses. + */ +;(function() +{ + // CommonJS + typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null; + + function Brush() + { + // Contributed by Andres Almiray + // http://jroller.com/aalmiray/entry/nice_source_code_syntax_highlighter + + var keywords = 'as assert break case catch class continue def default do else extends finally ' + + 'if in implements import instanceof interface new package property return switch ' + + 'throw throws try while public protected private static'; + var types = 'void boolean byte char short int long float double'; + var constants = 'null'; + var methods = 'allProperties count get size '+ + 'collect each eachProperty eachPropertyName eachWithIndex find findAll ' + + 'findIndexOf grep inject max min reverseEach sort ' + + 'asImmutable asSynchronized flatten intersect join pop reverse subMap toList ' + + 'padRight padLeft contains eachMatch toCharacter toLong toUrl tokenize ' + + 'eachFile eachFileRecurse eachB yte eachLine readBytes readLine getText ' + + 'splitEachLine withReader append encodeBase64 decodeBase64 filterLine ' + + 'transformChar transformLine withOutputStream withPrintWriter withStream ' + + 'withStreams withWriter withWriterAppend write writeLine '+ + 'dump inspect invokeMethod print println step times upto use waitForOrKill '+ + 'getText'; + + this.regexList = [ + { regex: SyntaxHighlighter.regexLib.singleLineCComments, css: 'comments' }, // one line comments + { regex: SyntaxHighlighter.regexLib.multiLineCComments, css: 'comments' }, // multiline comments + { regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, // strings + { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // strings + { regex: /""".*"""/g, css: 'string' }, // GStrings + { regex: new RegExp('\\b([\\d]+(\\.[\\d]+)?|0x[a-f0-9]+)\\b', 'gi'), css: 'value' }, // numbers + { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' }, // goovy keyword + { regex: new RegExp(this.getKeywords(types), 'gm'), css: 'color1' }, // goovy/java type + { regex: new RegExp(this.getKeywords(constants), 'gm'), css: 'constants' }, // constants + { regex: new RegExp(this.getKeywords(methods), 'gm'), css: 'functions' } // methods + ]; + + this.forHtmlScript(SyntaxHighlighter.regexLib.aspScriptTags); + } + + Brush.prototype = new SyntaxHighlighter.Highlighter(); + Brush.aliases = ['groovy']; + + SyntaxHighlighter.brushes.Groovy = Brush; + + // CommonJS + typeof(exports) != 'undefined' ? exports.Brush = Brush : null; +})(); diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushJScript.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushJScript.js new file mode 100644 index 0000000000..ff98daba16 --- /dev/null +++ b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushJScript.js @@ -0,0 +1,52 @@ +/** + * SyntaxHighlighter + * http://alexgorbatchev.com/SyntaxHighlighter + * + * SyntaxHighlighter is donationware. If you are using it, please donate. + * http://alexgorbatchev.com/SyntaxHighlighter/donate.html + * + * @version + * 3.0.83 (July 02 2010) + * + * @copyright + * Copyright (C) 2004-2010 Alex Gorbatchev. + * + * @license + * Dual licensed under the MIT and GPL licenses. + */ +;(function() +{ + // CommonJS + typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null; + + function Brush() + { + var keywords = 'break case catch continue ' + + 'default delete do else false ' + + 'for function if in instanceof ' + + 'new null return super switch ' + + 'this throw true try typeof var while with' + ; + + var r = SyntaxHighlighter.regexLib; + + this.regexList = [ + { regex: r.multiLineDoubleQuotedString, css: 'string' }, // double quoted strings + { regex: r.multiLineSingleQuotedString, css: 'string' }, // single quoted strings + { regex: r.singleLineCComments, css: 'comments' }, // one line comments + { regex: r.multiLineCComments, css: 'comments' }, // multiline comments + { regex: /\s*#.*/gm, css: 'preprocessor' }, // preprocessor tags like #region and #endregion + { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' } // keywords + ]; + + this.forHtmlScript(r.scriptScriptTags); + }; + + Brush.prototype = new SyntaxHighlighter.Highlighter(); + Brush.aliases = ['js', 'jscript', 'javascript']; + + SyntaxHighlighter.brushes.JScript = Brush; + + // CommonJS + typeof(exports) != 'undefined' ? exports.Brush = Brush : null; +})(); diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushJava.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushJava.js new file mode 100644 index 0000000000..d692fd6382 --- /dev/null +++ b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushJava.js @@ -0,0 +1,57 @@ +/** + * SyntaxHighlighter + * http://alexgorbatchev.com/SyntaxHighlighter + * + * SyntaxHighlighter is donationware. If you are using it, please donate. + * http://alexgorbatchev.com/SyntaxHighlighter/donate.html + * + * @version + * 3.0.83 (July 02 2010) + * + * @copyright + * Copyright (C) 2004-2010 Alex Gorbatchev. + * + * @license + * Dual licensed under the MIT and GPL licenses. + */ +;(function() +{ + // CommonJS + typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null; + + function Brush() + { + var keywords = 'abstract assert boolean break byte case catch char class const ' + + 'continue default do double else enum extends ' + + 'false final finally float for goto if implements import ' + + 'instanceof int interface long native new null ' + + 'package private protected public return ' + + 'short static strictfp super switch synchronized this throw throws true ' + + 'transient try void volatile while'; + + this.regexList = [ + { regex: SyntaxHighlighter.regexLib.singleLineCComments, css: 'comments' }, // one line comments + { regex: /\/\*([^\*][\s\S]*)?\*\//gm, css: 'comments' }, // multiline comments + { regex: /\/\*(?!\*\/)\*[\s\S]*?\*\//gm, css: 'preprocessor' }, // documentation comments + { regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, // strings + { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // strings + { regex: /\b([\d]+(\.[\d]+)?|0x[a-f0-9]+)\b/gi, css: 'value' }, // numbers + { regex: /(?!\@interface\b)\@[\$\w]+\b/g, css: 'color1' }, // annotation @anno + { regex: /\@interface\b/g, css: 'color2' }, // @interface keyword + { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' } // java keyword + ]; + + this.forHtmlScript({ + left : /(<|<)%[@!=]?/g, + right : /%(>|>)/g + }); + }; + + Brush.prototype = new SyntaxHighlighter.Highlighter(); + Brush.aliases = ['java']; + + SyntaxHighlighter.brushes.Java = Brush; + + // CommonJS + typeof(exports) != 'undefined' ? exports.Brush = Brush : null; +})(); diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushJavaFX.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushJavaFX.js new file mode 100644 index 0000000000..1a150a6ad3 --- /dev/null +++ b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushJavaFX.js @@ -0,0 +1,58 @@ +/** + * SyntaxHighlighter + * http://alexgorbatchev.com/SyntaxHighlighter + * + * SyntaxHighlighter is donationware. If you are using it, please donate. + * http://alexgorbatchev.com/SyntaxHighlighter/donate.html + * + * @version + * 3.0.83 (July 02 2010) + * + * @copyright + * Copyright (C) 2004-2010 Alex Gorbatchev. + * + * @license + * Dual licensed under the MIT and GPL licenses. + */ +;(function() +{ + // CommonJS + typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null; + + function Brush() + { + // Contributed by Patrick Webster + // http://patrickwebster.blogspot.com/2009/04/javafx-brush-for-syntaxhighlighter.html + var datatypes = 'Boolean Byte Character Double Duration ' + + 'Float Integer Long Number Short String Void' + ; + + var keywords = 'abstract after and as assert at before bind bound break catch class ' + + 'continue def delete else exclusive extends false finally first for from ' + + 'function if import in indexof init insert instanceof into inverse last ' + + 'lazy mixin mod nativearray new not null on or override package postinit ' + + 'protected public public-init public-read replace return reverse sizeof ' + + 'step super then this throw true try tween typeof var where while with ' + + 'attribute let private readonly static trigger' + ; + + this.regexList = [ + { regex: SyntaxHighlighter.regexLib.singleLineCComments, css: 'comments' }, + { regex: SyntaxHighlighter.regexLib.multiLineCComments, css: 'comments' }, + { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, + { regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, + { regex: /(-?\.?)(\b(\d*\.?\d+|\d+\.?\d*)(e[+-]?\d+)?|0x[a-f\d]+)\b\.?/gi, css: 'color2' }, // numbers + { regex: new RegExp(this.getKeywords(datatypes), 'gm'), css: 'variable' }, // datatypes + { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' } + ]; + this.forHtmlScript(SyntaxHighlighter.regexLib.aspScriptTags); + }; + + Brush.prototype = new SyntaxHighlighter.Highlighter(); + Brush.aliases = ['jfx', 'javafx']; + + SyntaxHighlighter.brushes.JavaFX = Brush; + + // CommonJS + typeof(exports) != 'undefined' ? exports.Brush = Brush : null; +})(); diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushPerl.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushPerl.js new file mode 100644 index 0000000000..d94a2e0ec5 --- /dev/null +++ b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushPerl.js @@ -0,0 +1,72 @@ +/** + * SyntaxHighlighter + * http://alexgorbatchev.com/SyntaxHighlighter + * + * SyntaxHighlighter is donationware. If you are using it, please donate. + * http://alexgorbatchev.com/SyntaxHighlighter/donate.html + * + * @version + * 3.0.83 (July 02 2010) + * + * @copyright + * Copyright (C) 2004-2010 Alex Gorbatchev. + * + * @license + * Dual licensed under the MIT and GPL licenses. + */ +;(function() +{ + // CommonJS + typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null; + + function Brush() + { + // Contributed by David Simmons-Duffin and Marty Kube + + var funcs = + 'abs accept alarm atan2 bind binmode chdir chmod chomp chop chown chr ' + + 'chroot close closedir connect cos crypt defined delete each endgrent ' + + 'endhostent endnetent endprotoent endpwent endservent eof exec exists ' + + 'exp fcntl fileno flock fork format formline getc getgrent getgrgid ' + + 'getgrnam gethostbyaddr gethostbyname gethostent getlogin getnetbyaddr ' + + 'getnetbyname getnetent getpeername getpgrp getppid getpriority ' + + 'getprotobyname getprotobynumber getprotoent getpwent getpwnam getpwuid ' + + 'getservbyname getservbyport getservent getsockname getsockopt glob ' + + 'gmtime grep hex index int ioctl join keys kill lc lcfirst length link ' + + 'listen localtime lock log lstat map mkdir msgctl msgget msgrcv msgsnd ' + + 'oct open opendir ord pack pipe pop pos print printf prototype push ' + + 'quotemeta rand read readdir readline readlink readpipe recv rename ' + + 'reset reverse rewinddir rindex rmdir scalar seek seekdir select semctl ' + + 'semget semop send setgrent sethostent setnetent setpgrp setpriority ' + + 'setprotoent setpwent setservent setsockopt shift shmctl shmget shmread ' + + 'shmwrite shutdown sin sleep socket socketpair sort splice split sprintf ' + + 'sqrt srand stat study substr symlink syscall sysopen sysread sysseek ' + + 'system syswrite tell telldir time times tr truncate uc ucfirst umask ' + + 'undef unlink unpack unshift utime values vec wait waitpid warn write'; + + var keywords = + 'bless caller continue dbmclose dbmopen die do dump else elsif eval exit ' + + 'for foreach goto if import last local my next no our package redo ref ' + + 'require return sub tie tied unless untie until use wantarray while'; + + this.regexList = [ + { regex: new RegExp('#[^!].*$', 'gm'), css: 'comments' }, + { regex: new RegExp('^\\s*#!.*$', 'gm'), css: 'preprocessor' }, // shebang + { regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, + { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, + { regex: new RegExp('(\\$|@|%)\\w+', 'g'), css: 'variable' }, + { regex: new RegExp(this.getKeywords(funcs), 'gmi'), css: 'functions' }, + { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' } + ]; + + this.forHtmlScript(SyntaxHighlighter.regexLib.phpScriptTags); + } + + Brush.prototype = new SyntaxHighlighter.Highlighter(); + Brush.aliases = ['perl', 'Perl', 'pl']; + + SyntaxHighlighter.brushes.Perl = Brush; + + // CommonJS + typeof(exports) != 'undefined' ? exports.Brush = Brush : null; +})(); diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushPhp.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushPhp.js new file mode 100644 index 0000000000..95e6e4325b --- /dev/null +++ b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushPhp.js @@ -0,0 +1,88 @@ +/** + * SyntaxHighlighter + * http://alexgorbatchev.com/SyntaxHighlighter + * + * SyntaxHighlighter is donationware. If you are using it, please donate. + * http://alexgorbatchev.com/SyntaxHighlighter/donate.html + * + * @version + * 3.0.83 (July 02 2010) + * + * @copyright + * Copyright (C) 2004-2010 Alex Gorbatchev. + * + * @license + * Dual licensed under the MIT and GPL licenses. + */ +;(function() +{ + // CommonJS + typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null; + + function Brush() + { + var funcs = 'abs acos acosh addcslashes addslashes ' + + 'array_change_key_case array_chunk array_combine array_count_values array_diff '+ + 'array_diff_assoc array_diff_key array_diff_uassoc array_diff_ukey array_fill '+ + 'array_filter array_flip array_intersect array_intersect_assoc array_intersect_key '+ + 'array_intersect_uassoc array_intersect_ukey array_key_exists array_keys array_map '+ + 'array_merge array_merge_recursive array_multisort array_pad array_pop array_product '+ + 'array_push array_rand array_reduce array_reverse array_search array_shift '+ + 'array_slice array_splice array_sum array_udiff array_udiff_assoc '+ + 'array_udiff_uassoc array_uintersect array_uintersect_assoc '+ + 'array_uintersect_uassoc array_unique array_unshift array_values array_walk '+ + 'array_walk_recursive atan atan2 atanh base64_decode base64_encode base_convert '+ + 'basename bcadd bccomp bcdiv bcmod bcmul bindec bindtextdomain bzclose bzcompress '+ + 'bzdecompress bzerrno bzerror bzerrstr bzflush bzopen bzread bzwrite ceil chdir '+ + 'checkdate checkdnsrr chgrp chmod chop chown chr chroot chunk_split class_exists '+ + 'closedir closelog copy cos cosh count count_chars date decbin dechex decoct '+ + 'deg2rad delete ebcdic2ascii echo empty end ereg ereg_replace eregi eregi_replace error_log '+ + 'error_reporting escapeshellarg escapeshellcmd eval exec exit exp explode extension_loaded '+ + 'feof fflush fgetc fgetcsv fgets fgetss file_exists file_get_contents file_put_contents '+ + 'fileatime filectime filegroup fileinode filemtime fileowner fileperms filesize filetype '+ + 'floatval flock floor flush fmod fnmatch fopen fpassthru fprintf fputcsv fputs fread fscanf '+ + 'fseek fsockopen fstat ftell ftok getallheaders getcwd getdate getenv gethostbyaddr gethostbyname '+ + 'gethostbynamel getimagesize getlastmod getmxrr getmygid getmyinode getmypid getmyuid getopt '+ + 'getprotobyname getprotobynumber getrandmax getrusage getservbyname getservbyport gettext '+ + 'gettimeofday gettype glob gmdate gmmktime ini_alter ini_get ini_get_all ini_restore ini_set '+ + 'interface_exists intval ip2long is_a is_array is_bool is_callable is_dir is_double '+ + 'is_executable is_file is_finite is_float is_infinite is_int is_integer is_link is_long '+ + 'is_nan is_null is_numeric is_object is_readable is_real is_resource is_scalar is_soap_fault '+ + 'is_string is_subclass_of is_uploaded_file is_writable is_writeable mkdir mktime nl2br '+ + 'parse_ini_file parse_str parse_url passthru pathinfo print readlink realpath rewind rewinddir rmdir '+ + 'round str_ireplace str_pad str_repeat str_replace str_rot13 str_shuffle str_split '+ + 'str_word_count strcasecmp strchr strcmp strcoll strcspn strftime strip_tags stripcslashes '+ + 'stripos stripslashes stristr strlen strnatcasecmp strnatcmp strncasecmp strncmp strpbrk '+ + 'strpos strptime strrchr strrev strripos strrpos strspn strstr strtok strtolower strtotime '+ + 'strtoupper strtr strval substr substr_compare'; + + var keywords = 'abstract and array as break case catch cfunction class clone const continue declare default die do ' + + 'else elseif enddeclare endfor endforeach endif endswitch endwhile extends final for foreach ' + + 'function include include_once global goto if implements interface instanceof namespace new ' + + 'old_function or private protected public return require require_once static switch ' + + 'throw try use var while xor '; + + var constants = '__FILE__ __LINE__ __METHOD__ __FUNCTION__ __CLASS__'; + + this.regexList = [ + { regex: SyntaxHighlighter.regexLib.singleLineCComments, css: 'comments' }, // one line comments + { regex: SyntaxHighlighter.regexLib.multiLineCComments, css: 'comments' }, // multiline comments + { regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, // double quoted strings + { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // single quoted strings + { regex: /\$\w+/g, css: 'variable' }, // variables + { regex: new RegExp(this.getKeywords(funcs), 'gmi'), css: 'functions' }, // common functions + { regex: new RegExp(this.getKeywords(constants), 'gmi'), css: 'constants' }, // constants + { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' } // keyword + ]; + + this.forHtmlScript(SyntaxHighlighter.regexLib.phpScriptTags); + }; + + Brush.prototype = new SyntaxHighlighter.Highlighter(); + Brush.aliases = ['php']; + + SyntaxHighlighter.brushes.Php = Brush; + + // CommonJS + typeof(exports) != 'undefined' ? exports.Brush = Brush : null; +})(); diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushPlain.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushPlain.js new file mode 100644 index 0000000000..9f7d9e90c3 --- /dev/null +++ b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushPlain.js @@ -0,0 +1,33 @@ +/** + * SyntaxHighlighter + * http://alexgorbatchev.com/SyntaxHighlighter + * + * SyntaxHighlighter is donationware. If you are using it, please donate. + * http://alexgorbatchev.com/SyntaxHighlighter/donate.html + * + * @version + * 3.0.83 (July 02 2010) + * + * @copyright + * Copyright (C) 2004-2010 Alex Gorbatchev. + * + * @license + * Dual licensed under the MIT and GPL licenses. + */ +;(function() +{ + // CommonJS + typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null; + + function Brush() + { + }; + + Brush.prototype = new SyntaxHighlighter.Highlighter(); + Brush.aliases = ['text', 'plain']; + + SyntaxHighlighter.brushes.Plain = Brush; + + // CommonJS + typeof(exports) != 'undefined' ? exports.Brush = Brush : null; +})(); diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushPowerShell.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushPowerShell.js new file mode 100644 index 0000000000..0be1752968 --- /dev/null +++ b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushPowerShell.js @@ -0,0 +1,74 @@ +/** + * SyntaxHighlighter + * http://alexgorbatchev.com/SyntaxHighlighter + * + * SyntaxHighlighter is donationware. If you are using it, please donate. + * http://alexgorbatchev.com/SyntaxHighlighter/donate.html + * + * @version + * 3.0.83 (July 02 2010) + * + * @copyright + * Copyright (C) 2004-2010 Alex Gorbatchev. + * + * @license + * Dual licensed under the MIT and GPL licenses. + */ +;(function() +{ + // CommonJS + typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null; + + function Brush() + { + // Contributes by B.v.Zanten, Getronics + // http://confluence.atlassian.com/display/CONFEXT/New+Code+Macro + + var keywords = 'Add-Content Add-History Add-Member Add-PSSnapin Clear(-Content)? Clear-Item ' + + 'Clear-ItemProperty Clear-Variable Compare-Object ConvertFrom-SecureString Convert-Path ' + + 'ConvertTo-Html ConvertTo-SecureString Copy(-Item)? Copy-ItemProperty Export-Alias ' + + 'Export-Clixml Export-Console Export-Csv ForEach(-Object)? Format-Custom Format-List ' + + 'Format-Table Format-Wide Get-Acl Get-Alias Get-AuthenticodeSignature Get-ChildItem Get-Command ' + + 'Get-Content Get-Credential Get-Culture Get-Date Get-EventLog Get-ExecutionPolicy ' + + 'Get-Help Get-History Get-Host Get-Item Get-ItemProperty Get-Location Get-Member ' + + 'Get-PfxCertificate Get-Process Get-PSDrive Get-PSProvider Get-PSSnapin Get-Service ' + + 'Get-TraceSource Get-UICulture Get-Unique Get-Variable Get-WmiObject Group-Object ' + + 'Import-Alias Import-Clixml Import-Csv Invoke-Expression Invoke-History Invoke-Item ' + + 'Join-Path Measure-Command Measure-Object Move(-Item)? Move-ItemProperty New-Alias ' + + 'New-Item New-ItemProperty New-Object New-PSDrive New-Service New-TimeSpan ' + + 'New-Variable Out-Default Out-File Out-Host Out-Null Out-Printer Out-String Pop-Location ' + + 'Push-Location Read-Host Remove-Item Remove-ItemProperty Remove-PSDrive Remove-PSSnapin ' + + 'Remove-Variable Rename-Item Rename-ItemProperty Resolve-Path Restart-Service Resume-Service ' + + 'Select-Object Select-String Set-Acl Set-Alias Set-AuthenticodeSignature Set-Content ' + + 'Set-Date Set-ExecutionPolicy Set-Item Set-ItemProperty Set-Location Set-PSDebug ' + + 'Set-Service Set-TraceSource Set(-Variable)? Sort-Object Split-Path Start-Service ' + + 'Start-Sleep Start-Transcript Stop-Process Stop-Service Stop-Transcript Suspend-Service ' + + 'Tee-Object Test-Path Trace-Command Update-FormatData Update-TypeData Where(-Object)? ' + + 'Write-Debug Write-Error Write(-Host)? Write-Output Write-Progress Write-Verbose Write-Warning'; + var alias = 'ac asnp clc cli clp clv cpi cpp cvpa diff epal epcsv fc fl ' + + 'ft fw gal gc gci gcm gdr ghy gi gl gm gp gps group gsv ' + + 'gsnp gu gv gwmi iex ihy ii ipal ipcsv mi mp nal ndr ni nv oh rdr ' + + 'ri rni rnp rp rsnp rv rvpa sal sasv sc select si sl sleep sort sp ' + + 'spps spsv sv tee cat cd cp h history kill lp ls ' + + 'mount mv popd ps pushd pwd r rm rmdir echo cls chdir del dir ' + + 'erase rd ren type % \\?'; + + this.regexList = [ + { regex: /#.*$/gm, css: 'comments' }, // one line comments + { regex: /\$[a-zA-Z0-9]+\b/g, css: 'value' }, // variables $Computer1 + { regex: /\-[a-zA-Z]+\b/g, css: 'keyword' }, // Operators -not -and -eq + { regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, // strings + { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // strings + { regex: new RegExp(this.getKeywords(keywords), 'gmi'), css: 'keyword' }, + { regex: new RegExp(this.getKeywords(alias), 'gmi'), css: 'keyword' } + ]; + }; + + Brush.prototype = new SyntaxHighlighter.Highlighter(); + Brush.aliases = ['powershell', 'ps']; + + SyntaxHighlighter.brushes.PowerShell = Brush; + + // CommonJS + typeof(exports) != 'undefined' ? exports.Brush = Brush : null; +})(); diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushPython.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushPython.js new file mode 100644 index 0000000000..ce77462975 --- /dev/null +++ b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushPython.js @@ -0,0 +1,64 @@ +/** + * SyntaxHighlighter + * http://alexgorbatchev.com/SyntaxHighlighter + * + * SyntaxHighlighter is donationware. If you are using it, please donate. + * http://alexgorbatchev.com/SyntaxHighlighter/donate.html + * + * @version + * 3.0.83 (July 02 2010) + * + * @copyright + * Copyright (C) 2004-2010 Alex Gorbatchev. + * + * @license + * Dual licensed under the MIT and GPL licenses. + */ +;(function() +{ + // CommonJS + typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null; + + function Brush() + { + // Contributed by Gheorghe Milas and Ahmad Sherif + + var keywords = 'and assert break class continue def del elif else ' + + 'except exec finally for from global if import in is ' + + 'lambda not or pass print raise return try yield while'; + + var funcs = '__import__ abs all any apply basestring bin bool buffer callable ' + + 'chr classmethod cmp coerce compile complex delattr dict dir ' + + 'divmod enumerate eval execfile file filter float format frozenset ' + + 'getattr globals hasattr hash help hex id input int intern ' + + 'isinstance issubclass iter len list locals long map max min next ' + + 'object oct open ord pow print property range raw_input reduce ' + + 'reload repr reversed round set setattr slice sorted staticmethod ' + + 'str sum super tuple type type unichr unicode vars xrange zip'; + + var special = 'None True False self cls class_'; + + this.regexList = [ + { regex: SyntaxHighlighter.regexLib.singleLinePerlComments, css: 'comments' }, + { regex: /^\s*@\w+/gm, css: 'decorator' }, + { regex: /(['\"]{3})([^\1])*?\1/gm, css: 'comments' }, + { regex: /"(?!")(?:\.|\\\"|[^\""\n])*"/gm, css: 'string' }, + { regex: /'(?!')(?:\.|(\\\')|[^\''\n])*'/gm, css: 'string' }, + { regex: /\+|\-|\*|\/|\%|=|==/gm, css: 'keyword' }, + { regex: /\b\d+\.?\w*/g, css: 'value' }, + { regex: new RegExp(this.getKeywords(funcs), 'gmi'), css: 'functions' }, + { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' }, + { regex: new RegExp(this.getKeywords(special), 'gm'), css: 'color1' } + ]; + + this.forHtmlScript(SyntaxHighlighter.regexLib.aspScriptTags); + }; + + Brush.prototype = new SyntaxHighlighter.Highlighter(); + Brush.aliases = ['py', 'python']; + + SyntaxHighlighter.brushes.Python = Brush; + + // CommonJS + typeof(exports) != 'undefined' ? exports.Brush = Brush : null; +})(); diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushRuby.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushRuby.js new file mode 100644 index 0000000000..ff82130a7a --- /dev/null +++ b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushRuby.js @@ -0,0 +1,55 @@ +/** + * SyntaxHighlighter + * http://alexgorbatchev.com/SyntaxHighlighter + * + * SyntaxHighlighter is donationware. If you are using it, please donate. + * http://alexgorbatchev.com/SyntaxHighlighter/donate.html + * + * @version + * 3.0.83 (July 02 2010) + * + * @copyright + * Copyright (C) 2004-2010 Alex Gorbatchev. + * + * @license + * Dual licensed under the MIT and GPL licenses. + */ +;(function() +{ + // CommonJS + typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null; + + function Brush() + { + // Contributed by Erik Peterson. + + var keywords = 'alias and BEGIN begin break case class def define_method defined do each else elsif ' + + 'END end ensure false for if in module new next nil not or raise redo rescue retry return ' + + 'self super then throw true undef unless until when while yield'; + + var builtins = 'Array Bignum Binding Class Continuation Dir Exception FalseClass File::Stat File Fixnum Fload ' + + 'Hash Integer IO MatchData Method Module NilClass Numeric Object Proc Range Regexp String Struct::TMS Symbol ' + + 'ThreadGroup Thread Time TrueClass'; + + this.regexList = [ + { regex: SyntaxHighlighter.regexLib.singleLinePerlComments, css: 'comments' }, // one line comments + { regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, // double quoted strings + { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // single quoted strings + { regex: /\b[A-Z0-9_]+\b/g, css: 'constants' }, // constants + { regex: /:[a-z][A-Za-z0-9_]*/g, css: 'color2' }, // symbols + { regex: /(\$|@@|@)\w+/g, css: 'variable bold' }, // $global, @instance, and @@class variables + { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' }, // keywords + { regex: new RegExp(this.getKeywords(builtins), 'gm'), css: 'color1' } // builtins + ]; + + this.forHtmlScript(SyntaxHighlighter.regexLib.aspScriptTags); + }; + + Brush.prototype = new SyntaxHighlighter.Highlighter(); + Brush.aliases = ['ruby', 'rails', 'ror', 'rb']; + + SyntaxHighlighter.brushes.Ruby = Brush; + + // CommonJS + typeof(exports) != 'undefined' ? exports.Brush = Brush : null; +})(); diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushSass.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushSass.js new file mode 100644 index 0000000000..aa04da0996 --- /dev/null +++ b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushSass.js @@ -0,0 +1,94 @@ +/** + * SyntaxHighlighter + * http://alexgorbatchev.com/SyntaxHighlighter + * + * SyntaxHighlighter is donationware. If you are using it, please donate. + * http://alexgorbatchev.com/SyntaxHighlighter/donate.html + * + * @version + * 3.0.83 (July 02 2010) + * + * @copyright + * Copyright (C) 2004-2010 Alex Gorbatchev. + * + * @license + * Dual licensed under the MIT and GPL licenses. + */ +;(function() +{ + // CommonJS + typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null; + + function Brush() + { + function getKeywordsCSS(str) + { + return '\\b([a-z_]|)' + str.replace(/ /g, '(?=:)\\b|\\b([a-z_\\*]|\\*|)') + '(?=:)\\b'; + }; + + function getValuesCSS(str) + { + return '\\b' + str.replace(/ /g, '(?!-)(?!:)\\b|\\b()') + '\:\\b'; + }; + + var keywords = 'ascent azimuth background-attachment background-color background-image background-position ' + + 'background-repeat background baseline bbox border-collapse border-color border-spacing border-style border-top ' + + 'border-right border-bottom border-left border-top-color border-right-color border-bottom-color border-left-color ' + + 'border-top-style border-right-style border-bottom-style border-left-style border-top-width border-right-width ' + + 'border-bottom-width border-left-width border-width border bottom cap-height caption-side centerline clear clip color ' + + 'content counter-increment counter-reset cue-after cue-before cue cursor definition-src descent direction display ' + + 'elevation empty-cells float font-size-adjust font-family font-size font-stretch font-style font-variant font-weight font ' + + 'height left letter-spacing line-height list-style-image list-style-position list-style-type list-style margin-top ' + + 'margin-right margin-bottom margin-left margin marker-offset marks mathline max-height max-width min-height min-width orphans ' + + 'outline-color outline-style outline-width outline overflow padding-top padding-right padding-bottom padding-left padding page ' + + 'page-break-after page-break-before page-break-inside pause pause-after pause-before pitch pitch-range play-during position ' + + 'quotes right richness size slope src speak-header speak-numeral speak-punctuation speak speech-rate stemh stemv stress ' + + 'table-layout text-align top text-decoration text-indent text-shadow text-transform unicode-bidi unicode-range units-per-em ' + + 'vertical-align visibility voice-family volume white-space widows width widths word-spacing x-height z-index'; + + var values = 'above absolute all always aqua armenian attr aural auto avoid baseline behind below bidi-override black blink block blue bold bolder '+ + 'both bottom braille capitalize caption center center-left center-right circle close-quote code collapse compact condensed '+ + 'continuous counter counters crop cross crosshair cursive dashed decimal decimal-leading-zero digits disc dotted double '+ + 'embed embossed e-resize expanded extra-condensed extra-expanded fantasy far-left far-right fast faster fixed format fuchsia '+ + 'gray green groove handheld hebrew help hidden hide high higher icon inline-table inline inset inside invert italic '+ + 'justify landscape large larger left-side left leftwards level lighter lime line-through list-item local loud lower-alpha '+ + 'lowercase lower-greek lower-latin lower-roman lower low ltr marker maroon medium message-box middle mix move narrower '+ + 'navy ne-resize no-close-quote none no-open-quote no-repeat normal nowrap n-resize nw-resize oblique olive once open-quote outset '+ + 'outside overline pointer portrait pre print projection purple red relative repeat repeat-x repeat-y rgb ridge right right-side '+ + 'rightwards rtl run-in screen scroll semi-condensed semi-expanded separate se-resize show silent silver slower slow '+ + 'small small-caps small-caption smaller soft solid speech spell-out square s-resize static status-bar sub super sw-resize '+ + 'table-caption table-cell table-column table-column-group table-footer-group table-header-group table-row table-row-group teal '+ + 'text-bottom text-top thick thin top transparent tty tv ultra-condensed ultra-expanded underline upper-alpha uppercase upper-latin '+ + 'upper-roman url visible wait white wider w-resize x-fast x-high x-large x-loud x-low x-slow x-small x-soft xx-large xx-small yellow'; + + var fonts = '[mM]onospace [tT]ahoma [vV]erdana [aA]rial [hH]elvetica [sS]ans-serif [sS]erif [cC]ourier mono sans serif'; + + var statements = '!important !default'; + var preprocessor = '@import @extend @debug @warn @if @for @while @mixin @include'; + + var r = SyntaxHighlighter.regexLib; + + this.regexList = [ + { regex: r.multiLineCComments, css: 'comments' }, // multiline comments + { regex: r.singleLineCComments, css: 'comments' }, // singleline comments + { regex: r.doubleQuotedString, css: 'string' }, // double quoted strings + { regex: r.singleQuotedString, css: 'string' }, // single quoted strings + { regex: /\#[a-fA-F0-9]{3,6}/g, css: 'value' }, // html colors + { regex: /\b(-?\d+)(\.\d+)?(px|em|pt|\:|\%|)\b/g, css: 'value' }, // sizes + { regex: /\$\w+/g, css: 'variable' }, // variables + { regex: new RegExp(this.getKeywords(statements), 'g'), css: 'color3' }, // statements + { regex: new RegExp(this.getKeywords(preprocessor), 'g'), css: 'preprocessor' }, // preprocessor + { regex: new RegExp(getKeywordsCSS(keywords), 'gm'), css: 'keyword' }, // keywords + { regex: new RegExp(getValuesCSS(values), 'g'), css: 'value' }, // values + { regex: new RegExp(this.getKeywords(fonts), 'g'), css: 'color1' } // fonts + ]; + }; + + Brush.prototype = new SyntaxHighlighter.Highlighter(); + Brush.aliases = ['sass', 'scss']; + + SyntaxHighlighter.brushes.Sass = Brush; + + // CommonJS + typeof(exports) != 'undefined' ? exports.Brush = Brush : null; +})(); diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushScala.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushScala.js new file mode 100644 index 0000000000..4b0b6f04d2 --- /dev/null +++ b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushScala.js @@ -0,0 +1,51 @@ +/** + * SyntaxHighlighter + * http://alexgorbatchev.com/SyntaxHighlighter + * + * SyntaxHighlighter is donationware. If you are using it, please donate. + * http://alexgorbatchev.com/SyntaxHighlighter/donate.html + * + * @version + * 3.0.83 (July 02 2010) + * + * @copyright + * Copyright (C) 2004-2010 Alex Gorbatchev. + * + * @license + * Dual licensed under the MIT and GPL licenses. + */ +;(function() +{ + // CommonJS + typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null; + + function Brush() + { + // Contributed by Yegor Jbanov and David Bernard. + + var keywords = 'val sealed case def true trait implicit forSome import match object null finally super ' + + 'override try lazy for var catch throw type extends class while with new final yield abstract ' + + 'else do if return protected private this package false'; + + var keyops = '[_:=><%#@]+'; + + this.regexList = [ + { regex: SyntaxHighlighter.regexLib.singleLineCComments, css: 'comments' }, // one line comments + { regex: SyntaxHighlighter.regexLib.multiLineCComments, css: 'comments' }, // multiline comments + { regex: SyntaxHighlighter.regexLib.multiLineSingleQuotedString, css: 'string' }, // multi-line strings + { regex: SyntaxHighlighter.regexLib.multiLineDoubleQuotedString, css: 'string' }, // double-quoted string + { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // strings + { regex: /0x[a-f0-9]+|\d+(\.\d+)?/gi, css: 'value' }, // numbers + { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' }, // keywords + { regex: new RegExp(keyops, 'gm'), css: 'keyword' } // scala keyword + ]; + } + + Brush.prototype = new SyntaxHighlighter.Highlighter(); + Brush.aliases = ['scala']; + + SyntaxHighlighter.brushes.Scala = Brush; + + // CommonJS + typeof(exports) != 'undefined' ? exports.Brush = Brush : null; +})(); diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushSql.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushSql.js new file mode 100644 index 0000000000..5c2cd8806f --- /dev/null +++ b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushSql.js @@ -0,0 +1,66 @@ +/** + * SyntaxHighlighter + * http://alexgorbatchev.com/SyntaxHighlighter + * + * SyntaxHighlighter is donationware. If you are using it, please donate. + * http://alexgorbatchev.com/SyntaxHighlighter/donate.html + * + * @version + * 3.0.83 (July 02 2010) + * + * @copyright + * Copyright (C) 2004-2010 Alex Gorbatchev. + * + * @license + * Dual licensed under the MIT and GPL licenses. + */ +;(function() +{ + // CommonJS + typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null; + + function Brush() + { + var funcs = 'abs avg case cast coalesce convert count current_timestamp ' + + 'current_user day isnull left lower month nullif replace right ' + + 'session_user space substring sum system_user upper user year'; + + var keywords = 'absolute action add after alter as asc at authorization begin bigint ' + + 'binary bit by cascade char character check checkpoint close collate ' + + 'column commit committed connect connection constraint contains continue ' + + 'create cube current current_date current_time cursor database date ' + + 'deallocate dec decimal declare default delete desc distinct double drop ' + + 'dynamic else end end-exec escape except exec execute false fetch first ' + + 'float for force foreign forward free from full function global goto grant ' + + 'group grouping having hour ignore index inner insensitive insert instead ' + + 'int integer intersect into is isolation key last level load local max min ' + + 'minute modify move name national nchar next no numeric of off on only ' + + 'open option order out output partial password precision prepare primary ' + + 'prior privileges procedure public read real references relative repeatable ' + + 'restrict return returns revoke rollback rollup rows rule schema scroll ' + + 'second section select sequence serializable set size smallint static ' + + 'statistics table temp temporary then time timestamp to top transaction ' + + 'translation trigger true truncate uncommitted union unique update values ' + + 'varchar varying view when where with work'; + + var operators = 'all and any between cross in join like not null or outer some'; + + this.regexList = [ + { regex: /--(.*)$/gm, css: 'comments' }, // one line and multiline comments + { regex: SyntaxHighlighter.regexLib.multiLineDoubleQuotedString, css: 'string' }, // double quoted strings + { regex: SyntaxHighlighter.regexLib.multiLineSingleQuotedString, css: 'string' }, // single quoted strings + { regex: new RegExp(this.getKeywords(funcs), 'gmi'), css: 'color2' }, // functions + { regex: new RegExp(this.getKeywords(operators), 'gmi'), css: 'color1' }, // operators and such + { regex: new RegExp(this.getKeywords(keywords), 'gmi'), css: 'keyword' } // keyword + ]; + }; + + Brush.prototype = new SyntaxHighlighter.Highlighter(); + Brush.aliases = ['sql']; + + SyntaxHighlighter.brushes.Sql = Brush; + + // CommonJS + typeof(exports) != 'undefined' ? exports.Brush = Brush : null; +})(); + diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushVb.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushVb.js new file mode 100644 index 0000000000..be845dc0b3 --- /dev/null +++ b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushVb.js @@ -0,0 +1,56 @@ +/** + * SyntaxHighlighter + * http://alexgorbatchev.com/SyntaxHighlighter + * + * SyntaxHighlighter is donationware. If you are using it, please donate. + * http://alexgorbatchev.com/SyntaxHighlighter/donate.html + * + * @version + * 3.0.83 (July 02 2010) + * + * @copyright + * Copyright (C) 2004-2010 Alex Gorbatchev. + * + * @license + * Dual licensed under the MIT and GPL licenses. + */ +;(function() +{ + // CommonJS + typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null; + + function Brush() + { + var keywords = 'AddHandler AddressOf AndAlso Alias And Ansi As Assembly Auto ' + + 'Boolean ByRef Byte ByVal Call Case Catch CBool CByte CChar CDate ' + + 'CDec CDbl Char CInt Class CLng CObj Const CShort CSng CStr CType ' + + 'Date Decimal Declare Default Delegate Dim DirectCast Do Double Each ' + + 'Else ElseIf End Enum Erase Error Event Exit False Finally For Friend ' + + 'Function Get GetType GoSub GoTo Handles If Implements Imports In ' + + 'Inherits Integer Interface Is Let Lib Like Long Loop Me Mod Module ' + + 'MustInherit MustOverride MyBase MyClass Namespace New Next Not Nothing ' + + 'NotInheritable NotOverridable Object On Option Optional Or OrElse ' + + 'Overloads Overridable Overrides ParamArray Preserve Private Property ' + + 'Protected Public RaiseEvent ReadOnly ReDim REM RemoveHandler Resume ' + + 'Return Select Set Shadows Shared Short Single Static Step Stop String ' + + 'Structure Sub SyncLock Then Throw To True Try TypeOf Unicode Until ' + + 'Variant When While With WithEvents WriteOnly Xor'; + + this.regexList = [ + { regex: /'.*$/gm, css: 'comments' }, // one line comments + { regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, // strings + { regex: /^\s*#.*$/gm, css: 'preprocessor' }, // preprocessor tags like #region and #endregion + { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' } // vb keyword + ]; + + this.forHtmlScript(SyntaxHighlighter.regexLib.aspScriptTags); + }; + + Brush.prototype = new SyntaxHighlighter.Highlighter(); + Brush.aliases = ['vb', 'vbnet']; + + SyntaxHighlighter.brushes.Vb = Brush; + + // CommonJS + typeof(exports) != 'undefined' ? exports.Brush = Brush : null; +})(); diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushXml.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushXml.js new file mode 100644 index 0000000000..69d9fd0b1f --- /dev/null +++ b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushXml.js @@ -0,0 +1,69 @@ +/** + * SyntaxHighlighter + * http://alexgorbatchev.com/SyntaxHighlighter + * + * SyntaxHighlighter is donationware. If you are using it, please donate. + * http://alexgorbatchev.com/SyntaxHighlighter/donate.html + * + * @version + * 3.0.83 (July 02 2010) + * + * @copyright + * Copyright (C) 2004-2010 Alex Gorbatchev. + * + * @license + * Dual licensed under the MIT and GPL licenses. + */ +;(function() +{ + // CommonJS + typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null; + + function Brush() + { + function process(match, regexInfo) + { + var constructor = SyntaxHighlighter.Match, + code = match[0], + tag = new XRegExp('(<|<)[\\s\\/\\?]*(?<name>[:\\w-\\.]+)', 'xg').exec(code), + result = [] + ; + + if (match.attributes != null) + { + var attributes, + regex = new XRegExp('(?<name> [\\w:\\-\\.]+)' + + '\\s*=\\s*' + + '(?<value> ".*?"|\'.*?\'|\\w+)', + 'xg'); + + while ((attributes = regex.exec(code)) != null) + { + result.push(new constructor(attributes.name, match.index + attributes.index, 'color1')); + result.push(new constructor(attributes.value, match.index + attributes.index + attributes[0].indexOf(attributes.value), 'string')); + } + } + + if (tag != null) + result.push( + new constructor(tag.name, match.index + tag[0].indexOf(tag.name), 'keyword') + ); + + return result; + } + + this.regexList = [ + { regex: new XRegExp('(\\<|<)\\!\\[[\\w\\s]*?\\[(.|\\s)*?\\]\\](\\>|>)', 'gm'), css: 'color2' }, // <![ ... [ ... ]]> + { regex: SyntaxHighlighter.regexLib.xmlComments, css: 'comments' }, // <!-- ... --> + { regex: new XRegExp('(<|<)[\\s\\/\\?]*(\\w+)(?<attributes>.*?)[\\s\\/\\?]*(>|>)', 'sg'), func: process } + ]; + }; + + Brush.prototype = new SyntaxHighlighter.Highlighter(); + Brush.aliases = ['xml', 'xhtml', 'xslt', 'html']; + + SyntaxHighlighter.brushes.Xml = Brush; + + // CommonJS + typeof(exports) != 'undefined' ? exports.Brush = Brush : null; +})(); diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shCore.js b/railties/guides/assets/javascripts/syntaxhighlighter/shCore.js new file mode 100644 index 0000000000..b47b645472 --- /dev/null +++ b/railties/guides/assets/javascripts/syntaxhighlighter/shCore.js @@ -0,0 +1,17 @@ +/** + * SyntaxHighlighter + * http://alexgorbatchev.com/SyntaxHighlighter + * + * SyntaxHighlighter is donationware. If you are using it, please donate. + * http://alexgorbatchev.com/SyntaxHighlighter/donate.html + * + * @version + * 3.0.83 (July 02 2010) + * + * @copyright + * Copyright (C) 2004-2010 Alex Gorbatchev. + * + * @license + * Dual licensed under the MIT and GPL licenses. + */ +eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('K M;I(M)1S 2U("2a\'t 4k M 4K 2g 3l 4G 4H");(6(){6 r(f,e){I(!M.1R(f))1S 3m("3s 15 4R");K a=f.1w;f=M(f.1m,t(f)+(e||""));I(a)f.1w={1m:a.1m,19:a.19?a.19.1a(0):N};H f}6 t(f){H(f.1J?"g":"")+(f.4s?"i":"")+(f.4p?"m":"")+(f.4v?"x":"")+(f.3n?"y":"")}6 B(f,e,a,b){K c=u.L,d,h,g;v=R;5K{O(;c--;){g=u[c];I(a&g.3r&&(!g.2p||g.2p.W(b))){g.2q.12=e;I((h=g.2q.X(f))&&h.P===e){d={3k:g.2b.W(b,h,a),1C:h};1N}}}}5v(i){1S i}5q{v=11}H d}6 p(f,e,a){I(3b.Z.1i)H f.1i(e,a);O(a=a||0;a<f.L;a++)I(f[a]===e)H a;H-1}M=6(f,e){K a=[],b=M.1B,c=0,d,h;I(M.1R(f)){I(e!==1d)1S 3m("2a\'t 5r 5I 5F 5B 5C 15 5E 5p");H r(f)}I(v)1S 2U("2a\'t W 3l M 59 5m 5g 5x 5i");e=e||"";O(d={2N:11,19:[],2K:6(g){H e.1i(g)>-1},3d:6(g){e+=g}};c<f.L;)I(h=B(f,c,b,d)){a.U(h.3k);c+=h.1C[0].L||1}Y I(h=n.X.W(z[b],f.1a(c))){a.U(h[0]);c+=h[0].L}Y{h=f.3a(c);I(h==="[")b=M.2I;Y I(h==="]")b=M.1B;a.U(h);c++}a=15(a.1K(""),n.Q.W(e,w,""));a.1w={1m:f,19:d.2N?d.19:N};H a};M.3v="1.5.0";M.2I=1;M.1B=2;K C=/\\$(?:(\\d\\d?|[$&`\'])|{([$\\w]+)})/g,w=/[^5h]+|([\\s\\S])(?=[\\s\\S]*\\1)/g,A=/^(?:[?*+]|{\\d+(?:,\\d*)?})\\??/,v=11,u=[],n={X:15.Z.X,1A:15.Z.1A,1C:1r.Z.1C,Q:1r.Z.Q,1e:1r.Z.1e},x=n.X.W(/()??/,"")[1]===1d,D=6(){K f=/^/g;n.1A.W(f,"");H!f.12}(),y=6(){K f=/x/g;n.Q.W("x",f,"");H!f.12}(),E=15.Z.3n!==1d,z={};z[M.2I]=/^(?:\\\\(?:[0-3][0-7]{0,2}|[4-7][0-7]?|x[\\29-26-f]{2}|u[\\29-26-f]{4}|c[A-3o-z]|[\\s\\S]))/;z[M.1B]=/^(?:\\\\(?:0(?:[0-3][0-7]{0,2}|[4-7][0-7]?)?|[1-9]\\d*|x[\\29-26-f]{2}|u[\\29-26-f]{4}|c[A-3o-z]|[\\s\\S])|\\(\\?[:=!]|[?*+]\\?|{\\d+(?:,\\d*)?}\\??)/;M.1h=6(f,e,a,b){u.U({2q:r(f,"g"+(E?"y":"")),2b:e,3r:a||M.1B,2p:b||N})};M.2n=6(f,e){K a=f+"/"+(e||"");H M.2n[a]||(M.2n[a]=M(f,e))};M.3c=6(f){H r(f,"g")};M.5l=6(f){H f.Q(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g,"\\\\$&")};M.5e=6(f,e,a,b){e=r(e,"g"+(b&&E?"y":""));e.12=a=a||0;f=e.X(f);H b?f&&f.P===a?f:N:f};M.3q=6(){M.1h=6(){1S 2U("2a\'t 55 1h 54 3q")}};M.1R=6(f){H 53.Z.1q.W(f)==="[2m 15]"};M.3p=6(f,e,a,b){O(K c=r(e,"g"),d=-1,h;h=c.X(f);){a.W(b,h,++d,f,c);c.12===h.P&&c.12++}I(e.1J)e.12=0};M.57=6(f,e){H 6 a(b,c){K d=e[c].1I?e[c]:{1I:e[c]},h=r(d.1I,"g"),g=[],i;O(i=0;i<b.L;i++)M.3p(b[i],h,6(k){g.U(d.3j?k[d.3j]||"":k[0])});H c===e.L-1||!g.L?g:a(g,c+1)}([f],0)};15.Z.1p=6(f,e){H J.X(e[0])};15.Z.W=6(f,e){H J.X(e)};15.Z.X=6(f){K e=n.X.1p(J,14),a;I(e){I(!x&&e.L>1&&p(e,"")>-1){a=15(J.1m,n.Q.W(t(J),"g",""));n.Q.W(f.1a(e.P),a,6(){O(K c=1;c<14.L-2;c++)I(14[c]===1d)e[c]=1d})}I(J.1w&&J.1w.19)O(K b=1;b<e.L;b++)I(a=J.1w.19[b-1])e[a]=e[b];!D&&J.1J&&!e[0].L&&J.12>e.P&&J.12--}H e};I(!D)15.Z.1A=6(f){(f=n.X.W(J,f))&&J.1J&&!f[0].L&&J.12>f.P&&J.12--;H!!f};1r.Z.1C=6(f){M.1R(f)||(f=15(f));I(f.1J){K e=n.1C.1p(J,14);f.12=0;H e}H f.X(J)};1r.Z.Q=6(f,e){K a=M.1R(f),b,c;I(a&&1j e.58()==="3f"&&e.1i("${")===-1&&y)H n.Q.1p(J,14);I(a){I(f.1w)b=f.1w.19}Y f+="";I(1j e==="6")c=n.Q.W(J,f,6(){I(b){14[0]=1f 1r(14[0]);O(K d=0;d<b.L;d++)I(b[d])14[0][b[d]]=14[d+1]}I(a&&f.1J)f.12=14[14.L-2]+14[0].L;H e.1p(N,14)});Y{c=J+"";c=n.Q.W(c,f,6(){K d=14;H n.Q.W(e,C,6(h,g,i){I(g)5b(g){24"$":H"$";24"&":H d[0];24"`":H d[d.L-1].1a(0,d[d.L-2]);24"\'":H d[d.L-1].1a(d[d.L-2]+d[0].L);5a:i="";g=+g;I(!g)H h;O(;g>d.L-3;){i=1r.Z.1a.W(g,-1)+i;g=1Q.3i(g/10)}H(g?d[g]||"":"$")+i}Y{g=+i;I(g<=d.L-3)H d[g];g=b?p(b,i):-1;H g>-1?d[g+1]:h}})})}I(a&&f.1J)f.12=0;H c};1r.Z.1e=6(f,e){I(!M.1R(f))H n.1e.1p(J,14);K a=J+"",b=[],c=0,d,h;I(e===1d||+e<0)e=5D;Y{e=1Q.3i(+e);I(!e)H[]}O(f=M.3c(f);d=f.X(a);){I(f.12>c){b.U(a.1a(c,d.P));d.L>1&&d.P<a.L&&3b.Z.U.1p(b,d.1a(1));h=d[0].L;c=f.12;I(b.L>=e)1N}f.12===d.P&&f.12++}I(c===a.L){I(!n.1A.W(f,"")||h)b.U("")}Y b.U(a.1a(c));H b.L>e?b.1a(0,e):b};M.1h(/\\(\\?#[^)]*\\)/,6(f){H n.1A.W(A,f.2S.1a(f.P+f[0].L))?"":"(?:)"});M.1h(/\\((?!\\?)/,6(){J.19.U(N);H"("});M.1h(/\\(\\?<([$\\w]+)>/,6(f){J.19.U(f[1]);J.2N=R;H"("});M.1h(/\\\\k<([\\w$]+)>/,6(f){K e=p(J.19,f[1]);H e>-1?"\\\\"+(e+1)+(3R(f.2S.3a(f.P+f[0].L))?"":"(?:)"):f[0]});M.1h(/\\[\\^?]/,6(f){H f[0]==="[]"?"\\\\b\\\\B":"[\\\\s\\\\S]"});M.1h(/^\\(\\?([5A]+)\\)/,6(f){J.3d(f[1]);H""});M.1h(/(?:\\s+|#.*)+/,6(f){H n.1A.W(A,f.2S.1a(f.P+f[0].L))?"":"(?:)"},M.1B,6(){H J.2K("x")});M.1h(/\\./,6(){H"[\\\\s\\\\S]"},M.1B,6(){H J.2K("s")})})();1j 2e!="1d"&&(2e.M=M);K 1v=6(){6 r(a,b){a.1l.1i(b)!=-1||(a.1l+=" "+b)}6 t(a){H a.1i("3e")==0?a:"3e"+a}6 B(a){H e.1Y.2A[t(a)]}6 p(a,b,c){I(a==N)H N;K d=c!=R?a.3G:[a.2G],h={"#":"1c",".":"1l"}[b.1o(0,1)]||"3h",g,i;g=h!="3h"?b.1o(1):b.5u();I((a[h]||"").1i(g)!=-1)H a;O(a=0;d&&a<d.L&&i==N;a++)i=p(d[a],b,c);H i}6 C(a,b){K c={},d;O(d 2g a)c[d]=a[d];O(d 2g b)c[d]=b[d];H c}6 w(a,b,c,d){6 h(g){g=g||1P.5y;I(!g.1F){g.1F=g.52;g.3N=6(){J.5w=11}}c.W(d||1P,g)}a.3g?a.3g("4U"+b,h):a.4y(b,h,11)}6 A(a,b){K c=e.1Y.2j,d=N;I(c==N){c={};O(K h 2g e.1U){K g=e.1U[h];d=g.4x;I(d!=N){g.1V=h.4w();O(g=0;g<d.L;g++)c[d[g]]=h}}e.1Y.2j=c}d=e.1U[c[a]];d==N&&b!=11&&1P.1X(e.13.1x.1X+(e.13.1x.3E+a));H d}6 v(a,b){O(K c=a.1e("\\n"),d=0;d<c.L;d++)c[d]=b(c[d],d);H c.1K("\\n")}6 u(a,b){I(a==N||a.L==0||a=="\\n")H a;a=a.Q(/</g,"&1y;");a=a.Q(/ {2,}/g,6(c){O(K d="",h=0;h<c.L-1;h++)d+=e.13.1W;H d+" "});I(b!=N)a=v(a,6(c){I(c.L==0)H"";K d="";c=c.Q(/^(&2s;| )+/,6(h){d=h;H""});I(c.L==0)H d;H d+\'<17 1g="\'+b+\'">\'+c+"</17>"});H a}6 n(a,b){a.1e("\\n");O(K c="",d=0;d<50;d++)c+=" ";H a=v(a,6(h){I(h.1i("\\t")==-1)H h;O(K g=0;(g=h.1i("\\t"))!=-1;)h=h.1o(0,g)+c.1o(0,b-g%b)+h.1o(g+1,h.L);H h})}6 x(a){H a.Q(/^\\s+|\\s+$/g,"")}6 D(a,b){I(a.P<b.P)H-1;Y I(a.P>b.P)H 1;Y I(a.L<b.L)H-1;Y I(a.L>b.L)H 1;H 0}6 y(a,b){6 c(k){H k[0]}O(K d=N,h=[],g=b.2D?b.2D:c;(d=b.1I.X(a))!=N;){K i=g(d,b);I(1j i=="3f")i=[1f e.2L(i,d.P,b.23)];h=h.1O(i)}H h}6 E(a){K b=/(.*)((&1G;|&1y;).*)/;H a.Q(e.3A.3M,6(c){K d="",h=N;I(h=b.X(c)){c=h[1];d=h[2]}H\'<a 2h="\'+c+\'">\'+c+"</a>"+d})}6 z(){O(K a=1E.36("1k"),b=[],c=0;c<a.L;c++)a[c].3s=="20"&&b.U(a[c]);H b}6 f(a){a=a.1F;K b=p(a,".20",R);a=p(a,".3O",R);K c=1E.4i("3t");I(!(!a||!b||p(a,"3t"))){B(b.1c);r(b,"1m");O(K d=a.3G,h=[],g=0;g<d.L;g++)h.U(d[g].4z||d[g].4A);h=h.1K("\\r");c.39(1E.4D(h));a.39(c);c.2C();c.4C();w(c,"4u",6(){c.2G.4E(c);b.1l=b.1l.Q("1m","")})}}I(1j 3F!="1d"&&1j M=="1d")M=3F("M").M;K e={2v:{"1g-27":"","2i-1s":1,"2z-1s-2t":11,1M:N,1t:N,"42-45":R,"43-22":4,1u:R,16:R,"3V-17":R,2l:11,"41-40":R,2k:11,"1z-1k":11},13:{1W:"&2s;",2M:R,46:11,44:11,34:"4n",1x:{21:"4o 1m",2P:"?",1X:"1v\\n\\n",3E:"4r\'t 4t 1D O: ",4g:"4m 4B\'t 51 O 1z-1k 4F: ",37:\'<!4T 1z 4S "-//4V//3H 4W 1.0 4Z//4Y" "1Z://2y.3L.3K/4X/3I/3H/3I-4P.4J"><1z 4I="1Z://2y.3L.3K/4L/5L"><3J><4N 1Z-4M="5G-5M" 6K="2O/1z; 6J=6I-8" /><1t>6L 1v</1t></3J><3B 1L="25-6M:6Q,6P,6O,6N-6F;6y-2f:#6x;2f:#6w;25-22:6v;2O-3D:3C;"><T 1L="2O-3D:3C;3w-32:1.6z;"><T 1L="25-22:6A-6E;">1v</T><T 1L="25-22:.6C;3w-6B:6R;"><T>3v 3.0.76 (72 73 3x)</T><T><a 2h="1Z://3u.2w/1v" 1F="38" 1L="2f:#3y">1Z://3u.2w/1v</a></T><T>70 17 6U 71.</T><T>6T 6X-3x 6Y 6D.</T></T><T>6t 61 60 J 1k, 5Z <a 2h="6u://2y.62.2w/63-66/65?64=5X-5W&5P=5O" 1L="2f:#3y">5R</a> 5V <2R/>5U 5T 5S!</T></T></3B></1z>\'}},1Y:{2j:N,2A:{}},1U:{},3A:{6n:/\\/\\*[\\s\\S]*?\\*\\//2c,6m:/\\/\\/.*$/2c,6l:/#.*$/2c,6k:/"([^\\\\"\\n]|\\\\.)*"/g,6o:/\'([^\\\\\'\\n]|\\\\.)*\'/g,6p:1f M(\'"([^\\\\\\\\"]|\\\\\\\\.)*"\',"3z"),6s:1f M("\'([^\\\\\\\\\']|\\\\\\\\.)*\'","3z"),6q:/(&1y;|<)!--[\\s\\S]*?--(&1G;|>)/2c,3M:/\\w+:\\/\\/[\\w-.\\/?%&=:@;]*/g,6a:{18:/(&1y;|<)\\?=?/g,1b:/\\?(&1G;|>)/g},69:{18:/(&1y;|<)%=?/g,1b:/%(&1G;|>)/g},6d:{18:/(&1y;|<)\\s*1k.*?(&1G;|>)/2T,1b:/(&1y;|<)\\/\\s*1k\\s*(&1G;|>)/2T}},16:{1H:6(a){6 b(i,k){H e.16.2o(i,k,e.13.1x[k])}O(K c=\'<T 1g="16">\',d=e.16.2x,h=d.2X,g=0;g<h.L;g++)c+=(d[h[g]].1H||b)(a,h[g]);c+="</T>";H c},2o:6(a,b,c){H\'<2W><a 2h="#" 1g="6e 6h\'+b+" "+b+\'">\'+c+"</a></2W>"},2b:6(a){K b=a.1F,c=b.1l||"";b=B(p(b,".20",R).1c);K d=6(h){H(h=15(h+"6f(\\\\w+)").X(c))?h[1]:N}("6g");b&&d&&e.16.2x[d].2B(b);a.3N()},2x:{2X:["21","2P"],21:{1H:6(a){I(a.V("2l")!=R)H"";K b=a.V("1t");H e.16.2o(a,"21",b?b:e.13.1x.21)},2B:6(a){a=1E.6j(t(a.1c));a.1l=a.1l.Q("47","")}},2P:{2B:6(){K a="68=0";a+=", 18="+(31.30-33)/2+", 32="+(31.2Z-2Y)/2+", 30=33, 2Z=2Y";a=a.Q(/^,/,"");a=1P.6Z("","38",a);a.2C();K b=a.1E;b.6W(e.13.1x.37);b.6V();a.2C()}}}},35:6(a,b){K c;I(b)c=[b];Y{c=1E.36(e.13.34);O(K d=[],h=0;h<c.L;h++)d.U(c[h]);c=d}c=c;d=[];I(e.13.2M)c=c.1O(z());I(c.L===0)H d;O(h=0;h<c.L;h++){O(K g=c[h],i=a,k=c[h].1l,j=3W 0,l={},m=1f M("^\\\\[(?<2V>(.*?))\\\\]$"),s=1f M("(?<27>[\\\\w-]+)\\\\s*:\\\\s*(?<1T>[\\\\w-%#]+|\\\\[.*?\\\\]|\\".*?\\"|\'.*?\')\\\\s*;?","g");(j=s.X(k))!=N;){K o=j.1T.Q(/^[\'"]|[\'"]$/g,"");I(o!=N&&m.1A(o)){o=m.X(o);o=o.2V.L>0?o.2V.1e(/\\s*,\\s*/):[]}l[j.27]=o}g={1F:g,1n:C(i,l)};g.1n.1D!=N&&d.U(g)}H d},1M:6(a,b){K c=J.35(a,b),d=N,h=e.13;I(c.L!==0)O(K g=0;g<c.L;g++){b=c[g];K i=b.1F,k=b.1n,j=k.1D,l;I(j!=N){I(k["1z-1k"]=="R"||e.2v["1z-1k"]==R){d=1f e.4l(j);j="4O"}Y I(d=A(j))d=1f d;Y 6H;l=i.3X;I(h.2M){l=l;K m=x(l),s=11;I(m.1i("<![6G[")==0){m=m.4h(9);s=R}K o=m.L;I(m.1i("]]\\>")==o-3){m=m.4h(0,o-3);s=R}l=s?m:l}I((i.1t||"")!="")k.1t=i.1t;k.1D=j;d.2Q(k);b=d.2F(l);I((i.1c||"")!="")b.1c=i.1c;i.2G.74(b,i)}}},2E:6(a){w(1P,"4k",6(){e.1M(a)})}};e.2E=e.2E;e.1M=e.1M;e.2L=6(a,b,c){J.1T=a;J.P=b;J.L=a.L;J.23=c;J.1V=N};e.2L.Z.1q=6(){H J.1T};e.4l=6(a){6 b(j,l){O(K m=0;m<j.L;m++)j[m].P+=l}K c=A(a),d,h=1f e.1U.5Y,g=J,i="2F 1H 2Q".1e(" ");I(c!=N){d=1f c;O(K k=0;k<i.L;k++)(6(){K j=i[k];g[j]=6(){H h[j].1p(h,14)}})();d.28==N?1P.1X(e.13.1x.1X+(e.13.1x.4g+a)):h.2J.U({1I:d.28.17,2D:6(j){O(K l=j.17,m=[],s=d.2J,o=j.P+j.18.L,F=d.28,q,G=0;G<s.L;G++){q=y(l,s[G]);b(q,o);m=m.1O(q)}I(F.18!=N&&j.18!=N){q=y(j.18,F.18);b(q,j.P);m=m.1O(q)}I(F.1b!=N&&j.1b!=N){q=y(j.1b,F.1b);b(q,j.P+j[0].5Q(j.1b));m=m.1O(q)}O(j=0;j<m.L;j++)m[j].1V=c.1V;H m}})}};e.4j=6(){};e.4j.Z={V:6(a,b){K c=J.1n[a];c=c==N?b:c;K d={"R":R,"11":11}[c];H d==N?c:d},3Y:6(a){H 1E.4i(a)},4c:6(a,b){K c=[];I(a!=N)O(K d=0;d<a.L;d++)I(1j a[d]=="2m")c=c.1O(y(b,a[d]));H J.4e(c.6b(D))},4e:6(a){O(K b=0;b<a.L;b++)I(a[b]!==N)O(K c=a[b],d=c.P+c.L,h=b+1;h<a.L&&a[b]!==N;h++){K g=a[h];I(g!==N)I(g.P>d)1N;Y I(g.P==c.P&&g.L>c.L)a[b]=N;Y I(g.P>=c.P&&g.P<d)a[h]=N}H a},4d:6(a){K b=[],c=2u(J.V("2i-1s"));v(a,6(d,h){b.U(h+c)});H b},3U:6(a){K b=J.V("1M",[]);I(1j b!="2m"&&b.U==N)b=[b];a:{a=a.1q();K c=3W 0;O(c=c=1Q.6c(c||0,0);c<b.L;c++)I(b[c]==a){b=c;1N a}b=-1}H b!=-1},2r:6(a,b,c){a=["1s","6i"+b,"P"+a,"6r"+(b%2==0?1:2).1q()];J.3U(b)&&a.U("67");b==0&&a.U("1N");H\'<T 1g="\'+a.1K(" ")+\'">\'+c+"</T>"},3Q:6(a,b){K c="",d=a.1e("\\n").L,h=2u(J.V("2i-1s")),g=J.V("2z-1s-2t");I(g==R)g=(h+d-1).1q().L;Y I(3R(g)==R)g=0;O(K i=0;i<d;i++){K k=b?b[i]:h+i,j;I(k==0)j=e.13.1W;Y{j=g;O(K l=k.1q();l.L<j;)l="0"+l;j=l}a=j;c+=J.2r(i,k,a)}H c},49:6(a,b){a=x(a);K c=a.1e("\\n");J.V("2z-1s-2t");K d=2u(J.V("2i-1s"));a="";O(K h=J.V("1D"),g=0;g<c.L;g++){K i=c[g],k=/^(&2s;|\\s)+/.X(i),j=N,l=b?b[g]:d+g;I(k!=N){j=k[0].1q();i=i.1o(j.L);j=j.Q(" ",e.13.1W)}i=x(i);I(i.L==0)i=e.13.1W;a+=J.2r(g,l,(j!=N?\'<17 1g="\'+h+\' 5N">\'+j+"</17>":"")+i)}H a},4f:6(a){H a?"<4a>"+a+"</4a>":""},4b:6(a,b){6 c(l){H(l=l?l.1V||g:g)?l+" ":""}O(K d=0,h="",g=J.V("1D",""),i=0;i<b.L;i++){K k=b[i],j;I(!(k===N||k.L===0)){j=c(k);h+=u(a.1o(d,k.P-d),j+"48")+u(k.1T,j+k.23);d=k.P+k.L+(k.75||0)}}h+=u(a.1o(d),c()+"48");H h},1H:6(a){K b="",c=["20"],d;I(J.V("2k")==R)J.1n.16=J.1n.1u=11;1l="20";J.V("2l")==R&&c.U("47");I((1u=J.V("1u"))==11)c.U("6S");c.U(J.V("1g-27"));c.U(J.V("1D"));a=a.Q(/^[ ]*[\\n]+|[\\n]*[ ]*$/g,"").Q(/\\r/g," ");b=J.V("43-22");I(J.V("42-45")==R)a=n(a,b);Y{O(K h="",g=0;g<b;g++)h+=" ";a=a.Q(/\\t/g,h)}a=a;a:{b=a=a;h=/<2R\\s*\\/?>|&1y;2R\\s*\\/?&1G;/2T;I(e.13.46==R)b=b.Q(h,"\\n");I(e.13.44==R)b=b.Q(h,"");b=b.1e("\\n");h=/^\\s*/;g=4Q;O(K i=0;i<b.L&&g>0;i++){K k=b[i];I(x(k).L!=0){k=h.X(k);I(k==N){a=a;1N a}g=1Q.4q(k[0].L,g)}}I(g>0)O(i=0;i<b.L;i++)b[i]=b[i].1o(g);a=b.1K("\\n")}I(1u)d=J.4d(a);b=J.4c(J.2J,a);b=J.4b(a,b);b=J.49(b,d);I(J.V("41-40"))b=E(b);1j 2H!="1d"&&2H.3S&&2H.3S.1C(/5s/)&&c.U("5t");H b=\'<T 1c="\'+t(J.1c)+\'" 1g="\'+c.1K(" ")+\'">\'+(J.V("16")?e.16.1H(J):"")+\'<3Z 5z="0" 5H="0" 5J="0">\'+J.4f(J.V("1t"))+"<3T><3P>"+(1u?\'<2d 1g="1u">\'+J.3Q(a)+"</2d>":"")+\'<2d 1g="17"><T 1g="3O">\'+b+"</T></2d></3P></3T></3Z></T>"},2F:6(a){I(a===N)a="";J.17=a;K b=J.3Y("T");b.3X=J.1H(a);J.V("16")&&w(p(b,".16"),"5c",e.16.2b);J.V("3V-17")&&w(p(b,".17"),"56",f);H b},2Q:6(a){J.1c=""+1Q.5d(1Q.5n()*5k).1q();e.1Y.2A[t(J.1c)]=J;J.1n=C(e.2v,a||{});I(J.V("2k")==R)J.1n.16=J.1n.1u=11},5j:6(a){a=a.Q(/^\\s+|\\s+$/g,"").Q(/\\s+/g,"|");H"\\\\b(?:"+a+")\\\\b"},5f:6(a){J.28={18:{1I:a.18,23:"1k"},1b:{1I:a.1b,23:"1k"},17:1f M("(?<18>"+a.18.1m+")(?<17>.*?)(?<1b>"+a.1b.1m+")","5o")}}};H e}();1j 2e!="1d"&&(2e.1v=1v);',62,441,'||||||function|||||||||||||||||||||||||||||||||||||return|if|this|var|length|XRegExp|null|for|index|replace|true||div|push|getParam|call|exec|else|prototype||false|lastIndex|config|arguments|RegExp|toolbar|code|left|captureNames|slice|right|id|undefined|split|new|class|addToken|indexOf|typeof|script|className|source|params|substr|apply|toString|String|line|title|gutter|SyntaxHighlighter|_xregexp|strings|lt|html|test|OUTSIDE_CLASS|match|brush|document|target|gt|getHtml|regex|global|join|style|highlight|break|concat|window|Math|isRegExp|throw|value|brushes|brushName|space|alert|vars|http|syntaxhighlighter|expandSource|size|css|case|font|Fa|name|htmlScript|dA|can|handler|gm|td|exports|color|in|href|first|discoveredBrushes|light|collapse|object|cache|getButtonHtml|trigger|pattern|getLineHtml|nbsp|numbers|parseInt|defaults|com|items|www|pad|highlighters|execute|focus|func|all|getDiv|parentNode|navigator|INSIDE_CLASS|regexList|hasFlag|Match|useScriptTags|hasNamedCapture|text|help|init|br|input|gi|Error|values|span|list|250|height|width|screen|top|500|tagName|findElements|getElementsByTagName|aboutDialog|_blank|appendChild|charAt|Array|copyAsGlobal|setFlag|highlighter_|string|attachEvent|nodeName|floor|backref|output|the|TypeError|sticky|Za|iterate|freezeTokens|scope|type|textarea|alexgorbatchev|version|margin|2010|005896|gs|regexLib|body|center|align|noBrush|require|childNodes|DTD|xhtml1|head|org|w3|url|preventDefault|container|tr|getLineNumbersHtml|isNaN|userAgent|tbody|isLineHighlighted|quick|void|innerHTML|create|table|links|auto|smart|tab|stripBrs|tabs|bloggerMode|collapsed|plain|getCodeLinesHtml|caption|getMatchesHtml|findMatches|figureOutLineNumbers|removeNestedMatches|getTitleHtml|brushNotHtmlScript|substring|createElement|Highlighter|load|HtmlScript|Brush|pre|expand|multiline|min|Can|ignoreCase|find|blur|extended|toLowerCase|aliases|addEventListener|innerText|textContent|wasn|select|createTextNode|removeChild|option|same|frame|xmlns|dtd|twice|1999|equiv|meta|htmlscript|transitional|1E3|expected|PUBLIC|DOCTYPE|on|W3C|XHTML|TR|EN|Transitional||configured|srcElement|Object|after|run|dblclick|matchChain|valueOf|constructor|default|switch|click|round|execAt|forHtmlScript|token|gimy|functions|getKeywords|1E6|escape|within|random|sgi|another|finally|supply|MSIE|ie|toUpperCase|catch|returnValue|definition|event|border|imsx|constructing|one|Infinity|from|when|Content|cellpadding|flags|cellspacing|try|xhtml|Type|spaces|2930402|hosted_button_id|lastIndexOf|donate|active|development|keep|to|xclick|_s|Xml|please|like|you|paypal|cgi|cmd|webscr|bin|highlighted|scrollbars|aspScriptTags|phpScriptTags|sort|max|scriptScriptTags|toolbar_item|_|command|command_|number|getElementById|doubleQuotedString|singleLinePerlComments|singleLineCComments|multiLineCComments|singleQuotedString|multiLineDoubleQuotedString|xmlComments|alt|multiLineSingleQuotedString|If|https|1em|000|fff|background|5em|xx|bottom|75em|Gorbatchev|large|serif|CDATA|continue|utf|charset|content|About|family|sans|Helvetica|Arial|Geneva|3em|nogutter|Copyright|syntax|close|write|2004|Alex|open|JavaScript|highlighter|July|02|replaceChild|offset|83'.split('|'),0,{})) diff --git a/railties/guides/assets/stylesheets/fixes.css b/railties/guides/assets/stylesheets/fixes.css new file mode 100644 index 0000000000..54efa5b9b7 --- /dev/null +++ b/railties/guides/assets/stylesheets/fixes.css @@ -0,0 +1,16 @@ +/* + Fix a rendering issue affecting WebKits on Mac. + See https://github.com/lifo/docrails/issues#issue/16 for more information. +*/ +.syntaxhighlighter a, +.syntaxhighlighter div, +.syntaxhighlighter code, +.syntaxhighlighter table, +.syntaxhighlighter table td, +.syntaxhighlighter table tr, +.syntaxhighlighter table tbody, +.syntaxhighlighter table thead, +.syntaxhighlighter table caption, +.syntaxhighlighter textarea { + line-height: 1.2em !important; +} diff --git a/railties/guides/assets/stylesheets/main.css b/railties/guides/assets/stylesheets/main.css index bab0b7a9d9..cf6e9e5cc8 100644 --- a/railties/guides/assets/stylesheets/main.css +++ b/railties/guides/assets/stylesheets/main.css @@ -22,9 +22,13 @@ ol { list-style-type: decimal; } dl { margin: 0 0 1.5em 0; } dl dt { font-weight: bold; } dd { margin-left: 1.5em;} - -pre,code { margin: 1.5em 0; white-space: pre; overflow: auto; } -pre,code,tt { font: 1em 'andale mono', 'lucida console', monospace; line-height: 1.5; } + +pre,code { margin: 1.5em 0; overflow: auto; color: #222;} +pre,code,tt { + font-size: 1em; + font-family: "Anonymous Pro", "Inconsolata", "Menlo", "Consolas", "Bitstream Vera Sans Mono", "Courier New", monospace; + line-height: 1.5; +} abbr, acronym { border-bottom: 1px dotted #666; } address { margin: 0 0 1.5em; font-style: italic; } @@ -53,7 +57,7 @@ table { background: #FFF; border-collapse: collapse; } - + table th, table td { padding: 0.25em 1em; border: 1px solid #CCC; @@ -76,7 +80,7 @@ body { font-family: Helvetica, Arial, sans-serif; font-size: 87.5%; line-height: 1.5em; - background: #222; + background: #222; color: #999; } @@ -114,7 +118,7 @@ body { #mainCol { width: 45em; margin-left: 2em; - } + } #subCol { position: absolute; @@ -127,7 +131,7 @@ body { font-size: 0.9285em; line-height: 1.3846em; } - + #extraCol {display: none;} #footer { @@ -180,7 +184,7 @@ a, a:link, a:visited { #header .nav .index a { background: #980905 url(../images/nav_arrow.gif) no-repeat right top; - padding-right: 1em; + padding-right: 1em; position: relative; z-index: 15; padding-bottom: 0.125em; @@ -246,7 +250,7 @@ h3 { margin: 0.875em 0 0.2916em; font-weight: bold; } - + h4 { font-size: 1.2857em; line-height: 1.2em; @@ -261,7 +265,7 @@ h5 { font-weight: bold; } -h6 { +h6 { font-size: 1em; line-height: 1.5em; margin: 1em 0 .5em; @@ -329,7 +333,7 @@ h6 { padding: 0.125em 0 0.25em 28px;*/ } -#mainCol dd.ticket, #subCol dd.ticket { +#mainCol dd.work-in-progress, #subCol dd.work-in-progress { background: #fff9d8 url(../images/tab_yellow.gif) no-repeat left top; border: none; padding: 1.25em 1em 1.25em 48px; @@ -361,20 +365,9 @@ h6 { font-weight: normal; } -tt { - font-family: monaco, "Bitstream Vera Sans Mono", "Courier New", courier, monospace; -} - div.code_container { background: #EEE url(../images/tab_grey.gif) no-repeat left top; - padding: 0.25em 1em 0.5em 48px; -} - -code { - font-family: monaco, "Bitstream Vera Sans Mono", "Courier New", courier, monospace; - border: none; - margin: 0.25em 0 1.5em 0; - display: block; + padding: 0.25em 1em 0.5em 48px; } .note { @@ -411,15 +404,15 @@ code { padding: 0 0 1em; font-size: 1.1667em; } - + /* Clearing --------------------------------------- */ .clearfix:after { - content: "."; - display: block; - height: 0; - clear: both; + content: "."; + display: block; + height: 0; + clear: both; visibility: hidden; } diff --git a/railties/guides/assets/stylesheets/syntax.css b/railties/guides/assets/stylesheets/syntax.css deleted file mode 100644 index 55fc5b209f..0000000000 --- a/railties/guides/assets/stylesheets/syntax.css +++ /dev/null @@ -1,31 +0,0 @@ -.html .tag { - color : green; -} - -.html .doctype { - color: #708090; -} - -.erb .tag { - color : green; -} - -.erb .doctype { - color: #708090; -} - -.ruby .keywords { - color : red; -} - -.ruby .ivar { - color : blue; -} - -.ruby .comment { - color: #708090; -} - -.ruby .symbol { - color: green; -} diff --git a/railties/guides/assets/stylesheets/syntaxhighlighter/shCore.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shCore.css new file mode 100644 index 0000000000..34f6864a15 --- /dev/null +++ b/railties/guides/assets/stylesheets/syntaxhighlighter/shCore.css @@ -0,0 +1,226 @@ +/** + * SyntaxHighlighter + * http://alexgorbatchev.com/SyntaxHighlighter + * + * SyntaxHighlighter is donationware. If you are using it, please donate. + * http://alexgorbatchev.com/SyntaxHighlighter/donate.html + * + * @version + * 3.0.83 (July 02 2010) + * + * @copyright + * Copyright (C) 2004-2010 Alex Gorbatchev. + * + * @license + * Dual licensed under the MIT and GPL licenses. + */ +.syntaxhighlighter a, +.syntaxhighlighter div, +.syntaxhighlighter code, +.syntaxhighlighter table, +.syntaxhighlighter table td, +.syntaxhighlighter table tr, +.syntaxhighlighter table tbody, +.syntaxhighlighter table thead, +.syntaxhighlighter table caption, +.syntaxhighlighter textarea { + -moz-border-radius: 0 0 0 0 !important; + -webkit-border-radius: 0 0 0 0 !important; + background: none !important; + border: 0 !important; + bottom: auto !important; + float: none !important; + height: auto !important; + left: auto !important; + line-height: 1.1em !important; + margin: 0 !important; + outline: 0 !important; + overflow: visible !important; + padding: 0 !important; + position: static !important; + right: auto !important; + text-align: left !important; + top: auto !important; + vertical-align: baseline !important; + width: auto !important; + box-sizing: content-box !important; + font-family: "Consolas", "Bitstream Vera Sans Mono", "Courier New", Courier, monospace !important; + font-weight: normal !important; + font-style: normal !important; + font-size: 1em !important; + min-height: inherit !important; + min-height: auto !important; +} + +.syntaxhighlighter { + width: 100% !important; + margin: 1em 0 1em 0 !important; + position: relative !important; + overflow: auto !important; + font-size: 1em !important; +} +.syntaxhighlighter.source { + overflow: hidden !important; +} +.syntaxhighlighter .bold { + font-weight: bold !important; +} +.syntaxhighlighter .italic { + font-style: italic !important; +} +.syntaxhighlighter .line { + white-space: pre !important; +} +.syntaxhighlighter table { + width: 100% !important; +} +.syntaxhighlighter table caption { + text-align: left !important; + padding: .5em 0 0.5em 1em !important; +} +.syntaxhighlighter table td.code { + width: 100% !important; +} +.syntaxhighlighter table td.code .container { + position: relative !important; +} +.syntaxhighlighter table td.code .container textarea { + box-sizing: border-box !important; + position: absolute !important; + left: 0 !important; + top: 0 !important; + width: 100% !important; + height: 100% !important; + border: none !important; + background: white !important; + padding-left: 1em !important; + overflow: hidden !important; + white-space: pre !important; +} +.syntaxhighlighter table td.gutter .line { + text-align: right !important; + padding: 0 0.5em 0 1em !important; +} +.syntaxhighlighter table td.code .line { + padding: 0 1em !important; +} +.syntaxhighlighter.nogutter td.code .container textarea, .syntaxhighlighter.nogutter td.code .line { + padding-left: 0em !important; +} +.syntaxhighlighter.show { + display: block !important; +} +.syntaxhighlighter.collapsed table { + display: none !important; +} +.syntaxhighlighter.collapsed .toolbar { + padding: 0.1em 0.8em 0em 0.8em !important; + font-size: 1em !important; + position: static !important; + width: auto !important; + height: auto !important; +} +.syntaxhighlighter.collapsed .toolbar span { + display: inline !important; + margin-right: 1em !important; +} +.syntaxhighlighter.collapsed .toolbar span a { + padding: 0 !important; + display: none !important; +} +.syntaxhighlighter.collapsed .toolbar span a.expandSource { + display: inline !important; +} +.syntaxhighlighter .toolbar { + position: absolute !important; + right: 1px !important; + top: 1px !important; + width: 11px !important; + height: 11px !important; + font-size: 10px !important; + z-index: 10 !important; +} +.syntaxhighlighter .toolbar span.title { + display: inline !important; +} +.syntaxhighlighter .toolbar a { + display: block !important; + text-align: center !important; + text-decoration: none !important; + padding-top: 1px !important; +} +.syntaxhighlighter .toolbar a.expandSource { + display: none !important; +} +.syntaxhighlighter.ie { + font-size: .9em !important; + padding: 1px 0 1px 0 !important; +} +.syntaxhighlighter.ie .toolbar { + line-height: 8px !important; +} +.syntaxhighlighter.ie .toolbar a { + padding-top: 0px !important; +} +.syntaxhighlighter.printing .line.alt1 .content, +.syntaxhighlighter.printing .line.alt2 .content, +.syntaxhighlighter.printing .line.highlighted .number, +.syntaxhighlighter.printing .line.highlighted.alt1 .content, +.syntaxhighlighter.printing .line.highlighted.alt2 .content { + background: none !important; +} +.syntaxhighlighter.printing .line .number { + color: #bbbbbb !important; +} +.syntaxhighlighter.printing .line .content { + color: black !important; +} +.syntaxhighlighter.printing .toolbar { + display: none !important; +} +.syntaxhighlighter.printing a { + text-decoration: none !important; +} +.syntaxhighlighter.printing .plain, .syntaxhighlighter.printing .plain a { + color: black !important; +} +.syntaxhighlighter.printing .comments, .syntaxhighlighter.printing .comments a { + color: #008200 !important; +} +.syntaxhighlighter.printing .string, .syntaxhighlighter.printing .string a { + color: blue !important; +} +.syntaxhighlighter.printing .keyword { + color: #006699 !important; + font-weight: bold !important; +} +.syntaxhighlighter.printing .preprocessor { + color: gray !important; +} +.syntaxhighlighter.printing .variable { + color: #aa7700 !important; +} +.syntaxhighlighter.printing .value { + color: #009900 !important; +} +.syntaxhighlighter.printing .functions { + color: #ff1493 !important; +} +.syntaxhighlighter.printing .constants { + color: #0066cc !important; +} +.syntaxhighlighter.printing .script { + font-weight: bold !important; +} +.syntaxhighlighter.printing .color1, .syntaxhighlighter.printing .color1 a { + color: gray !important; +} +.syntaxhighlighter.printing .color2, .syntaxhighlighter.printing .color2 a { + color: #ff1493 !important; +} +.syntaxhighlighter.printing .color3, .syntaxhighlighter.printing .color3 a { + color: red !important; +} +.syntaxhighlighter.printing .break, .syntaxhighlighter.printing .break a { + color: black !important; +} diff --git a/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreDefault.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreDefault.css new file mode 100644 index 0000000000..08f9e10e4e --- /dev/null +++ b/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreDefault.css @@ -0,0 +1,328 @@ +/** + * SyntaxHighlighter + * http://alexgorbatchev.com/SyntaxHighlighter + * + * SyntaxHighlighter is donationware. If you are using it, please donate. + * http://alexgorbatchev.com/SyntaxHighlighter/donate.html + * + * @version + * 3.0.83 (July 02 2010) + * + * @copyright + * Copyright (C) 2004-2010 Alex Gorbatchev. + * + * @license + * Dual licensed under the MIT and GPL licenses. + */ +.syntaxhighlighter a, +.syntaxhighlighter div, +.syntaxhighlighter code, +.syntaxhighlighter table, +.syntaxhighlighter table td, +.syntaxhighlighter table tr, +.syntaxhighlighter table tbody, +.syntaxhighlighter table thead, +.syntaxhighlighter table caption, +.syntaxhighlighter textarea { + -moz-border-radius: 0 0 0 0 !important; + -webkit-border-radius: 0 0 0 0 !important; + background: none !important; + border: 0 !important; + bottom: auto !important; + float: none !important; + height: auto !important; + left: auto !important; + line-height: 1.1em !important; + margin: 0 !important; + outline: 0 !important; + overflow: visible !important; + padding: 0 !important; + position: static !important; + right: auto !important; + text-align: left !important; + top: auto !important; + vertical-align: baseline !important; + width: auto !important; + box-sizing: content-box !important; + font-family: "Consolas", "Bitstream Vera Sans Mono", "Courier New", Courier, monospace !important; + font-weight: normal !important; + font-style: normal !important; + font-size: 1em !important; + min-height: inherit !important; + min-height: auto !important; +} + +.syntaxhighlighter { + width: 100% !important; + margin: 1em 0 1em 0 !important; + position: relative !important; + overflow: auto !important; + font-size: 1em !important; +} +.syntaxhighlighter.source { + overflow: hidden !important; +} +.syntaxhighlighter .bold { + font-weight: bold !important; +} +.syntaxhighlighter .italic { + font-style: italic !important; +} +.syntaxhighlighter .line { + white-space: pre !important; +} +.syntaxhighlighter table { + width: 100% !important; +} +.syntaxhighlighter table caption { + text-align: left !important; + padding: .5em 0 0.5em 1em !important; +} +.syntaxhighlighter table td.code { + width: 100% !important; +} +.syntaxhighlighter table td.code .container { + position: relative !important; +} +.syntaxhighlighter table td.code .container textarea { + box-sizing: border-box !important; + position: absolute !important; + left: 0 !important; + top: 0 !important; + width: 100% !important; + height: 100% !important; + border: none !important; + background: white !important; + padding-left: 1em !important; + overflow: hidden !important; + white-space: pre !important; +} +.syntaxhighlighter table td.gutter .line { + text-align: right !important; + padding: 0 0.5em 0 1em !important; +} +.syntaxhighlighter table td.code .line { + padding: 0 1em !important; +} +.syntaxhighlighter.nogutter td.code .container textarea, .syntaxhighlighter.nogutter td.code .line { + padding-left: 0em !important; +} +.syntaxhighlighter.show { + display: block !important; +} +.syntaxhighlighter.collapsed table { + display: none !important; +} +.syntaxhighlighter.collapsed .toolbar { + padding: 0.1em 0.8em 0em 0.8em !important; + font-size: 1em !important; + position: static !important; + width: auto !important; + height: auto !important; +} +.syntaxhighlighter.collapsed .toolbar span { + display: inline !important; + margin-right: 1em !important; +} +.syntaxhighlighter.collapsed .toolbar span a { + padding: 0 !important; + display: none !important; +} +.syntaxhighlighter.collapsed .toolbar span a.expandSource { + display: inline !important; +} +.syntaxhighlighter .toolbar { + position: absolute !important; + right: 1px !important; + top: 1px !important; + width: 11px !important; + height: 11px !important; + font-size: 10px !important; + z-index: 10 !important; +} +.syntaxhighlighter .toolbar span.title { + display: inline !important; +} +.syntaxhighlighter .toolbar a { + display: block !important; + text-align: center !important; + text-decoration: none !important; + padding-top: 1px !important; +} +.syntaxhighlighter .toolbar a.expandSource { + display: none !important; +} +.syntaxhighlighter.ie { + font-size: .9em !important; + padding: 1px 0 1px 0 !important; +} +.syntaxhighlighter.ie .toolbar { + line-height: 8px !important; +} +.syntaxhighlighter.ie .toolbar a { + padding-top: 0px !important; +} +.syntaxhighlighter.printing .line.alt1 .content, +.syntaxhighlighter.printing .line.alt2 .content, +.syntaxhighlighter.printing .line.highlighted .number, +.syntaxhighlighter.printing .line.highlighted.alt1 .content, +.syntaxhighlighter.printing .line.highlighted.alt2 .content { + background: none !important; +} +.syntaxhighlighter.printing .line .number { + color: #bbbbbb !important; +} +.syntaxhighlighter.printing .line .content { + color: black !important; +} +.syntaxhighlighter.printing .toolbar { + display: none !important; +} +.syntaxhighlighter.printing a { + text-decoration: none !important; +} +.syntaxhighlighter.printing .plain, .syntaxhighlighter.printing .plain a { + color: black !important; +} +.syntaxhighlighter.printing .comments, .syntaxhighlighter.printing .comments a { + color: #008200 !important; +} +.syntaxhighlighter.printing .string, .syntaxhighlighter.printing .string a { + color: blue !important; +} +.syntaxhighlighter.printing .keyword { + color: #006699 !important; + font-weight: bold !important; +} +.syntaxhighlighter.printing .preprocessor { + color: gray !important; +} +.syntaxhighlighter.printing .variable { + color: #aa7700 !important; +} +.syntaxhighlighter.printing .value { + color: #009900 !important; +} +.syntaxhighlighter.printing .functions { + color: #ff1493 !important; +} +.syntaxhighlighter.printing .constants { + color: #0066cc !important; +} +.syntaxhighlighter.printing .script { + font-weight: bold !important; +} +.syntaxhighlighter.printing .color1, .syntaxhighlighter.printing .color1 a { + color: gray !important; +} +.syntaxhighlighter.printing .color2, .syntaxhighlighter.printing .color2 a { + color: #ff1493 !important; +} +.syntaxhighlighter.printing .color3, .syntaxhighlighter.printing .color3 a { + color: red !important; +} +.syntaxhighlighter.printing .break, .syntaxhighlighter.printing .break a { + color: black !important; +} + +.syntaxhighlighter { + background-color: white !important; +} +.syntaxhighlighter .line.alt1 { + background-color: white !important; +} +.syntaxhighlighter .line.alt2 { + background-color: white !important; +} +.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 { + background-color: #e0e0e0 !important; +} +.syntaxhighlighter .line.highlighted.number { + color: black !important; +} +.syntaxhighlighter table caption { + color: black !important; +} +.syntaxhighlighter .gutter { + color: #afafaf !important; +} +.syntaxhighlighter .gutter .line { + border-right: 3px solid #6ce26c !important; +} +.syntaxhighlighter .gutter .line.highlighted { + background-color: #6ce26c !important; + color: white !important; +} +.syntaxhighlighter.printing .line .content { + border: none !important; +} +.syntaxhighlighter.collapsed { + overflow: visible !important; +} +.syntaxhighlighter.collapsed .toolbar { + color: blue !important; + background: white !important; + border: 1px solid #6ce26c !important; +} +.syntaxhighlighter.collapsed .toolbar a { + color: blue !important; +} +.syntaxhighlighter.collapsed .toolbar a:hover { + color: red !important; +} +.syntaxhighlighter .toolbar { + color: white !important; + background: #6ce26c !important; + border: none !important; +} +.syntaxhighlighter .toolbar a { + color: white !important; +} +.syntaxhighlighter .toolbar a:hover { + color: black !important; +} +.syntaxhighlighter .plain, .syntaxhighlighter .plain a { + color: black !important; +} +.syntaxhighlighter .comments, .syntaxhighlighter .comments a { + color: #008200 !important; +} +.syntaxhighlighter .string, .syntaxhighlighter .string a { + color: blue !important; +} +.syntaxhighlighter .keyword { + color: #006699 !important; +} +.syntaxhighlighter .preprocessor { + color: gray !important; +} +.syntaxhighlighter .variable { + color: #aa7700 !important; +} +.syntaxhighlighter .value { + color: #009900 !important; +} +.syntaxhighlighter .functions { + color: #ff1493 !important; +} +.syntaxhighlighter .constants { + color: #0066cc !important; +} +.syntaxhighlighter .script { + font-weight: bold !important; + color: #006699 !important; + background-color: none !important; +} +.syntaxhighlighter .color1, .syntaxhighlighter .color1 a { + color: gray !important; +} +.syntaxhighlighter .color2, .syntaxhighlighter .color2 a { + color: #ff1493 !important; +} +.syntaxhighlighter .color3, .syntaxhighlighter .color3 a { + color: red !important; +} + +.syntaxhighlighter .keyword { + font-weight: bold !important; +} diff --git a/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreDjango.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreDjango.css new file mode 100644 index 0000000000..1db1f70cb0 --- /dev/null +++ b/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreDjango.css @@ -0,0 +1,331 @@ +/** + * SyntaxHighlighter + * http://alexgorbatchev.com/SyntaxHighlighter + * + * SyntaxHighlighter is donationware. If you are using it, please donate. + * http://alexgorbatchev.com/SyntaxHighlighter/donate.html + * + * @version + * 3.0.83 (July 02 2010) + * + * @copyright + * Copyright (C) 2004-2010 Alex Gorbatchev. + * + * @license + * Dual licensed under the MIT and GPL licenses. + */ +.syntaxhighlighter a, +.syntaxhighlighter div, +.syntaxhighlighter code, +.syntaxhighlighter table, +.syntaxhighlighter table td, +.syntaxhighlighter table tr, +.syntaxhighlighter table tbody, +.syntaxhighlighter table thead, +.syntaxhighlighter table caption, +.syntaxhighlighter textarea { + -moz-border-radius: 0 0 0 0 !important; + -webkit-border-radius: 0 0 0 0 !important; + background: none !important; + border: 0 !important; + bottom: auto !important; + float: none !important; + height: auto !important; + left: auto !important; + line-height: 1.1em !important; + margin: 0 !important; + outline: 0 !important; + overflow: visible !important; + padding: 0 !important; + position: static !important; + right: auto !important; + text-align: left !important; + top: auto !important; + vertical-align: baseline !important; + width: auto !important; + box-sizing: content-box !important; + font-family: "Consolas", "Bitstream Vera Sans Mono", "Courier New", Courier, monospace !important; + font-weight: normal !important; + font-style: normal !important; + font-size: 1em !important; + min-height: inherit !important; + min-height: auto !important; +} + +.syntaxhighlighter { + width: 100% !important; + margin: 1em 0 1em 0 !important; + position: relative !important; + overflow: auto !important; + font-size: 1em !important; +} +.syntaxhighlighter.source { + overflow: hidden !important; +} +.syntaxhighlighter .bold { + font-weight: bold !important; +} +.syntaxhighlighter .italic { + font-style: italic !important; +} +.syntaxhighlighter .line { + white-space: pre !important; +} +.syntaxhighlighter table { + width: 100% !important; +} +.syntaxhighlighter table caption { + text-align: left !important; + padding: .5em 0 0.5em 1em !important; +} +.syntaxhighlighter table td.code { + width: 100% !important; +} +.syntaxhighlighter table td.code .container { + position: relative !important; +} +.syntaxhighlighter table td.code .container textarea { + box-sizing: border-box !important; + position: absolute !important; + left: 0 !important; + top: 0 !important; + width: 100% !important; + height: 100% !important; + border: none !important; + background: white !important; + padding-left: 1em !important; + overflow: hidden !important; + white-space: pre !important; +} +.syntaxhighlighter table td.gutter .line { + text-align: right !important; + padding: 0 0.5em 0 1em !important; +} +.syntaxhighlighter table td.code .line { + padding: 0 1em !important; +} +.syntaxhighlighter.nogutter td.code .container textarea, .syntaxhighlighter.nogutter td.code .line { + padding-left: 0em !important; +} +.syntaxhighlighter.show { + display: block !important; +} +.syntaxhighlighter.collapsed table { + display: none !important; +} +.syntaxhighlighter.collapsed .toolbar { + padding: 0.1em 0.8em 0em 0.8em !important; + font-size: 1em !important; + position: static !important; + width: auto !important; + height: auto !important; +} +.syntaxhighlighter.collapsed .toolbar span { + display: inline !important; + margin-right: 1em !important; +} +.syntaxhighlighter.collapsed .toolbar span a { + padding: 0 !important; + display: none !important; +} +.syntaxhighlighter.collapsed .toolbar span a.expandSource { + display: inline !important; +} +.syntaxhighlighter .toolbar { + position: absolute !important; + right: 1px !important; + top: 1px !important; + width: 11px !important; + height: 11px !important; + font-size: 10px !important; + z-index: 10 !important; +} +.syntaxhighlighter .toolbar span.title { + display: inline !important; +} +.syntaxhighlighter .toolbar a { + display: block !important; + text-align: center !important; + text-decoration: none !important; + padding-top: 1px !important; +} +.syntaxhighlighter .toolbar a.expandSource { + display: none !important; +} +.syntaxhighlighter.ie { + font-size: .9em !important; + padding: 1px 0 1px 0 !important; +} +.syntaxhighlighter.ie .toolbar { + line-height: 8px !important; +} +.syntaxhighlighter.ie .toolbar a { + padding-top: 0px !important; +} +.syntaxhighlighter.printing .line.alt1 .content, +.syntaxhighlighter.printing .line.alt2 .content, +.syntaxhighlighter.printing .line.highlighted .number, +.syntaxhighlighter.printing .line.highlighted.alt1 .content, +.syntaxhighlighter.printing .line.highlighted.alt2 .content { + background: none !important; +} +.syntaxhighlighter.printing .line .number { + color: #bbbbbb !important; +} +.syntaxhighlighter.printing .line .content { + color: black !important; +} +.syntaxhighlighter.printing .toolbar { + display: none !important; +} +.syntaxhighlighter.printing a { + text-decoration: none !important; +} +.syntaxhighlighter.printing .plain, .syntaxhighlighter.printing .plain a { + color: black !important; +} +.syntaxhighlighter.printing .comments, .syntaxhighlighter.printing .comments a { + color: #008200 !important; +} +.syntaxhighlighter.printing .string, .syntaxhighlighter.printing .string a { + color: blue !important; +} +.syntaxhighlighter.printing .keyword { + color: #006699 !important; + font-weight: bold !important; +} +.syntaxhighlighter.printing .preprocessor { + color: gray !important; +} +.syntaxhighlighter.printing .variable { + color: #aa7700 !important; +} +.syntaxhighlighter.printing .value { + color: #009900 !important; +} +.syntaxhighlighter.printing .functions { + color: #ff1493 !important; +} +.syntaxhighlighter.printing .constants { + color: #0066cc !important; +} +.syntaxhighlighter.printing .script { + font-weight: bold !important; +} +.syntaxhighlighter.printing .color1, .syntaxhighlighter.printing .color1 a { + color: gray !important; +} +.syntaxhighlighter.printing .color2, .syntaxhighlighter.printing .color2 a { + color: #ff1493 !important; +} +.syntaxhighlighter.printing .color3, .syntaxhighlighter.printing .color3 a { + color: red !important; +} +.syntaxhighlighter.printing .break, .syntaxhighlighter.printing .break a { + color: black !important; +} + +.syntaxhighlighter { + background-color: #0a2b1d !important; +} +.syntaxhighlighter .line.alt1 { + background-color: #0a2b1d !important; +} +.syntaxhighlighter .line.alt2 { + background-color: #0a2b1d !important; +} +.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 { + background-color: #233729 !important; +} +.syntaxhighlighter .line.highlighted.number { + color: white !important; +} +.syntaxhighlighter table caption { + color: #f8f8f8 !important; +} +.syntaxhighlighter .gutter { + color: #497958 !important; +} +.syntaxhighlighter .gutter .line { + border-right: 3px solid #41a83e !important; +} +.syntaxhighlighter .gutter .line.highlighted { + background-color: #41a83e !important; + color: #0a2b1d !important; +} +.syntaxhighlighter.printing .line .content { + border: none !important; +} +.syntaxhighlighter.collapsed { + overflow: visible !important; +} +.syntaxhighlighter.collapsed .toolbar { + color: #96dd3b !important; + background: black !important; + border: 1px solid #41a83e !important; +} +.syntaxhighlighter.collapsed .toolbar a { + color: #96dd3b !important; +} +.syntaxhighlighter.collapsed .toolbar a:hover { + color: white !important; +} +.syntaxhighlighter .toolbar { + color: white !important; + background: #41a83e !important; + border: none !important; +} +.syntaxhighlighter .toolbar a { + color: white !important; +} +.syntaxhighlighter .toolbar a:hover { + color: #ffe862 !important; +} +.syntaxhighlighter .plain, .syntaxhighlighter .plain a { + color: #f8f8f8 !important; +} +.syntaxhighlighter .comments, .syntaxhighlighter .comments a { + color: #336442 !important; +} +.syntaxhighlighter .string, .syntaxhighlighter .string a { + color: #9df39f !important; +} +.syntaxhighlighter .keyword { + color: #96dd3b !important; +} +.syntaxhighlighter .preprocessor { + color: #91bb9e !important; +} +.syntaxhighlighter .variable { + color: #ffaa3e !important; +} +.syntaxhighlighter .value { + color: #f7e741 !important; +} +.syntaxhighlighter .functions { + color: #ffaa3e !important; +} +.syntaxhighlighter .constants { + color: #e0e8ff !important; +} +.syntaxhighlighter .script { + font-weight: bold !important; + color: #96dd3b !important; + background-color: none !important; +} +.syntaxhighlighter .color1, .syntaxhighlighter .color1 a { + color: #eb939a !important; +} +.syntaxhighlighter .color2, .syntaxhighlighter .color2 a { + color: #91bb9e !important; +} +.syntaxhighlighter .color3, .syntaxhighlighter .color3 a { + color: #edef7d !important; +} + +.syntaxhighlighter .comments { + font-style: italic !important; +} +.syntaxhighlighter .keyword { + font-weight: bold !important; +} diff --git a/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreEclipse.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreEclipse.css new file mode 100644 index 0000000000..a45de9fd8e --- /dev/null +++ b/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreEclipse.css @@ -0,0 +1,339 @@ +/** + * SyntaxHighlighter + * http://alexgorbatchev.com/SyntaxHighlighter + * + * SyntaxHighlighter is donationware. If you are using it, please donate. + * http://alexgorbatchev.com/SyntaxHighlighter/donate.html + * + * @version + * 3.0.83 (July 02 2010) + * + * @copyright + * Copyright (C) 2004-2010 Alex Gorbatchev. + * + * @license + * Dual licensed under the MIT and GPL licenses. + */ +.syntaxhighlighter a, +.syntaxhighlighter div, +.syntaxhighlighter code, +.syntaxhighlighter table, +.syntaxhighlighter table td, +.syntaxhighlighter table tr, +.syntaxhighlighter table tbody, +.syntaxhighlighter table thead, +.syntaxhighlighter table caption, +.syntaxhighlighter textarea { + -moz-border-radius: 0 0 0 0 !important; + -webkit-border-radius: 0 0 0 0 !important; + background: none !important; + border: 0 !important; + bottom: auto !important; + float: none !important; + height: auto !important; + left: auto !important; + line-height: 1.1em !important; + margin: 0 !important; + outline: 0 !important; + overflow: visible !important; + padding: 0 !important; + position: static !important; + right: auto !important; + text-align: left !important; + top: auto !important; + vertical-align: baseline !important; + width: auto !important; + box-sizing: content-box !important; + font-family: "Consolas", "Bitstream Vera Sans Mono", "Courier New", Courier, monospace !important; + font-weight: normal !important; + font-style: normal !important; + font-size: 1em !important; + min-height: inherit !important; + min-height: auto !important; +} + +.syntaxhighlighter { + width: 100% !important; + margin: 1em 0 1em 0 !important; + position: relative !important; + overflow: auto !important; + font-size: 1em !important; +} +.syntaxhighlighter.source { + overflow: hidden !important; +} +.syntaxhighlighter .bold { + font-weight: bold !important; +} +.syntaxhighlighter .italic { + font-style: italic !important; +} +.syntaxhighlighter .line { + white-space: pre !important; +} +.syntaxhighlighter table { + width: 100% !important; +} +.syntaxhighlighter table caption { + text-align: left !important; + padding: .5em 0 0.5em 1em !important; +} +.syntaxhighlighter table td.code { + width: 100% !important; +} +.syntaxhighlighter table td.code .container { + position: relative !important; +} +.syntaxhighlighter table td.code .container textarea { + box-sizing: border-box !important; + position: absolute !important; + left: 0 !important; + top: 0 !important; + width: 100% !important; + height: 100% !important; + border: none !important; + background: white !important; + padding-left: 1em !important; + overflow: hidden !important; + white-space: pre !important; +} +.syntaxhighlighter table td.gutter .line { + text-align: right !important; + padding: 0 0.5em 0 1em !important; +} +.syntaxhighlighter table td.code .line { + padding: 0 1em !important; +} +.syntaxhighlighter.nogutter td.code .container textarea, .syntaxhighlighter.nogutter td.code .line { + padding-left: 0em !important; +} +.syntaxhighlighter.show { + display: block !important; +} +.syntaxhighlighter.collapsed table { + display: none !important; +} +.syntaxhighlighter.collapsed .toolbar { + padding: 0.1em 0.8em 0em 0.8em !important; + font-size: 1em !important; + position: static !important; + width: auto !important; + height: auto !important; +} +.syntaxhighlighter.collapsed .toolbar span { + display: inline !important; + margin-right: 1em !important; +} +.syntaxhighlighter.collapsed .toolbar span a { + padding: 0 !important; + display: none !important; +} +.syntaxhighlighter.collapsed .toolbar span a.expandSource { + display: inline !important; +} +.syntaxhighlighter .toolbar { + position: absolute !important; + right: 1px !important; + top: 1px !important; + width: 11px !important; + height: 11px !important; + font-size: 10px !important; + z-index: 10 !important; +} +.syntaxhighlighter .toolbar span.title { + display: inline !important; +} +.syntaxhighlighter .toolbar a { + display: block !important; + text-align: center !important; + text-decoration: none !important; + padding-top: 1px !important; +} +.syntaxhighlighter .toolbar a.expandSource { + display: none !important; +} +.syntaxhighlighter.ie { + font-size: .9em !important; + padding: 1px 0 1px 0 !important; +} +.syntaxhighlighter.ie .toolbar { + line-height: 8px !important; +} +.syntaxhighlighter.ie .toolbar a { + padding-top: 0px !important; +} +.syntaxhighlighter.printing .line.alt1 .content, +.syntaxhighlighter.printing .line.alt2 .content, +.syntaxhighlighter.printing .line.highlighted .number, +.syntaxhighlighter.printing .line.highlighted.alt1 .content, +.syntaxhighlighter.printing .line.highlighted.alt2 .content { + background: none !important; +} +.syntaxhighlighter.printing .line .number { + color: #bbbbbb !important; +} +.syntaxhighlighter.printing .line .content { + color: black !important; +} +.syntaxhighlighter.printing .toolbar { + display: none !important; +} +.syntaxhighlighter.printing a { + text-decoration: none !important; +} +.syntaxhighlighter.printing .plain, .syntaxhighlighter.printing .plain a { + color: black !important; +} +.syntaxhighlighter.printing .comments, .syntaxhighlighter.printing .comments a { + color: #008200 !important; +} +.syntaxhighlighter.printing .string, .syntaxhighlighter.printing .string a { + color: blue !important; +} +.syntaxhighlighter.printing .keyword { + color: #006699 !important; + font-weight: bold !important; +} +.syntaxhighlighter.printing .preprocessor { + color: gray !important; +} +.syntaxhighlighter.printing .variable { + color: #aa7700 !important; +} +.syntaxhighlighter.printing .value { + color: #009900 !important; +} +.syntaxhighlighter.printing .functions { + color: #ff1493 !important; +} +.syntaxhighlighter.printing .constants { + color: #0066cc !important; +} +.syntaxhighlighter.printing .script { + font-weight: bold !important; +} +.syntaxhighlighter.printing .color1, .syntaxhighlighter.printing .color1 a { + color: gray !important; +} +.syntaxhighlighter.printing .color2, .syntaxhighlighter.printing .color2 a { + color: #ff1493 !important; +} +.syntaxhighlighter.printing .color3, .syntaxhighlighter.printing .color3 a { + color: red !important; +} +.syntaxhighlighter.printing .break, .syntaxhighlighter.printing .break a { + color: black !important; +} + +.syntaxhighlighter { + background-color: white !important; +} +.syntaxhighlighter .line.alt1 { + background-color: white !important; +} +.syntaxhighlighter .line.alt2 { + background-color: white !important; +} +.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 { + background-color: #c3defe !important; +} +.syntaxhighlighter .line.highlighted.number { + color: white !important; +} +.syntaxhighlighter table caption { + color: black !important; +} +.syntaxhighlighter .gutter { + color: #787878 !important; +} +.syntaxhighlighter .gutter .line { + border-right: 3px solid #d4d0c8 !important; +} +.syntaxhighlighter .gutter .line.highlighted { + background-color: #d4d0c8 !important; + color: white !important; +} +.syntaxhighlighter.printing .line .content { + border: none !important; +} +.syntaxhighlighter.collapsed { + overflow: visible !important; +} +.syntaxhighlighter.collapsed .toolbar { + color: #3f5fbf !important; + background: white !important; + border: 1px solid #d4d0c8 !important; +} +.syntaxhighlighter.collapsed .toolbar a { + color: #3f5fbf !important; +} +.syntaxhighlighter.collapsed .toolbar a:hover { + color: #aa7700 !important; +} +.syntaxhighlighter .toolbar { + color: #a0a0a0 !important; + background: #d4d0c8 !important; + border: none !important; +} +.syntaxhighlighter .toolbar a { + color: #a0a0a0 !important; +} +.syntaxhighlighter .toolbar a:hover { + color: red !important; +} +.syntaxhighlighter .plain, .syntaxhighlighter .plain a { + color: black !important; +} +.syntaxhighlighter .comments, .syntaxhighlighter .comments a { + color: #3f5fbf !important; +} +.syntaxhighlighter .string, .syntaxhighlighter .string a { + color: #2a00ff !important; +} +.syntaxhighlighter .keyword { + color: #7f0055 !important; +} +.syntaxhighlighter .preprocessor { + color: #646464 !important; +} +.syntaxhighlighter .variable { + color: #aa7700 !important; +} +.syntaxhighlighter .value { + color: #009900 !important; +} +.syntaxhighlighter .functions { + color: #ff1493 !important; +} +.syntaxhighlighter .constants { + color: #0066cc !important; +} +.syntaxhighlighter .script { + font-weight: bold !important; + color: #7f0055 !important; + background-color: none !important; +} +.syntaxhighlighter .color1, .syntaxhighlighter .color1 a { + color: gray !important; +} +.syntaxhighlighter .color2, .syntaxhighlighter .color2 a { + color: #ff1493 !important; +} +.syntaxhighlighter .color3, .syntaxhighlighter .color3 a { + color: red !important; +} + +.syntaxhighlighter .keyword { + font-weight: bold !important; +} +.syntaxhighlighter .xml .keyword { + color: #3f7f7f !important; + font-weight: normal !important; +} +.syntaxhighlighter .xml .color1, .syntaxhighlighter .xml .color1 a { + color: #7f007f !important; +} +.syntaxhighlighter .xml .string { + font-style: italic !important; + color: #2a00ff !important; +} diff --git a/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreEmacs.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreEmacs.css new file mode 100644 index 0000000000..706c77a0a8 --- /dev/null +++ b/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreEmacs.css @@ -0,0 +1,324 @@ +/** + * SyntaxHighlighter + * http://alexgorbatchev.com/SyntaxHighlighter + * + * SyntaxHighlighter is donationware. If you are using it, please donate. + * http://alexgorbatchev.com/SyntaxHighlighter/donate.html + * + * @version + * 3.0.83 (July 02 2010) + * + * @copyright + * Copyright (C) 2004-2010 Alex Gorbatchev. + * + * @license + * Dual licensed under the MIT and GPL licenses. + */ +.syntaxhighlighter a, +.syntaxhighlighter div, +.syntaxhighlighter code, +.syntaxhighlighter table, +.syntaxhighlighter table td, +.syntaxhighlighter table tr, +.syntaxhighlighter table tbody, +.syntaxhighlighter table thead, +.syntaxhighlighter table caption, +.syntaxhighlighter textarea { + -moz-border-radius: 0 0 0 0 !important; + -webkit-border-radius: 0 0 0 0 !important; + background: none !important; + border: 0 !important; + bottom: auto !important; + float: none !important; + height: auto !important; + left: auto !important; + line-height: 1.1em !important; + margin: 0 !important; + outline: 0 !important; + overflow: visible !important; + padding: 0 !important; + position: static !important; + right: auto !important; + text-align: left !important; + top: auto !important; + vertical-align: baseline !important; + width: auto !important; + box-sizing: content-box !important; + font-family: "Consolas", "Bitstream Vera Sans Mono", "Courier New", Courier, monospace !important; + font-weight: normal !important; + font-style: normal !important; + font-size: 1em !important; + min-height: inherit !important; + min-height: auto !important; +} + +.syntaxhighlighter { + width: 100% !important; + margin: 1em 0 1em 0 !important; + position: relative !important; + overflow: auto !important; + font-size: 1em !important; +} +.syntaxhighlighter.source { + overflow: hidden !important; +} +.syntaxhighlighter .bold { + font-weight: bold !important; +} +.syntaxhighlighter .italic { + font-style: italic !important; +} +.syntaxhighlighter .line { + white-space: pre !important; +} +.syntaxhighlighter table { + width: 100% !important; +} +.syntaxhighlighter table caption { + text-align: left !important; + padding: .5em 0 0.5em 1em !important; +} +.syntaxhighlighter table td.code { + width: 100% !important; +} +.syntaxhighlighter table td.code .container { + position: relative !important; +} +.syntaxhighlighter table td.code .container textarea { + box-sizing: border-box !important; + position: absolute !important; + left: 0 !important; + top: 0 !important; + width: 100% !important; + height: 100% !important; + border: none !important; + background: white !important; + padding-left: 1em !important; + overflow: hidden !important; + white-space: pre !important; +} +.syntaxhighlighter table td.gutter .line { + text-align: right !important; + padding: 0 0.5em 0 1em !important; +} +.syntaxhighlighter table td.code .line { + padding: 0 1em !important; +} +.syntaxhighlighter.nogutter td.code .container textarea, .syntaxhighlighter.nogutter td.code .line { + padding-left: 0em !important; +} +.syntaxhighlighter.show { + display: block !important; +} +.syntaxhighlighter.collapsed table { + display: none !important; +} +.syntaxhighlighter.collapsed .toolbar { + padding: 0.1em 0.8em 0em 0.8em !important; + font-size: 1em !important; + position: static !important; + width: auto !important; + height: auto !important; +} +.syntaxhighlighter.collapsed .toolbar span { + display: inline !important; + margin-right: 1em !important; +} +.syntaxhighlighter.collapsed .toolbar span a { + padding: 0 !important; + display: none !important; +} +.syntaxhighlighter.collapsed .toolbar span a.expandSource { + display: inline !important; +} +.syntaxhighlighter .toolbar { + position: absolute !important; + right: 1px !important; + top: 1px !important; + width: 11px !important; + height: 11px !important; + font-size: 10px !important; + z-index: 10 !important; +} +.syntaxhighlighter .toolbar span.title { + display: inline !important; +} +.syntaxhighlighter .toolbar a { + display: block !important; + text-align: center !important; + text-decoration: none !important; + padding-top: 1px !important; +} +.syntaxhighlighter .toolbar a.expandSource { + display: none !important; +} +.syntaxhighlighter.ie { + font-size: .9em !important; + padding: 1px 0 1px 0 !important; +} +.syntaxhighlighter.ie .toolbar { + line-height: 8px !important; +} +.syntaxhighlighter.ie .toolbar a { + padding-top: 0px !important; +} +.syntaxhighlighter.printing .line.alt1 .content, +.syntaxhighlighter.printing .line.alt2 .content, +.syntaxhighlighter.printing .line.highlighted .number, +.syntaxhighlighter.printing .line.highlighted.alt1 .content, +.syntaxhighlighter.printing .line.highlighted.alt2 .content { + background: none !important; +} +.syntaxhighlighter.printing .line .number { + color: #bbbbbb !important; +} +.syntaxhighlighter.printing .line .content { + color: black !important; +} +.syntaxhighlighter.printing .toolbar { + display: none !important; +} +.syntaxhighlighter.printing a { + text-decoration: none !important; +} +.syntaxhighlighter.printing .plain, .syntaxhighlighter.printing .plain a { + color: black !important; +} +.syntaxhighlighter.printing .comments, .syntaxhighlighter.printing .comments a { + color: #008200 !important; +} +.syntaxhighlighter.printing .string, .syntaxhighlighter.printing .string a { + color: blue !important; +} +.syntaxhighlighter.printing .keyword { + color: #006699 !important; + font-weight: bold !important; +} +.syntaxhighlighter.printing .preprocessor { + color: gray !important; +} +.syntaxhighlighter.printing .variable { + color: #aa7700 !important; +} +.syntaxhighlighter.printing .value { + color: #009900 !important; +} +.syntaxhighlighter.printing .functions { + color: #ff1493 !important; +} +.syntaxhighlighter.printing .constants { + color: #0066cc !important; +} +.syntaxhighlighter.printing .script { + font-weight: bold !important; +} +.syntaxhighlighter.printing .color1, .syntaxhighlighter.printing .color1 a { + color: gray !important; +} +.syntaxhighlighter.printing .color2, .syntaxhighlighter.printing .color2 a { + color: #ff1493 !important; +} +.syntaxhighlighter.printing .color3, .syntaxhighlighter.printing .color3 a { + color: red !important; +} +.syntaxhighlighter.printing .break, .syntaxhighlighter.printing .break a { + color: black !important; +} + +.syntaxhighlighter { + background-color: black !important; +} +.syntaxhighlighter .line.alt1 { + background-color: black !important; +} +.syntaxhighlighter .line.alt2 { + background-color: black !important; +} +.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 { + background-color: #2a3133 !important; +} +.syntaxhighlighter .line.highlighted.number { + color: white !important; +} +.syntaxhighlighter table caption { + color: #d3d3d3 !important; +} +.syntaxhighlighter .gutter { + color: #d3d3d3 !important; +} +.syntaxhighlighter .gutter .line { + border-right: 3px solid #990000 !important; +} +.syntaxhighlighter .gutter .line.highlighted { + background-color: #990000 !important; + color: black !important; +} +.syntaxhighlighter.printing .line .content { + border: none !important; +} +.syntaxhighlighter.collapsed { + overflow: visible !important; +} +.syntaxhighlighter.collapsed .toolbar { + color: #ebdb8d !important; + background: black !important; + border: 1px solid #990000 !important; +} +.syntaxhighlighter.collapsed .toolbar a { + color: #ebdb8d !important; +} +.syntaxhighlighter.collapsed .toolbar a:hover { + color: #ff7d27 !important; +} +.syntaxhighlighter .toolbar { + color: white !important; + background: #990000 !important; + border: none !important; +} +.syntaxhighlighter .toolbar a { + color: white !important; +} +.syntaxhighlighter .toolbar a:hover { + color: #9ccff4 !important; +} +.syntaxhighlighter .plain, .syntaxhighlighter .plain a { + color: #d3d3d3 !important; +} +.syntaxhighlighter .comments, .syntaxhighlighter .comments a { + color: #ff7d27 !important; +} +.syntaxhighlighter .string, .syntaxhighlighter .string a { + color: #ff9e7b !important; +} +.syntaxhighlighter .keyword { + color: aqua !important; +} +.syntaxhighlighter .preprocessor { + color: #aec4de !important; +} +.syntaxhighlighter .variable { + color: #ffaa3e !important; +} +.syntaxhighlighter .value { + color: #009900 !important; +} +.syntaxhighlighter .functions { + color: #81cef9 !important; +} +.syntaxhighlighter .constants { + color: #ff9e7b !important; +} +.syntaxhighlighter .script { + font-weight: bold !important; + color: aqua !important; + background-color: none !important; +} +.syntaxhighlighter .color1, .syntaxhighlighter .color1 a { + color: #ebdb8d !important; +} +.syntaxhighlighter .color2, .syntaxhighlighter .color2 a { + color: #ff7d27 !important; +} +.syntaxhighlighter .color3, .syntaxhighlighter .color3 a { + color: #aec4de !important; +} diff --git a/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css new file mode 100644 index 0000000000..6101eba51f --- /dev/null +++ b/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css @@ -0,0 +1,328 @@ +/** + * SyntaxHighlighter + * http://alexgorbatchev.com/SyntaxHighlighter + * + * SyntaxHighlighter is donationware. If you are using it, please donate. + * http://alexgorbatchev.com/SyntaxHighlighter/donate.html + * + * @version + * 3.0.83 (July 02 2010) + * + * @copyright + * Copyright (C) 2004-2010 Alex Gorbatchev. + * + * @license + * Dual licensed under the MIT and GPL licenses. + */ +.syntaxhighlighter a, +.syntaxhighlighter div, +.syntaxhighlighter code, +.syntaxhighlighter table, +.syntaxhighlighter table td, +.syntaxhighlighter table tr, +.syntaxhighlighter table tbody, +.syntaxhighlighter table thead, +.syntaxhighlighter table caption, +.syntaxhighlighter textarea { + -moz-border-radius: 0 0 0 0 !important; + -webkit-border-radius: 0 0 0 0 !important; + background: none !important; + border: 0 !important; + bottom: auto !important; + float: none !important; + height: auto !important; + left: auto !important; + line-height: 1.1em !important; + margin: 0 !important; + outline: 0 !important; + overflow: visible !important; + padding: 0 !important; + position: static !important; + right: auto !important; + text-align: left !important; + top: auto !important; + vertical-align: baseline !important; + width: auto !important; + box-sizing: content-box !important; + font-family: "Consolas", "Bitstream Vera Sans Mono", "Courier New", Courier, monospace !important; + font-weight: normal !important; + font-style: normal !important; + font-size: 1em !important; + min-height: inherit !important; + min-height: auto !important; +} + +.syntaxhighlighter { + width: 100% !important; + margin: 1em 0 1em 0 !important; + position: relative !important; + overflow: auto !important; + font-size: 1em !important; +} +.syntaxhighlighter.source { + overflow: hidden !important; +} +.syntaxhighlighter .bold { + font-weight: bold !important; +} +.syntaxhighlighter .italic { + font-style: italic !important; +} +.syntaxhighlighter .line { + white-space: pre !important; +} +.syntaxhighlighter table { + width: 100% !important; +} +.syntaxhighlighter table caption { + text-align: left !important; + padding: .5em 0 0.5em 1em !important; +} +.syntaxhighlighter table td.code { + width: 100% !important; +} +.syntaxhighlighter table td.code .container { + position: relative !important; +} +.syntaxhighlighter table td.code .container textarea { + box-sizing: border-box !important; + position: absolute !important; + left: 0 !important; + top: 0 !important; + width: 100% !important; + height: 100% !important; + border: none !important; + background: white !important; + padding-left: 1em !important; + overflow: hidden !important; + white-space: pre !important; +} +.syntaxhighlighter table td.gutter .line { + text-align: right !important; + padding: 0 0.5em 0 1em !important; +} +.syntaxhighlighter table td.code .line { + padding: 0 1em !important; +} +.syntaxhighlighter.nogutter td.code .container textarea, .syntaxhighlighter.nogutter td.code .line { + padding-left: 0em !important; +} +.syntaxhighlighter.show { + display: block !important; +} +.syntaxhighlighter.collapsed table { + display: none !important; +} +.syntaxhighlighter.collapsed .toolbar { + padding: 0.1em 0.8em 0em 0.8em !important; + font-size: 1em !important; + position: static !important; + width: auto !important; + height: auto !important; +} +.syntaxhighlighter.collapsed .toolbar span { + display: inline !important; + margin-right: 1em !important; +} +.syntaxhighlighter.collapsed .toolbar span a { + padding: 0 !important; + display: none !important; +} +.syntaxhighlighter.collapsed .toolbar span a.expandSource { + display: inline !important; +} +.syntaxhighlighter .toolbar { + position: absolute !important; + right: 1px !important; + top: 1px !important; + width: 11px !important; + height: 11px !important; + font-size: 10px !important; + z-index: 10 !important; +} +.syntaxhighlighter .toolbar span.title { + display: inline !important; +} +.syntaxhighlighter .toolbar a { + display: block !important; + text-align: center !important; + text-decoration: none !important; + padding-top: 1px !important; +} +.syntaxhighlighter .toolbar a.expandSource { + display: none !important; +} +.syntaxhighlighter.ie { + font-size: .9em !important; + padding: 1px 0 1px 0 !important; +} +.syntaxhighlighter.ie .toolbar { + line-height: 8px !important; +} +.syntaxhighlighter.ie .toolbar a { + padding-top: 0px !important; +} +.syntaxhighlighter.printing .line.alt1 .content, +.syntaxhighlighter.printing .line.alt2 .content, +.syntaxhighlighter.printing .line.highlighted .number, +.syntaxhighlighter.printing .line.highlighted.alt1 .content, +.syntaxhighlighter.printing .line.highlighted.alt2 .content { + background: none !important; +} +.syntaxhighlighter.printing .line .number { + color: #bbbbbb !important; +} +.syntaxhighlighter.printing .line .content { + color: black !important; +} +.syntaxhighlighter.printing .toolbar { + display: none !important; +} +.syntaxhighlighter.printing a { + text-decoration: none !important; +} +.syntaxhighlighter.printing .plain, .syntaxhighlighter.printing .plain a { + color: black !important; +} +.syntaxhighlighter.printing .comments, .syntaxhighlighter.printing .comments a { + color: #008200 !important; +} +.syntaxhighlighter.printing .string, .syntaxhighlighter.printing .string a { + color: blue !important; +} +.syntaxhighlighter.printing .keyword { + color: #006699 !important; + font-weight: bold !important; +} +.syntaxhighlighter.printing .preprocessor { + color: gray !important; +} +.syntaxhighlighter.printing .variable { + color: #aa7700 !important; +} +.syntaxhighlighter.printing .value { + color: #009900 !important; +} +.syntaxhighlighter.printing .functions { + color: #ff1493 !important; +} +.syntaxhighlighter.printing .constants { + color: #0066cc !important; +} +.syntaxhighlighter.printing .script { + font-weight: bold !important; +} +.syntaxhighlighter.printing .color1, .syntaxhighlighter.printing .color1 a { + color: gray !important; +} +.syntaxhighlighter.printing .color2, .syntaxhighlighter.printing .color2 a { + color: #ff1493 !important; +} +.syntaxhighlighter.printing .color3, .syntaxhighlighter.printing .color3 a { + color: red !important; +} +.syntaxhighlighter.printing .break, .syntaxhighlighter.printing .break a { + color: black !important; +} + +.syntaxhighlighter { + background-color: #121212 !important; +} +.syntaxhighlighter .line.alt1 { + background-color: #121212 !important; +} +.syntaxhighlighter .line.alt2 { + background-color: #121212 !important; +} +.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 { + background-color: #2c2c29 !important; +} +.syntaxhighlighter .line.highlighted.number { + color: white !important; +} +.syntaxhighlighter table caption { + color: white !important; +} +.syntaxhighlighter .gutter { + color: #afafaf !important; +} +.syntaxhighlighter .gutter .line { + border-right: 3px solid #3185b9 !important; +} +.syntaxhighlighter .gutter .line.highlighted { + background-color: #3185b9 !important; + color: #121212 !important; +} +.syntaxhighlighter.printing .line .content { + border: none !important; +} +.syntaxhighlighter.collapsed { + overflow: visible !important; +} +.syntaxhighlighter.collapsed .toolbar { + color: #3185b9 !important; + background: black !important; + border: 1px solid #3185b9 !important; +} +.syntaxhighlighter.collapsed .toolbar a { + color: #3185b9 !important; +} +.syntaxhighlighter.collapsed .toolbar a:hover { + color: #d01d33 !important; +} +.syntaxhighlighter .toolbar { + color: white !important; + background: #3185b9 !important; + border: none !important; +} +.syntaxhighlighter .toolbar a { + color: white !important; +} +.syntaxhighlighter .toolbar a:hover { + color: #96daff !important; +} +.syntaxhighlighter .plain, .syntaxhighlighter .plain a { + color: white !important; +} +.syntaxhighlighter .comments, .syntaxhighlighter .comments a { + color: #696854 !important; +} +.syntaxhighlighter .string, .syntaxhighlighter .string a { + color: #e3e658 !important; +} +.syntaxhighlighter .keyword { + color: #d01d33 !important; +} +.syntaxhighlighter .preprocessor { + color: #435a5f !important; +} +.syntaxhighlighter .variable { + color: #898989 !important; +} +.syntaxhighlighter .value { + color: #009900 !important; +} +.syntaxhighlighter .functions { + color: #aaaaaa !important; +} +.syntaxhighlighter .constants { + color: #96daff !important; +} +.syntaxhighlighter .script { + font-weight: bold !important; + color: #d01d33 !important; + background-color: none !important; +} +.syntaxhighlighter .color1, .syntaxhighlighter .color1 a { + color: #ffc074 !important; +} +.syntaxhighlighter .color2, .syntaxhighlighter .color2 a { + color: #4a8cdb !important; +} +.syntaxhighlighter .color3, .syntaxhighlighter .color3 a { + color: #96daff !important; +} + +.syntaxhighlighter .functions { + font-weight: bold !important; +} diff --git a/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreMDUltra.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreMDUltra.css new file mode 100644 index 0000000000..2923ce7367 --- /dev/null +++ b/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreMDUltra.css @@ -0,0 +1,324 @@ +/** + * SyntaxHighlighter + * http://alexgorbatchev.com/SyntaxHighlighter + * + * SyntaxHighlighter is donationware. If you are using it, please donate. + * http://alexgorbatchev.com/SyntaxHighlighter/donate.html + * + * @version + * 3.0.83 (July 02 2010) + * + * @copyright + * Copyright (C) 2004-2010 Alex Gorbatchev. + * + * @license + * Dual licensed under the MIT and GPL licenses. + */ +.syntaxhighlighter a, +.syntaxhighlighter div, +.syntaxhighlighter code, +.syntaxhighlighter table, +.syntaxhighlighter table td, +.syntaxhighlighter table tr, +.syntaxhighlighter table tbody, +.syntaxhighlighter table thead, +.syntaxhighlighter table caption, +.syntaxhighlighter textarea { + -moz-border-radius: 0 0 0 0 !important; + -webkit-border-radius: 0 0 0 0 !important; + background: none !important; + border: 0 !important; + bottom: auto !important; + float: none !important; + height: auto !important; + left: auto !important; + line-height: 1.1em !important; + margin: 0 !important; + outline: 0 !important; + overflow: visible !important; + padding: 0 !important; + position: static !important; + right: auto !important; + text-align: left !important; + top: auto !important; + vertical-align: baseline !important; + width: auto !important; + box-sizing: content-box !important; + font-family: "Consolas", "Bitstream Vera Sans Mono", "Courier New", Courier, monospace !important; + font-weight: normal !important; + font-style: normal !important; + font-size: 1em !important; + min-height: inherit !important; + min-height: auto !important; +} + +.syntaxhighlighter { + width: 100% !important; + margin: 1em 0 1em 0 !important; + position: relative !important; + overflow: auto !important; + font-size: 1em !important; +} +.syntaxhighlighter.source { + overflow: hidden !important; +} +.syntaxhighlighter .bold { + font-weight: bold !important; +} +.syntaxhighlighter .italic { + font-style: italic !important; +} +.syntaxhighlighter .line { + white-space: pre !important; +} +.syntaxhighlighter table { + width: 100% !important; +} +.syntaxhighlighter table caption { + text-align: left !important; + padding: .5em 0 0.5em 1em !important; +} +.syntaxhighlighter table td.code { + width: 100% !important; +} +.syntaxhighlighter table td.code .container { + position: relative !important; +} +.syntaxhighlighter table td.code .container textarea { + box-sizing: border-box !important; + position: absolute !important; + left: 0 !important; + top: 0 !important; + width: 100% !important; + height: 100% !important; + border: none !important; + background: white !important; + padding-left: 1em !important; + overflow: hidden !important; + white-space: pre !important; +} +.syntaxhighlighter table td.gutter .line { + text-align: right !important; + padding: 0 0.5em 0 1em !important; +} +.syntaxhighlighter table td.code .line { + padding: 0 1em !important; +} +.syntaxhighlighter.nogutter td.code .container textarea, .syntaxhighlighter.nogutter td.code .line { + padding-left: 0em !important; +} +.syntaxhighlighter.show { + display: block !important; +} +.syntaxhighlighter.collapsed table { + display: none !important; +} +.syntaxhighlighter.collapsed .toolbar { + padding: 0.1em 0.8em 0em 0.8em !important; + font-size: 1em !important; + position: static !important; + width: auto !important; + height: auto !important; +} +.syntaxhighlighter.collapsed .toolbar span { + display: inline !important; + margin-right: 1em !important; +} +.syntaxhighlighter.collapsed .toolbar span a { + padding: 0 !important; + display: none !important; +} +.syntaxhighlighter.collapsed .toolbar span a.expandSource { + display: inline !important; +} +.syntaxhighlighter .toolbar { + position: absolute !important; + right: 1px !important; + top: 1px !important; + width: 11px !important; + height: 11px !important; + font-size: 10px !important; + z-index: 10 !important; +} +.syntaxhighlighter .toolbar span.title { + display: inline !important; +} +.syntaxhighlighter .toolbar a { + display: block !important; + text-align: center !important; + text-decoration: none !important; + padding-top: 1px !important; +} +.syntaxhighlighter .toolbar a.expandSource { + display: none !important; +} +.syntaxhighlighter.ie { + font-size: .9em !important; + padding: 1px 0 1px 0 !important; +} +.syntaxhighlighter.ie .toolbar { + line-height: 8px !important; +} +.syntaxhighlighter.ie .toolbar a { + padding-top: 0px !important; +} +.syntaxhighlighter.printing .line.alt1 .content, +.syntaxhighlighter.printing .line.alt2 .content, +.syntaxhighlighter.printing .line.highlighted .number, +.syntaxhighlighter.printing .line.highlighted.alt1 .content, +.syntaxhighlighter.printing .line.highlighted.alt2 .content { + background: none !important; +} +.syntaxhighlighter.printing .line .number { + color: #bbbbbb !important; +} +.syntaxhighlighter.printing .line .content { + color: black !important; +} +.syntaxhighlighter.printing .toolbar { + display: none !important; +} +.syntaxhighlighter.printing a { + text-decoration: none !important; +} +.syntaxhighlighter.printing .plain, .syntaxhighlighter.printing .plain a { + color: black !important; +} +.syntaxhighlighter.printing .comments, .syntaxhighlighter.printing .comments a { + color: #008200 !important; +} +.syntaxhighlighter.printing .string, .syntaxhighlighter.printing .string a { + color: blue !important; +} +.syntaxhighlighter.printing .keyword { + color: #006699 !important; + font-weight: bold !important; +} +.syntaxhighlighter.printing .preprocessor { + color: gray !important; +} +.syntaxhighlighter.printing .variable { + color: #aa7700 !important; +} +.syntaxhighlighter.printing .value { + color: #009900 !important; +} +.syntaxhighlighter.printing .functions { + color: #ff1493 !important; +} +.syntaxhighlighter.printing .constants { + color: #0066cc !important; +} +.syntaxhighlighter.printing .script { + font-weight: bold !important; +} +.syntaxhighlighter.printing .color1, .syntaxhighlighter.printing .color1 a { + color: gray !important; +} +.syntaxhighlighter.printing .color2, .syntaxhighlighter.printing .color2 a { + color: #ff1493 !important; +} +.syntaxhighlighter.printing .color3, .syntaxhighlighter.printing .color3 a { + color: red !important; +} +.syntaxhighlighter.printing .break, .syntaxhighlighter.printing .break a { + color: black !important; +} + +.syntaxhighlighter { + background-color: #222222 !important; +} +.syntaxhighlighter .line.alt1 { + background-color: #222222 !important; +} +.syntaxhighlighter .line.alt2 { + background-color: #222222 !important; +} +.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 { + background-color: #253e5a !important; +} +.syntaxhighlighter .line.highlighted.number { + color: white !important; +} +.syntaxhighlighter table caption { + color: lime !important; +} +.syntaxhighlighter .gutter { + color: #38566f !important; +} +.syntaxhighlighter .gutter .line { + border-right: 3px solid #435a5f !important; +} +.syntaxhighlighter .gutter .line.highlighted { + background-color: #435a5f !important; + color: #222222 !important; +} +.syntaxhighlighter.printing .line .content { + border: none !important; +} +.syntaxhighlighter.collapsed { + overflow: visible !important; +} +.syntaxhighlighter.collapsed .toolbar { + color: #428bdd !important; + background: black !important; + border: 1px solid #435a5f !important; +} +.syntaxhighlighter.collapsed .toolbar a { + color: #428bdd !important; +} +.syntaxhighlighter.collapsed .toolbar a:hover { + color: lime !important; +} +.syntaxhighlighter .toolbar { + color: #aaaaff !important; + background: #435a5f !important; + border: none !important; +} +.syntaxhighlighter .toolbar a { + color: #aaaaff !important; +} +.syntaxhighlighter .toolbar a:hover { + color: #9ccff4 !important; +} +.syntaxhighlighter .plain, .syntaxhighlighter .plain a { + color: lime !important; +} +.syntaxhighlighter .comments, .syntaxhighlighter .comments a { + color: #428bdd !important; +} +.syntaxhighlighter .string, .syntaxhighlighter .string a { + color: lime !important; +} +.syntaxhighlighter .keyword { + color: #aaaaff !important; +} +.syntaxhighlighter .preprocessor { + color: #8aa6c1 !important; +} +.syntaxhighlighter .variable { + color: aqua !important; +} +.syntaxhighlighter .value { + color: #f7e741 !important; +} +.syntaxhighlighter .functions { + color: #ff8000 !important; +} +.syntaxhighlighter .constants { + color: yellow !important; +} +.syntaxhighlighter .script { + font-weight: bold !important; + color: #aaaaff !important; + background-color: none !important; +} +.syntaxhighlighter .color1, .syntaxhighlighter .color1 a { + color: red !important; +} +.syntaxhighlighter .color2, .syntaxhighlighter .color2 a { + color: yellow !important; +} +.syntaxhighlighter .color3, .syntaxhighlighter .color3 a { + color: #ffaa3e !important; +} diff --git a/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreMidnight.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreMidnight.css new file mode 100644 index 0000000000..e3733eed56 --- /dev/null +++ b/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreMidnight.css @@ -0,0 +1,324 @@ +/** + * SyntaxHighlighter + * http://alexgorbatchev.com/SyntaxHighlighter + * + * SyntaxHighlighter is donationware. If you are using it, please donate. + * http://alexgorbatchev.com/SyntaxHighlighter/donate.html + * + * @version + * 3.0.83 (July 02 2010) + * + * @copyright + * Copyright (C) 2004-2010 Alex Gorbatchev. + * + * @license + * Dual licensed under the MIT and GPL licenses. + */ +.syntaxhighlighter a, +.syntaxhighlighter div, +.syntaxhighlighter code, +.syntaxhighlighter table, +.syntaxhighlighter table td, +.syntaxhighlighter table tr, +.syntaxhighlighter table tbody, +.syntaxhighlighter table thead, +.syntaxhighlighter table caption, +.syntaxhighlighter textarea { + -moz-border-radius: 0 0 0 0 !important; + -webkit-border-radius: 0 0 0 0 !important; + background: none !important; + border: 0 !important; + bottom: auto !important; + float: none !important; + height: auto !important; + left: auto !important; + line-height: 1.1em !important; + margin: 0 !important; + outline: 0 !important; + overflow: visible !important; + padding: 0 !important; + position: static !important; + right: auto !important; + text-align: left !important; + top: auto !important; + vertical-align: baseline !important; + width: auto !important; + box-sizing: content-box !important; + font-family: "Consolas", "Bitstream Vera Sans Mono", "Courier New", Courier, monospace !important; + font-weight: normal !important; + font-style: normal !important; + font-size: 1em !important; + min-height: inherit !important; + min-height: auto !important; +} + +.syntaxhighlighter { + width: 100% !important; + margin: 1em 0 1em 0 !important; + position: relative !important; + overflow: auto !important; + font-size: 1em !important; +} +.syntaxhighlighter.source { + overflow: hidden !important; +} +.syntaxhighlighter .bold { + font-weight: bold !important; +} +.syntaxhighlighter .italic { + font-style: italic !important; +} +.syntaxhighlighter .line { + white-space: pre !important; +} +.syntaxhighlighter table { + width: 100% !important; +} +.syntaxhighlighter table caption { + text-align: left !important; + padding: .5em 0 0.5em 1em !important; +} +.syntaxhighlighter table td.code { + width: 100% !important; +} +.syntaxhighlighter table td.code .container { + position: relative !important; +} +.syntaxhighlighter table td.code .container textarea { + box-sizing: border-box !important; + position: absolute !important; + left: 0 !important; + top: 0 !important; + width: 100% !important; + height: 100% !important; + border: none !important; + background: white !important; + padding-left: 1em !important; + overflow: hidden !important; + white-space: pre !important; +} +.syntaxhighlighter table td.gutter .line { + text-align: right !important; + padding: 0 0.5em 0 1em !important; +} +.syntaxhighlighter table td.code .line { + padding: 0 1em !important; +} +.syntaxhighlighter.nogutter td.code .container textarea, .syntaxhighlighter.nogutter td.code .line { + padding-left: 0em !important; +} +.syntaxhighlighter.show { + display: block !important; +} +.syntaxhighlighter.collapsed table { + display: none !important; +} +.syntaxhighlighter.collapsed .toolbar { + padding: 0.1em 0.8em 0em 0.8em !important; + font-size: 1em !important; + position: static !important; + width: auto !important; + height: auto !important; +} +.syntaxhighlighter.collapsed .toolbar span { + display: inline !important; + margin-right: 1em !important; +} +.syntaxhighlighter.collapsed .toolbar span a { + padding: 0 !important; + display: none !important; +} +.syntaxhighlighter.collapsed .toolbar span a.expandSource { + display: inline !important; +} +.syntaxhighlighter .toolbar { + position: absolute !important; + right: 1px !important; + top: 1px !important; + width: 11px !important; + height: 11px !important; + font-size: 10px !important; + z-index: 10 !important; +} +.syntaxhighlighter .toolbar span.title { + display: inline !important; +} +.syntaxhighlighter .toolbar a { + display: block !important; + text-align: center !important; + text-decoration: none !important; + padding-top: 1px !important; +} +.syntaxhighlighter .toolbar a.expandSource { + display: none !important; +} +.syntaxhighlighter.ie { + font-size: .9em !important; + padding: 1px 0 1px 0 !important; +} +.syntaxhighlighter.ie .toolbar { + line-height: 8px !important; +} +.syntaxhighlighter.ie .toolbar a { + padding-top: 0px !important; +} +.syntaxhighlighter.printing .line.alt1 .content, +.syntaxhighlighter.printing .line.alt2 .content, +.syntaxhighlighter.printing .line.highlighted .number, +.syntaxhighlighter.printing .line.highlighted.alt1 .content, +.syntaxhighlighter.printing .line.highlighted.alt2 .content { + background: none !important; +} +.syntaxhighlighter.printing .line .number { + color: #bbbbbb !important; +} +.syntaxhighlighter.printing .line .content { + color: black !important; +} +.syntaxhighlighter.printing .toolbar { + display: none !important; +} +.syntaxhighlighter.printing a { + text-decoration: none !important; +} +.syntaxhighlighter.printing .plain, .syntaxhighlighter.printing .plain a { + color: black !important; +} +.syntaxhighlighter.printing .comments, .syntaxhighlighter.printing .comments a { + color: #008200 !important; +} +.syntaxhighlighter.printing .string, .syntaxhighlighter.printing .string a { + color: blue !important; +} +.syntaxhighlighter.printing .keyword { + color: #006699 !important; + font-weight: bold !important; +} +.syntaxhighlighter.printing .preprocessor { + color: gray !important; +} +.syntaxhighlighter.printing .variable { + color: #aa7700 !important; +} +.syntaxhighlighter.printing .value { + color: #009900 !important; +} +.syntaxhighlighter.printing .functions { + color: #ff1493 !important; +} +.syntaxhighlighter.printing .constants { + color: #0066cc !important; +} +.syntaxhighlighter.printing .script { + font-weight: bold !important; +} +.syntaxhighlighter.printing .color1, .syntaxhighlighter.printing .color1 a { + color: gray !important; +} +.syntaxhighlighter.printing .color2, .syntaxhighlighter.printing .color2 a { + color: #ff1493 !important; +} +.syntaxhighlighter.printing .color3, .syntaxhighlighter.printing .color3 a { + color: red !important; +} +.syntaxhighlighter.printing .break, .syntaxhighlighter.printing .break a { + color: black !important; +} + +.syntaxhighlighter { + background-color: #0f192a !important; +} +.syntaxhighlighter .line.alt1 { + background-color: #0f192a !important; +} +.syntaxhighlighter .line.alt2 { + background-color: #0f192a !important; +} +.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 { + background-color: #253e5a !important; +} +.syntaxhighlighter .line.highlighted.number { + color: #38566f !important; +} +.syntaxhighlighter table caption { + color: #d1edff !important; +} +.syntaxhighlighter .gutter { + color: #afafaf !important; +} +.syntaxhighlighter .gutter .line { + border-right: 3px solid #435a5f !important; +} +.syntaxhighlighter .gutter .line.highlighted { + background-color: #435a5f !important; + color: #0f192a !important; +} +.syntaxhighlighter.printing .line .content { + border: none !important; +} +.syntaxhighlighter.collapsed { + overflow: visible !important; +} +.syntaxhighlighter.collapsed .toolbar { + color: #428bdd !important; + background: black !important; + border: 1px solid #435a5f !important; +} +.syntaxhighlighter.collapsed .toolbar a { + color: #428bdd !important; +} +.syntaxhighlighter.collapsed .toolbar a:hover { + color: #1dc116 !important; +} +.syntaxhighlighter .toolbar { + color: #d1edff !important; + background: #435a5f !important; + border: none !important; +} +.syntaxhighlighter .toolbar a { + color: #d1edff !important; +} +.syntaxhighlighter .toolbar a:hover { + color: #8aa6c1 !important; +} +.syntaxhighlighter .plain, .syntaxhighlighter .plain a { + color: #d1edff !important; +} +.syntaxhighlighter .comments, .syntaxhighlighter .comments a { + color: #428bdd !important; +} +.syntaxhighlighter .string, .syntaxhighlighter .string a { + color: #1dc116 !important; +} +.syntaxhighlighter .keyword { + color: #b43d3d !important; +} +.syntaxhighlighter .preprocessor { + color: #8aa6c1 !important; +} +.syntaxhighlighter .variable { + color: #ffaa3e !important; +} +.syntaxhighlighter .value { + color: #f7e741 !important; +} +.syntaxhighlighter .functions { + color: #ffaa3e !important; +} +.syntaxhighlighter .constants { + color: #e0e8ff !important; +} +.syntaxhighlighter .script { + font-weight: bold !important; + color: #b43d3d !important; + background-color: none !important; +} +.syntaxhighlighter .color1, .syntaxhighlighter .color1 a { + color: #f8bb00 !important; +} +.syntaxhighlighter .color2, .syntaxhighlighter .color2 a { + color: white !important; +} +.syntaxhighlighter .color3, .syntaxhighlighter .color3 a { + color: #ffaa3e !important; +} diff --git a/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreRDark.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreRDark.css new file mode 100644 index 0000000000..d09368384d --- /dev/null +++ b/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreRDark.css @@ -0,0 +1,324 @@ +/** + * SyntaxHighlighter + * http://alexgorbatchev.com/SyntaxHighlighter + * + * SyntaxHighlighter is donationware. If you are using it, please donate. + * http://alexgorbatchev.com/SyntaxHighlighter/donate.html + * + * @version + * 3.0.83 (July 02 2010) + * + * @copyright + * Copyright (C) 2004-2010 Alex Gorbatchev. + * + * @license + * Dual licensed under the MIT and GPL licenses. + */ +.syntaxhighlighter a, +.syntaxhighlighter div, +.syntaxhighlighter code, +.syntaxhighlighter table, +.syntaxhighlighter table td, +.syntaxhighlighter table tr, +.syntaxhighlighter table tbody, +.syntaxhighlighter table thead, +.syntaxhighlighter table caption, +.syntaxhighlighter textarea { + -moz-border-radius: 0 0 0 0 !important; + -webkit-border-radius: 0 0 0 0 !important; + background: none !important; + border: 0 !important; + bottom: auto !important; + float: none !important; + height: auto !important; + left: auto !important; + line-height: 1.1em !important; + margin: 0 !important; + outline: 0 !important; + overflow: visible !important; + padding: 0 !important; + position: static !important; + right: auto !important; + text-align: left !important; + top: auto !important; + vertical-align: baseline !important; + width: auto !important; + box-sizing: content-box !important; + font-family: "Consolas", "Bitstream Vera Sans Mono", "Courier New", Courier, monospace !important; + font-weight: normal !important; + font-style: normal !important; + font-size: 1em !important; + min-height: inherit !important; + min-height: auto !important; +} + +.syntaxhighlighter { + width: 100% !important; + margin: 1em 0 1em 0 !important; + position: relative !important; + overflow: auto !important; + font-size: 1em !important; +} +.syntaxhighlighter.source { + overflow: hidden !important; +} +.syntaxhighlighter .bold { + font-weight: bold !important; +} +.syntaxhighlighter .italic { + font-style: italic !important; +} +.syntaxhighlighter .line { + white-space: pre !important; +} +.syntaxhighlighter table { + width: 100% !important; +} +.syntaxhighlighter table caption { + text-align: left !important; + padding: .5em 0 0.5em 1em !important; +} +.syntaxhighlighter table td.code { + width: 100% !important; +} +.syntaxhighlighter table td.code .container { + position: relative !important; +} +.syntaxhighlighter table td.code .container textarea { + box-sizing: border-box !important; + position: absolute !important; + left: 0 !important; + top: 0 !important; + width: 100% !important; + height: 100% !important; + border: none !important; + background: white !important; + padding-left: 1em !important; + overflow: hidden !important; + white-space: pre !important; +} +.syntaxhighlighter table td.gutter .line { + text-align: right !important; + padding: 0 0.5em 0 1em !important; +} +.syntaxhighlighter table td.code .line { + padding: 0 1em !important; +} +.syntaxhighlighter.nogutter td.code .container textarea, .syntaxhighlighter.nogutter td.code .line { + padding-left: 0em !important; +} +.syntaxhighlighter.show { + display: block !important; +} +.syntaxhighlighter.collapsed table { + display: none !important; +} +.syntaxhighlighter.collapsed .toolbar { + padding: 0.1em 0.8em 0em 0.8em !important; + font-size: 1em !important; + position: static !important; + width: auto !important; + height: auto !important; +} +.syntaxhighlighter.collapsed .toolbar span { + display: inline !important; + margin-right: 1em !important; +} +.syntaxhighlighter.collapsed .toolbar span a { + padding: 0 !important; + display: none !important; +} +.syntaxhighlighter.collapsed .toolbar span a.expandSource { + display: inline !important; +} +.syntaxhighlighter .toolbar { + position: absolute !important; + right: 1px !important; + top: 1px !important; + width: 11px !important; + height: 11px !important; + font-size: 10px !important; + z-index: 10 !important; +} +.syntaxhighlighter .toolbar span.title { + display: inline !important; +} +.syntaxhighlighter .toolbar a { + display: block !important; + text-align: center !important; + text-decoration: none !important; + padding-top: 1px !important; +} +.syntaxhighlighter .toolbar a.expandSource { + display: none !important; +} +.syntaxhighlighter.ie { + font-size: .9em !important; + padding: 1px 0 1px 0 !important; +} +.syntaxhighlighter.ie .toolbar { + line-height: 8px !important; +} +.syntaxhighlighter.ie .toolbar a { + padding-top: 0px !important; +} +.syntaxhighlighter.printing .line.alt1 .content, +.syntaxhighlighter.printing .line.alt2 .content, +.syntaxhighlighter.printing .line.highlighted .number, +.syntaxhighlighter.printing .line.highlighted.alt1 .content, +.syntaxhighlighter.printing .line.highlighted.alt2 .content { + background: none !important; +} +.syntaxhighlighter.printing .line .number { + color: #bbbbbb !important; +} +.syntaxhighlighter.printing .line .content { + color: black !important; +} +.syntaxhighlighter.printing .toolbar { + display: none !important; +} +.syntaxhighlighter.printing a { + text-decoration: none !important; +} +.syntaxhighlighter.printing .plain, .syntaxhighlighter.printing .plain a { + color: black !important; +} +.syntaxhighlighter.printing .comments, .syntaxhighlighter.printing .comments a { + color: #008200 !important; +} +.syntaxhighlighter.printing .string, .syntaxhighlighter.printing .string a { + color: blue !important; +} +.syntaxhighlighter.printing .keyword { + color: #006699 !important; + font-weight: bold !important; +} +.syntaxhighlighter.printing .preprocessor { + color: gray !important; +} +.syntaxhighlighter.printing .variable { + color: #aa7700 !important; +} +.syntaxhighlighter.printing .value { + color: #009900 !important; +} +.syntaxhighlighter.printing .functions { + color: #ff1493 !important; +} +.syntaxhighlighter.printing .constants { + color: #0066cc !important; +} +.syntaxhighlighter.printing .script { + font-weight: bold !important; +} +.syntaxhighlighter.printing .color1, .syntaxhighlighter.printing .color1 a { + color: gray !important; +} +.syntaxhighlighter.printing .color2, .syntaxhighlighter.printing .color2 a { + color: #ff1493 !important; +} +.syntaxhighlighter.printing .color3, .syntaxhighlighter.printing .color3 a { + color: red !important; +} +.syntaxhighlighter.printing .break, .syntaxhighlighter.printing .break a { + color: black !important; +} + +.syntaxhighlighter { + background-color: #1b2426 !important; +} +.syntaxhighlighter .line.alt1 { + background-color: #1b2426 !important; +} +.syntaxhighlighter .line.alt2 { + background-color: #1b2426 !important; +} +.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 { + background-color: #323e41 !important; +} +.syntaxhighlighter .line.highlighted.number { + color: #b9bdb6 !important; +} +.syntaxhighlighter table caption { + color: #b9bdb6 !important; +} +.syntaxhighlighter .gutter { + color: #afafaf !important; +} +.syntaxhighlighter .gutter .line { + border-right: 3px solid #435a5f !important; +} +.syntaxhighlighter .gutter .line.highlighted { + background-color: #435a5f !important; + color: #1b2426 !important; +} +.syntaxhighlighter.printing .line .content { + border: none !important; +} +.syntaxhighlighter.collapsed { + overflow: visible !important; +} +.syntaxhighlighter.collapsed .toolbar { + color: #5ba1cf !important; + background: black !important; + border: 1px solid #435a5f !important; +} +.syntaxhighlighter.collapsed .toolbar a { + color: #5ba1cf !important; +} +.syntaxhighlighter.collapsed .toolbar a:hover { + color: #5ce638 !important; +} +.syntaxhighlighter .toolbar { + color: white !important; + background: #435a5f !important; + border: none !important; +} +.syntaxhighlighter .toolbar a { + color: white !important; +} +.syntaxhighlighter .toolbar a:hover { + color: #e0e8ff !important; +} +.syntaxhighlighter .plain, .syntaxhighlighter .plain a { + color: #b9bdb6 !important; +} +.syntaxhighlighter .comments, .syntaxhighlighter .comments a { + color: #878a85 !important; +} +.syntaxhighlighter .string, .syntaxhighlighter .string a { + color: #5ce638 !important; +} +.syntaxhighlighter .keyword { + color: #5ba1cf !important; +} +.syntaxhighlighter .preprocessor { + color: #435a5f !important; +} +.syntaxhighlighter .variable { + color: #ffaa3e !important; +} +.syntaxhighlighter .value { + color: #009900 !important; +} +.syntaxhighlighter .functions { + color: #ffaa3e !important; +} +.syntaxhighlighter .constants { + color: #e0e8ff !important; +} +.syntaxhighlighter .script { + font-weight: bold !important; + color: #5ba1cf !important; + background-color: none !important; +} +.syntaxhighlighter .color1, .syntaxhighlighter .color1 a { + color: #e0e8ff !important; +} +.syntaxhighlighter .color2, .syntaxhighlighter .color2 a { + color: white !important; +} +.syntaxhighlighter .color3, .syntaxhighlighter .color3 a { + color: #ffaa3e !important; +} diff --git a/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeDefault.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeDefault.css new file mode 100644 index 0000000000..136541172d --- /dev/null +++ b/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeDefault.css @@ -0,0 +1,117 @@ +/** + * SyntaxHighlighter + * http://alexgorbatchev.com/SyntaxHighlighter + * + * SyntaxHighlighter is donationware. If you are using it, please donate. + * http://alexgorbatchev.com/SyntaxHighlighter/donate.html + * + * @version + * 3.0.83 (July 02 2010) + * + * @copyright + * Copyright (C) 2004-2010 Alex Gorbatchev. + * + * @license + * Dual licensed under the MIT and GPL licenses. + */ +.syntaxhighlighter { + background-color: white !important; +} +.syntaxhighlighter .line.alt1 { + background-color: white !important; +} +.syntaxhighlighter .line.alt2 { + background-color: white !important; +} +.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 { + background-color: #e0e0e0 !important; +} +.syntaxhighlighter .line.highlighted.number { + color: black !important; +} +.syntaxhighlighter table caption { + color: black !important; +} +.syntaxhighlighter .gutter { + color: #afafaf !important; +} +.syntaxhighlighter .gutter .line { + border-right: 3px solid #6ce26c !important; +} +.syntaxhighlighter .gutter .line.highlighted { + background-color: #6ce26c !important; + color: white !important; +} +.syntaxhighlighter.printing .line .content { + border: none !important; +} +.syntaxhighlighter.collapsed { + overflow: visible !important; +} +.syntaxhighlighter.collapsed .toolbar { + color: blue !important; + background: white !important; + border: 1px solid #6ce26c !important; +} +.syntaxhighlighter.collapsed .toolbar a { + color: blue !important; +} +.syntaxhighlighter.collapsed .toolbar a:hover { + color: red !important; +} +.syntaxhighlighter .toolbar { + color: white !important; + background: #6ce26c !important; + border: none !important; +} +.syntaxhighlighter .toolbar a { + color: white !important; +} +.syntaxhighlighter .toolbar a:hover { + color: black !important; +} +.syntaxhighlighter .plain, .syntaxhighlighter .plain a { + color: black !important; +} +.syntaxhighlighter .comments, .syntaxhighlighter .comments a { + color: #008200 !important; +} +.syntaxhighlighter .string, .syntaxhighlighter .string a { + color: blue !important; +} +.syntaxhighlighter .keyword { + color: #006699 !important; +} +.syntaxhighlighter .preprocessor { + color: gray !important; +} +.syntaxhighlighter .variable { + color: #aa7700 !important; +} +.syntaxhighlighter .value { + color: #009900 !important; +} +.syntaxhighlighter .functions { + color: #ff1493 !important; +} +.syntaxhighlighter .constants { + color: #0066cc !important; +} +.syntaxhighlighter .script { + font-weight: bold !important; + color: #006699 !important; + background-color: none !important; +} +.syntaxhighlighter .color1, .syntaxhighlighter .color1 a { + color: gray !important; +} +.syntaxhighlighter .color2, .syntaxhighlighter .color2 a { + color: #ff1493 !important; +} +.syntaxhighlighter .color3, .syntaxhighlighter .color3 a { + color: red !important; +} + +.syntaxhighlighter .keyword { + font-weight: bold !important; +} diff --git a/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeDjango.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeDjango.css new file mode 100644 index 0000000000..d8b4313433 --- /dev/null +++ b/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeDjango.css @@ -0,0 +1,120 @@ +/** + * SyntaxHighlighter + * http://alexgorbatchev.com/SyntaxHighlighter + * + * SyntaxHighlighter is donationware. If you are using it, please donate. + * http://alexgorbatchev.com/SyntaxHighlighter/donate.html + * + * @version + * 3.0.83 (July 02 2010) + * + * @copyright + * Copyright (C) 2004-2010 Alex Gorbatchev. + * + * @license + * Dual licensed under the MIT and GPL licenses. + */ +.syntaxhighlighter { + background-color: #0a2b1d !important; +} +.syntaxhighlighter .line.alt1 { + background-color: #0a2b1d !important; +} +.syntaxhighlighter .line.alt2 { + background-color: #0a2b1d !important; +} +.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 { + background-color: #233729 !important; +} +.syntaxhighlighter .line.highlighted.number { + color: white !important; +} +.syntaxhighlighter table caption { + color: #f8f8f8 !important; +} +.syntaxhighlighter .gutter { + color: #497958 !important; +} +.syntaxhighlighter .gutter .line { + border-right: 3px solid #41a83e !important; +} +.syntaxhighlighter .gutter .line.highlighted { + background-color: #41a83e !important; + color: #0a2b1d !important; +} +.syntaxhighlighter.printing .line .content { + border: none !important; +} +.syntaxhighlighter.collapsed { + overflow: visible !important; +} +.syntaxhighlighter.collapsed .toolbar { + color: #96dd3b !important; + background: black !important; + border: 1px solid #41a83e !important; +} +.syntaxhighlighter.collapsed .toolbar a { + color: #96dd3b !important; +} +.syntaxhighlighter.collapsed .toolbar a:hover { + color: white !important; +} +.syntaxhighlighter .toolbar { + color: white !important; + background: #41a83e !important; + border: none !important; +} +.syntaxhighlighter .toolbar a { + color: white !important; +} +.syntaxhighlighter .toolbar a:hover { + color: #ffe862 !important; +} +.syntaxhighlighter .plain, .syntaxhighlighter .plain a { + color: #f8f8f8 !important; +} +.syntaxhighlighter .comments, .syntaxhighlighter .comments a { + color: #336442 !important; +} +.syntaxhighlighter .string, .syntaxhighlighter .string a { + color: #9df39f !important; +} +.syntaxhighlighter .keyword { + color: #96dd3b !important; +} +.syntaxhighlighter .preprocessor { + color: #91bb9e !important; +} +.syntaxhighlighter .variable { + color: #ffaa3e !important; +} +.syntaxhighlighter .value { + color: #f7e741 !important; +} +.syntaxhighlighter .functions { + color: #ffaa3e !important; +} +.syntaxhighlighter .constants { + color: #e0e8ff !important; +} +.syntaxhighlighter .script { + font-weight: bold !important; + color: #96dd3b !important; + background-color: none !important; +} +.syntaxhighlighter .color1, .syntaxhighlighter .color1 a { + color: #eb939a !important; +} +.syntaxhighlighter .color2, .syntaxhighlighter .color2 a { + color: #91bb9e !important; +} +.syntaxhighlighter .color3, .syntaxhighlighter .color3 a { + color: #edef7d !important; +} + +.syntaxhighlighter .comments { + font-style: italic !important; +} +.syntaxhighlighter .keyword { + font-weight: bold !important; +} diff --git a/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeEclipse.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeEclipse.css new file mode 100644 index 0000000000..77377d9533 --- /dev/null +++ b/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeEclipse.css @@ -0,0 +1,128 @@ +/** + * SyntaxHighlighter + * http://alexgorbatchev.com/SyntaxHighlighter + * + * SyntaxHighlighter is donationware. If you are using it, please donate. + * http://alexgorbatchev.com/SyntaxHighlighter/donate.html + * + * @version + * 3.0.83 (July 02 2010) + * + * @copyright + * Copyright (C) 2004-2010 Alex Gorbatchev. + * + * @license + * Dual licensed under the MIT and GPL licenses. + */ +.syntaxhighlighter { + background-color: white !important; +} +.syntaxhighlighter .line.alt1 { + background-color: white !important; +} +.syntaxhighlighter .line.alt2 { + background-color: white !important; +} +.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 { + background-color: #c3defe !important; +} +.syntaxhighlighter .line.highlighted.number { + color: white !important; +} +.syntaxhighlighter table caption { + color: black !important; +} +.syntaxhighlighter .gutter { + color: #787878 !important; +} +.syntaxhighlighter .gutter .line { + border-right: 3px solid #d4d0c8 !important; +} +.syntaxhighlighter .gutter .line.highlighted { + background-color: #d4d0c8 !important; + color: white !important; +} +.syntaxhighlighter.printing .line .content { + border: none !important; +} +.syntaxhighlighter.collapsed { + overflow: visible !important; +} +.syntaxhighlighter.collapsed .toolbar { + color: #3f5fbf !important; + background: white !important; + border: 1px solid #d4d0c8 !important; +} +.syntaxhighlighter.collapsed .toolbar a { + color: #3f5fbf !important; +} +.syntaxhighlighter.collapsed .toolbar a:hover { + color: #aa7700 !important; +} +.syntaxhighlighter .toolbar { + color: #a0a0a0 !important; + background: #d4d0c8 !important; + border: none !important; +} +.syntaxhighlighter .toolbar a { + color: #a0a0a0 !important; +} +.syntaxhighlighter .toolbar a:hover { + color: red !important; +} +.syntaxhighlighter .plain, .syntaxhighlighter .plain a { + color: black !important; +} +.syntaxhighlighter .comments, .syntaxhighlighter .comments a { + color: #3f5fbf !important; +} +.syntaxhighlighter .string, .syntaxhighlighter .string a { + color: #2a00ff !important; +} +.syntaxhighlighter .keyword { + color: #7f0055 !important; +} +.syntaxhighlighter .preprocessor { + color: #646464 !important; +} +.syntaxhighlighter .variable { + color: #aa7700 !important; +} +.syntaxhighlighter .value { + color: #009900 !important; +} +.syntaxhighlighter .functions { + color: #ff1493 !important; +} +.syntaxhighlighter .constants { + color: #0066cc !important; +} +.syntaxhighlighter .script { + font-weight: bold !important; + color: #7f0055 !important; + background-color: none !important; +} +.syntaxhighlighter .color1, .syntaxhighlighter .color1 a { + color: gray !important; +} +.syntaxhighlighter .color2, .syntaxhighlighter .color2 a { + color: #ff1493 !important; +} +.syntaxhighlighter .color3, .syntaxhighlighter .color3 a { + color: red !important; +} + +.syntaxhighlighter .keyword { + font-weight: bold !important; +} +.syntaxhighlighter .xml .keyword { + color: #3f7f7f !important; + font-weight: normal !important; +} +.syntaxhighlighter .xml .color1, .syntaxhighlighter .xml .color1 a { + color: #7f007f !important; +} +.syntaxhighlighter .xml .string { + font-style: italic !important; + color: #2a00ff !important; +} diff --git a/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeEmacs.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeEmacs.css new file mode 100644 index 0000000000..dae5053fea --- /dev/null +++ b/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeEmacs.css @@ -0,0 +1,113 @@ +/** + * SyntaxHighlighter + * http://alexgorbatchev.com/SyntaxHighlighter + * + * SyntaxHighlighter is donationware. If you are using it, please donate. + * http://alexgorbatchev.com/SyntaxHighlighter/donate.html + * + * @version + * 3.0.83 (July 02 2010) + * + * @copyright + * Copyright (C) 2004-2010 Alex Gorbatchev. + * + * @license + * Dual licensed under the MIT and GPL licenses. + */ +.syntaxhighlighter { + background-color: black !important; +} +.syntaxhighlighter .line.alt1 { + background-color: black !important; +} +.syntaxhighlighter .line.alt2 { + background-color: black !important; +} +.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 { + background-color: #2a3133 !important; +} +.syntaxhighlighter .line.highlighted.number { + color: white !important; +} +.syntaxhighlighter table caption { + color: #d3d3d3 !important; +} +.syntaxhighlighter .gutter { + color: #d3d3d3 !important; +} +.syntaxhighlighter .gutter .line { + border-right: 3px solid #990000 !important; +} +.syntaxhighlighter .gutter .line.highlighted { + background-color: #990000 !important; + color: black !important; +} +.syntaxhighlighter.printing .line .content { + border: none !important; +} +.syntaxhighlighter.collapsed { + overflow: visible !important; +} +.syntaxhighlighter.collapsed .toolbar { + color: #ebdb8d !important; + background: black !important; + border: 1px solid #990000 !important; +} +.syntaxhighlighter.collapsed .toolbar a { + color: #ebdb8d !important; +} +.syntaxhighlighter.collapsed .toolbar a:hover { + color: #ff7d27 !important; +} +.syntaxhighlighter .toolbar { + color: white !important; + background: #990000 !important; + border: none !important; +} +.syntaxhighlighter .toolbar a { + color: white !important; +} +.syntaxhighlighter .toolbar a:hover { + color: #9ccff4 !important; +} +.syntaxhighlighter .plain, .syntaxhighlighter .plain a { + color: #d3d3d3 !important; +} +.syntaxhighlighter .comments, .syntaxhighlighter .comments a { + color: #ff7d27 !important; +} +.syntaxhighlighter .string, .syntaxhighlighter .string a { + color: #ff9e7b !important; +} +.syntaxhighlighter .keyword { + color: aqua !important; +} +.syntaxhighlighter .preprocessor { + color: #aec4de !important; +} +.syntaxhighlighter .variable { + color: #ffaa3e !important; +} +.syntaxhighlighter .value { + color: #009900 !important; +} +.syntaxhighlighter .functions { + color: #81cef9 !important; +} +.syntaxhighlighter .constants { + color: #ff9e7b !important; +} +.syntaxhighlighter .script { + font-weight: bold !important; + color: aqua !important; + background-color: none !important; +} +.syntaxhighlighter .color1, .syntaxhighlighter .color1 a { + color: #ebdb8d !important; +} +.syntaxhighlighter .color2, .syntaxhighlighter .color2 a { + color: #ff7d27 !important; +} +.syntaxhighlighter .color3, .syntaxhighlighter .color3 a { + color: #aec4de !important; +} diff --git a/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css new file mode 100644 index 0000000000..8fbd871fb5 --- /dev/null +++ b/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css @@ -0,0 +1,117 @@ +/** + * SyntaxHighlighter + * http://alexgorbatchev.com/SyntaxHighlighter + * + * SyntaxHighlighter is donationware. If you are using it, please donate. + * http://alexgorbatchev.com/SyntaxHighlighter/donate.html + * + * @version + * 3.0.83 (July 02 2010) + * + * @copyright + * Copyright (C) 2004-2010 Alex Gorbatchev. + * + * @license + * Dual licensed under the MIT and GPL licenses. + */ +.syntaxhighlighter { + background-color: #121212 !important; +} +.syntaxhighlighter .line.alt1 { + background-color: #121212 !important; +} +.syntaxhighlighter .line.alt2 { + background-color: #121212 !important; +} +.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 { + background-color: #2c2c29 !important; +} +.syntaxhighlighter .line.highlighted.number { + color: white !important; +} +.syntaxhighlighter table caption { + color: white !important; +} +.syntaxhighlighter .gutter { + color: #afafaf !important; +} +.syntaxhighlighter .gutter .line { + border-right: 3px solid #3185b9 !important; +} +.syntaxhighlighter .gutter .line.highlighted { + background-color: #3185b9 !important; + color: #121212 !important; +} +.syntaxhighlighter.printing .line .content { + border: none !important; +} +.syntaxhighlighter.collapsed { + overflow: visible !important; +} +.syntaxhighlighter.collapsed .toolbar { + color: #3185b9 !important; + background: black !important; + border: 1px solid #3185b9 !important; +} +.syntaxhighlighter.collapsed .toolbar a { + color: #3185b9 !important; +} +.syntaxhighlighter.collapsed .toolbar a:hover { + color: #d01d33 !important; +} +.syntaxhighlighter .toolbar { + color: white !important; + background: #3185b9 !important; + border: none !important; +} +.syntaxhighlighter .toolbar a { + color: white !important; +} +.syntaxhighlighter .toolbar a:hover { + color: #96daff !important; +} +.syntaxhighlighter .plain, .syntaxhighlighter .plain a { + color: white !important; +} +.syntaxhighlighter .comments, .syntaxhighlighter .comments a { + color: #696854 !important; +} +.syntaxhighlighter .string, .syntaxhighlighter .string a { + color: #e3e658 !important; +} +.syntaxhighlighter .keyword { + color: #d01d33 !important; +} +.syntaxhighlighter .preprocessor { + color: #435a5f !important; +} +.syntaxhighlighter .variable { + color: #898989 !important; +} +.syntaxhighlighter .value { + color: #009900 !important; +} +.syntaxhighlighter .functions { + color: #aaaaaa !important; +} +.syntaxhighlighter .constants { + color: #96daff !important; +} +.syntaxhighlighter .script { + font-weight: bold !important; + color: #d01d33 !important; + background-color: none !important; +} +.syntaxhighlighter .color1, .syntaxhighlighter .color1 a { + color: #ffc074 !important; +} +.syntaxhighlighter .color2, .syntaxhighlighter .color2 a { + color: #4a8cdb !important; +} +.syntaxhighlighter .color3, .syntaxhighlighter .color3 a { + color: #96daff !important; +} + +.syntaxhighlighter .functions { + font-weight: bold !important; +} diff --git a/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeMDUltra.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeMDUltra.css new file mode 100755 index 0000000000..f4db39cd83 --- /dev/null +++ b/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeMDUltra.css @@ -0,0 +1,113 @@ +/** + * SyntaxHighlighter + * http://alexgorbatchev.com/SyntaxHighlighter + * + * SyntaxHighlighter is donationware. If you are using it, please donate. + * http://alexgorbatchev.com/SyntaxHighlighter/donate.html + * + * @version + * 3.0.83 (July 02 2010) + * + * @copyright + * Copyright (C) 2004-2010 Alex Gorbatchev. + * + * @license + * Dual licensed under the MIT and GPL licenses. + */ +.syntaxhighlighter { + background-color: #222222 !important; +} +.syntaxhighlighter .line.alt1 { + background-color: #222222 !important; +} +.syntaxhighlighter .line.alt2 { + background-color: #222222 !important; +} +.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 { + background-color: #253e5a !important; +} +.syntaxhighlighter .line.highlighted.number { + color: white !important; +} +.syntaxhighlighter table caption { + color: lime !important; +} +.syntaxhighlighter .gutter { + color: #38566f !important; +} +.syntaxhighlighter .gutter .line { + border-right: 3px solid #435a5f !important; +} +.syntaxhighlighter .gutter .line.highlighted { + background-color: #435a5f !important; + color: #222222 !important; +} +.syntaxhighlighter.printing .line .content { + border: none !important; +} +.syntaxhighlighter.collapsed { + overflow: visible !important; +} +.syntaxhighlighter.collapsed .toolbar { + color: #428bdd !important; + background: black !important; + border: 1px solid #435a5f !important; +} +.syntaxhighlighter.collapsed .toolbar a { + color: #428bdd !important; +} +.syntaxhighlighter.collapsed .toolbar a:hover { + color: lime !important; +} +.syntaxhighlighter .toolbar { + color: #aaaaff !important; + background: #435a5f !important; + border: none !important; +} +.syntaxhighlighter .toolbar a { + color: #aaaaff !important; +} +.syntaxhighlighter .toolbar a:hover { + color: #9ccff4 !important; +} +.syntaxhighlighter .plain, .syntaxhighlighter .plain a { + color: lime !important; +} +.syntaxhighlighter .comments, .syntaxhighlighter .comments a { + color: #428bdd !important; +} +.syntaxhighlighter .string, .syntaxhighlighter .string a { + color: lime !important; +} +.syntaxhighlighter .keyword { + color: #aaaaff !important; +} +.syntaxhighlighter .preprocessor { + color: #8aa6c1 !important; +} +.syntaxhighlighter .variable { + color: aqua !important; +} +.syntaxhighlighter .value { + color: #f7e741 !important; +} +.syntaxhighlighter .functions { + color: #ff8000 !important; +} +.syntaxhighlighter .constants { + color: yellow !important; +} +.syntaxhighlighter .script { + font-weight: bold !important; + color: #aaaaff !important; + background-color: none !important; +} +.syntaxhighlighter .color1, .syntaxhighlighter .color1 a { + color: red !important; +} +.syntaxhighlighter .color2, .syntaxhighlighter .color2 a { + color: yellow !important; +} +.syntaxhighlighter .color3, .syntaxhighlighter .color3 a { + color: #ffaa3e !important; +} diff --git a/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeMidnight.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeMidnight.css new file mode 100644 index 0000000000..c49563cc9d --- /dev/null +++ b/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeMidnight.css @@ -0,0 +1,113 @@ +/** + * SyntaxHighlighter + * http://alexgorbatchev.com/SyntaxHighlighter + * + * SyntaxHighlighter is donationware. If you are using it, please donate. + * http://alexgorbatchev.com/SyntaxHighlighter/donate.html + * + * @version + * 3.0.83 (July 02 2010) + * + * @copyright + * Copyright (C) 2004-2010 Alex Gorbatchev. + * + * @license + * Dual licensed under the MIT and GPL licenses. + */ +.syntaxhighlighter { + background-color: #0f192a !important; +} +.syntaxhighlighter .line.alt1 { + background-color: #0f192a !important; +} +.syntaxhighlighter .line.alt2 { + background-color: #0f192a !important; +} +.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 { + background-color: #253e5a !important; +} +.syntaxhighlighter .line.highlighted.number { + color: #38566f !important; +} +.syntaxhighlighter table caption { + color: #d1edff !important; +} +.syntaxhighlighter .gutter { + color: #afafaf !important; +} +.syntaxhighlighter .gutter .line { + border-right: 3px solid #435a5f !important; +} +.syntaxhighlighter .gutter .line.highlighted { + background-color: #435a5f !important; + color: #0f192a !important; +} +.syntaxhighlighter.printing .line .content { + border: none !important; +} +.syntaxhighlighter.collapsed { + overflow: visible !important; +} +.syntaxhighlighter.collapsed .toolbar { + color: #428bdd !important; + background: black !important; + border: 1px solid #435a5f !important; +} +.syntaxhighlighter.collapsed .toolbar a { + color: #428bdd !important; +} +.syntaxhighlighter.collapsed .toolbar a:hover { + color: #1dc116 !important; +} +.syntaxhighlighter .toolbar { + color: #d1edff !important; + background: #435a5f !important; + border: none !important; +} +.syntaxhighlighter .toolbar a { + color: #d1edff !important; +} +.syntaxhighlighter .toolbar a:hover { + color: #8aa6c1 !important; +} +.syntaxhighlighter .plain, .syntaxhighlighter .plain a { + color: #d1edff !important; +} +.syntaxhighlighter .comments, .syntaxhighlighter .comments a { + color: #428bdd !important; +} +.syntaxhighlighter .string, .syntaxhighlighter .string a { + color: #1dc116 !important; +} +.syntaxhighlighter .keyword { + color: #b43d3d !important; +} +.syntaxhighlighter .preprocessor { + color: #8aa6c1 !important; +} +.syntaxhighlighter .variable { + color: #ffaa3e !important; +} +.syntaxhighlighter .value { + color: #f7e741 !important; +} +.syntaxhighlighter .functions { + color: #ffaa3e !important; +} +.syntaxhighlighter .constants { + color: #e0e8ff !important; +} +.syntaxhighlighter .script { + font-weight: bold !important; + color: #b43d3d !important; + background-color: none !important; +} +.syntaxhighlighter .color1, .syntaxhighlighter .color1 a { + color: #f8bb00 !important; +} +.syntaxhighlighter .color2, .syntaxhighlighter .color2 a { + color: white !important; +} +.syntaxhighlighter .color3, .syntaxhighlighter .color3 a { + color: #ffaa3e !important; +} diff --git a/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeRDark.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeRDark.css new file mode 100644 index 0000000000..6305a10e4e --- /dev/null +++ b/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeRDark.css @@ -0,0 +1,113 @@ +/** + * SyntaxHighlighter + * http://alexgorbatchev.com/SyntaxHighlighter + * + * SyntaxHighlighter is donationware. If you are using it, please donate. + * http://alexgorbatchev.com/SyntaxHighlighter/donate.html + * + * @version + * 3.0.83 (July 02 2010) + * + * @copyright + * Copyright (C) 2004-2010 Alex Gorbatchev. + * + * @license + * Dual licensed under the MIT and GPL licenses. + */ +.syntaxhighlighter { + background-color: #1b2426 !important; +} +.syntaxhighlighter .line.alt1 { + background-color: #1b2426 !important; +} +.syntaxhighlighter .line.alt2 { + background-color: #1b2426 !important; +} +.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 { + background-color: #323e41 !important; +} +.syntaxhighlighter .line.highlighted.number { + color: #b9bdb6 !important; +} +.syntaxhighlighter table caption { + color: #b9bdb6 !important; +} +.syntaxhighlighter .gutter { + color: #afafaf !important; +} +.syntaxhighlighter .gutter .line { + border-right: 3px solid #435a5f !important; +} +.syntaxhighlighter .gutter .line.highlighted { + background-color: #435a5f !important; + color: #1b2426 !important; +} +.syntaxhighlighter.printing .line .content { + border: none !important; +} +.syntaxhighlighter.collapsed { + overflow: visible !important; +} +.syntaxhighlighter.collapsed .toolbar { + color: #5ba1cf !important; + background: black !important; + border: 1px solid #435a5f !important; +} +.syntaxhighlighter.collapsed .toolbar a { + color: #5ba1cf !important; +} +.syntaxhighlighter.collapsed .toolbar a:hover { + color: #5ce638 !important; +} +.syntaxhighlighter .toolbar { + color: white !important; + background: #435a5f !important; + border: none !important; +} +.syntaxhighlighter .toolbar a { + color: white !important; +} +.syntaxhighlighter .toolbar a:hover { + color: #e0e8ff !important; +} +.syntaxhighlighter .plain, .syntaxhighlighter .plain a { + color: #b9bdb6 !important; +} +.syntaxhighlighter .comments, .syntaxhighlighter .comments a { + color: #878a85 !important; +} +.syntaxhighlighter .string, .syntaxhighlighter .string a { + color: #5ce638 !important; +} +.syntaxhighlighter .keyword { + color: #5ba1cf !important; +} +.syntaxhighlighter .preprocessor { + color: #435a5f !important; +} +.syntaxhighlighter .variable { + color: #ffaa3e !important; +} +.syntaxhighlighter .value { + color: #009900 !important; +} +.syntaxhighlighter .functions { + color: #ffaa3e !important; +} +.syntaxhighlighter .constants { + color: #e0e8ff !important; +} +.syntaxhighlighter .script { + font-weight: bold !important; + color: #5ba1cf !important; + background-color: none !important; +} +.syntaxhighlighter .color1, .syntaxhighlighter .color1 a { + color: #e0e8ff !important; +} +.syntaxhighlighter .color2, .syntaxhighlighter .color2 a { + color: white !important; +} +.syntaxhighlighter .color3, .syntaxhighlighter .color3 a { + color: #ffaa3e !important; +} diff --git a/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeRailsGuides.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeRailsGuides.css new file mode 100644 index 0000000000..6d2edb2eb8 --- /dev/null +++ b/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeRailsGuides.css @@ -0,0 +1,116 @@ +/** + * Theme by fxn, took shThemeEclipse.css as starting point. + */ +.syntaxhighlighter { + background-color: #eee !important; + font-family: "Anonymous Pro", "Inconsolata", "Menlo", "Consolas", "Bitstream Vera Sans Mono", "Courier New", monospace !important; + overflow-y: hidden !important; + overflow-x: auto !important; +} +.syntaxhighlighter .line.alt1 { + background-color: #eee !important; +} +.syntaxhighlighter .line.alt2 { + background-color: #eee !important; +} +.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 { + background-color: #c3defe !important; +} +.syntaxhighlighter .line.highlighted.number { + color: #eee !important; +} +.syntaxhighlighter table caption { + color: #222 !important; +} +.syntaxhighlighter .gutter { + color: #787878 !important; +} +.syntaxhighlighter .gutter .line { + border-right: 3px solid #d4d0c8 !important; +} +.syntaxhighlighter .gutter .line.highlighted { + background-color: #d4d0c8 !important; + color: #eee !important; +} +.syntaxhighlighter.printing .line .content { + border: none !important; +} +.syntaxhighlighter.collapsed { + overflow: visible !important; +} +.syntaxhighlighter.collapsed .toolbar { + color: #3f5fbf !important; + background: #eee !important; + border: 1px solid #d4d0c8 !important; +} +.syntaxhighlighter.collapsed .toolbar a { + color: #3f5fbf !important; +} +.syntaxhighlighter.collapsed .toolbar a:hover { + color: #aa7700 !important; +} +.syntaxhighlighter .toolbar { + color: #a0a0a0 !important; + background: #d4d0c8 !important; + border: none !important; +} +.syntaxhighlighter .toolbar a { + color: #a0a0a0 !important; +} +.syntaxhighlighter .toolbar a:hover { + color: red !important; +} +.syntaxhighlighter .plain, .syntaxhighlighter .plain a { + color: #222 !important; +} +.syntaxhighlighter .comments, .syntaxhighlighter .comments a { + color: #708090 !important; +} +.syntaxhighlighter .string, .syntaxhighlighter .string a { + font-style: italic !important; + color: #6588A8 !important; +} +.syntaxhighlighter .keyword { + color: #64434d !important; +} +.syntaxhighlighter .preprocessor { + color: #646464 !important; +} +.syntaxhighlighter .variable { + color: #222 !important; +} +.syntaxhighlighter .value { + color: #009900 !important; +} +.syntaxhighlighter .functions { + color: #ff1493 !important; +} +.syntaxhighlighter .constants { + color: #0066cc !important; +} +.syntaxhighlighter .script { + color: #222 !important; + background-color: none !important; +} +.syntaxhighlighter .color1, .syntaxhighlighter .color1 a { + color: gray !important; +} +.syntaxhighlighter .color2, .syntaxhighlighter .color2 a { + color: #222 !important; + font-weight: bold !important; +} +.syntaxhighlighter .color3, .syntaxhighlighter .color3 a { + color: red !important; +} + +.syntaxhighlighter .xml .keyword { + color: #64434d !important; + font-weight: normal !important; +} +.syntaxhighlighter .xml .color1, .syntaxhighlighter .xml .color1 a { + color: #7f007f !important; +} +.syntaxhighlighter .xml .string { + font-style: italic !important; + color: #6588A8 !important; +} diff --git a/railties/guides/rails_guides.rb b/railties/guides/rails_guides.rb index dfbb06cc76..feb5fe3937 100644 --- a/railties/guides/rails_guides.rb +++ b/railties/guides/rails_guides.rb @@ -24,14 +24,14 @@ rescue LoadError end begin - gem 'RedCloth', '>= 4.1.1' require 'redcloth' rescue Gem::LoadError + # This can happen if doc:guides is executed in an application. $stderr.puts('Generating guides requires RedCloth 4.1.1+.') $stderr.puts(<<ERROR) if bundler? Please add - gem 'RedCloth', '>= 4.1.1' + gem 'RedCloth', '~> 4.2' to the Gemfile, run diff --git a/railties/guides/rails_guides/generator.rb b/railties/guides/rails_guides/generator.rb index bb7cdb6756..154355cac1 100644 --- a/railties/guides/rails_guides/generator.rb +++ b/railties/guides/rails_guides/generator.rb @@ -32,12 +32,16 @@ # # Separate many using commas: # -# # generates only +# # generates only association_basics.html and migrations.html # ONLY=assoc,migrations ruby rails_guides.rb # # Note that if you are working on a guide generation will by default process # only that one, so ONLY is rarely used nowadays. # +# LANGUAGE +# Use LANGUAGE when you want to generate translated guides in <tt>source/<LANGUAGE></tt> +# folder (such as <tt>source/es</tt>). Ignore it when generating English guides. +# # EDGE # Set to "1" to indicate generated guides should be marked as edge. This # inserts a badge and changes the preamble of the home page. @@ -63,6 +67,7 @@ module RailsGuides GUIDES_RE = /\.(?:textile|html\.erb)$/ def initialize(output=nil) + @lang = ENV['LANGUAGE'] initialize_dirs(output) create_output_dir_if_needed set_flags_from_environment @@ -76,8 +81,8 @@ module RailsGuides private def initialize_dirs(output) @guides_dir = File.join(File.dirname(__FILE__), '..') - @source_dir = File.join(@guides_dir, "source") - @output_dir = output || File.join(@guides_dir, "output") + @source_dir = File.join(@guides_dir, "source", @lang.to_s) + @output_dir = output || File.join(@guides_dir, "output", @lang.to_s) end def create_output_dir_if_needed @@ -116,7 +121,7 @@ module RailsGuides def output_file_for(guide) guide.sub(GUIDES_RE, '.html') end - + def generate?(source_file, output_file) fin = File.join(source_dir, source_file) fout = File.join(output_dir, output_file) @@ -207,15 +212,33 @@ module RailsGuides # with code blocks by hand. def with_workaround_for_notextile(body) code_blocks = [] + body.gsub!(%r{<(yaml|shell|ruby|erb|html|sql|plain)>(.*?)</\1>}m) do |m| - es = ERB::Util.h($2) - css_class = ['erb', 'shell'].include?($1) ? 'html' : $1 - code_blocks << %{<div class="code_container"><code class="#{css_class}">#{es}</code></div>} + brush = case $1 + when 'ruby', 'sql', 'plain' + $1 + when 'erb' + 'ruby; html-script: true' + when 'html' + 'xml' # html is understood, but there are .xml rules in the CSS + else + 'plain' + end + + code_blocks.push(<<HTML) +<notextile> +<div class="code_container"> +<pre class="brush: #{brush}; gutter: false; toolbar: false"> +#{ERB::Util.h($2).strip} +</pre> +</div> +</notextile> +HTML "\ndirty_workaround_for_notextile_#{code_blocks.size - 1}\n" end - + body = yield body - + body.gsub(%r{<p>dirty_workaround_for_notextile_(\d+)</p>}) do |_| code_blocks[$1.to_i] end @@ -225,7 +248,7 @@ module RailsGuides anchors = extract_anchors(html) check_fragment_identifiers(html, anchors) end - + def extract_anchors(html) # Textile generates headers with IDs computed from titles. anchors = Set.new @@ -237,11 +260,12 @@ module RailsGuides end end - # Also, footnotes are rendered as paragraphs this way. + # Footnotes. anchors += Set.new(html.scan(/<p\s+class="footnote"\s+id="([^"]+)/).flatten) + anchors += Set.new(html.scan(/<sup\s+class="footnote"\s+id="([^"]+)/).flatten) return anchors end - + def check_fragment_identifiers(html, anchors) html.scan(/<a\s+href="#([^"]+)/).flatten.each do |fragment_identifier| next if fragment_identifier == 'mainCol' # in layout, jumps to some DIV diff --git a/railties/guides/rails_guides/helpers.rb b/railties/guides/rails_guides/helpers.rb index bf99538696..d466c76c7c 100644 --- a/railties/guides/rails_guides/helpers.rb +++ b/railties/guides/rails_guides/helpers.rb @@ -4,19 +4,14 @@ module RailsGuides link = content_tag(:a, :href => url) { name } result = content_tag(:dt, link) - if ticket = options[:ticket] - result << content_tag(:dd, lh(ticket), :class => 'ticket') + if options[:work_in_progress] + result << content_tag(:dd, 'Work in progress', :class => 'work-in-progress') end result << content_tag(:dd, capture(&block)) result end - def lh(id, label = "Lighthouse Ticket") - url = "http://rails.lighthouseapp.com/projects/16213/tickets/#{id}" - content_tag(:a, label, :href => url) - end - def author(name, nick, image = 'credits_pic_blank.gif', &block) image = "images/#{image}" diff --git a/railties/guides/rails_guides/indexer.rb b/railties/guides/rails_guides/indexer.rb index bd817786ed..fb46491817 100644 --- a/railties/guides/rails_guides/indexer.rb +++ b/railties/guides/rails_guides/indexer.rb @@ -1,5 +1,6 @@ require 'active_support/core_ext/object/blank' require 'active_support/ordered_hash' +require 'active_support/core_ext/string/inflections' module RailsGuides class Indexer @@ -58,7 +59,7 @@ module RailsGuides end def title_to_idx(title) - idx = title.strip.downcase.gsub(/\s+|_/, '-').delete('^a-z0-9-').sub(/^[^a-z]*/, '') + idx = title.strip.parameterize.sub(/^\d+/, '') if warnings && idx.blank? puts "BLANK ID: please put an explicit ID for section #{title}, as in h5(#my-id)" end diff --git a/railties/guides/source/2_2_release_notes.textile b/railties/guides/source/2_2_release_notes.textile index 5628d7e52f..8e2d528eee 100644 --- a/railties/guides/source/2_2_release_notes.textile +++ b/railties/guides/source/2_2_release_notes.textile @@ -260,15 +260,15 @@ h4. Other Action Controller Changes * Benchmarking numbers are now reported in milliseconds rather than tiny fractions of seconds * Rails now supports HTTP-only cookies (and uses them for sessions), which help mitigate some cross-site scripting risks in newer browsers. * +redirect_to+ now fully supports URI schemes (so, for example, you can redirect to a svn+ssh: URI). -* +render+ now supports a +:js+ option to render plain vanilla javascript with the right mime type. +* +render+ now supports a +:js+ option to render plain vanilla JavaScript with the right mime type. * Request forgery protection has been tightened up to apply to HTML-formatted content requests only. * Polymorphic URLs behave more sensibly if a passed parameter is nil. For example, calling +polymorphic_path([@project, @date, @area])+ with a nil date will give you +project_area_path+. h3. Action View * +javascript_include_tag+ and +stylesheet_link_tag+ support a new +:recursive+ option to be used along with +:all+, so that you can load an entire tree of files with a single line of code. -* The included Prototype javascript library has been upgraded to version 1.6.0.3. -* +RJS#page.reload+ to reload the browser's current location via javascript +* The included Prototype JavaScript library has been upgraded to version 1.6.0.3. +* +RJS#page.reload+ to reload the browser's current location via JavaScript * The +atom_feed+ helper now takes an +:instruct+ option to let you insert XML processing instructions. h3. Action Mailer diff --git a/railties/guides/source/2_3_release_notes.textile b/railties/guides/source/2_3_release_notes.textile index f3530c4ddd..67743a4797 100644 --- a/railties/guides/source/2_3_release_notes.textile +++ b/railties/guides/source/2_3_release_notes.textile @@ -53,7 +53,7 @@ The "Ruby on Rails guides":http://guides.rubyonrails.org/ project has published h3. Ruby 1.9.1 Support -Rails 2.3 should pass all of its own tests whether you are running on Ruby 1.8 or the now-released Ruby 1.9.1. You should be aware, though, that moving to 1.9.1 entails checking all of the data adapters, plugins, and other code that you depend on for Ruby 1.9.1 compatibility, as well as Rails core. +Rails 2.3 should pass all of its own tests whether you are running on Ruby 1.8 or the now-released Ruby 1.9.1. You should be aware, though, that moving to 1.9.1 entails checking all of the data adapters, plugins, and other code that you depend on for Ruby 1.9.1 compatibility, as well as Rails core. h3. Active Record @@ -77,7 +77,7 @@ Turning on nested attributes enables a number of things: automatic (and atomic) You can also specify requirements for any new records that are added via nested attributes using the +:reject_if+ option: <ruby> -accepts_nested_attributes_for :author, +accepts_nested_attributes_for :author, :reject_if => proc { |attributes| attributes['name'].blank? } </ruby> @@ -149,7 +149,7 @@ end Note that you should only use this method for batch processing: for small numbers of records (less than 1000), you should just use the regular find methods with your own loop. -* More Information (at that point the convenience method was called just +each+): +* More Information (at that point the convenience method was called just +each+): ** "Rails 2.3: Batch Finding":http://afreshcup.com/2009/02/23/rails-23-batch-finding/ ** "What's New in Edge Rails: Batched Find":http://ryandaigle.com/articles/2009/2/23/what-s-new-in-edge-rails-batched-find @@ -278,7 +278,7 @@ Mime::JS =~ "text/javascript" => true Mime::JS =~ "application/javascript" => true </ruby> -The other change is that the framework now uses the +Mime::JS+ when checking for javascript in various spots, making it handle those alternatives cleanly. +The other change is that the framework now uses the +Mime::JS+ when checking for JavaScript in various spots, making it handle those alternatives cleanly. * Lead Contributor: "Seth Fitzsimmons":http://www.workingwithrails.com/person/5510-seth-fitzsimmons @@ -449,7 +449,7 @@ returns <option>joke</option> <option>poem</option> <option disabled=“disabled“>private</option> -</select> +</select> </ruby> You can also use an anonymous function to determine at runtime which options from collections will be selected and/or disabled: @@ -502,7 +502,7 @@ The support for XML parsing in ActiveSupport has been made more flexible by allo XmlMini.backend = 'LibXML' </ruby> -* Lead Contributor: "Bart ten Brinke":http://www.movesonrails.com/ +* Lead Contributor: "Bart ten Brinke":http://www.movesonrails.com/ * Lead Contributor: "Aaron Patterson":http://tenderlovemaking.com/ h4. Fractional seconds for TimeWithZone diff --git a/railties/guides/source/3_0_release_notes.textile b/railties/guides/source/3_0_release_notes.textile index 14da650e83..f75b245ed8 100644 --- a/railties/guides/source/3_0_release_notes.textile +++ b/railties/guides/source/3_0_release_notes.textile @@ -18,13 +18,11 @@ These release notes cover the major upgrades, but don't include every little bug endprologue. -WARNING: Rails 3.0 is currently in beta. This means that there are probably bugs and that you should "report them":http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/overview if you see them. You also may not want to run the NORAD nuclear launch application off a beta version. But if you're starting development on a new application and you don't mind getting wind in your hair, please do jump on board! - -To install the last Rails 3 beta: +To install Rails 3: <shell> # Use sudo if your setup requires it -gem install rails --pre +$ gem install rails </shell> @@ -49,8 +47,8 @@ h4. script/* replaced by script/rails The new <tt>script/rails</tt> replaces all the scripts that used to be in the <tt>script</tt> directory. You do not run <tt>script/rails</tt> directly though, the +rails+ command detects it is being invoked in the root of a Rails application and runs the script for you. Intended usage is: <shell> -rails console # instead of script/console -rails g scaffold post title:string # instead of script/generate scaffold post title:string +$ rails console # instead of script/console +$ rails g scaffold post title:string # instead of script/generate scaffold post title:string </shell> Run <tt>rails --help</tt> for a list of all the options. @@ -61,12 +59,12 @@ The +config.gem+ method is gone and has been replaced by using +bundler+ and a + h4. Upgrade Process -To help with the upgrade process, a plugin named "Rails Upgrade":http://github.com/rails/rails_upgrade has been created to automate part of it. +To help with the upgrade process, a plugin named "Rails Upgrade":http://github.com/jm/rails_upgrade has been created to automate part of it. Simply install the plugin, then run +rake rails:upgrade:check+ to check your app for pieces that need to be updated (with links to information on how to update them). It also offers a task to generate a +Gemfile+ based on your current +config.gem+ calls and a task to generate a new routes file from your current one. To get the plugin, simply run the following: <shell> -ruby script/plugin install git://github.com/rails/rails_upgrade.git +$ ruby script/plugin install git://github.com/jm/rails_upgrade.git </shell> You can see an example of how that works at "Rails Upgrade is now an Official Plugin":http://omgbloglol.com/post/364624593/rails-upgrade-is-now-an-official-plugin @@ -77,10 +75,8 @@ More information - "The Path to Rails 3: Approaching the upgrade":http://omgblog h3. Creating a Rails 3.0 application -The new installing rails sequence (for the beta) is: - <shell> -$ gem install rails --prerelease +# You should have the 'rails' rubygem installed $ rails new myapp $ cd myapp </shell> @@ -201,9 +197,9 @@ Finally a couple of enhancements were added to the rake tasks: Railties now deprecates: -* <tt>RAILS_ROOT</tt> in favour of <tt>Rails.root</tt>, -* <tt>RAILS_ENV</tt> in favour of <tt>Rails.env</tt>, and -* <tt>RAILS_DEFAULT_LOGGER</tt> in favour of <tt>Rails.logger</tt>. +* <tt>RAILS_ROOT</tt> in favor of <tt>Rails.root</tt>, +* <tt>RAILS_ENV</tt> in favor of <tt>Rails.env</tt>, and +* <tt>RAILS_DEFAULT_LOGGER</tt> in favor of <tt>Rails.logger</tt>. <tt>PLUGIN/rails/tasks</tt>, and <tt>PLUGIN/tasks</tt> are no longer loaded all tasks now must be in <tt>PLUGIN/lib/tasks</tt>. @@ -241,7 +237,7 @@ h4. Action Controller Deprecations: -* <tt>filter_parameter_logging</tt> is deprecated in favour of <tt>config.filter_parameters << :password</tt>. +* <tt>filter_parameter_logging</tt> is deprecated in favor of <tt>config.filter_parameters << :password</tt>. More Information: * "Render Options in Rails 3":http://www.engineyard.com/blog/2010/render-options-in-rails-3/ @@ -275,10 +271,10 @@ end <ruby> scope 'es' do - resources :projects, :path_names => { :edit => 'cambiar' }, :path => 'projeto' + resources :projects, :path_names => { :edit => 'cambiar' }, :path => 'proyecto' end -# Gives you the edit action with /es/projeto/1/cambiar +# Gives you the edit action with /es/proyecto/1/cambiar </ruby> * Added +root+ method to the router as a short cut for <tt>match '/', :to => path</tt>. @@ -361,15 +357,15 @@ Validations have been moved from Active Record into Active Model, providing an i * There is now a <tt>validates :attribute, options_hash</tt> shortcut method that allows you to pass options for all the validates class methods, you can pass more than one option to a validate method. * The +validates+ method has the following options: - * <tt>:acceptance => Boolean</tt>. - * <tt>:confirmation => Boolean</tt>. - * <tt>:exclusion => { :in => Ennumerable }</tt>. - * <tt>:inclusion => { :in => Ennumerable }</tt>. - * <tt>:format => { :with => Regexp, :on => :create }</tt>. - * <tt>:length => { :maximum => Fixnum }</tt>. - * <tt>:numericality => Boolean</tt>. - * <tt>:presence => Boolean</tt>. - * <tt>:uniqueness => Boolean</tt>. +** <tt>:acceptance => Boolean</tt>. +** <tt>:confirmation => Boolean</tt>. +** <tt>:exclusion => { :in => Enumerable }</tt>. +** <tt>:inclusion => { :in => Enumerable }</tt>. +** <tt>:format => { :with => Regexp, :on => :create }</tt>. +** <tt>:length => { :maximum => Fixnum }</tt>. +** <tt>:numericality => Boolean</tt>. +** <tt>:presence => Boolean</tt>. +** <tt>:uniqueness => Boolean</tt>. NOTE: All the Rails version 2.3 style validation methods are still supported in Rails 3.0, the new validates method is designed as an additional aid in your model validations, not a replacement for the existing API. @@ -452,7 +448,7 @@ h4. Patches and Deprecations Additionally, many fixes in the Active Record branch: -* SQLite 2 support has been dropped in favour of SQLite 3. +* SQLite 2 support has been dropped in favor of SQLite 3. * MySQL support for column order. * PostgreSQL adapter has had its +TIME ZONE+ support fixed so it no longer inserts incorrect values. * Support multiple schemas in table names for PostgreSQL. @@ -464,11 +460,11 @@ As well as the following deprecations: * +named_scope+ in an Active Record class is deprecated and has been renamed to just +scope+. * In +scope+ methods, you should move to using the relation methods, instead of a <tt>:conditions => {}</tt> finder method, for example <tt>scope :since, lambda {|time| where("created_at > ?", time) }</tt>. -* <tt>save(false)</tt> is deprecated, in favour of <tt>save(:validate => false)</tt>. +* <tt>save(false)</tt> is deprecated, in favor of <tt>save(:validate => false)</tt>. * I18n error messages for ActiveRecord should be changed from :en.activerecord.errors.template to <tt>:en.errors.template</tt>. -* <tt>model.errors.on</tt> is deprecated in favour of <tt>model.errors[]</tt> +* <tt>model.errors.on</tt> is deprecated in favor of <tt>model.errors[]</tt> * validates_presence_of => validates... :presence => true -* <tt>ActiveRecord::Base.colorize_logging</tt> and <tt>config.active_record.colorize_logging</tt> are deprecated in favour of <tt>Rails::LogSubscriber.colorize_logging</tt> or <tt>config.colorize_logging</tt> +* <tt>ActiveRecord::Base.colorize_logging</tt> and <tt>config.active_record.colorize_logging</tt> are deprecated in favor of <tt>Rails::LogSubscriber.colorize_logging</tt> or <tt>config.colorize_logging</tt> NOTE: While an implementation of State Machine has been in Active Record edge for some months now, it has been removed from the Rails 3.0 release. @@ -491,7 +487,7 @@ Active Resource was also extracted out to Active Model allowing you to use Activ * Renamed <tt>SchemaDefinition</tt> to <tt>Schema</tt> and <tt>define_schema</tt> to <tt>schema</tt>. * Use the <tt>format</tt> of Active Resources rather than the <tt>content-type</tt> of remote errors to load errors. * Use <tt>instance_eval</tt> for schema block. -* Fix <tt>ActiveResource::ConnectionError#to_s</tt> when +@response+ does not respond to #code or #message, handles Ruby 1.9 compat. +* Fix <tt>ActiveResource::ConnectionError#to_s</tt> when +@response+ does not respond to #code or #message, handles Ruby 1.9 compatibility. * Add support for errors in JSON format. * Ensure <tt>load</tt> works with numeric arrays. * Recognizes a 410 response from remote resource as the resource has been deleted. @@ -500,7 +496,7 @@ Active Resource was also extracted out to Active Model allowing you to use Activ Deprecations: -* <tt>save(false)</tt> is deprecated, in favour of <tt>save(:validate => false)</tt>. +* <tt>save(false)</tt> is deprecated, in favor of <tt>save(:validate => false)</tt>. * Ruby 1.9.2: <tt>URI.parse</tt> and <tt>.decode</tt> are deprecated and are no longer used in the library. @@ -551,7 +547,7 @@ The following methods have been removed because they are now available in Ruby 1 * <tt>Object#instance_variable_defined?</tt> * <tt>Enumerable#none?</tt> -The security patch for REXML remains in Active Support because early patchlevels of Ruby 1.8.7 still need it. Active Support knows whether it has to apply it or not. +The security patch for REXML remains in Active Support because early patch-levels of Ruby 1.8.7 still need it. Active Support knows whether it has to apply it or not. The following methods have been removed because they are no longer used in the framework: @@ -579,7 +575,7 @@ Action Mailer has been given a new API with TMail being replaced out with the ne Deprecations: -* <tt>:charset</tt>, <tt>:content_type</tt>, <tt>:mime_version</tt>, <tt>:implicit_parts_order</tt> are all deprecated in favour of <tt>ActionMailer.default :key => value</tt> style declarations. +* <tt>:charset</tt>, <tt>:content_type</tt>, <tt>:mime_version</tt>, <tt>:implicit_parts_order</tt> are all deprecated in favor of <tt>ActionMailer.default :key => value</tt> style declarations. * Mailer dynamic <tt>create_method_name</tt> and <tt>deliver_method_name</tt> are deprecated, just call <tt>method_name</tt> which now returns a <tt>Mail::Message</tt> object. * <tt>ActionMailer.deliver(message)</tt> is deprecated, just call <tt>message.deliver</tt>. * <tt>template_root</tt> is deprecated, pass options to a render call inside a proc from the <tt>format.mime_type</tt> method inside the <tt>mail</tt> generation block diff --git a/railties/guides/source/action_controller_overview.textile b/railties/guides/source/action_controller_overview.textile index ec2d5b2787..ecb03a48e4 100644 --- a/railties/guides/source/action_controller_overview.textile +++ b/railties/guides/source/action_controller_overview.textile @@ -98,7 +98,7 @@ The value of +params[:ids]+ will now be +["1", "2", "3"]+. Note that parameter v To send a hash you include the key name inside the brackets: <html> -<form action="/clients" method="post"> +<form accept-charset="UTF-8" action="/clients" method="post"> <input type="text" name="client[name]" value="Acme" /> <input type="text" name="client[phone]" value="12345" /> <input type="text" name="client[address][postcode]" value="12345" /> @@ -115,10 +115,7 @@ h4. Routing Parameters The +params+ hash will always contain the +:controller+ and +:action+ keys, but you should use the methods +controller_name+ and +action_name+ instead to access these values. Any other parameters defined by the routing, such as +:id+ will also be available. As an example, consider a listing of clients where the list can show either active or inactive clients. We can add a route which captures the +:status+ parameter in a "pretty" URL: <ruby> -map.connect "/clients/:status", - :controller => "clients", - :action => "index", - :foo => "bar" +match '/clients/:status' => 'clients#index', :foo => "bar" </ruby> In this case, when a user opens the URL +/clients/active+, +params[:status]+ will be set to "active". When this route is used, +params[:foo]+ will also be set to "bar" just like it was passed in the query string. In the same way +params[:action]+ will contain "index". @@ -161,7 +158,7 @@ If you need a different session storage mechanism, you can change it in the +con <ruby> # Use the database for sessions instead of the cookie-based default, # which shouldn't be used to store highly confidential information -# (create the session table with "rake db:sessions:create") +# (create the session table with "script/rails g session_migration") # YourApp::Application.config.session_store :active_record_store </ruby> @@ -214,7 +211,7 @@ class ApplicationController < ActionController::Base # logging out removes it. def current_user @_current_user ||= session[:current_user_id] && - User.find(session[:current_user_id]) + User.find_by_id(session[:current_user_id]) end end </ruby> @@ -242,7 +239,7 @@ class LoginsController < ApplicationController # "Delete" a login, aka "log the user out" def destroy # Remove the user id from the session - session[:current_user_id] = nil + @_current_user = session[:current_user_id] = nil redirect_to root_url end end @@ -264,6 +261,13 @@ class LoginsController < ApplicationController end </ruby> +Note it is also possible to assign a flash message as part of the redirection. + +<ruby> +redirect_to root_url, :notice => "You have successfully logged out" +</ruby> + + The +destroy+ action redirects to the application's +root_url+, where the message will be displayed. Note that it's entirely up to the next action to decide what, if anything, it will do with what the previous action put in the flash. It's conventional to display eventual errors or notices from the flash in the application's layout: <ruby> @@ -296,7 +300,7 @@ class MainController < ApplicationController # Will persist all flash values. flash.keep - # You can also use a key to keep only some kind of value. + # You can also use a key to keep only some kind of value. # flash.keep(:notice) redirect_to users_url end @@ -364,19 +368,20 @@ class UsersController < ApplicationController respond_to do |format| format.html # index.html.erb format.xml { render :xml => @users} + format.json { render :json => @users} end end end </ruby> -Notice that in the above case code is <tt>render :xml => @users</tt> and not <tt>render :xml => @users.to_xml</tt>. That is because if the input is not string then rails automatically invokes +to_xml+ . +Notice that in the above case code is <tt>render :xml => @users</tt> and not <tt>render :xml => @users.to_xml</tt>. That is because if the input is not string then rails automatically invokes +to_xml+ . h3. Filters -Filters are methods that are run before, after or "around" a controller action. +Filters are methods that are run before, after or "around" a controller action. -Filters are inherited, so if you set a filter on +ApplicationController+, it will be run on every controller in your application. +Filters are inherited, so if you set a filter on +ApplicationController+, it will be run on every controller in your application. Before filters may halt the request cycle. A common before filter is one which requires that a user is logged in for an action to be run. You can define the filter method this way: @@ -418,27 +423,36 @@ Now, the +LoginsController+'s +new+ and +create+ actions will work as before wit h4. After Filters and Around Filters -In addition to before filters, you can run filters after an action has run or both before and after. The after filter is similar to the before filter, but because the action has already been run it has access to the response data that's about to be sent to the client. Obviously, after filters can not stop the action from running. +In addition to before filters, you can also run filters after an action has been executed, or both before and after. + +After filters are similar to before filters, but because the action has already been run they have access to the response data that's about to be sent to the client. Obviously, after filters cannot stop the action from running. -Around filters are responsible for running the action, but they can choose not to, which is the around filter's way of stopping it. +Around filters are responsible for running their associated actions by yielding, similar to how Rack middlewares work. + +For example, in a website where changes have an approval workflow an administrator could be able to preview them easily, just apply them within a transaction: <ruby> -# Example taken from the Rails API filter documentation: -# http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html -class ApplicationController < ActionController::Base - around_filter :catch_exceptions +class ChangesController < ActionController::Base + around_filter :wrap_in_transaction, :only => :show private - def catch_exceptions - yield - rescue => exception - logger.debug "Caught exception! #{exception}" - raise + def wrap_in_transaction + ActiveRecord::Base.transaction do + begin + yield + ensure + raise ActiveRecord::Rollback + end + end end end </ruby> +Note that an around filter wraps also rendering. In particular, if in the example above the view itself reads from the database via a scope or whatever, it will do so within the transaction and thus present the data to preview. + +They can choose not to yield and build the response themselves, in which case the action is not run. + h4. Other Ways to Use Filters While the most common way to use filters is by creating private methods and using *_filter to add them, there are two other ways to do the same thing. @@ -474,11 +488,9 @@ end Again, this is not an ideal example for this filter, because it's not run in the scope of the controller but gets the controller passed as an argument. The filter class has a class method +filter+ which gets run before or after the action, depending on if it's a before or after filter. Classes used as around filters can also use the same +filter+ method, which will get run in the same way. The method must +yield+ to execute the action. Alternatively, it can have both a +before+ and an +after+ method that are run before and after the action. -The Rails API documentation has "more information on using filters":http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html. - h3. Verification -Verifications make sure certain criteria are met in order for a controller or action to run. They can specify that a certain key (or several keys in the form of an array) is present in the +params+, +session+ or +flash+ hashes or that a certain HTTP method was used or that the request was made using +XMLHttpRequest+ (Ajax). The default action taken when these criteria are not met is to render a 400 Bad Request response, but you can customize this by specifying a redirect URL or rendering something else and you can also add flash messages and HTTP headers to the response. It is described in the "API documentation":http://api.rubyonrails.org/classes/ActionController/Verification/ClassMethods.html as "essentially a special kind of before_filter". +Verifications make sure certain criteria are met in order for a controller or action to run. They can specify that a certain key (or several keys in the form of an array) is present in the +params+, +session+ or +flash+ hashes or that a certain HTTP method was used or that the request was made using +XMLHttpRequest+ (Ajax). The default action taken when these criteria are not met is to render a 400 Bad Request response, but you can customize this by specifying a redirect URL or rendering something else and you can also add flash messages and HTTP headers to the response. Here's an example of using verification to make sure the user supplies a username and a password in order to log in: @@ -535,8 +547,8 @@ If you generate a form like this: You will see how the token gets added as a hidden field: <html> -<form action="/users/1" method="post"> -<input type="hidden" +<form accept-charset="UTF-8" action="/users/1" method="post"> +<input type="hidden" value="67250ab105eb5ad10851c00a5621854a23af5489" name="authenticity_token"/> <!-- fields --> @@ -555,7 +567,7 @@ In every controller there are two accessor methods pointing to the request and t h4. The +request+ Object -The request object contains a lot of useful information about the request coming in from the client. To get a full list of the available methods, refer to the "API documentation":http://api.rubyonrails.org/classes/ActionController/AbstractRequest.html. Among the properties that you can access on this object are: +The request object contains a lot of useful information about the request coming in from the client. To get a full list of the available methods, refer to the "API documentation":http://api.rubyonrails.org/classes/ActionDispatch/Request.html. Among the properties that you can access on this object are: |_.Property of +request+|_.Purpose| |host|The hostname used for this request.| @@ -659,7 +671,7 @@ class ClientsController < ApplicationController # returns it. The user will get the PDF as a file download. def download_pdf client = Client.find(params[:id]) - send_data generate_pdf(client), + send_data generate_pdf(client), :filename => "#{client.name}.pdf", :type => "application/pdf" end @@ -734,16 +746,12 @@ GET /clients/1.pdf h3. Parameter Filtering -Rails keeps a log file for each environment in the +log+ folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. The +filter_parameter_logging+ method can be used to filter out sensitive information from the log. It works by replacing certain values in the +params+ hash with "[FILTERED]" as they are written to the log. As an example, let's see how to filter all parameters with keys that include "password": +Rails keeps a log file for each environment in the +log+ folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. You can filter certain request parameters from your log files by appending them to <tt>config.filter_parameters</tt> in the application configuration. These parameters will be marked [FILTERED] in the log. <ruby> -class ApplicationController < ActionController::Base - filter_parameter_logging :password -end +config.filter_parameters << :password </ruby> -The method works recursively through all levels of the +params+ hash and takes an optional second parameter which is used as the replacement string if present. It can also take a block which receives each key in turn and replaces those for which the block returns true. - h3. Rescue Most likely your application is going to contain bugs or otherwise throw an exception that needs to be handled. For example, if the user follows a link to a resource that no longer exists in the database, Active Record will throw the +ActiveRecord::RecordNotFound+ exception. @@ -810,8 +818,6 @@ NOTE: Certain exceptions are only rescuable from the +ApplicationController+ cla h3. Changelog -"Lighthouse Ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/17 - * February 17, 2009: Yet another proofread by Xavier Noria. * November 4, 2008: First release version by Tore Darell diff --git a/railties/guides/source/action_mailer_basics.textile b/railties/guides/source/action_mailer_basics.textile index 8eb48e2751..56da360972 100644 --- a/railties/guides/source/action_mailer_basics.textile +++ b/railties/guides/source/action_mailer_basics.textile @@ -19,7 +19,7 @@ h4. Walkthrough to Generating a Mailer h5. Create the Mailer <shell> -rails generate mailer UserMailer +$ rails generate mailer UserMailer create app/mailers/user_mailer.rb invoke erb create app/views/user_mailer @@ -27,7 +27,7 @@ invoke test_unit create test/functional/user_mailer_test.rb </shell> -So we got the mailer, the fixtures, and the tests. +So we got the mailer, the views, and the tests. h5. Edit the Mailer @@ -144,7 +144,7 @@ This provides a much simpler implementation that does not require the registerin The method +welcome_email+ returns a Mail::Message object which can then just be told +deliver+ to send itself out. -NOTE: In previous versions of Rails, you would call +deliver_welcome_email+ or +create_welcome_email+ however in Rails 3.0 this has been deprecated in favour of just calling the method name itself. +NOTE: In previous versions of Rails, you would call +deliver_welcome_email+ or +create_welcome_email+. This has been deprecated in Rails 3.0 in favour of just calling the method name itself. WARNING: Sending out one email should only take a fraction of a second, if you are planning on sending out many emails, or you have a slow domain resolution service, you might want to investigate using a background process like delayed job. @@ -154,7 +154,7 @@ Action Mailer now handles the auto encoding of multibyte characters inside of he If you are using UTF-8 as your character set, you do not have to do anything special, just go ahead and send in UTF-8 data to the address fields, subject, keywords, filenames or body of the email and ActionMailer will auto encode it into quoted printable for you in the case of a header field or Base64 encode any body parts that are non US-ASCII. -For more complex examples, such as defining alternate character sets or self encoding text first, please refer to the Mail library. +For more complex examples such as defining alternate character sets or self encoding text first, please refer to the Mail library. h4. Complete List of Action Mailer Methods @@ -198,7 +198,7 @@ Adding attachments has been simplified in Action Mailer 3.0. attachments['filename.jpg'] = File.read('/path/to/filename.jpg') </ruby> -NOTE: Mail will automatically Base64 encode an attachment, if you want something different, pre encode your content and pass in the encoded content and encoding in a +Hash+ to the +attachments+ method. +NOTE: Mail will automatically Base64 encode an attachment, if you want something different, pre-encode your content and pass in the encoded content and encoding in a +Hash+ to the +attachments+ method. * Pass the file name and specify headers and content and Action Mailer and Mail will use the settings you pass in. @@ -213,9 +213,7 @@ NOTE: If you specify an encoding, Mail will assume that your content is already h5. Making Inline Attachments -Inline attachments are now possible in ActionMailer. While previously in the pre 3.0 version of Rails, you could do inline attachments, it involved a lot of hacking and determination to pull it off. - -ActionMailer now makes inline attachments as trivial as they should be. +ActionMailer 3.0 makes inline attachments, which involved a lot of hacking in pre 3.0 versions, much simpler and trivial as they should be. * Firstly, to tell Mail to turn an attachment into an inline attachment, you just call <tt>#inline</tt> on the attachments method within your Mailer: @@ -242,9 +240,39 @@ end :class => 'photos' %> </erb> +h5. Sending Email To Multiple Recipients + +It is possible to send email to one or more recipients in one email (for e.g. informing all admins of a new signup) by setting the list of emails to the <tt>:to</tt> key. The <tt>to:</tt> key however expects a string so you have join the list of recipients using a comma. + +<ruby> + class AdminMailer < ActionMailer::Base + default :to => Admin.all.map(&:email).join(", "), + :from => "notification@example.com" + + def new_registration(user) + @user = user + mail(:subject => "New User Signup: #{@user.email}") + end + end +</ruby> + +h5. Sending Email With Name + +Sometimes you wish to show the name of the person instead of just their email address when they receive the email. The trick to doing that is +to format the email address in the format <tt>"Name <email>"</tt>. + +<ruby> + def welcome_email(user) + @user = user + email_with_name = "#{@user.name} <#{@user.email}>" + mail(:to => email_with_name, + :subject => "Welcome to My Awesome Site") + end +</ruby> + h4. Mailer Views -Mailer views are located in the +app/views/name_of_mailer_class+ directory. The specific mailer view is known to the class because it's name is the same as the mailer method. So for example, in our example from above, our mailer view for the +welcome_email+ method will be in +app/views/user_mailer/welcome_email.html.erb+ for the HTML version and +welcome_email.text.erb+ for the plain text version. +Mailer views are located in the +app/views/name_of_mailer_class+ directory. The specific mailer view is known to the class because its name is the same as the mailer method. In our example from above, our mailer view for the +welcome_email+ method will be in +app/views/user_mailer/welcome_email.html.erb+ for the HTML version and +welcome_email.text.erb+ for the plain text version. To change the default mailer view for your action you do something like: @@ -373,7 +401,7 @@ The above will send a multipart email with an attachment, properly nested with t h3. Receiving Emails -Receiving and parsing emails with Action Mailer can be a rather complex endeavour. Before your email reaches your Rails app, you would have had to configure your system to somehow forward emails to your app, which needs to be listening for that. So, to receive emails in your Rails app you'll need: +Receiving and parsing emails with Action Mailer can be a rather complex endeavour. Before your email reaches your Rails app, you would have had to configure your system to somehow forward emails to your app, which needs to be listening for that. So, to receive emails in your Rails app you'll need to: * Implement a +receive+ method in your mailer. @@ -411,12 +439,12 @@ h3. Action Mailer Configuration The following configuration options are best made in one of the environment files (environment.rb, production.rb, etc...) |template_root|Determines the base from which template references will be made.| -|logger|the logger is used for generating information on the mailing run if available. Can be set to nil for no logging. Compatible with both Ruby's own Logger and Log4r loggers.| -|smtp_settings|Allows detailed configuration for :smtp delivery method: :address - Allows you to use a remote mail server. Just change it from its default "localhost" setting. :port - On the off chance that your mail server doesn't run on port 25, you can change it. :domain - If you need to specify a HELO domain, you can do it here. :user_name - If your mail server requires authentication, set the username in this setting. :password - If your mail server requires authentication, set the password in this setting. :authentication - If your mail server requires authentication, you need to specify the authentication type here. This is a symbol and one of :plain, :login, :cram_md5.| -|sendmail_settings|Allows you to override options for the :sendmail delivery method. :location - The location of the sendmail executable. Defaults to /usr/sbin/sendmail. :arguments - The command line arguments. Defaults to -i -t.| +|logger|Generates information on the mailing run if available. Can be set to nil for no logging. Compatible with both Ruby's own Logger and Log4r loggers.| +|smtp_settings|Allows detailed configuration for :smtp delivery method:<ul><li>:address - Allows you to use a remote mail server. Just change it from its default "localhost" setting.</li><li>:port - On the off chance that your mail server doesn't run on port 25, you can change it.</li><li>:domain - If you need to specify a HELO domain, you can do it here.</li><li>:user_name - If your mail server requires authentication, set the username in this setting.</li><li>:password - If your mail server requires authentication, set the password in this setting.</li><li>: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.</li></ul>| +|sendmail_settings|Allows you to override options for the :sendmail delivery method.<ul><li>:location - The location of the sendmail executable. Defaults to /usr/sbin/sendmail.</li><li>:arguments - The command line arguments to be passed to sendmail. Defaults to -i -t.</li></ul>| |raise_delivery_errors|Whether or not errors should be raised if the email fails to be delivered.| -|delivery_method|Defines a delivery method. Possible values are :smtp (default), :sendmail, and :test.| -|perform_deliveries|Determines whether deliver_* methods are actually carried out. By default they are, but this can be turned off to help functional testing.| +|delivery_method|Defines a delivery method. Possible values are :smtp (default), :sendmail, :file and :test.| +|perform_deliveries|Determines whether deliveries are actually carried out when the +deliver+ method is invoked on the Mail message. By default they are, but this can be turned off to help functional testing.| |deliveries|Keeps an array of all the emails sent out through the Action Mailer with delivery_method :test. Most useful for unit and functional testing.| h4. Example Action Mailer Configuration @@ -462,7 +490,7 @@ class UserMailerTest < ActionMailer::TestCase user = users(:some_user_in_your_fixtures) # Send the email, then test that it got queued - email = UserMailer.deliver_welcome_email(user) + email = UserMailer.welcome_email(user).deliver assert !ActionMailer::Base.deliveries.empty? # Test the body of the sent email contains what we expect it to @@ -474,8 +502,8 @@ class UserMailerTest < ActionMailer::TestCase end </ruby> -In the test we send the email and store the returned object in the +email+ variable. We then ensure that it was sent (the first assert), then, in the second batch of assertions, we ensure that the email does indeed contain the what we expect. +In the test we send the email and store the returned object in the +email+ variable. We then ensure that it was sent (the first assert), then, in the second batch of assertions, we ensure that the email does indeed contain what we expect. h3. Changelog -"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213/tickets/25 +* September 30, 2010: Fixed typos and reformatted Action Mailer configuration table for better understanding. "Jaime Iniesta":http://jaimeiniesta.com diff --git a/railties/guides/source/action_view_overview.textile b/railties/guides/source/action_view_overview.textile index 8b5eda0973..cfd71ad287 100644 --- a/railties/guides/source/action_view_overview.textile +++ b/railties/guides/source/action_view_overview.textile @@ -12,9 +12,9 @@ endprologue. h3. What is Action View? -Action View and Action Controller are the two major components of Action Pack. In Rails, web requests are handled by Action Pack, which splits the work into a controller part (performing the logic) and a view part (rendering a template). Typically, Action Controller will be concerned with communicating with the database and performing CRUD actions where necessary. Action View is then responsible for compiling the response. +Action View and Action Controller are the two major components of Action Pack. In Rails, web requests are handled by Action Pack, which splits the work into a controller part (performing the logic) and a view part (rendering a template). Typically, Action Controller will be concerned with communicating with the database and performing CRUD actions where necessary. Action View is then responsible for compiling the response. -Action View templates are written using embedded Ruby in tags mingled with HTML. To avoid cluttering the templates with boilerplate code, a number of helper classes provide common behavior for forms, dates, and strings. It's also easy to add new helpers to your application as it evolves. +Action View templates are written using embedded Ruby in tags mingled with HTML. To avoid cluttering the templates with boilerplate code, a number of helper classes provide common behavior for forms, dates, and strings. It's also easy to add new helpers to your application as it evolves. Note: Some features of Action View are tied to Active Record, but that doesn't mean that Action View depends on Active Record. Action View is an independent package that can be used with any sort of backend. @@ -24,13 +24,13 @@ TODO... h3. Using Action View outside of Rails -Action View works well with Action Record, but it can also be used with other Ruby tools. We can demonstrate this by creating a small "Rack":http://rack.rubyforge.org/ application that includes Action View functionality. This may be useful, for example, if you'd like access to Action View's helpers in a Rack application. +Action View works well with Action Record, but it can also be used with other Ruby tools. We can demonstrate this by creating a small "Rack":http://rack.rubyforge.org/ application that includes Action View functionality. This may be useful, for example, if you'd like access to Action View's helpers in a Rack application. Let's start by ensuring that you have the Action Pack and Rack gems installed: <shell> -gem install actionpack -gem install rack +$ gem install actionpack +$ gem install rack </shell> Now we'll create a simple "Hello World" application that uses the +titleize+ method provided by Active Support. @@ -52,20 +52,20 @@ Rack::Handler::Mongrel.run method(:hello_world), :Port => 4567 We can see this all come together by starting up the application and then visiting +http://localhost:4567/+ <shell> -ruby hello_world.rb +$ ruby hello_world.rb </shell> -TODO needs a screenshot? I have one - not sure where to put it. +TODO needs a screenshot? I have one - not sure where to put it. -Notice how 'hello world' has been converted into 'Hello World' by the +titleize+ helper method. +Notice how 'hello world' has been converted into 'Hello World' by the +titleize+ helper method. -Action View can also be used with "Sinatra":http://www.sinatrarb.com/ in the same way. +Action View can also be used with "Sinatra":http://www.sinatrarb.com/ in the same way. Let's start by ensuring that you have the Action Pack and Sinatra gems installed: <shell> -gem install actionpack -gem install sinatra +$ gem install actionpack +$ gem install sinatra </shell> Now we'll create the same "Hello World" application in Sinatra. @@ -85,12 +85,12 @@ end Then, we can run the application: <shell> -ruby hello_world.rb +$ ruby hello_world.rb </shell> Once the application is running, you can see Sinatra and Action View working together by visiting +http://localhost:4567/+ -TODO needs a screenshot? I have one - not sure where to put it. +TODO needs a screenshot? I have one - not sure where to put it. h3. Templates, Partials and Layouts @@ -172,7 +172,7 @@ TODO... h3. Overview of all the helpers provided by Action View -The following is only a brief overview summary of the helpers available in Action View. It's recommended that you review the API Documentation, which covers all of the helpers in more detail, but this should serve as a good starting point. +The following is only a brief overview summary of the helpers available in Action View. It's recommended that you review the API Documentation, which covers all of the helpers in more detail, but this should serve as a good starting point. h4. ActiveRecordHelper @@ -196,7 +196,7 @@ error_messages_for "post" h5. form -Returns a form with inputs for all attributes of the specified Active Record object. For example, let's say we have a +@post+ with attributes named +title+ of type +String+ and +body+ of type +Text+. Calling +form+ would produce a form to creating a new post with inputs for those attributes. +Returns a form with inputs for all attributes of the specified Active Record object. For example, let's say we have a +@post+ with attributes named +title+ of type +String+ and +body+ of type +Text+. Calling +form+ would produce a form to creating a new post with inputs for those attributes. <ruby> form("post") @@ -220,29 +220,29 @@ Typically, +form_for+ is used instead of +form+ because it doesn't automatically h5. input -Returns a default input tag for the type of object returned by the method. +Returns a default input tag for the type of object returned by the method. For example, if +@post+ has an attribute +title+ mapped to a +String+ column that holds "Hello World": <ruby> -input("post", "title") # => +input("post", "title") # => <input id="post_title" name="post[title]" size="30" type="text" value="Hello World" /> </ruby> h4. AssetTagHelper -This module provides methods for generating HTML that links views to assets such as images, javascripts, stylesheets, and feeds. +This module provides methods for generating HTML that links views to assets such as images, JavaScript files, stylesheets, and feeds. -By default, Rails links to these assets on the current host in the public folder, but you can direct Rails to link to assets from a dedicated assets server by setting +ActionController::Base.asset_host+ in your +config/environment.rb+. For example, let's say your asset host is +assets.example.com+: +By default, Rails links to these assets on the current host in the public folder, but you can direct Rails to link to assets from a dedicated assets server by setting +ActionController::Base.asset_host+ in the application configuration, typically in +config/environments/production.rb+. For example, let's say your asset host is +assets.example.com+: <ruby> ActionController::Base.asset_host = "assets.example.com" -image_tag("rails.png") # => <img src="http://assets.example.com/images/rails.png" alt="Rails" /> +image_tag("rails.png") # => <img src="http://assets.example.com/images/rails.png" alt="Rails" /> </ruby> h5. register_javascript_expansion -Register one or more javascript files to be included when symbol is passed to javascript_include_tag. This method is typically intended to be called from plugin initialization to register javascript files that the plugin installed in public/javascripts. +Register one or more JavaScript files to be included when symbol is passed to javascript_include_tag. This method is typically intended to be called from plugin initialization to register JavaScript files that the plugin installed in +public/javascripts+. <ruby> ActionView::Helpers::AssetTagHelper.register_javascript_expansion :monkey => ["head", "body", "tail"] @@ -253,9 +253,6 @@ javascript_include_tag :monkey # => <script type="text/javascript" src="/javascripts/tail.js"></script> </ruby> -h5. register_javascript_include_default - -Register one or more additional JavaScript files to be included when +javascript_include_tag :defaults+ is called. This method is typically intended to be called from plugin initialization to register additional +.js+ files that the plugin installed in +public/javascripts+. h5. register_stylesheet_expansion @@ -281,7 +278,7 @@ auto_discovery_link_tag(:rss, "http://www.example.com/feed.rss", {:title => "RSS h5. image_path -Computes the path to an image asset in the public images directory. Full paths from the document root will be passed through. Used internally by +image_tag+ to build the image path. +Computes the path to an image asset in the +public/images+ directory. Full paths from the document root will be passed through. Used internally by +image_tag+ to build the image path. <ruby> image_path("edit.png") # => /images/edit.png @@ -289,7 +286,7 @@ image_path("edit.png") # => /images/edit.png h5. image_tag -Returns an html image tag for the source. The source can be a full path or a file that exists in your public images directory. +Returns an html image tag for the source. The source can be a full path or a file that exists in your +public/images+ directory. <ruby> image_tag("icon.png") # => <img src="/images/icon.png" alt="Icon" /> @@ -297,35 +294,35 @@ image_tag("icon.png") # => <img src="/images/icon.png" alt="Icon" /> h5. javascript_include_tag -Returns an html script tag for each of the sources provided. You can pass in the filename (+.js+ extension is optional) of javascript files that exist in your +public/javascripts+ directory for inclusion into the current page or you can pass the full path relative to your document root. +Returns an html script tag for each of the sources provided. You can pass in the filename (+.js+ extension is optional) of JavaScript files that exist in your +public/javascripts+ directory for inclusion into the current page or you can pass the full path relative to your document root. <ruby> javascript_include_tag "common" # => - <script type="text/javascript" src="/javascripts/common.js"></script> + <script type="text/javascript" src="/javascripts/common.js"></script> </ruby> -To include the Prototype and Scriptaculous javascript libraries in your application, pass +:defaults+ as the source. When using +:defaults+, if an +application.js+ file exists in your +public/javascripts+ directory, it will be included as well. +To include the Prototype and Scriptaculous JavaScript libraries in your application, pass +:defaults+ as the source. When using +:defaults+, if an +application.js+ file exists in your +public/javascripts+ directory, it will be included as well. <ruby> javascript_include_tag :defaults </ruby> -You can also include all javascripts in the javascripts directory using +:all+ as the source. +You can also include all JavaScript files in the +public/javascripts+ directory using +:all+ as the source. <ruby> javascript_include_tag :all </ruby> -You can also cache multiple javascripts into one file, which requires less HTTP connections to download and can better be compressed by gzip (leading to faster transfers). Caching will only happen if +ActionController::Base.perform_caching+ is set to true (which is the case by default for the Rails production environment, but not for the development environment). +You can also cache multiple JavaScript files into one file, which requires less HTTP connections to download and can better be compressed by gzip (leading to faster transfers). Caching will only happen if +ActionController::Base.perform_caching+ is set to true (which is the case by default for the Rails production environment, but not for the development environment). <ruby> -javascript_include_tag :all, :cache => true # => - <script type="text/javascript" src="/javascripts/all.js"></script> +javascript_include_tag :all, :cache => true # => + <script type="text/javascript" src="/javascripts/all.js"></script> </ruby> h5. javascript_path -Computes the path to a javascript asset in the +public/javascripts+ directory. If the source filename has no extension, +.js+ will be appended. Full paths from the document root will be passed through. Used internally by +javascript_include_tag+ to build the script path. +Computes the path to a JavaScript asset in the +public/javascripts+ directory. If the source filename has no extension, +.js+ will be appended. Full paths from the document root will be passed through. Used internally by +javascript_include_tag+ to build the script path. <ruby> javascript_path "common" # => /javascripts/common.js @@ -333,7 +330,7 @@ javascript_path "common" # => /javascripts/common.js h5. stylesheet_link_tag -Returns a stylesheet link tag for the sources specified as arguments. If you don't specify an extension, +.css+ will be appended automatically. +Returns a stylesheet link tag for the sources specified as arguments. If you don't specify an extension, +.css+ will be appended automatically. <ruby> stylesheet_link_tag "application" # => @@ -346,7 +343,7 @@ You can also include all styles in the stylesheet directory using :all as the so stylesheet_link_tag :all </ruby> -You can also cache multiple stylesheets into one file, which requires less HTTP connections and can better be compressed by gzip (leading to faster transfers). Caching will only happen if ActionController::Base.perform_caching is set to true (which is the case by default for the Rails production environment, but not for the development environment). +You can also cache multiple stylesheets into one file, which requires less HTTP connections and can better be compressed by gzip (leading to faster transfers). Caching will only happen if ActionController::Base.perform_caching is set to true (which is the case by default for the Rails production environment, but not for the development environment). <ruby> stylesheet_link_tag :all, :cache => true @@ -355,7 +352,7 @@ stylesheet_link_tag :all, :cache => true h5. stylesheet_path -Computes the path to a stylesheet asset in the public stylesheets directory. If the source filename has no extension, .css will be appended. Full paths from the document root will be passed through. Used internally by stylesheet_link_tag to build the stylesheet path. +Computes the path to a stylesheet asset in the +public/stylesheets+ directory. If the source filename has no extension, .css will be appended. Full paths from the document root will be passed through. Used internally by stylesheet_link_tag to build the stylesheet path. <ruby> stylesheet_path "application" # => /stylesheets/application.css @@ -370,14 +367,14 @@ This helper makes building an ATOM feed easy. Here's a full usage example: *config/routes.rb* <ruby> -map.resources :posts +resources :posts </ruby> *app/controllers/posts_controller.rb* <ruby> def index - @posts = Post.find(:all) + @posts = Post.all respond_to do |format| format.html @@ -415,7 +412,7 @@ Allows you to measure the execution time of a block in a template and records th <ruby> <% benchmark "Process data files" do %> <%= expensive_files_operation %> -<% end %> +<% end %> </ruby> This would add something like "Process data files (0.34523)" to the log, which you can then use to compare timings when optimizing your code. @@ -428,7 +425,7 @@ A method for caching fragments of a view rather than an entire action or page. T <ruby> <% cache do %> - <%= render :partial => "shared/footer" %> + <%= render "shared/footer" %> <% end %> </ruby> @@ -442,7 +439,7 @@ The +capture+ method allows you to extract part of a template into a variable. Y <% @greeting = capture do %> <p>Welcome! The date and time is <%= Time.now %></p> <% end %> -<ruby> +</ruby> The captured variable can then be used anywhere else. @@ -455,7 +452,7 @@ The captured variable can then be used anywhere else. <%= @greeting %> </body> </html> -</ruby> +</ruby> h5. content_for @@ -484,7 +481,7 @@ For example, let's say we have a standard application layout, but also a special <% content_for :special_script do %> <script type="text/javascript">alert('Hello!')</script> -<% end %> +<% end %> </ruby> h4. DateHelper @@ -523,7 +520,7 @@ Returns a set of html select-tags (one for year, month, and day) pre-selected wi select_date(Time.today + 6.days) # Generates a date select that defaults to today (no specified date) -select_date() +select_date() </ruby> h5. select_datetime @@ -535,7 +532,7 @@ Returns a set of html select-tags (one for year, month, day, hour, and minute) p select_datetime(Time.now + 4.days) # Generates a datetime select that defaults to today (no specified datetime) -select_datetime() +select_datetime() </ruby> h5. select_day @@ -583,7 +580,7 @@ Returns a select tag with options for each of the seconds 0 through 59 with the <ruby> # Generates a select field for seconds that defaults to the seconds for the time provided -select_second(Time.now + 16.minutes) +select_second(Time.now + 16.minutes) </ruby> h5. select_time @@ -592,7 +589,7 @@ Returns a set of html select-tags (one for hour and minute). <ruby> # Generates a time select that defaults to the time provided -select_time(Time.now) +select_time(Time.now) </ruby> h5. select_year @@ -621,7 +618,7 @@ Returns a set of select tags (one for hour, minute and optionally second) pre-se <ruby> # Creates a time select tag that, when POSTed, will be stored in the order variable in the submitted attribute -time_select("order", "submitted") +time_select("order", "submitted") </ruby> h4. DebugHelper @@ -654,7 +651,7 @@ The core method of this helper, form_for, gives you the ability to create a form <ruby> # Note: a @person variable will have been created in the controller (e.g. @person = Person.new) -<%= form_for :person, @person, :url => { :action => "create" } do |f| %> +<%= form_for @person, :url => { :action => "create" } do |f| %> <%= f.text_field :first_name %> <%= f.text_field :last_name %> <%= submit_tag 'Create' %> @@ -711,7 +708,7 @@ Returns an file upload input tag tailored for accessing a specified attribute. <ruby> file_field(:user, :avatar) -# => <input type="file" id="user_avatar" name="user[avatar]" /> +# => <input type="file" id="user_avatar" name="user[avatar]" /> </ruby> h5. form_for @@ -733,7 +730,7 @@ Returns a hidden input tag tailored for accessing a specified attribute. <ruby> hidden_field(:user, :token) -# => <input type="hidden" id="user_token" name="user[token]" value="#{@user.token}" /> +# => <input type="hidden" id="user_token" name="user[token]" value="#{@user.token}" /> </ruby> h5. label @@ -751,7 +748,7 @@ Returns an input tag of the "password" type tailored for accessing a specified a <ruby> password_field(:login, :pass) -# => <input type="text" id="login_pass" name="login[pass]" value="#{@login.pass}" /> +# => <input type="text" id="login_pass" name="login[pass]" value="#{@login.pass}" /> </ruby> h5. radio_button @@ -812,7 +809,7 @@ end Sample usage (selecting the associated Author for an instance of Post, +@post+): <ruby> -collection_select(:post, :author_id, Author.find(:all), :id, :name_with_initial, {:prompt => true}) +collection_select(:post, :author_id, Author.all, :id, :name_with_initial, {:prompt => true}) </ruby> If @post.author_id is already 1, this would return: @@ -854,7 +851,7 @@ end Sample usage: -<ruby> +<ruby> option_groups_from_collection_for_select(@continents, :countries, :name, :id, :name, 3) </ruby> @@ -880,7 +877,7 @@ Note: Only the +optgroup+ and +option+ tags are returned, so you still have to w h5. options_for_select -Accepts a container (hash, array, enumerable, your type) and returns a string of option tags. +Accepts a container (hash, array, enumerable, your type) and returns a string of option tags. <ruby> options_for_select([ "VISA", "MasterCard" ]) @@ -891,7 +888,7 @@ Note: Only the +option+ tags are returned, you have to wrap this call in a regul h5. options_from_collection_for_select -Returns a string of option tags that have been compiled by iterating over the +collection+ and assigning the the result of a call to the +value_method+ as the option value and the +text_method+ as the option text. +Returns a string of option tags that have been compiled by iterating over the +collection+ and assigning the result of a call to the +value_method+ as the option value and the +text_method+ as the option text. <ruby> # options_from_collection_for_select(collection, value_method, text_method, selected = nil) @@ -902,7 +899,7 @@ For example, imagine a loop iterating over each person in @project.people to gen <ruby> options_from_collection_for_select(@project.people, "id", "name") # => <option value="#{person.id}">#{person.name}</option> -</ruby> +</ruby> Note: Only the +option+ tags are returned, you have to wrap this call in a regular HTML +select+ tag. @@ -913,7 +910,7 @@ Create a select tag and a series of contained option tags for the provided objec Example with @post.person_id => 1: <ruby> -select("post", "person_id", Person.find(:all).collect {|p| [ p.name, p.id ] }, { :include_blank => true }) +select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, { :include_blank => true }) </ruby> could become: @@ -949,7 +946,7 @@ Creates a check box form input tag. <ruby> check_box_tag 'accept' -# => <input id="accept" name="accept" type="checkbox" value="1" /> +# => <input id="accept" name="accept" type="checkbox" value="1" /> </ruby> h5. field_set_tag @@ -965,7 +962,7 @@ Creates a field set for grouping HTML form elements. h5. file_field_tag -Creates a file upload field. +Creates a file upload field. If you are using file uploads then you will also need to set the multipart option for the form tag: @@ -1079,7 +1076,7 @@ h4. JavaScriptHelper Provides functionality for working with JavaScript in your views. -Rails includes the Prototype JavaScript framework and the Scriptaculous JavaScript controls and visual effects library. If you wish to use these libraries and their helpers, make sure +<%= javascript_include_tag :defaults, :cache => true %>+ is in the HEAD section of your page. This function will include the necessary JavaScript files Rails generated in the public/javascripts directory. +Rails includes the Prototype JavaScript framework and the Scriptaculous JavaScript controls and visual effects library. If you wish to use these libraries and their helpers, make sure +<%= javascript_include_tag :defaults, :cache => true %>+ is in the HEAD section of your page. This function will include the necessary JavaScript files Rails generated in the +public/javascripts+ directory. h5. button_to_function @@ -1173,7 +1170,7 @@ number_with_delimiter(12345678) # => 12,345,678 h5. number_with_precision -Formats a number with the specified level of +precision+, which defaults to 3. +Formats a number with the specified level of +precision+, which defaults to 3. <ruby> number_with_precision(111.2345) # => 111.235 @@ -1207,7 +1204,7 @@ form_remote_tag :html => { :action => url_for(:controller => "some", :action => would generate the following: <html> -<form action="/some/place" method="post" onsubmit="new Ajax.Request('', +<form action="/some/place" method="post" onsubmit="new Ajax.Request('', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)}); return false;"> </html> @@ -1293,7 +1290,7 @@ Yields a JavaScriptGenerator and returns the generated JavaScript code. Use this <ruby> update_page do |page| page.hide 'spinner' -end +end </ruby> h5. update_page_tag @@ -1395,7 +1392,7 @@ h5. remove Removes the DOM elements with the given ids from the page. <ruby> -page.remove 'person_23', 'person_9', 'person_2' +page.remove 'person_23', 'person_9', 'person_2' </ruby> h5. replace @@ -1420,7 +1417,7 @@ Returns a collection reference by finding it through a CSS pattern in the DOM. <ruby> page.select('p.welcome b').first.hide # => $$('p.welcome b').first().hide(); -</ruby> +</ruby> h5. show @@ -1440,7 +1437,7 @@ Toggles the visibility of the DOM elements with the given ids. Example: <ruby> page.toggle 'person_14', 'person_12', 'person_23' # Hides the elements -page.toggle 'person_14', 'person_12', 'person_23' # Shows the previously hidden elements +page.toggle 'person_14', 'person_12', 'person_23' # Shows the previously hidden elements </ruby> h5. visual_effect @@ -1455,11 +1452,11 @@ h3. Localized Views Action View has the ability render different templates depending on the current locale. -For example, suppose you have a Posts controller with a show action. By default, calling this action will render +app/views/posts/show.html.erb+. But if you set +I18n.locale = :de+, then +app/views/posts/show.de.html.erb+ will be rendered instead. If the localized template isn't present, the undecorated version will be used. This means you're not required to provide localized views for all cases, but they will be preferred and used if available. +For example, suppose you have a Posts controller with a show action. By default, calling this action will render +app/views/posts/show.html.erb+. But if you set +I18n.locale = :de+, then +app/views/posts/show.de.html.erb+ will be rendered instead. If the localized template isn't present, the undecorated version will be used. This means you're not required to provide localized views for all cases, but they will be preferred and used if available. You can use the same technique to localize the rescue files in your public directory. For example, setting +I18n.locale = :de+ and creating +public/500.de.html+ and +public/404.de.html+ would allow you to have localized rescue pages. -Since Rails doesn't restrict the symbols that you use to set I18n.locale, you can leverage this system to display different content depending on anything you like. For example, suppose you have some "expert" users that should see different pages from "normal" users. You could add the following to +app/controllers/application.rb+: +Since Rails doesn't restrict the symbols that you use to set I18n.locale, you can leverage this system to display different content depending on anything you like. For example, suppose you have some "expert" users that should see different pages from "normal" users. You could add the following to +app/controllers/application.rb+: <ruby> before_filter :set_expert_locale @@ -1471,11 +1468,9 @@ end Then you could create special views like +app/views/posts/show.expert.html.erb+ that would only be displayed to expert users. -You can read more about the Rails Internationalization (I18n) API "here":i18n.html. +You can read more about the Rails Internationalization (I18n) API "here":i18n.html. h3. Changelog -"Lighthouse Ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/71 - -* September 3, 2009: Continuing work by Trevor Turk, leveraging the "Action Pack docs":http://ap.rubyonrails.org/ and "What's new in Edge Rails":http://ryandaigle.com/articles/2007/8/3/what-s-new-in-edge-rails-partials-get-layouts +* September 3, 2009: Continuing work by Trevor Turk, leveraging the Action Pack docs and "What's new in Edge Rails":http://ryandaigle.com/articles/2007/8/3/what-s-new-in-edge-rails-partials-get-layouts * April 5, 2009: Starting work by Trevor Turk, leveraging Mike Gunderloy's docs diff --git a/railties/guides/source/active_record_basics.textile b/railties/guides/source/active_record_basics.textile index e6ef2cdd20..b7926f3a3b 100644 --- a/railties/guides/source/active_record_basics.textile +++ b/railties/guides/source/active_record_basics.textile @@ -16,7 +16,7 @@ Active Record is the M in "MVC":getting_started.html#the-mvc-architecture - the h4. The Active Record Pattern -Active Record was described by Martin Fowler in his book _Patterns of Enterprise Application Architecture_. In Active Record, objects carry both persistent data and behavior which operates on that data. Active Record takes the opinion that ensuring data access logic is part of the object will educate users of that object on how to write to and read from the database. +Active Record was described by Martin Fowler in his book _Patterns of Enterprise Application Architecture_. In Active Record, objects carry both persistent data and behavior which operates on that data. Active Record takes the opinion that ensuring data access logic is part of the object will educate users of that object on how to write to and read from the database. h4. Object Relational Mapping @@ -132,7 +132,7 @@ CRUD is an acronym for the four verbs we use to operate on data: *C*reate, *R*ea h4. Create -Active Record objects can be created from a hash, a block or have its attributes manually set after creation. The _new_ method will return a new object while _create_ will return the object and save it to the database. +Active Record objects can be created from a hash, a block or have its attributes manually set after creation. The _new_ method will return a new object while _create_ will return the object and save it to the database. For example, given a model +User+ with attributes of +name+ and +occupation+, the _create_ method call will create and save a new record into the database: @@ -180,7 +180,7 @@ Active Record provides a rich API for accessing data within a database. Below ar <ruby> # find all users named David who are Code Artists and sort by created_at in reverse chronological order - users = User.all(:conditions => { :name => 'David', :occupation => 'Code Artist'}, :order => 'created_at DESC') + users = User.where(:name => 'David', :occupation => 'Code Artist').order('created_at DESC') </ruby> You can learn more about querying an Active Record model in the "Active Record Query Interface":"active_record_querying.html" guide. diff --git a/railties/guides/source/active_record_querying.textile b/railties/guides/source/active_record_querying.textile index 53095a2bd3..009d541106 100644 --- a/railties/guides/source/active_record_querying.textile +++ b/railties/guides/source/active_record_querying.textile @@ -19,8 +19,6 @@ Code examples throughout this guide will refer to one or more of the following m TIP: All of the following models use +id+ as the primary key, unless specified otherwise. -<br /> - <ruby> class Client < ActiveRecord::Base has_one :address @@ -65,6 +63,7 @@ The methods are: * +lock+ * +readonly+ * +from+ +* +having+ All of the above methods return an instance of <tt>ActiveRecord::Relation</tt>. @@ -103,7 +102,7 @@ h5. +first+ <ruby> client = Client.first -=> #<Client id: 1, first_name: => "Lifo"> +=> #<Client id: 1, first_name: "Lifo"> </ruby> SQL equivalent of the above is: @@ -120,7 +119,7 @@ h5. +last+ <ruby> client = Client.last -=> #<Client id: 221, first_name: => "Russel"> +=> #<Client id: 221, first_name: "Russel"> </ruby> SQL equivalent of the above is: @@ -149,24 +148,24 @@ SQL equivalent of the above is: SELECT * FROM clients WHERE (clients.id IN (1,10)) </sql> -<tt>Model.find(array_of_primary_key)</tt> will raise an +ActiveRecord::RecordNotFound+ exception unless a matching record is found for <strong>all</strong> of the supplied primary keys. +WARNING: <tt>Model.find(array_of_primary_key)</tt> will raise an +ActiveRecord::RecordNotFound+ exception unless a matching record is found for <strong>all</strong> of the supplied primary keys. h4. Retrieving Multiple Objects in Batches -Sometimes you need to iterate over a large set of records. For example to send a newsletter to all users, to export some data, etc. +Sometimes you need to iterate over a large set of records. For example to send a newsletter to all users, to export some data, etc. The following may seem very straight forward at first: <ruby> # Very inefficient when users table has thousands of rows. -User.each do |user| +User.all.each do |user| NewsLetter.weekly_deliver(user) end </ruby> But if the total number of rows in the table is very large, the above approach may vary from being under performant to just plain impossible. -This is because +User.each+ makes Active Record fetch _the entire table_, build a model object per row, and keep the entire array in the memory. Sometimes that is just too many objects and demands too much memory. +This is because +User.all.each+ makes Active Record fetch _the entire table_, build a model object per row, and keep the entire array in the memory. Sometimes that is just too many objects and demands too much memory. h5. +find_each+ @@ -231,10 +230,10 @@ WARNING: Building your own conditions as pure strings can leave you vulnerable t h4. Array Conditions -Now what if that number could vary, say as an argument from somewhere, or perhaps from the user's level status somewhere? The find then becomes something like: +Now what if that number could vary, say as an argument from somewhere? The find then becomes something like: <ruby> -Client.where(["orders_count = ?", params[:orders]]) +Client.where("orders_count = ?", params[:orders]) </ruby> Active Record will go through the first element in the conditions value and any additional elements will replace the question marks +(?)+ in the first element. @@ -242,7 +241,7 @@ Active Record will go through the first element in the conditions value and any Or if you want to specify two conditions, you can do it like: <ruby> -Client.where(["orders_count = ? AND locked = ?", params[:orders], false]) +Client.where("orders_count = ? AND locked = ?", params[:orders], false) </ruby> In this example, the first question mark will be replaced with the value in +params[:orders]+ and the second will be replaced with the SQL representation of +false+, which depends on the adapter. @@ -250,7 +249,7 @@ In this example, the first question mark will be replaced with the value in +par The reason for doing code like: <ruby> -Client.where(["orders_count = ?", params[:orders]]) +Client.where("orders_count = ?", params[:orders]) </ruby> instead of: @@ -268,8 +267,8 @@ h5. Placeholder Conditions Similar to the +(?)+ replacement style of params, you can also specify keys/values hash in your array conditions: <ruby> -Client.where( - ["created_at >= :start_date AND created_at <= :end_date", { :start_date => params[:start_date], :end_date => params[:end_date] }]) +Client.where("created_at >= :start_date AND created_at <= :end_date", + {:start_date => params[:start_date], :end_date => params[:end_date]}) </ruby> This makes for clearer readability if you have a large number of variable conditions. @@ -279,62 +278,15 @@ h5(#array-range_conditions). Range Conditions If you're looking for a range inside of a table (for example, users created in a certain timeframe) you can use the conditions option coupled with the +IN+ SQL statement for this. If you had two dates coming in from a controller you could do something like this to look for a range: <ruby> -Client.where(["created_at IN (?)", - (params[:start_date].to_date)..(params[:end_date].to_date)]) +Client.where(:created_at => (params[:start_date].to_date)..(params[:end_date].to_date)) </ruby> -This would generate the proper query which is great for small ranges but not so good for larger ranges. For example if you pass in a range of date objects spanning a year that's 365 (or possibly 366, depending on the year) strings it will attempt to match your field against. +This query will generate something similar to the following SQL: <sql> -SELECT * FROM users WHERE (created_at IN - ('2007-12-31','2008-01-01','2008-01-02','2008-01-03','2008-01-04','2008-01-05', - '2008-01-06','2008-01-07','2008-01-08','2008-01-09','2008-01-10','2008-01-11', - '2008-01-12','2008-01-13','2008-01-14','2008-01-15','2008-01-16','2008-01-17', - '2008-01-18','2008-01-19','2008-01-20','2008-01-21','2008-01-22','2008-01-23',... - ‘2008-12-15','2008-12-16','2008-12-17','2008-12-18','2008-12-19','2008-12-20', - '2008-12-21','2008-12-22','2008-12-23','2008-12-24','2008-12-25','2008-12-26', - '2008-12-27','2008-12-28','2008-12-29','2008-12-30','2008-12-31')) + SELECT "clients".* FROM "clients" WHERE ("clients"."created_at" BETWEEN '2010-09-29' AND '2010-11-30') </sql> -h5. Time and Date Conditions - -Things can get *really* messy if you pass in Time objects as it will attempt to compare your field to *every second* in that range: - -<ruby> -Client.where(["created_at IN (?)", - (params[:start_date].to_date.to_time)..(params[:end_date].to_date.to_time)]) -</ruby> - -<sql> -SELECT * FROM users WHERE (created_at IN - ('2007-12-01 00:00:00', '2007-12-01 00:00:01' ... - '2007-12-01 23:59:59', '2007-12-02 00:00:00')) -</sql> - -This could possibly cause your database server to raise an unexpected error, for example MySQL will throw back this error: - -<shell> -Got a packet bigger than 'max_allowed_packet' bytes: _query_ -</shell> - -Where _query_ is the actual query used to get that error. - -In this example it would be better to use greater-than and less-than operators in SQL, like so: - -<ruby> -Client.where( - ["created_at > ? AND created_at < ?", params[:start_date], params[:end_date]]) -</ruby> - -You can also use the greater-than-or-equal-to and less-than-or-equal-to like this: - -<ruby> -Client.where( - ["created_at >= ? AND created_at <= ?", params[:start_date], params[:end_date]]) -</ruby> - -Just like in Ruby. If you want a shorter syntax be sure to check out the "Hash Conditions":#hash-conditions section later on in the guide. - h4. Hash Conditions Active Record also allows you to pass in hash conditions which can increase the readability of your conditions syntax. With hash conditions, you pass in a hash with keys of the fields you want conditionalised and the values of how you want to conditionalise them: @@ -344,13 +296,13 @@ NOTE: Only equality, range and subset checking are possible with Hash conditions h5. Equality Conditions <ruby> -Client.where({ :locked => true }) +Client.where(:locked => true) </ruby> The field name can also be a string: <ruby> -Client.where({ 'locked' => true }) +Client.where('locked' => true) </ruby> h5(#hash-range_conditions). Range Conditions @@ -358,7 +310,7 @@ h5(#hash-range_conditions). Range Conditions The good thing about this is that we can pass in a range for our fields without it generating a large query as shown in the preamble of this section. <ruby> -Client.where({ :created_at => (Time.now.midnight - 1.day)..Time.now.midnight}) +Client.where(:created_at => (Time.now.midnight - 1.day)..Time.now.midnight) </ruby> This will find all clients created yesterday by using a +BETWEEN+ SQL statement: @@ -374,7 +326,7 @@ h5. Subset Conditions If you want to find records using the +IN+ expression you can pass an array to the conditions hash: <ruby> -Client.where({ :orders_count => [1,3,5] }) +Client.where(:orders_count => [1,3,5]) </ruby> This code will generate SQL like this: @@ -383,9 +335,9 @@ This code will generate SQL like this: SELECT * FROM clients WHERE (clients.orders_count IN (1,3,5)) </sql> -h4. Ordering +h3. Ordering -To retrieve records from the database in a specific order, you can specify the +:order+ option to the +find+ call. +To retrieve records from the database in a specific order, you can use the +order+ method. For example, if you're getting a set of records and want to order them in ascending order by the +created_at+ field in your table: @@ -407,7 +359,7 @@ Or ordering by multiple fields: Client.order("orders_count ASC, created_at DESC") </ruby> -h4. Selecting Specific Fields +h3. Selecting Specific Fields By default, <tt>Model.find</tt> selects all the fields from the result set using +select *+. @@ -443,7 +395,7 @@ You can also call SQL functions within the select option. For example, if you wo Client.select("DISTINCT(name)") </ruby> -h4. Limit and Offset +h3. Limit and Offset To apply +LIMIT+ to the SQL fired by the +Model.find+, you can specify the +LIMIT+ using +limit+ and +offset+ methods on the relation. @@ -468,10 +420,10 @@ Client.limit(5).offset(30) will return instead a maximum of 5 clients beginning with the 31st. The SQL looks like: <sql> -SELECT * FROM clients LIMIT 5, 30 +SELECT * FROM clients LIMIT 5 OFFSET 30 </sql> -h4. Group +h3. Group To apply a +GROUP BY+ clause to the SQL fired by the finder, you can specify the +group+ method on the find. @@ -486,17 +438,17 @@ 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) +SELECT * FROM orders GROUP BY date(created_at) ORDER BY created_at </sql> -h4. Having +h3. Having SQL uses the +HAVING+ clause to specify conditions on the +GROUP BY+ fields. You can add the +HAVING+ clause to the SQL fired by the +Model.find+ by adding the +:having+ option to the find. For example: <ruby> -Order.group("date(created_at)".having(["created_at > ?", 1.month.ago]) +Order.group("date(created_at)").having("created_at > ?", 1.month.ago) </ruby> The SQL that would be executed would be something like this: @@ -507,25 +459,49 @@ SELECT * FROM orders GROUP BY date(created_at) HAVING created_at > '2009-01-15' This will return single order objects for each day, but only for the last month. -h4. Readonly Objects +h3. Overriding Conditions -To explicitly disallow modification/destruction of the matching records returned in a Relation object, you could chain the +readonly+ method as +true+ to the find call. +You can specify certain conditions to be excepted by using the +except+ method. -Any attempt to alter or destroy the readonly records will not succeed, raising an +ActiveRecord::ReadOnlyRecord+ exception. To set this option, specify it like this: +For example: <ruby> -Client.first.readonly(true) +Post.where('id > 10').limit(20).order('id asc').except(:order) </ruby> -For example, calling the following code will raise an +ActiveRecord::ReadOnlyRecord+ exception: +The SQL that would be executed: + +<sql> +SELECT * FROM posts WHERE id > 10 LIMIT 20 +</sql> + +You can also override conditions using the +only+ method. + +For example: <ruby> -client = Client.first.readonly(true) -client.locked = false +Post.where('id > 10').limit(20).order('id desc').only(:order, :where) +</ruby> + +The SQL that would be executed: + +<sql> +SELECT * FROM posts WHERE id > 10 ORDER BY id DESC +</sql> + +h3. Readonly Objects + +Active Record provides +readonly+ method on a relation to explicitly disallow modification or deletion of any of the returned object. Any attempt to alter or destroy a readonly record will not succeed, raising an +ActiveRecord::ReadOnlyRecord+ exception. + +<ruby> +client = Client.readonly.first +client.visits += 1 client.save </ruby> -h4. Locking Records for Update +As +client+ is explicitly set to be a readonly object, the above code will raise an +ActiveRecord::ReadOnlyRecord+ exception when calling +client.save+ with an updated value of _visits_. + +h3. Locking Records for Update Locking is helpful for preventing race conditions when updating records in the database and ensuring atomic updates. @@ -534,7 +510,7 @@ Active Record provides two locking mechanisms: * Optimistic Locking * Pessimistic Locking -h5. Optimistic Locking +h4. Optimistic Locking Optimistic locking allows multiple users to access the same record for edits, and assumes a minimum of conflicts with the data. It does this by checking whether another process has made changes to a record since it was opened. An +ActiveRecord::StaleObjectError+ exception is thrown if that has occurred and the update is ignored. @@ -569,15 +545,15 @@ class Client < ActiveRecord::Base end </ruby> -h5. Pessimistic Locking +h4. Pessimistic Locking -Pessimistic locking uses a locking mechanism provided by the underlying database. Passing +:lock => true+ to +Model.find+ obtains an exclusive lock on the selected rows. +Model.find+ using +:lock+ are usually wrapped inside a transaction for preventing deadlock conditions. +Pessimistic locking uses a locking mechanism provided by the underlying database. Using +lock+ when building a relation obtains an exclusive lock on the selected rows. Relations using +lock+ are usually wrapped inside a transaction for preventing deadlock conditions. For example: <ruby> Item.transaction do - i = Item.first(:lock => true) + i = Item.lock.first i.name = 'Jones' i.save end @@ -592,25 +568,25 @@ Item Update (0.4ms) UPDATE `items` SET `updated_at` = '2009-02-07 18:05:56', ` SQL (0.8ms) COMMIT </sql> -You can also pass raw SQL to the +:lock+ option to allow different types of locks. For example, MySQL has an expression called +LOCK IN SHARE MODE+ where you can lock a record but still allow other queries to read it. To specify this expression just pass it in as the lock option: +You can also pass raw SQL to the +lock+ method for allowing different types of locks. For example, MySQL has an expression called +LOCK IN SHARE MODE+ where you can lock a record but still allow other queries to read it. To specify this expression just pass it in as the lock option: <ruby> Item.transaction do - i = Item.find(1, :lock => "LOCK IN SHARE MODE") + i = Item.lock("LOCK IN SHARE MODE").find(1) i.increment!(:views) end </ruby> h3. Joining Tables -<tt>Model.find</tt> provides a +:joins+ option for specifying +JOIN+ clauses on the resulting SQL. There are multiple ways to specify the +:joins+ option: +Active Record provides a finder method called +joins+ for specifying +JOIN+ clauses on the resulting SQL. There are multiple ways to use the +joins+ method. h4. Using a String SQL Fragment -You can just supply the raw SQL specifying the +JOIN+ clause to the +:joins+ option. For example: +You can just supply the raw SQL specifying the +JOIN+ clause to +joins+: <ruby> -Client.all(:joins => 'LEFT OUTER JOIN addresses ON addresses.client_id = clients.id') +Client.joins('LEFT OUTER JOIN addresses ON addresses.client_id = clients.id') </ruby> This will result in the following SQL: @@ -621,11 +597,9 @@ SELECT clients.* FROM clients LEFT OUTER JOIN addresses ON addresses.client_id = h4. Using Array/Hash of Named Associations -WARNING: This method only works with +INNER JOIN+, +WARNING: This method only works with +INNER JOIN+. -<br /> - -Active Record lets you use the names of the "associations":association_basics.html defined on the model as a shortcut for specifying the +:joins+ option. +Active Record lets you use the names of the "associations":association_basics.html defined on the model as a shortcut for specifying +JOIN+ clause for those associations when using the +joins+ method. For example, consider the following +Category+, +Post+, +Comments+ and +Guest+ models: @@ -674,7 +648,7 @@ Post.joins(:category, :comments) This produces: <sql> -SELECT posts.* FROM posts +SELECT posts.* FROM posts INNER JOIN categories ON posts.category_id = categories.id INNER JOIN comments ON comments.post_id = posts.id </sql> @@ -718,7 +692,7 @@ Eager loading is the mechanism for loading the associated records of the objects Consider the following code, which finds 10 clients and prints their postcodes: <ruby> -clients = Client.all(:limit => 10) +clients = Client.limit(10) clients.each do |client| puts client.address.postcode @@ -753,7 +727,7 @@ h4. Eager Loading Multiple Associations Active Record lets you eager load any number of associations with a single +Model.find+ call by using an array, hash, or a nested hash of array/hash with the +includes+ method. -h5. Array of Multiple Associations +h5. Array of Multiple Associations <ruby> Post.includes(:category, :comments) @@ -771,17 +745,119 @@ This will find the category with id 1 and eager load all of the associated posts h4. Specifying Conditions on Eager Loaded Associations -Even though Active Record lets you specify conditions on the eager loaded associations just like +joins+, the recommended way is to use "joins":#joining-tables instead. +Even though Active Record lets you specify conditions on the eager loaded associations just like +joins+, the recommended way is to use "joins":#joining-tables instead. + +However if you must do this, you may use +where+ as you would normally. + +<ruby> +Post.includes(:comments).where("comments.visible", true) +</ruby> + +This would generate a query which contains a +LEFT OUTER JOIN+ whereas the +joins+ method would generate one using the +INNER JOIN+ function instead. + +<ruby> + SELECT "posts"."id" AS t0_r0, ... "comments"."updated_at" AS t1_r5 FROM "posts" LEFT OUTER JOIN "comments" ON "comments"."post_id" = "posts"."id" WHERE (comments.visible) +</ruby> + +If there was no +where+ condition, this would generate the normal set of two queries. + +If, in the case of this +includes+ query, there were no comments for any posts, all the posts would still be loaded. By using +joins+ (an INNER JOIN), the join conditions *must* match, otherwise no records will be returned. + +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. + +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: + +<ruby> +class Post < ActiveRecord::Base + scope :published, where(:published => true) +end +</ruby> + +Just like before, these methods are also chainable: + +<ruby> +class Post < ActiveRecord::Base + scope :published, where(:published => true).joins(:category) +end +</ruby> + +Scopes are also chainable within scopes: + +<ruby> +class Post < ActiveRecord::Base + scope :published, where(:published => true) + scope :published_and_commented, published.and(self.arel_table[:comments_count].gt(0)) +end +</ruby> + +To call this +published+ scope we can call it on either the class: + +<ruby> +Post.published => [published posts] +</ruby> + +Or on an association consisting of +Post+ objects: + +<ruby> +category = Category.first +category.posts.published => [published posts belonging to this category] +</ruby> + +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. + +<ruby> +class Post < ActiveRecord::Base + scope :last_week, lambda { where("created_at < ?", Time.zone.now ) } +end +</ruby> + +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: + +<ruby> +class Post < ActiveRecord::Base + scope :1_week_before, lambda { |time| where("created_at < ?", time) +end +</ruby> + +This may then be called using this: + +<ruby> +Post.1_week_before(Time.zone.now) +</ruby> + +However, this is just duplicating the functionality that would be provided to you by a class method. + +<ruby> +class Post < ActiveRecord::Base + def self.1_week_before(time) + where("created_at < ?", time) + end +end +</ruby> + +Using a class method is the preferred way to accept arguments for scopes. These methods will still be accessible on the association objects: + +<ruby> +category.posts.1_week_before(time) +</ruby> 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 also have a +locked+ field on the +Client+ model, you also get +find_by_locked+ and +find_all_by_locked+. +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. -You can do +find_last_by_*+ methods too which will find the last record matching your argument. +You can also use +find_last_by_*+ methods which will find the last record matching your argument. You can specify an exclamation point (<tt>!</tt>) on the end of the dynamic finders to get them to raise an +ActiveRecord::RecordNotFound+ error if they do not return any records, like +Client.find_by_name!("Ryan")+ -If you want to find both by name and locked, you can chain these finders together by simply typing +and+ between the fields for example +Client.find_by_first_name_and_locked("Ryan", true)+. +If you want to find both by name and locked, you can chain these finders together by simply typing +and+ between the fields. For example, +Client.find_by_first_name_and_locked("Ryan", true)+. There's another set of dynamic finders that let you find or create/initialize objects if they aren't found. These work in a similar fashion to the other finders and can be used like +find_or_create_by_first_name(params[:first_name])+. Using this will first perform a find and then create if the find returns +nil+. The SQL looks like this for +Client.find_or_create_by_first_name("Ryan")+: @@ -807,8 +883,8 @@ h3. Finding by SQL If you'd like to use your own SQL to find records in a table you can use +find_by_sql+. The +find_by_sql+ method will return an array of objects even if the underlying query returns just a single record. For example you could run this query: <ruby> -Client.find_by_sql("SELECT * FROM clients - INNER JOIN orders ON clients.id = orders.client_id +Client.find_by_sql("SELECT * FROM clients + INNER JOIN orders ON clients.id = orders.client_id ORDER clients.created_at desc") </ruby> @@ -838,13 +914,13 @@ Client.exists?(1,2,3) Client.exists?([1,2,3]) </ruby> -The +exists+ method may also take a +conditions+ option much like find: +It's even possible to use +exists?+ without any arguments on a model or a relation. <ruby> -Client.exists?(:conditions => "first_name = 'Ryan'") +Client.where(:first_name => 'Ryan').exists? </ruby> -It's even possible to use +exists?+ without any arguments: +The above returns +true+ if there is at least one client with the +first_name+ 'Ryan' and +false+ otherwise. <ruby> Client.exists? @@ -856,22 +932,24 @@ h3. Calculations This section uses count as an example method in this preamble, but the options described apply to all sub-sections. -<tt>count</tt> takes conditions much in the same way +exists?+ does: +All calculation methods work directly on a model: <ruby> -Client.count(:conditions => "first_name = 'Ryan'") +Client.count +# SELECT count(*) AS count_all FROM clients </ruby> -Which will execute: +Or on a relation : -<sql> -SELECT count(*) AS count_all FROM clients WHERE (first_name = 'Ryan') -</sql> +<ruby> +Client.where(:first_name => 'Ryan').count +# SELECT count(*) AS count_all FROM clients WHERE (first_name = 'Ryan') +</ruby> -You can also use the +includes+ or +joins+ methods for this to do something a little more complex: +You can also use various finder methods on a relation for performing complex calculations: <ruby> -Client.where("clients.first_name = 'Ryan' AND orders.status = 'received'").includes("orders").count +Client.includes("orders").where(:first_name => 'Ryan', :orders => {:status => 'received'}).count </ruby> Which will execute: @@ -882,8 +960,6 @@ SELECT count(DISTINCT clients.id) AS count_all FROM clients (clients.first_name = 'Ryan' AND orders.status = 'received') </sql> -This code specifies +clients.first_name+ just in case one of the join tables has a field also called +first_name+ and it uses +orders.status+ because that's the name of our join table. - h4. Count If you want to see how many records are in your model's table you could call +Client.count+ and that will return the number. If you want to be more specific and find all the clients with their age present in the database you can use +Client.count(:age)+. @@ -934,8 +1010,7 @@ For options, please see the parent section, "Calculations":#calculations. h3. Changelog -"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16 - +* December 23 2010: Add documentation for the +scope+ method. "Ryan Bigg":http://ryanbigg.com * April 7, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com * February 3, 2010: Update to Rails 3 by "James Miller":credits.html#bensie * February 7, 2009: Second version by "Pratik":credits.html#lifo diff --git a/railties/guides/source/active_record_validations_callbacks.textile b/railties/guides/source/active_record_validations_callbacks.textile index 37a65d211e..e5349d546c 100644 --- a/railties/guides/source/active_record_validations_callbacks.textile +++ b/railties/guides/source/active_record_validations_callbacks.textile @@ -16,7 +16,7 @@ endprologue. h3. The Object Life Cycle -During the normal operation of a Rails application, objects may be created, updated, and destroyed. Active Record provides hooks into this <em>object life cycle</em> so that you can control your application and its data. +During the normal operation of a Rails application, objects may be created, updated, and destroyed. Active Record provides hooks into this <em>object life cycle</em> so that you can control your application and its data. Validations allow you to ensure that only valid data is stored in your database. Callbacks and observers allow you to trigger logic before or after an alteration of an object's state. @@ -33,7 +33,7 @@ There are several ways to validate data before it is saved into your database, i * Database constraints and/or stored procedures make the validation mechanisms database-dependent and can make testing and maintenance more difficult. However, if your database is used by other applications, it may be a good idea to use some constraints at the database level. Additionally, database-level validations can safely handle some things (such as uniqueness in heavily-used tables) that can be difficult to implement otherwise. * Client-side validations can be useful, but are generally unreliable if used alone. If they are implemented using JavaScript, they may be bypassed if JavaScript is turned off in the user's browser. However, if combined with other techniques, client-side validation can be a convenient way to provide users with immediate feedback as they use your site. * Controller-level validations can be tempting to use, but often become unwieldy and difficult to test and maintain. Whenever possible, it's a good idea to "keep your controllers skinny":http://weblog.jamisbuck.org/2006/10/18/skinny-controller-fat-model, as it will make your application a pleasure to work with in the long run. -* Model-level validations are the best way to ensure that only valid data is saved into your database. They are database agnostic, cannot be bypassed by end users, and are convenient to test and maintain. Rails makes them easy to use, provides built-in helpers for common needs, and allows you to create your own validation methods as well. +* Model-level validations are the best way to ensure that only valid data is saved into your database. They are database agnostic, cannot be bypassed by end users, and are convenient to test and maintain. Rails makes them easy to use, provides built-in helpers for common needs, and allows you to create your own validation methods as well. h4. When Does Validation Happen? @@ -57,7 +57,7 @@ We can see how it works by looking at some +rails console+ output: => false </shell> -Creating and saving a new record will send a SQL +INSERT+ operation to the database. Updating an existing record will send a SQL +UPDATE+ operation instead. Validations are typically run before these commands are sent to the database. If any validations fail, the object will be marked as invalid and Active Record will not perform the +INSERT+ or +UPDATE+ operation. This helps to avoid storing an invalid object in the database. You can choose to have specific validations run when an object is created, saved, or updated. +Creating and saving a new record will send an SQL +INSERT+ operation to the database. Updating an existing record will send an SQL +UPDATE+ operation instead. Validations are typically run before these commands are sent to the database. If any validations fail, the object will be marked as invalid and Active Record will not perform the +INSERT+ or +UPDATE+ operation. This helps to avoid storing an invalid object in the database. You can choose to have specific validations run when an object is created, saved, or updated. CAUTION: There are many ways to change the state of an object in the database. Some methods will trigger validations, but some will not. This means that it's possible to save an object in the database in an invalid state if you aren't careful. @@ -96,7 +96,7 @@ To verify whether or not an object is valid, Rails uses the +valid?+ method. You <ruby> class Person < ActiveRecord::Base - validates_presence_of :name + validates :name, :presence => true end Person.create(:name => "John Doe").valid? # => true @@ -109,14 +109,14 @@ Note that an object instantiated with +new+ will not report errors even if it's <ruby> class Person < ActiveRecord::Base - validates_presence_of :name + validates :name, :presence => true end >> p = Person.new => #<Person id: nil, name: nil> >> p.errors => {} - + >> p.valid? => false >> p.errors @@ -126,7 +126,7 @@ end => #<Person id: nil, name: nil> >> p.errors => {:name=>["can't be blank"]} - + >> p.save => false @@ -141,13 +141,13 @@ end h4(#validations_overview-errors). +errors[]+ -To verify whether or not a particular attribute of an object is valid, you can use +errors[:attribute]+ that returns an array with all attribute errors, when there are no errors on the specified attribute, an empty array is returned. +To verify whether or not a particular attribute of an object is valid, you can use +errors[:attribute]+. It returns an array of all the errors for +:attribute+. If there are no errors on the specified attribute, an empty array is returned. This method is only useful _after_ validations have been run, because it only inspects the errors collection and does not trigger validations itself. It's different from the +ActiveRecord::Base#invalid?+ method explained above because it doesn't verify the validity of the object as a whole. It only checks to see whether there are errors found on an individual attribute of the object. <ruby> class Person < ActiveRecord::Base - validates_presence_of :name + validates :name, :presence => true end >> Person.new.errors[:name].any? # => false @@ -197,7 +197,7 @@ end This validation will work with all of the association types. -CAUTION: Don't use +validates_associated+ on both ends of your associations, they would call each other in an infinite loop. +CAUTION: Don't use +validates_associated+ on both ends of your associations. They would call each other in an infinite loop. The default error message for +validates_associated+ is "_is invalid_". Note that each associated object will contain its own +errors+ collection; errors do not bubble up to the calling model. @@ -235,7 +235,7 @@ This helper validates that the attributes' values are not included in a given se <ruby> class Account < ActiveRecord::Base - validates_exclusion_of :subdomain, :in => %w(www), + validates_exclusion_of :subdomain, :in => %w(www us ca jp), :message => "Subdomain %{value} is reserved." end </ruby> @@ -314,6 +314,8 @@ class Essay < ActiveRecord::Base end </ruby> +Note that the default error messages are plural (e.g., "is too short (minimum is %{count} characters)"). For this reason, when +:minimum+ is 1 you should provide a personalized message or use +validates_presence_of+ instead. When +:in+ or +:within+ have a lower limit of 1, you should either provide a personalized message or call +validates_presence_of+ prior to +validates_length_of+. + The +validates_size_of+ helper is an alias for +validates_length_of+. h4. +validates_numericality_of+ @@ -355,7 +357,7 @@ This helper validates that the specified attributes are not empty. It uses the + <ruby> class Person < ActiveRecord::Base - validates_presence_of :name, :login, :email + validates :name, :login, :email, :presence => true end </ruby> @@ -368,7 +370,7 @@ class LineItem < ActiveRecord::Base end </ruby> -Since +false.blank?+ is true, if you want to validate the presence of a boolean field you should use +validates_inclusion_of :field_name, :in => [true, false]+. +Since +false.blank?+ is true, if you want to validate the presence of a boolean field you should use +validates_inclusion_of :field_name, :in => [true, false]+. The default error message for +validates_presence_of+ is "_can't be empty_". @@ -382,7 +384,7 @@ class Account < ActiveRecord::Base end </ruby> -The validation happens by performing a SQL query into the model's table, searching for an existing record with the same value in that attribute. +The validation happens by performing an SQL query into the model's table, searching for an existing record with the same value in that attribute. There is a +:scope+ option that you can use to specify other attributes that are used to limit the uniqueness check: @@ -414,8 +416,8 @@ class Person < ActiveRecord::Base validates_with GoodnessValidator end -class GoodnessValidator < ActiveRecord::Validator - def validate +class GoodnessValidator < ActiveModel::Validator + def validate(record) if record.first_name == "Evil" record.errors[:base] << "This person is evil" end @@ -425,10 +427,7 @@ end The +validates_with+ helper takes a class, or a list of classes to use for validation. There is no default error message for +validates_with+. You must manually add errors to the record's errors collection in the validator class. -The validator class has two attributes by default: - -* +record+ - the record to be validated -* +options+ - the extra options that were passed to +validates_with+ +To implement the validate method, you must have an +record+ parameter defined, which is the record to be validated. Like all other validations, +validates_with+ takes the +:if+, +:unless+ and +:on+ options. If you pass any other options, it will send those options to the validator class as +options+: @@ -437,8 +436,8 @@ class Person < ActiveRecord::Base validates_with GoodnessValidator, :fields => [:first_name, :last_name] end -class GoodnessValidator < ActiveRecord::Validator - def validate +class GoodnessValidator < ActiveModel::Validator + def validate(record) if options[:fields].any?{|field| record.send(field) == "Evil" } record.errors[:base] << "This person is evil" end @@ -462,11 +461,11 @@ The block receives the model, the attribute's name and the attribute's value. Yo h3. Common Validation Options -There are some common options that all the validation helpers can use. Here they are, except for the +:if+ and +:unless+ options, which are discussed later in "Conditional Validation":#conditional-validation. +These are common validation options: h4. +:allow_nil+ -The +:allow_nil+ option skips the validation when the value being validated is +nil+. Using +:allow_nil+ with +validates_presence_of+ allows for +nil+, but any other +blank?+ value will still be rejected. +The +:allow_nil+ option skips the validation when the value being validated is +nil+. <ruby> class Coffee < ActiveRecord::Base @@ -475,6 +474,8 @@ class Coffee < ActiveRecord::Base end </ruby> +TIP: +:allow_nil+ is ignored by the presence validator. + h4. +:allow_blank+ The +:allow_blank+ option is similar to the +:allow_nil+ option. This option will let validation pass if the attribute's value is +blank?+, like +nil+ or an empty string for example. @@ -488,6 +489,8 @@ Topic.create("title" => "").valid? # => true Topic.create("title" => nil).valid? # => true </ruby> +TIP: +:allow_blank+ is ignored by the presence validator. + h4. +:message+ As you've already seen, the +:message+ option lets you specify the message that will be added to the +errors+ collection when validation fails. When this option is not used, Active Record will use the respective default error message for each validation helper. @@ -505,7 +508,7 @@ class Person < ActiveRecord::Base validates_numericality_of :age, :on => :update # the default (validates on both create and update) - validates_presence_of :name, :on => :save + validates :name, :presence => true, :on => :save end </ruby> @@ -550,9 +553,9 @@ end h3. Creating Custom Validation Methods -When the built-in validation helpers are not enough for your needs, you can write your own validation methods. +When the built-in validation helpers are not enough for your needs, you can write your own validation methods. -Simply create methods that verify the state of your models and add messages to the +errors+ collection when they are invalid. You must then register these methods by using one or more of the +validate+, +validate_on_create+ or +validate_on_update+ class methods, passing in the symbols for the validation methods' names. +Simply create methods that verify the state of your models and add messages to the +errors+ collection when they are invalid. You must then register these methods by using one or more of the +validate+, +validate_on_create+ or +validate_on_update+ class methods, passing in the symbols for the validation methods' names. You can pass more than one symbol for each class method and the respective validations will be run in the same order as they were registered. @@ -593,7 +596,7 @@ end h3. Working with Validation Errors -In addition to the +valid?+ and +invalid?+ methods covered earlier, Rails provides a number of methods for working with the +errors+ collection and inquiring about the validity of objects. +In addition to the +valid?+ and +invalid?+ methods covered earlier, Rails provides a number of methods for working with the +errors+ collection and inquiring about the validity of objects. The following is a list of the most commonly used methods. Please refer to the +ActiveRecord::Errors+ documentation for a list of all the available methods. @@ -603,7 +606,7 @@ Returns an OrderedHash with all errors. Each key is the attribute name and the v <ruby> class Person < ActiveRecord::Base - validates_presence_of :name + validates :name, :presence => true validates_length_of :name, :minimum => 3 end @@ -611,7 +614,7 @@ person = Person.new person.valid? # => false person.errors # => {:name => ["can't be blank", "is too short (minimum is 3 characters)"]} - + person = Person.new(:name => "John Doe") person.valid? # => true person.errors # => [] @@ -623,7 +626,7 @@ h4(#working_with_validation_errors-errors-2). +errors[]+ <ruby> class Person < ActiveRecord::Base - validates_presence_of :name + validates :name, :presence => true validates_length_of :name, :minimum => 3 end @@ -660,7 +663,7 @@ person.errors[:name] person.errors.full_messages # => ["Name cannot contain the characters !@#%*()_-+="] </ruby> - + Another way to do this is using +[]=+ setter <ruby> @@ -699,7 +702,7 @@ The +clear+ method is used when you intentionally want to clear all the messages <ruby> class Person < ActiveRecord::Base - validates_presence_of :name + validates :name, :presence => true validates_length_of :name, :minimum => 3 end @@ -723,7 +726,7 @@ The +size+ method returns the total number of error messages for the object. <ruby> class Person < ActiveRecord::Base - validates_presence_of :name + validates :name, :presence => true validates_length_of :name, :minimum => 3 validates_presence_of :email end @@ -739,7 +742,20 @@ person.errors.size # => 0 h3. Displaying Validation Errors in the View -Rails provides built-in helpers to display the error messages of your models in your view templates. +Rails maintains an official plugin that provides helpers to display the error messages of your models in your view templates. You can install it as a plugin or as a Gem. + +h4. Installing as a plugin +<shell> +$ rails plugin install git://github.com/joelmoss/dynamic_form.git +</shell> + +h4 Installing as a Gem +Add this line on your Gemfile: +<ruby> +gem "dynamic_form" +</ruby> + +Now you will have access to these two methods in your view templates: h4. +error_messages+ and +error_messages_for+ @@ -811,7 +827,7 @@ The name of the class and the id can be changed with the +:class+ and +:id+ opti h4. Customizing the Error Messages HTML -By default, form fields with errors are displayed enclosed by a +div+ element with the +field_with_errors+ CSS class. However, it's possible to override that. +By default, form fields with errors are displayed enclosed by a +div+ element with the +field_with_errors+ CSS class. However, it's possible to override that. The way form fields with errors are treated is defined by +ActionView::Base.field_error_proc+. This is a +Proc+ that receives two parameters: @@ -824,10 +840,10 @@ Here is a simple example where we change the Rails behaviour to always display t ActionView::Base.field_error_proc = Proc.new do |html_tag, instance| if instance.error_message.kind_of?(Array) %(#{html_tag}<span class="validation-error"> - #{instance.error_message.join(',')}</span>) + #{instance.error_message.join(',')}</span>).html_safe else %(#{html_tag}<span class="validation-error"> - #{instance.error_message}</span>) + #{instance.error_message}</span>).html_safe end end </ruby> @@ -865,7 +881,7 @@ The macro-style class methods can also receive a block. Consider using this styl class User < ActiveRecord::Base validates_presence_of :login, :email - before_create {|user| user.name = user.login.capitalize + before_create {|user| user.name = user.login.capitalize if user.name.blank?} end </ruby> @@ -967,7 +983,7 @@ The +after_initialize+ callback is triggered every time a new object of the clas h3. Skipping Callbacks -Just as with validations, it's also possible to skip callbacks. These methods should be used with caution, however, because important business rules and application logic may be kept in callbacks. Bypassing them without understanding the potential implications may lead to invalid data. +Just as with validations, it's also possible to skip callbacks. These methods should be used with caution, however, because important business rules and application logic may be kept in callbacks. Bypassing them without understanding the potential implications may lead to invalid data. * +decrement+ * +decrement_counter+ @@ -982,7 +998,7 @@ Just as with validations, it's also possible to skip callbacks. These methods sh h3. Halting Execution -As you start registering new callbacks for your models, they will be queued for execution. This queue will include all your model's validations, the registered callbacks, and the database operation to be executed. +As you start registering new callbacks for your models, they will be queued for execution. This queue will include all your model's validations, the registered callbacks, and the database operation to be executed. The whole callback chain is wrapped in a transaction. If any <em>before</em> callback method returns exactly +false+ or raises an exception the execution chain gets halted and a ROLLBACK is issued; <em>after</em> callbacks can only accomplish that by raising an exception. @@ -990,11 +1006,11 @@ WARNING. Raising an arbitrary exception may break code that expects +save+ and f h3. Relational Callbacks -Callbacks work through model relationships, and can even be defined by them. Let's take an example where a user has many posts. In our example, a user's posts should be destroyed if the user is destroyed. So, we'll add an +after_destroy+ callback to the +User+ model by way of its relationship to the +Post+ model. +Callbacks work through model relationships, and can even be defined by them. Let's take an example where a user has many posts. In our example, a user's posts should be destroyed if the user is destroyed. So, we'll add an +after_destroy+ callback to the +User+ model by way of its relationship to the +Post+ model. <ruby> class User < ActiveRecord::Base - has_many :posts, :dependent => :destroy + has_many :posts, :dependent => :destroy end class Post < ActiveRecord::Base @@ -1069,7 +1085,7 @@ Here's an example where we create a class with an +after_destroy+ callback for a <ruby> class PictureFileCallbacks def after_destroy(picture_file) - File.delete(picture_file.filepath) + File.delete(picture_file.filepath) if File.exists?(picture_file.filepath) end end @@ -1088,7 +1104,7 @@ Note that we needed to instantiate a new +PictureFileCallbacks+ object, since we <ruby> class PictureFileCallbacks def self.after_destroy(picture_file) - File.delete(picture_file.filepath) + File.delete(picture_file.filepath) if File.exists?(picture_file.filepath) end end @@ -1113,7 +1129,7 @@ h4. Creating Observers For example, imagine a +User+ model where we want to send an email every time a new user is created. Because sending emails is not directly related to our model's purpose, we could create an observer to contain this functionality. <shell> -rails generate observer User +$ rails generate observer User </shell> <ruby> @@ -1128,14 +1144,14 @@ As with callback classes, the observer's methods receive the observed model as a h4. Registering Observers -Observers are conventionally placed inside of your +app/models+ directory and registered in your application's +config/environment.rb+ file. For example, the +UserObserver+ above would be saved as +app/models/user_observer.rb+ and registered in +config/environment.rb+ this way: +Observers are conventionally placed inside of your +app/models+ directory and registered in your application's +config/application.rb+ file. For example, the +UserObserver+ above would be saved as +app/models/user_observer.rb+ and registered in +config/application.rb+ this way: <ruby> # Activate observers that should always be running config.active_record.observers = :user_observer </ruby> -As usual, settings in +config/environments+ take precedence over those in +config/environment.rb+. So, if you prefer that an observer doesn't run in all environments, you can simply register it in a specific environment instead. +As usual, settings in +config/environments+ take precedence over those in +config/application.rb+. So, if you prefer that an observer doesn't run in all environments, you can simply register it in a specific environment instead. h4. Sharing Observers @@ -1144,24 +1160,57 @@ By default, Rails will simply strip "Observer" from an observer's name to find t <ruby> class MailerObserver < ActiveRecord::Observer observe :registration, :user - + def after_create(model) # code to send confirmation email... end end </ruby> -In this example, the +after_create+ method would be called whenever a +Registration+ or +User+ was created. Note that this new +MailerObserver+ would also need to be registered in +config/environment.rb+ in order to take effect. +In this example, the +after_create+ method would be called whenever a +Registration+ or +User+ was created. Note that this new +MailerObserver+ would also need to be registered in +config/application.rb+ in order to take effect. <ruby> # Activate observers that should always be running config.active_record.observers = :mailer_observer </ruby> -h3. Changelog +h3. Transaction Callbacks + +There are two additional callbacks that are triggered by the completion of a database transaction: +after_commit+ and +after_rollback+. These callbacks are very similar to the +after_save+ callback except that they don't execute until after database changes have either been committed or rolled back. They are most useful when your active record models need to interact with external systems which are not part of the database transaction. -"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213/tickets/26-active-record-validations-and-callbacks +Consider, for example, the previous example where the +PictureFile+ model needs to delete a file after a record is destroyed. If anything raises an exception after the +after_destroy+ callback is called and the transaction rolls back, the file will have been deleted and the model will be left in an inconsistent state. For example, suppose that +picture_file_2+ in the code below is not valid and the +save!+ method raises an error. + +<ruby> +PictureFile.transaction do + picture_file_1.destroy + picture_file_2.save! +end +</ruby> + +By using the +after_commit+ callback we can account for this case. + +<ruby> +class PictureFile < ActiveRecord::Base + attr_accessor :delete_file + + after_destroy do |picture_file| + picture_file.delete_file = picture_file.filepath + end + + after_commit do |picture_file| + if picture_file.delete_file && File.exist?(picture_file.delete_file) + File.delete(picture_file.delete_file) + picture_file.delete_file = nil + end + end +end +</ruby> + +The +after_commit+ and +after_rollback+ callbacks are guaranteed to be called for all models created, updated, or destroyed within a transaction block. If any exceptions are raised within one of these callbacks, they will be ignored so that they don't interfere with the other callbacks. As such, if your callback code could raise an exception, you'll need to rescue it and handle it appropriately within the callback. + +h3. Changelog +* February 17, 2011: Add description of transaction callbacks. * July 20, 2010: Fixed typos and rephrased some paragraphs for clarity. "Jaime Iniesta":http://jaimeiniesta.com * May 24, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com * May 15, 2010: Validation Errors section updated by "Emili Parreño":http://www.eparreno.com diff --git a/railties/guides/source/active_support_core_extensions.textile b/railties/guides/source/active_support_core_extensions.textile index 54f766fffd..788f528654 100644 --- a/railties/guides/source/active_support_core_extensions.textile +++ b/railties/guides/source/active_support_core_extensions.textile @@ -1,8 +1,10 @@ h2. Active Support Core Extensions -Active Support is the Rails component responsible for providing Ruby language extensions, utilities, and other transversal stuff. It offers a richer bottom-line at the language level, targeted both at the development of Rails applications, and at the development of Rails itself. +Active Support is the Ruby on Rails component responsible for providing Ruby language extensions, utilities, and other transversal stuff. -By referring to this guide you will learn the extensions to the Ruby core classes and modules provided by Rails. +It offers a richer bottom-line at the language level, targeted both at the development of Rails applications, and at the development of Ruby on Rails itself. + +By referring to this guide you will learn the extensions to the Ruby core classes and modules provided by Active Support. endprologue. @@ -18,7 +20,7 @@ Thus, after a simple require like: require 'active_support' </ruby> -objects do not even respond to +blank?+, let's see how to load its definition. +objects do not even respond to +blank?+. Let's see how to load its definition. h5. Cherry-picking a Definition @@ -40,7 +42,7 @@ h5. Loading Grouped Core Extensions The next level is to simply load all extensions to +Object+. As a rule of thumb, extensions to +SomeClass+ are available in one shot by loading +active_support/core_ext/some_class+. -Thus, if that would do, to have +blank?+ available we could just load all extensions to +Object+: +Thus, to load all extensions to +Object+ (including +blank?+): <ruby> require 'active_support/core_ext/object' @@ -84,32 +86,25 @@ The following values are considered to be blank in a Rails application: WARNING: Note that numbers are not mentioned, in particular 0 and 0.0 are *not* blank. -For example, this method from +ActionDispatch::Response+ uses +blank?+ to easily be robust to +nil+ and whitespace strings in one shot: +For example, this method from +ActionDispatch::Session::AbstractStore+ uses +blank?+ for checking whether a session key is present: <ruby> -def charset - charset = String(headers["Content-Type"] || headers["type"]).split(";")[1] - charset.blank? ? nil : charset.strip.split("=")[1] +def ensure_session_key! + if @key.blank? + raise ArgumentError, 'A key is required...' + end end </ruby> -That's a typical use case for +blank?+. - -Here, the method Rails runs to instantiate observers upon initialization has nothing to do if there are none: +The method +present?+ is equivalent to +!blank?+. This example is taken from +ActionDispatch::Http::Cache::Response+: <ruby> -def instantiate_observers - return if @observers.blank? - # ... +def set_conditional_cache_control! + return if self["Cache-Control"].present? + ... end </ruby> -The method +present?+ is equivalent to +!blank?+: - -<ruby> -assert @response.body.present? # same as !@response.body.blank? -</ruby> - NOTE: Defined in +active_support/core_ext/object/blank.rb+. h4. +presence+ @@ -151,36 +146,31 @@ Active Support provides +duplicable?+ to programmatically query an object about false.duplicable? # => false </ruby> -By definition all objects are +duplicable?+ except +nil+, +false+, +true+, symbols, numbers, and class objects. +By definition all objects are +duplicable?+ except +nil+, +false+, +true+, symbols, numbers, and class and module objects. -WARNING. Using +duplicable?+ is discouraged because it depends on a hard-coded list. Classes have means to disallow duplication like removing +dup+ and +clone+ or raising exceptions from them, only +rescue+ can tell. +WARNING. Any class can disallow duplication removing +dup+ and +clone+ or raising exceptions from them, only +rescue+ can tell whether a given arbitrary object is duplicable. +duplicable?+ depends on the hard-coded list above, but it is much faster than +rescue+. Use it only if you know the hard-coded list is enough in your use case. NOTE: Defined in +active_support/core_ext/object/duplicable.rb+. h4. +try+ -Sometimes you want to call a method provided the receiver object is not +nil+, which is something you usually check first. +Sometimes you want to call a method provided the receiver object is not +nil+, which is something you usually check first. +try+ is like +Object#send+ except that it returns +nil+ if sent to +nil+. -For instance, note how this method of +ActiveRecord::ConnectionAdapters::AbstractAdapter+ checks if there's a +@logger+: +For instance, in this code from +ActiveRecord::ConnectionAdapters::AbstractAdapter+ +@logger+ could be +nil+, but you save the check and write in an optimistic style: <ruby> def log_info(sql, name, ms) - if @logger && @logger.debug? + if @logger.try(:debug?) name = '%s (%.1fms)' % [name || 'SQL', ms] @logger.debug(format_log_entry(name, sql.squeeze(' '))) end end </ruby> -You can shorten that using +Object#try+. This method is a synonym for +Object#send+ except that it returns +nil+ if sent to +nil+. The previous example could then be rewritten as: ++try+ can also be called without arguments but a block, which will only be executed if the object is not nil: <ruby> -def log_info(sql, name, ms) - if @logger.try(:debug?) - name = '%s (%.1fms)' % [name || 'SQL', ms] - @logger.debug(format_log_entry(name, sql.squeeze(' '))) - end -end +@person.try { |p| "#{p.first_name} #{p.last_name}" } </ruby> NOTE: Defined in +active_support/core_ext/object/try.rb+. @@ -364,7 +354,7 @@ That idiom may convey _grouping_ to the reader as well. For example, say you wan <ruby> I18n.with_options :locale => user.locale, :scope => "newsletter" do |i18n| subject i18n.t :subject - body i18n.t :body, :user_name => user.name + body i18n.t :body, :user_name => user.name end </ruby> @@ -411,39 +401,6 @@ C.new(0, 1).instance_values # => {"x" => 0, "y" => 1} NOTE: Defined in +active_support/core_ext/object/instance_variables.rb+. -h5. +copy_instance_variables_from(object, exclude = [])+ - -Copies the instance variables of +object+ into +self+. - -Instance variable names in the +exclude+ array are ignored. If +object+ -responds to +protected_instance_variables+ the ones returned are -also ignored. For example, Rails controllers implement that method. - -In both arrays strings and symbols are understood, and they have to include -the at sign. - -<ruby> -class C - def initialize(x, y, z) - @x, @y, @z = x, y, z - end - - def protected_instance_variables - %w(@z) - end -end - -a = C.new(0, 1, 2) -b = C.new(3, 4, 5) - -a.copy_instance_variables_from(b, [:@y]) -# a is now: @x = 3, @y = 1, @z = 2 -</ruby> - -In the example +object+ and +self+ are of the same type, but they don't need to. - -NOTE: Defined in +active_support/core_ext/object/instance_variables.rb+. - h4. Silencing Warnings, Streams, and Exceptions The methods +silence_warnings+ and +enable_warnings+ change the value of +$VERBOSE+ accordingly for the duration of their block, and reset it afterwards: @@ -475,7 +432,7 @@ h4. +require_library_or_gem+ The convenience method +require_library_or_gem+ tries to load its argument with a regular +require+ first. If it fails loads +rubygems+ and tries again. -If the first attempt is a failure and +rubygems+ can't be loaded the method raises +LoadError+. On the other hand, if +rubygems+ is available but the argument is not loadable as a gem, the method gives up and +LoadError+ is also raised. +If the first attempt is a failure and +rubygems+ can't be loaded the method raises +LoadError+. A +LoadError+ is also raised if +rubygems+ is available but the argument is not loadable as a gem. For example, that's the way the MySQL adapter loads the MySQL library: @@ -541,12 +498,12 @@ h4. Attributes h5. +alias_attribute+ -Model attributes have a reader, a writer, and a predicate. You can aliase a model attribute having the corresponding three methods defined for you in one shot. As in other aliasing methods, the new name is the first argument, and the old name is the second (my mnemonic is they go in the same order as if you did an assignment): +Model attributes have a reader, a writer, and a predicate. You can alias a model attribute having the corresponding three methods defined for you in one shot. As in other aliasing methods, the new name is the first argument, and the old name is the second (my mnemonic is they go in the same order as if you did an assignment): <ruby> class User < ActiveRecord::Base # let me refer to the email column as "login", - # much meaningful for authentication code + # possibly meaningful for authentication code alias_attribute :login, :email end </ruby> @@ -571,7 +528,7 @@ The default value can be also specified with a block, which is called in the con class User attr_accessor :name, :surname attr_accessor_with_default(:full_name) { - [name, surname].compact.join(" ") + [name, surname].compact.join(" ") } end @@ -606,7 +563,7 @@ h5. Internal Attributes When you are defining an attribute in a class that is meant to be subclassed name collisions are a risk. That's remarkably important for libraries. -Active Support defines the macros +attr_internal_reader+, +attr_internal_writer+, and +attr_internal_accessor+. They behave like their Ruby builtin +attr_*+ counterparts, except they name the underlying instance variable in a way that makes collisions less likely. +Active Support defines the macros +attr_internal_reader+, +attr_internal_writer+, and +attr_internal_accessor+. They behave like their Ruby built-in +attr_*+ counterparts, except they name the underlying instance variable in a way that makes collisions less likely. The macro +attr_internal+ is a synonym for +attr_internal_accessor+: @@ -778,7 +735,7 @@ class Counter end </ruby> -The method receives the name of an action, and a +:with+ option with code. The code is evaluated in the context of the receiver each time the method is invoked, and it should evaluate to a +Mutex+ instance or any other object that responds to +synchronize+ and accepts a block. +The method receives the name of an action, and a +:with+ option with code. The code is evaluated in the context of the receiver each time the method is invoked, and it should evaluate to a +Mutex+ instance or any other object that responds to +synchronize+ and accepts a block. NOTE: Defined in +active_support/core_ext/module/synchronization.rb+. @@ -1034,7 +991,7 @@ a2.x # => 2, overridden in a2 The generation of the writer instance method can be prevented by setting the option +:instance_writer+ to false, as in <ruby> -module AcitveRecord +module ActiveRecord class Base class_attribute :table_name_prefix, :instance_writer => false self.table_name_prefix = "" @@ -1044,7 +1001,7 @@ end A model may find that option useful as a way to prevent mass-assignment from setting the attribute. -For convenience +class_attribute+ defines also an instance predicate which is the double negation of what the instance reader returns. In the examples above it would be called +x?+. +For convenience +class_attribute+ also defines an instance predicate which is the double negation of what the instance reader returns. In the examples above it would be called +x?+. NOTE: Defined in +active_support/core_ext/class/attribute.rb+ @@ -1088,6 +1045,8 @@ NOTE: Defined in +active_support/core_ext/class/attribute_accessors.rb+. h4. Class Inheritable Attributes +WARNING: Class Inheritable Attributes are deprecated. It's recommended that you use +Class#class_attribute+ instead. + Class variables are shared down the inheritance tree. Class instance variables are not shared, but they are not inherited either. The macros +class_inheritable_reader+, +class_inheritable_writer+, and +class_inheritable_accessor+ provide accessors for class-level data which is inherited but not shared with children: <ruby> @@ -1123,7 +1082,7 @@ module ActiveRecord end </ruby> -Since values are copied when a subclass is defined, if the base class changes the attribute after that, the subclass does not see the new value. That's the point. +Since values are copied when a subclass is defined, if the base class changes the attribute after that, the subclass does not see the new value. That's the point. NOTE: Defined in +active_support/core_ext/class/inheritable_attributes.rb+. @@ -1155,7 +1114,7 @@ NOTE: Defined in +active_support/core_ext/class/subclasses.rb+. h5. +descendants+ -The +descendants+ method returns all classes that are <tt><</tt> than its receiver: +The +descendants+ method returns all classes that are <tt><</tt> than its receiver: <ruby> class C; end @@ -1232,6 +1191,12 @@ To insert something verbatim use the +raw+ helper rather than calling +html_safe <%= raw @cms.current_template %> <%# inserts @cms.current_template as is %> </erb> +or, equivalently, use <tt><%==</tt>: + +<erb> +<%== @cms.current_template %> <%# inserts @cms.current_template as is %> +</erb> + The +raw+ helper calls +html_safe+ for you: <ruby> @@ -1276,7 +1241,7 @@ Pass a +:separator+ to truncate the string at a natural break: <ruby> "Oh dear! Oh dear! I shall be late!".truncate(18) -# => "Oh dear! Oh dea..." +# => "Oh dear! Oh dea..." "Oh dear! Oh dear! I shall be late!".truncate(18, :separator => ' ') # => "Oh dear! Oh..." </ruby> @@ -1301,7 +1266,7 @@ Active Support adds that functionality to <tt>%</tt> in previous versions of Rub NOTE: Defined in +active_support/core_ext/string/interpolation.rb+. -h4. +starts_with?+ and +ends_width?+ +h4. +starts_with?+ and +ends_with?+ Active Support defines 3rd person aliases of +String#start_with?+ and +String#end_with?+: @@ -1312,6 +1277,31 @@ Active Support defines 3rd person aliases of +String#start_with?+ and +String#en NOTE: Defined in +active_support/core_ext/string/starts_ends_with.rb+. +h4. +strip_heredoc+ + +The method +strip_heredoc+ strips indentation in heredocs. + +For example in + +<ruby> +if options[:usage] + puts <<-USAGE.strip_heredoc + This command does such and such. + + Supported options are: + -h This message + ... + USAGE +end +</ruby> + +the user would see the usage message aligned against the left margin. + +Technically, it looks for the least indented line in the whole string, and removes +that amount of leading whitespace. + +NOTE: Defined in +active_support/core_ext/string/strip.rb+. + h4. Access h5. +at(position)+ @@ -1580,7 +1570,7 @@ The method +tableize+ is +underscore+ followed by +pluralize+. "InvoiceLine".tableize # => "invoice_lines" </ruby> -As a rule of thumb, +tableize+ returns the table name that corresponds to a given model for simple cases. The actual implementation in Active Record is not straight +tableize+ indeed, because it also demodulizes de class name and checks a few options that may affect the returned string. +As a rule of thumb, +tableize+ returns the table name that corresponds to a given model for simple cases. The actual implementation in Active Record is not straight +tableize+ indeed, because it also demodulizes the class name and checks a few options that may affect the returned string. NOTE: Defined in +active_support/core_ext/string/inflections.rb+. @@ -1701,27 +1691,7 @@ foreign_key = options[:foreign_key] || reflection.active_record.name.foreign_key NOTE: Defined in +active_support/core_ext/string/inflections.rb+. -h4. Conversions - -h5. +constantize+ - -The method +constantize+ expects the receiver to contain the name of a constant, and tries to get you the object stored in there, assuming it is defined: - -<ruby> -"ActiveRecord::Base".constantize # => ActiveRecord::Base -</ruby> - -The name is assumed to be top-level, no matter whether it starts with "::" or not. No lexical context is taken into account: - -<ruby> -C = 1 -module M - C = 2 - "C".constantize # => 1, same as "::C".constantize -end -</ruby> - -NOTE: Defined in +active_support/core_ext/string/conversions.rb+. +h4(#string-conversions). Conversions h5. +ord+ @@ -1767,7 +1737,7 @@ The methods +to_date+, +to_time+, and +to_datetime+ are basically convenience wr <ruby> "2010-07-27".to_date # => Tue, 27 Jul 2010 "2010-07-27 23:37:00".to_time # => Tue Jul 27 23:37:00 UTC 2010 -"2010-07-27 23:37:00".to_datetime # => Tue, 27 Jul 2010 23:37:00 +0000 +"2010-07-27 23:37:00".to_datetime # => Tue, 27 Jul 2010 23:37:00 +0000 </ruby> +to_time+ receives an optional argument +:utc+ or +:local+, to indicate which time zone you want the time in: @@ -1848,7 +1818,7 @@ h3. Extensions to +Float+ h4. +round+ -The built-in method +Float#round+ rounds a float to the nearest integer. Active Support adds an optional parameter to let you specify a precision: +The built-in method +Float#round+ rounds a float to the nearest integer. In Ruby 1.9 this method takes an optional argument to let you specify a precision. Active Support adds that functionality to +round+ in previous versions of Ruby: <ruby> Math::E.round(4) # => 2.7183 @@ -1900,7 +1870,7 @@ The sum of an empty collection is zero by default, but this is customizable: [].sum(1) # => 1 </ruby> -If a block is given +sum+ becomes an iterator that yields the elements of the collection and sums the returned values: +If a block is given, +sum+ becomes an iterator that yields the elements of the collection and sums the returned values: <ruby> (1..5).sum {|n| n * 2 } # => 30 @@ -1928,7 +1898,7 @@ h4. +each_with_object+ The +inject+ method offers iteration with an accumulator: <ruby> -[2, 3, 4].inject(1) {|acc, i| product*i } # => 24 +[2, 3, 4].inject(1) {|product, i| product*i } # => 24 </ruby> The block is expected to return the value for the accumulator in the next iteration, and this makes building mutable objects a bit cumbersome: @@ -1974,7 +1944,7 @@ The method +many?+ is shorthand for +collection.size > 1+: <% end %> </erb> -If an optional block is given +many?+ only takes into account those elements that return true: +If an optional block is given, +many?+ only takes into account those elements that return true: <ruby> @see_more = videos.many? {|video| video.category == params[:category]} @@ -1984,7 +1954,7 @@ NOTE: Defined in +active_support/core_ext/enumerable.rb+. h4. +exclude?+ -The predicate +exclude?+ tests whether a given object does *not* belong to the collection. It is the negation of the builtin +include?+: +The predicate +exclude?+ tests whether a given object does *not* belong to the collection. It is the negation of the built-in +include?+: <ruby> to_visit << node if visited.exclude?(node) @@ -2039,9 +2009,9 @@ User.exists?(:email => params[:email]) That syntactic sugar is used a lot in Rails to avoid positional arguments where there would be too many, offering instead interfaces that emulate named parameters. In particular it is very idiomatic to use a trailing hash for options. -If a method expects a variable number of arguments and uses <tt>*</tt> in its declaration, however, such an options hash ends up being an item of the array of arguments, where kind of loses its role. +If a method expects a variable number of arguments and uses <tt>*</tt> in its declaration, however, such an options hash ends up being an item of the array of arguments, where it loses its role. -In those cases, you may give an options hash a distinguished treatment with +extract_options!+. That method checks the type of the last item of an array. If it is a hash it pops it and returns it, otherwise returns an empty hash. +In those cases, you may give an options hash a distinguished treatment with +extract_options!+. This method checks the type of the last item of an array. If it is a hash it pops it and returns it, otherwise it returns an empty hash. Let's see for example the definition of the +caches_action+ controller macro: @@ -2057,7 +2027,7 @@ This method receives an arbitrary number of action names, and an optional hash o NOTE: Defined in +active_support/core_ext/array/extract_options.rb+. -h4. Conversions +h4(#array-conversions). Conversions h5. +to_sentence+ @@ -2222,7 +2192,7 @@ Array.wrap(0) # => [0] This method is similar in purpose to <tt>Kernel#Array</tt>, but there are some differences: -* If the argument responds to +to_ary+ the method is invoked. <tt>Kernel#Array</tt> moves on to try +to_a+ if the returned value is +nil+, but <tt>Arraw.wrap</tt> returns such a +nil+ right away. +* If the argument responds to +to_ary+ the method is invoked. <tt>Kernel#Array</tt> moves on to try +to_a+ if the returned value is +nil+, but <tt>Array.wrap</tt> returns +nil+ right away. * If the returned value from +to_ary+ is neither +nil+ nor an +Array+ object, <tt>Kernel#Array</tt> raises an exception, while <tt>Array.wrap</tt> does not, it just returns the value. * It does not call +to_a+ on the argument, though special-cases +nil+ to return an empty array. @@ -2242,7 +2212,7 @@ There's also a related idiom that uses the splat operator: [*object] </ruby> -which returns +[nil]+ for +nil+, and calls to <tt>Array(object)</tt> otherwise +which in Ruby 1.8 returns +[nil]+ for +nil+, and calls to <tt>Array(object)</tt> otherwise. (Please if you know the exact behavior in 1.9 contact fxn.) Thus, in this case the behavior is different for +nil+, and the differences with <tt>Kernel#Array</tt> explained above apply to the rest of +object+s. @@ -2745,6 +2715,14 @@ WARNING: The original +Range#include?+ is still the one aliased to +Range#===+. NOTE: Defined in +active_support/core_ext/range/include_range.rb+. +h4. +cover?+ + +Ruby 1.9 provides +cover?+, and Active Support defines it for previous versions as an alias for +include?+. + +The method +include?+ in Ruby 1.9 is different from the one in 1.8 for non-numeric ranges: instead of being based on comparisons between the value and the range's endpoints, it walks the range with +succ+ looking for value. This works better for ranges with holes, but it has different complexity and may not finish in some other cases. + +In Ruby 1.9 the old behavior is still available in the new +cover?+, which Active Support backports for forward compatibility. For example, Rails uses +cover?+ for ranges in +validates_inclusion_of+. + h4. +overlaps?+ The method +Range#overlaps?+ says whether any two given ranges have non-void intersection: @@ -2815,6 +2793,8 @@ h5. +Date.current+ Active Support defines +Date.current+ to be today in the current time zone. That's like +Date.today+, except that it honors the user time zone, if defined. It also defines +Date.yesterday+ and +Date.tomorrow+, and the instance predicates +past?+, +today?+, and +future?+, all of them relative to +Date.current+. +When making Date comparisons using methods which honor the user time zone, make sure to use +Date.current+ and not +Date.today+. There are cases where the user time zone might be in the future compared to the system time zone, which +Date.today+ uses by default. This means +Date.today+ may equal +Date.yesterday+. + h5. Named dates h6. +prev_year+, +next_year+ @@ -2870,9 +2850,9 @@ d.end_of_week # => Sun, 09 May 2010 +beginning_of_week+ is aliased to +monday+ and +at_beginning_of_week+. +end_of_week+ is aliased to +sunday+ and +at_end_of_week+. -h6. +next_week+ +h6. +prev_week+, +next_week+ -+next_week+ receives a symbol with a day name in English (in lowercase, default is +:monday+) and it returns the date corresponding to that day in the next week: +The method +next_week+ receives a symbol with a day name in English (in lowercase, default is +:monday+) and it returns the date corresponding to that day: <ruby> d = Date.new(2010, 5, 9) # => Sun, 09 May 2010 @@ -2880,6 +2860,14 @@ d.next_week # => Mon, 10 May 2010 d.next_week(:saturday) # => Sat, 15 May 2010 </ruby> +The method +prev_week+ is analogous: + +<ruby> +d.prev_week # => Mon, 26 Apr 2010 +d.prev_week(:saturday) # => Sat, 01 May 2010 +d.prev_week(:friday) # => Fri, 30 Apr 2010 +</ruby> + h6. +beginning_of_month+, +end_of_month+ The methods +beginning_of_month+ and +end_of_month+ return the dates for the beginning and end of the month: @@ -2957,6 +2945,15 @@ Date.new(2010, 4, 30).months_ago(2) # => Sun, 28 Feb 2010 Date.new(2009, 12, 31).months_since(2) # => Sun, 28 Feb 2010 </ruby> +h6. +weeks_ago+ + +The method +weeks_ago+ works analogously for weeks: + +<ruby> +Date.new(2010, 5, 24).weeks_ago(1) # => Mon, 17 May 2010 +Date.new(2010, 5, 24).weeks_ago(2) # => Mon, 10 May 2010 +</ruby> + h6. +advance+ The most generic way to jump to other days is +advance+. This method receives a hash with keys +:years+, +:months+, +:weeks+, +:days+, and returns a date advanced as much as the present keys indicate: @@ -3001,7 +2998,7 @@ Date.new(2010, 1, 31).change(:month => 2) # => ArgumentError: invalid date </ruby> -h5. Durations +h5(#date-durations). Durations Durations can be added and substracted to dates: @@ -3048,14 +3045,14 @@ h6. +ago+, +since+ The method +ago+ receives a number of seconds as argument and returns a timestamp those many seconds ago from midnight: <ruby> -date = Date.current # => Fri, 11 Jun 2010 +date = Date.current # => Fri, 11 Jun 2010 date.ago(1) # => Thu, 10 Jun 2010 23:59:59 EDT -04:00 </ruby> Similarly, +since+ moves forward: <ruby> -date = Date.current # => Fri, 11 Jun 2010 +date = Date.current # => Fri, 11 Jun 2010 date.since(1) # => Fri, 11 Jun 2010 00:00:01 EDT -04:00 </ruby> @@ -3078,6 +3075,8 @@ yesterday tomorrow beginning_of_week (monday, at_beginning_of_week) end_on_week (at_end_of_week) +weeks_ago +prev_week next_week months_ago months_since @@ -3110,7 +3109,7 @@ h5. Named Datetimes h6. +DateTime.current+ -Active Support defines +DateTime.current+ to be like +Time.now.to_datetime+, except that it honors the user time zone, if defined. It also defines instance predicates +past?+, and +future?+ relative to +DateTime.current+. +Active Support defines +DateTime.current+ to be like +Time.now.to_datetime+, except that it honors the user time zone, if defined. It also defines +DateTime.yesterday+ and +DateTime.tomorrow+, and the instance predicates +past?+, and +future?+ relative to +DateTime.current+. h5. Other Extensions @@ -3207,7 +3206,7 @@ DateTime.current.change(:month => 2, :day => 30) # => ArgumentError: invalid date </ruby> -h5. Durations +h5(#datetime-durations). Durations Durations can be added and substracted to datetimes: @@ -3250,6 +3249,8 @@ beginning_of_day (midnight, at_midnight, at_beginning_of_day) end_of_day beginning_of_week (monday, at_beginning_of_week) end_on_week (at_end_of_week) +weeks_ago +prev_week next_week months_ago months_since @@ -3285,6 +3286,12 @@ t.advance(:seconds => 1) * If +since+ or +ago+ jump to a time that can't be expressed with +Time+ a +DateTime+ object is returned instead. +h5. +Time.current+ + +Active Support defines +Time.current+ to be today in the current time zone. That's like +Time.now+, except that it honors the user time zone, if defined. It also defines +Time.yesterday+ and +Time.tomorrow+, and the instance predicates +past?+, +today?+, and +future?+, all of them relative to +Time.current+. + +When making Time comparisons using methods which honor the user time zone, make sure to use +Time.current+ and not +Time.now+. There are cases where the user time zone might be in the future compared to the system time zone, which +Time.today+ uses by default. This means +Time.now+ may equal +Time.yesterday+. + h4. Time Constructors Active Support defines +Time.current+ to be +Time.zone.now+ if there's a user time zone defined, with fallback to +Time.now+: @@ -3320,7 +3327,7 @@ Both +local_time+ and +utc_time+ accept up to seven positional arguments: year, If the time to be constructed lies beyond the range supported by +Time+ in the runtime platform, usecs are discarded and a +DateTime+ object is returned instead. -h5. Durations +h5(#time-durations). Durations Durations can be added and substracted to time objects: @@ -3370,6 +3377,49 @@ The auxiliary file is written in a standard directory for temporary files, but y NOTE: Defined in +active_support/core_ext/file/atomic.rb+. +h3. Extensions to +Logger+ + +h4. +around_[level]+ + +Takes two arguments, a +before_message+ and +after_message+ and calls the current level method on the +Logger+ instance, passing in the +before_message+, then the specified message, then the +after_message+: + +<ruby> + logger = Logger.new("log/development.log") + logger.around_info("before", "after") { |logger| logger.info("during") } +</ruby> + +h4. +silence+ + +Silences every log level lesser to the specified one for the duration of the given block. Log level orders are: debug, info, error and fatal. + +<ruby> + logger = Logger.new("log/development.log") + logger.silence(Logger::INFO) do + logger.debug("In space, no one can hear you scream.") + logger.info("Scream all you want, small mailman!") + end +</ruby> + +h4. +datetime_format=+ + +Modifies the datetime format output by the formatter class associated with this logger. If the formatter class does not have a +datetime_format+ method then this is ignored. + +<ruby> + class Logger::FormatWithTime < Logger::Formatter + cattr_accessor(:datetime_format) { "%Y%m%d%H%m%S" } + + def self.call(severity, timestamp, progname, msg) + "#{timestamp.strftime(datetime_format)} -- #{String === msg ? msg : msg.inspect}\n" + end + end + + logger = Logger.new("log/development.log") + logger.formatter = Logger::FormatWithTime + logger.info("<- is the current time") +</ruby> + +NOTE: Defined in +active_support/core_ext/logger.rb+. + h3. Extensions to +NameError+ Active Support adds +missing_name?+ to +NameError+, which tests whether the exception was raised because of the name passed as argument. @@ -3418,7 +3468,5 @@ NOTE: Defined in +active_support/core_ext/load_error.rb+. h3. Changelog -"Lighthouse ticket":https://rails.lighthouseapp.com/projects/16213/tickets/67 - * August 10, 2010: Starts to take shape, added to the index. * April 18, 2009: Initial version by "Xavier Noria":credits.html#fxn diff --git a/railties/guides/source/ajax_on_rails.textile b/railties/guides/source/ajax_on_rails.textile index 8a38cf2dc2..b80df4aa58 100644 --- a/railties/guides/source/ajax_on_rails.textile +++ b/railties/guides/source/ajax_on_rails.textile @@ -1,10 +1,10 @@ h2. AJAX on Rails -This guide covers the built-in Ajax/Javascript functionality of Rails (and more); it will enable you to create rich and dynamic AJAX applications with ease! We will cover the following topics: +This guide covers the built-in Ajax/JavaScript functionality of Rails (and more); it will enable you to create rich and dynamic AJAX applications with ease! We will cover the following topics: * Quick introduction to AJAX and related technologies -* Handling Javascript the Rails way: Rails helpers, RJS, Prototype and script.aculo.us -* Testing Javascript functionality +* Handling JavaScript the Rails way: Rails helpers, RJS, Prototype and script.aculo.us +* Testing JavaScript functionality endprologue. @@ -12,7 +12,7 @@ h3. Hello AJAX - a Quick Intro If you are a 'show me the code' type of person, you might want to skip this part and jump to the RJS section right away. However, I would really recommend to read it - you'll need the basics of DOM, http requests and other topics discussed here to really understand Ajax on Rails. -h4. Asynchronous Javascript + XML +h4. Asynchronous JavaScript + XML Basic terminology, new style of creating web apps @@ -31,7 +31,7 @@ How do 'standard' and AJAX requests differ, why does this matter for understandi h3. Built-in Rails Helpers -Rails' Javascript framework of choice is "Prototype":http://www.prototypejs.org. Prototype is a generic-purpose Javascript framework that aims to ease the development of dynamic web applications by offering DOM manipulation, AJAX and other Javascript functionality ranging from utility functions to object oriented constructs. It is not specifically written for any language, so Rails provides a set of helpers to enable seamless integration of Prototype with your Rails views. +Rails' JavaScript framework of choice is "Prototype":http://www.prototypejs.org. Prototype is a generic-purpose JavaScript framework that aims to ease the development of dynamic web applications by offering DOM manipulation, AJAX and other JavaScript functionality ranging from utility functions to object oriented constructs. It is not specifically written for any language, so Rails provides a set of helpers to enable seamless integration of Prototype with your Rails views. To get access to these helpers, all you have to do is to include the prototype framework in your pages - typically in your master layout, application.html.erb - like so: <ruby> @@ -42,12 +42,12 @@ You are ready to add some AJAX love to your Rails app! h4. The Quintessential AJAX Rails Helper: link_to_remote -Let's start with the the probably most often used helper: +link_to_remote+, which has an interesting feature from the documentation point of view: the options supplied to +link_to_remote+ are shared by all other AJAX helpers, so learning the mechanics and options of +link_to_remote+ is a great help when using other helpers. +Let's start with what is probably the most often used helper: +link_to_remote+. It has an interesting feature from the documentation point of view: the options supplied to +link_to_remote+ are shared by all other AJAX helpers, so learning the mechanics and options of +link_to_remote+ is a great help when using other helpers. The signature of +link_to_remote+ function is the same as that of the standard +link_to+ helper: <ruby> -def link_to_remote(name, options = {}, html_options = nil) +def link_to_remote(name, options = {}, html_options = nil) </ruby> And here is a simple example of link_to_remote in action: @@ -98,7 +98,7 @@ link_to_remote "Delete the item", Note that if we wouldn't override the default behavior (POST), the above snippet would route to the create action rather than destroy. ** *JavaScript filters* You can customize the remote call further by wrapping it with some JavaScript code. Let's say in the previous example, when deleting a link, you'd like to ask for a confirmation by showing a simple modal text box to the user. This is a typical example what you can accomplish with these options - let's see them one by one: -*** +:confirm+ => +msg+ Pops up a JavaScript confirmation dialog, displaying +msg+. If the user chooses 'OK', the request is launched, otherwise canceled. +*** +:confirm+ => +msg+ Pops up a JavaScript confirmation dialog, displaying +msg+. If the user chooses 'OK', the request is launched, otherwise canceled. *** +:condition+ => +code+ Evaluates +code+ (which should evaluate to a boolean) and proceeds if it's true, cancels the request otherwise. *** +:before+ => +code+ Evaluates the +code+ just before launching the request. The output of the code has no influence on the execution. Typically used show a progress indicator (see this in action in the next example). *** +:after+ => +code+ Evaluates the +code+ after launching the request. Note that this is different from the +:success+ or +:complete+ callback (covered in the next section) since those are triggered after the request is completed, while the code snippet passed to +:after+ is evaluated after the remote call is made. A common example is to disable elements on the page or otherwise prevent further action while the request is completed. @@ -115,8 +115,8 @@ link_to_remote "Update record", This generates a remote link which adds 2 parameters to the standard URL generated by Rails, taken from the page (contained in the elements matched by the 'status' and 'completed' DOM id). ** *Callbacks* Since an AJAX call is typically asynchronous, as it's name suggests (this is not a rule, and you can fire a synchronous request - see the last option, +:type+) your only way of communicating with a request once it is fired is via specifying callbacks. There are six options at your disposal (in fact 508, counting all possible response types, but these six are the most frequent and therefore specified by a constant): -*** +:loading:+ => +code+ The request is in the process of receiving the data, but the transfer is not completed yet. -*** +:loaded:+ => +code+ The transfer is completed, but the data is not processed and returned yet +*** +:loading:+ => +code+ The request is in the process of receiving the data, but the transfer is not completed yet. +*** +:loaded:+ => +code+ The transfer is completed, but the data is not processed and returned yet *** +:interactive:+ => +code+ One step after +:loaded+: The data is fully received and being processed *** +:success:+ => +code+ The data is fully received, parsed and the server responded with "200 OK" *** +:failure:+ => +code+ The data is fully received, parsed and the server responded with *anything* but "200 OK" (typically 404 or 500, but in general with any status code ranging from 100 to 509) @@ -136,24 +136,24 @@ link_to_remote "Add new item", :before => "$('progress').show()", :complete => "$('progress').hide()", :success => "display_item_added(request)", - :failure => "display_error(request)", + :failure => "display_error(request)" </ruby> ** *:type* If you want to fire a synchronous request for some obscure reason (blocking the browser while the request is processed and doesn't return a status code), you can use the +:type+ option with the value of +:synchronous+. * Finally, using the +html_options+ parameter you can add HTML attributes to the generated tag. It works like the same parameter of the +link_to+ helper. There are interesting side effects for the +href+ and +onclick+ parameters though: ** If you specify the +href+ parameter, the AJAX link will degrade gracefully, i.e. the link will point to the URL even if JavaScript is disabled in the client browser ** +link_to_remote+ gains it's AJAX behavior by specifying the remote call in the onclick handler of the link. If you supply +html_options[:onclick]+ you override the default behavior, so use this with care! -We are finished with +link_to_remote+. I know this is quite a lot to digest for one helper function, but remember, these options are common for all the rest of the Rails view helpers, so we will take a look at the differences / additional parameters in the next sections. +We are finished with +link_to_remote+. I know this is quite a lot to digest for one helper function, but remember, these options are common for all the rest of the Rails view helpers, so we will take a look at the differences / additional parameters in the next sections. h4. AJAX Forms There are three different ways of adding AJAX forms to your view using Rails Prototype helpers. They are slightly different, but striving for the same goal: instead of submitting the form using the standard HTTP request/response cycle, it is submitted asynchronously, thus not reloading the page. These methods are the following: * +remote_form_for+ (and it's alias +form_remote_for+) is tied to Rails most tightly of the three since it takes a resource, model or array of resources (in case of a nested resource) as a parameter. -* +form_remote_tag+ AJAXifies the form by serializing and sending it's data in the background -* +submit_to_remote+ and +button_to_remote+ is more rarely used than the previous two. Rather than creating an AJAX form, you add a button/input +* +form_remote_tag+ AJAXifies the form by serializing and sending it's data in the background +* +submit_to_remote+ and +button_to_remote+ is more rarely used than the previous two. Rather than creating an AJAX form, you add a button/input -Let's se them in action one by one! +Let's see them in action one by one! h5. +remote_form_for+ @@ -161,7 +161,7 @@ h5. +form_remote_tag+ h5. +submit_to_remote+ -h4. Observing Elements +h4. Observing Elements h5. +observe_field+ @@ -183,13 +183,13 @@ h3. JavaScript the Rails way: RJS In the last section we sent some AJAX requests to the server, and inserted the HTML response into the page (with the +:update+ option). However, sometimes a more complicated interaction with the page is needed, which you can either achieve with JavaScript... or with RJS! You are sending JavaScript instructions to the server in both cases, but while in the former case you have to write vanilla JavaScript, in the second you can code Rails, and sit back while Rails generates the JavaScript for you - so basically RJS is a Ruby DSL to write JavaScript in your Rails code. -h4. Javascript without RJS +h4. JavaScript without RJS First we'll check out how to send JavaScript to the server manually. You are practically never going to need this, but it's interesting to understand what's going on under the hood. - + <ruby> def javascript_test - render :text => "alert('Hello, world!')", + render :text => "alert('Hello, world!')", :content_type => "text/javascript" end </ruby> @@ -207,14 +207,14 @@ def javascript_test render :update do |page| page.alert "Hello from inline RJS" end -end +end </ruby> -The above code snippet does exactly the same as the one in the previous section - going about it much more elegantly though. You don't need to worry about headers,write ugly JavaScript code into a string etc. When the first parameter to +render+ is +:update+, Rails expects a block with a single parameter (+page+ in our case, which is the traditional naming convention) which is an instance of the JavaScriptGenerator:"http://api.rubyonrails.org/classes/ActionView/Helpers/PrototypeHelper/JavaScriptGenerator/GeneratorMethods.html" object. As it's name suggests, JavaScriptGenerator is responsible for generating JavaScript from your Ruby code. You can execute multiple method calls on the +page+ instance - it's all turned into JavaScript code and sent to the server with the appropriate Content Type, "text/javascript". +The above code snippet does exactly the same as the one in the previous section - going about it much more elegantly though. You don't need to worry about headers,write ugly JavaScript code into a string etc. When the first parameter to +render+ is +:update+, Rails expects a block with a single parameter (+page+ in our case, which is the traditional naming convention) which is an instance of the JavaScriptGenerator:"http://api.rubyonrails.org/classes/ActionView/Helpers/PrototypeHelper/JavaScriptGenerator/GeneratorMethods.html" object. As it's name suggests, JavaScriptGenerator is responsible for generating JavaScript from your Ruby code. You can execute multiple method calls on the +page+ instance - it's all turned into JavaScript code and sent to the server with the appropriate Content Type, "text/javascript". h4. RJS Templates -If you don't want to clutter your controllers with view code (especially when your inline RJS is more than a few lines), you can move your RJS code to a template file. RJS templates should go to the +/app/views/+ directory, just as +.html.erb+ or any other view files of the appropriate controller, conventionally named +js.rjs+. +If you don't want to clutter your controllers with view code (especially when your inline RJS is more than a few lines), you can move your RJS code to a template file. RJS templates should go to the +/app/views/+ directory, just as +.html.erb+ or any other view files of the appropriate controller, conventionally named +js.rjs+. To rewrite the above example, you can leave the body of the action empty, and create a RJS template named +javascript_test.js.rjs+, containing the following line: @@ -265,7 +265,7 @@ The third parameter can either be a string, or a hash of options to be passed to page.insert_html :top, :result, :partial => "the_answer" </ruby> -You can replace the contents (innerHTML) of an element with the +replace_html+ method. The only difference is that since it's clear where should the new content go, there is no need for a position parameter - so +replace_html+ takes only two arguments, +You can replace the contents (innerHTML) of an element with the +replace_html+ method. The only difference is that since it's clear where should the new content go, there is no need for a position parameter - so +replace_html+ takes only two arguments, the DOM id of the element you wish to modify and a string or a hash of options to be passed to ActionView::Base#render. h6. Delay @@ -273,7 +273,7 @@ h6. Delay You can delay the execution of a block of code with +delay+: <ruby> -page.delay(10) { page.alert('Hey! Just waited 10 seconds') } +page.delay(10) { page.alert('Hey! Just waited 10 seconds') } </ruby> +delay+ takes one parameter (time to wait in seconds) and a block which will be executed after the specified time has passed - whatever else follows a +page.delay+ line is executed immediately, the delay affects only the code in the block. @@ -283,7 +283,7 @@ h6. Reloading and Redirecting You can reload the page with the +reload+ method: <ruby> -page.reload +page.reload </ruby> When using AJAX, you can't rely on the standard +redirect_to+ controller method - you have to use the +page+'s instance method, also called +redirect_to+: @@ -292,7 +292,7 @@ When using AJAX, you can't rely on the standard +redirect_to+ controller method page.redirect_to some_url </ruby> -h6. Generating Arbitrary JavaScript +h6. Generating Arbitrary JavaScript Sometimes even the full power of RJS is not enough to accomplish everything, but you still don't want to drop to pure JavaScript. A nice golden mean is offered by the combination of +<<+, +assign+ and +call+ methods: @@ -329,9 +329,9 @@ h4. Drag and Drop -h3. Testing Javascript +h3. Testing JavaScript -Javascript testing reminds me the definition of the world 'classic' by Mark Twain: "A classic is something that everybody wants to have read and nobody wants to read." It's similar with Javascript testing: everyone would like to have it, yet it's not done by too much developers as it is tedious, complicated, there is a proliferation of tools and no consensus/accepted best practices, but we will nevertheless take a stab at it: +JavaScript testing reminds me the definition of the world 'classic' by Mark Twain: "A classic is something that everybody wants to have read and nobody wants to read." It's similar with JavaScript testing: everyone would like to have it, yet it's not done by too much developers as it is tedious, complicated, there is a proliferation of tools and no consensus/accepted best practices, but we will nevertheless take a stab at it: * (Fire)Watir * Selenium @@ -339,4 +339,4 @@ Javascript testing reminds me the definition of the world 'classic' by Mark Twai * Cucumber+Webrat * Mention stuff like screw.unit/jsSpec -Note to self: check out the RailsConf JS testing video
\ No newline at end of file +Note to self: check out the RailsConf JS testing video diff --git a/railties/guides/source/api_documentation_guidelines.textile b/railties/guides/source/api_documentation_guidelines.textile index 9f201de49b..7433507866 100644 --- a/railties/guides/source/api_documentation_guidelines.textile +++ b/railties/guides/source/api_documentation_guidelines.textile @@ -6,7 +6,7 @@ endprologue. h3. RDoc -The Rails API documentation is generated with RDoc 2.5. Please consult the "RDoc documentation":http://rdoc.rubyforge.org/RDoc.htmlFor for help with its markup. +The Rails API documentation is generated with RDoc 2.5. Please consult the documentation for help with the "markup":http://rdoc.rubyforge.org/RDoc/Markup.html, and take into account also these "additional directives":http://rdoc.rubyforge.org/RDoc/Parser/Ruby.html. h3. Wording @@ -25,11 +25,13 @@ end Communicate to the reader the current way of doing things, both explicitly and implicitly. Use the recommended idioms in edge, reorder sections to emphasize favored approaches if needed, etc. The documentation should be a model for best practices and canonical, modern Rails usage. -Documentation has to be concise but comprehensive. Explore and document edge cases. What happens if a module is anonymous? What if a collection is empty? What if an argument is nil? +Documentation has to be concise but comprehensive. Explore and document edge cases. What happens if a module is anonymous? What if a collection is empty? What if an argument is nil? -The proper names of Rails components have a space in between the words, like "Active Support". +ActiveRecord+ is a Ruby module, whereas Active Record is an ORM. Historically there has been lack of consistency regarding this, but we checked with David when docrails started. All Rails documentation consistently refer to Rails components by their proper name, and if in your next blog post or presentation you remember this tidbit and take it into account that'd be fenomenal :). +The proper names of Rails components have a space in between the words, like "Active Support". +ActiveRecord+ is a Ruby module, whereas Active Record is an ORM. All Rails documentation should consistently refer to Rails components by their proper name, and if in your next blog post or presentation you remember this tidbit and take it into account that'd be phenomenal. -Spell names correctly: HTML, MySQL, JavaScript, ERb. Use the article "an" for "SQL", as in "an SQL statement". Also "an SQLite database". +Spell names correctly: Arel, Test::Unit, RSpec, HTML, MySQL, JavaScript, ERb. When in doubt, please have a look at some authoritative source like their official documentation. + +Use the article "an" for "SQL", as in "an SQL statement". Also "an SQLite database". h3. Example Code @@ -44,10 +46,10 @@ Short docs do not need an explicit "Examples" label to introduce snippets, they # Converts a collection of elements into a formatted string by calling # <tt>to_s</tt> on all elements and joining them. # -# Blog.find(:all).to_formatted_s # => "First PostSecond PostThird Post" +# Blog.all.to_formatted_s # => "First PostSecond PostThird Post" </ruby> -On the other hand big chunks of structured documentation may have a separate "Examples" section: +On the other hand, big chunks of structured documentation may have a separate "Examples" section: <ruby> # ==== Examples @@ -114,18 +116,16 @@ Use fixed-width fonts for: * file names <ruby> -# Copies the instance variables of +object+ into +self+. -# -# Instance variable names in the +exclude+ array are ignored. If +object+ -# responds to <tt>protected_instance_variables</tt> the ones returned are -# also ignored. For example, Rails controllers implement that method. -# ... -def copy_instance_variables_from(object, exclude = []) - ... +class Array + # Calls <tt>to_param</tt> on all its elements and joins the result with + # slashes. This is used by <tt>url_for</tt> in Action Pack. + def to_param + collect { |e| e.to_param }.join '/' + end end </ruby> -WARNING: Using a pair of ++...++ for fixed-width font only works with *words*; that is: anything matching <tt>\A\w+\z</tt>. For anything else use +<tt>...</tt>+, notably symbols, setters, inline snippets, etc: +WARNING: Using a pair of ++...++ for fixed-width font only works with *words*; that is: anything matching <tt>\A\w+\z</tt>. For anything else use +<tt>...</tt>+, notably symbols, setters, inline snippets, etc: h4. Regular Font diff --git a/railties/guides/source/association_basics.textile b/railties/guides/source/association_basics.textile index b1ee4b8be4..e5b8c73c43 100644 --- a/railties/guides/source/association_basics.textile +++ b/railties/guides/source/association_basics.textile @@ -30,7 +30,7 @@ Now, suppose we wanted to add a new order for an existing customer. We'd need to Or consider deleting a customer, and ensuring that all of its orders get deleted as well: <ruby> -@orders = Order.find_all_by_customer_id(@customer.id) +@orders = Order.where(:customer_id => @customer.id) @orders.each do |order| order.destroy end @@ -65,7 +65,7 @@ To learn more about the different types of associations, read the next section o h3. The Types of Associations -In Rails, an _association_ is a connection between two Active Record models. Associations are implemented using macro-style calls, so that you can declaratively add features to your models. For example, by declaring that one model +belongs_to+ another, you instruct Rails to maintain Primary Key–Foreign Key information between instances of the two models, and you also get a number of utility methods added to your model. Rails supports six types of association: +In Rails, an _association_ is a connection between two Active Record models. Associations are implemented using macro-style calls, so that you can declaratively add features to your models. For example, by declaring that one model +belongs_to+ another, you instruct Rails to maintain Primary Key–Foreign Key information between instances of the two models, and you also get a number of utility methods added to your model. Rails supports six types of associations: * +belongs_to+ * +has_one+ @@ -165,6 +165,12 @@ class Paragraph < ActiveRecord::Base end </ruby> +With +:through => :sections+ specified, Rails will now understand: + +<ruby> +@document.paragraphs +</ruby> + h4. The +has_one :through+ Association A +has_one :through+ association sets up a one-to-one connection with another model. This association indicates that the declaring model can be matched with one instance of another model by proceeding _through_ a third model. For example, if each supplier has one account, and each account is associated with one account history, then the customer model could look like this: @@ -550,7 +556,9 @@ build_customer create_customer </ruby> -h6. _association_(force_reload = false) +NOTE: When initializing a new +has_one+ or +belongs_to+ association you must use the +build_+ prefix to build the association, rather than the +association.build+ method that would be used for +has_many+ or +has_and_belongs_to_many+ associations. To create one, use the +create_+ prefix. + +h6(#belongs_to-association). <tt><em>association</em>(force_reload = false)</tt> The <tt><em>association</em></tt> method returns the associated object, if any. If no associated object is found, it returns +nil+. @@ -560,7 +568,7 @@ The <tt><em>association</em></tt> method returns the associated object, if any. If the associated object has already been retrieved from the database for this object, the cached version will be returned. To override this behavior (and force a database read), pass +true+ as the +force_reload+ argument. -h6. _association_=(associate) +h6(#belongs_to-association_equal). <tt>_association_=(associate)</tt> The <tt><em>association</em>=</tt> method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from the associate object and setting this object's foreign key to the same value. @@ -568,7 +576,7 @@ The <tt><em>association</em>=</tt> method assigns an associated object to this o @order.customer = @customer </ruby> -h6. build_<em>association</em>(attributes = {}) +h6(#belongs_to-build_association). <tt>build_<em>association</em>(attributes = {})</tt> The <tt>build_<em>association</em></tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through this object's foreign key will be set, but the associated object will _not_ yet be saved. @@ -577,7 +585,7 @@ The <tt>build_<em>association</em></tt> method returns a new object of the assoc :customer_name => "John Doe") </ruby> -h6. create_<em>association</em>(attributes = {}) +h6(#belongs_to-create_association). <tt>create_<em>association</em>(attributes = {})</tt> The <tt>create_<em>association</em></tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through this object's foreign key will be set. In addition, the associated object _will_ be saved (assuming that it passes any validations). @@ -629,7 +637,7 @@ end h6(#belongs_to-conditions). +:conditions+ -The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL +WHERE+ clause). +The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by an SQL +WHERE+ clause). <ruby> class Order < ActiveRecord::Base @@ -637,7 +645,7 @@ class Order < ActiveRecord::Base end </ruby> -h6. +:counter_cache+ +h6(#belongs_to-counter_cache). +:counter_cache+ The +:counter_cache+ option can be used to make finding the number of belonging objects more efficient. Consider these models: @@ -733,7 +741,7 @@ end NOTE: There's no need to use +:include+ for immediate associations - that is, if you have +Order belongs_to :customer+, then the customer is eager-loaded automatically when it's needed. -h6. +:polymorphic+ +h6(#belongs_to-polymorphic). +:polymorphic+ Passing +true+ to the +:polymorphic+ option indicates that this is a polymorphic association. Polymorphic associations were discussed in detail <a href="#polymorphic-associations">earlier in this guide</a>. @@ -747,7 +755,7 @@ The +:select+ option lets you override the SQL +SELECT+ clause that is used to r TIP: If you set the +:select+ option on a +belongs_to+ association, you should also set the +foreign_key+ option to guarantee the correct results. -h6. +:touch+ +h6(#belongs_to-touch). +:touch+ If you set the +:touch+ option to +:true+, then the +updated_at+ or +updated_on+ timestamp on the associated object will be set to the current time whenever this object is saved or destroyed: @@ -817,7 +825,9 @@ build_account create_account </ruby> -h6. <tt><em>association</em>(force_reload = false)</tt> +NOTE: When initializing a new +has_one+ or +belongs_to+ association you must use the +build_+ prefix to build the association, rather than the +association.build+ method that would be used for +has_many+ or +has_and_belongs_to_many+ associations. To create one, use the +create_+ prefix. + +h6(#has_one-association). <tt><em>association</em>(force_reload = false)</tt> The <tt><em>association</em></tt> method returns the associated object, if any. If no associated object is found, it returns +nil+. @@ -827,7 +837,7 @@ The <tt><em>association</em></tt> method returns the associated object, if any. If the associated object has already been retrieved from the database for this object, the cached version will be returned. To override this behavior (and force a database read), pass +true+ as the +force_reload+ argument. -h6. <tt><em>association</em>=(associate)</tt> +h6(#has_one-association_equal). <tt><em>association</em>=(associate)</tt> The <tt><em>association</em>=</tt> method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from this object and setting the associate object's foreign key to the same value. @@ -835,7 +845,7 @@ The <tt><em>association</em>=</tt> method assigns an associated object to this o @supplier.account = @account </ruby> -h6. <tt>build_<em>association</em>(attributes = {})</tt> +h6(#has_one-build_association). <tt>build_<em>association</em>(attributes = {})</tt> The <tt>build_<em>association</em></tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through its foreign key will be set, but the associated object will _not_ yet be saved. @@ -843,7 +853,7 @@ The <tt>build_<em>association</em></tt> method returns a new object of the assoc @account = @supplier.build_account(:terms => "Net 30") </ruby> -h6. <tt>create_<em>association</em>(attributes = {})</tt> +h6(#has_one-create_association). <tt>create_<em>association</em>(attributes = {})</tt> The <tt>create_<em>association</em></tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through its foreign key will be set. In addition, the associated object _will_ be saved (assuming that it passes any validations). @@ -899,7 +909,7 @@ end h6(#has_one-conditions). +:conditions+ -The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL +WHERE+ clause). +The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by an SQL +WHERE+ clause). <ruby> class Supplier < ActiveRecord::Base @@ -961,7 +971,7 @@ end h6(#has_one-order). +:order+ -The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +ORDER BY+ clause). Because a +has_one+ association will only retrieve a single associated object, this option should not be needed. +The +:order+ option dictates the order in which associated objects will be received (in the syntax used by an SQL +ORDER BY+ clause). Because a +has_one+ association will only retrieve a single associated object, this option should not be needed. h6(#has_one-primary_key). +:primary_key+ @@ -985,7 +995,7 @@ The +:source_type+ option specifies the source association type for a +has_one : h6(#has_one-through). +:through+ -The +:through+ option specifies a join model through which to perform the query. +has_one :through+ associations were discussed in detail <a href="#the-has-one-through-association">earlier in this guide</a>. +The +:through+ option specifies a join model through which to perform the query. +has_one :through+ associations were discussed in detail <a href="#the-has_one-through-association">earlier in this guide</a>. h6(#has_one-validate). +:validate+ @@ -1029,6 +1039,7 @@ When you declare a +has_many+ association, the declaring class automatically gai * <tt><em>collection</em>.empty?</tt> * <tt><em>collection</em>.size</tt> * <tt><em>collection</em>.find(...)</tt> +* <tt><em>collection</em>.where(...)</tt> * <tt><em>collection</em>.exists?(...)</tt> * <tt><em>collection</em>.build(attributes = {}, ...)</tt> * <tt><em>collection</em>.create(attributes = {})</tt> @@ -1054,6 +1065,7 @@ orders.clear orders.empty? orders.size orders.find(...) +orders.where(...) orders.exists?(...) orders.build(attributes = {}, ...) orders.create(attributes = {}) @@ -1083,10 +1095,10 @@ The <tt><em>collection</em>.delete</tt> method removes one or more objects from @customer.orders.delete(@order1) </ruby> -WARNING: Objects will be in addition destroyed if they're associated with +:dependent => :destroy+, and deleted if they're associated with +:dependent => :delete_all+. +WARNING: Additionally, objects will be destroyed if they're associated with +:dependent => :destroy+, and deleted if they're associated with +:dependent => :delete_all+. -h6(#has_many-collection_equal). <tt><em>collection</em>=objects</tt> +h6(#has_many-collection-equal). <tt><em>collection</em>=objects</tt> The <tt><em>collection</em>=</tt> method makes the collection contain only the supplied objects, by adding and deleting as appropriate. @@ -1102,11 +1114,11 @@ h6(#has_many-collection_singular_ids_ids). <tt><em>collection_singular</em>_ids= The <tt><em>collection_singular</em>_ids=</tt> method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate. -h6(#has_many-collection_clear). <tt><em>collection</em>.clear</tt> +h6(#has_many-collection-clear). <tt><em>collection</em>.clear</tt> The <tt><em>collection</em>.clear</tt> method removes every object from the collection. This destroys the associated objects if they are associated with +:dependent => :destroy+, deletes them directly from the database if +:dependent => :delete_all+, and otherwise sets their foreign keys to +NULL+. -h6. <tt><em>collection</em>.empty?</tt> +h6(#has_many-collection-empty). <tt><em>collection</em>.empty?</tt> The <tt><em>collection</em>.empty?</tt> method returns +true+ if the collection does not contain any associated objects. @@ -1116,7 +1128,7 @@ The <tt><em>collection</em>.empty?</tt> method returns +true+ if the collection <% end %> </ruby> -h6. <tt><em>collection</em>.size</tt> +h6(#has_many-collection-size). <tt><em>collection</em>.size</tt> The <tt><em>collection</em>.size</tt> method returns the number of objects in the collection. @@ -1124,19 +1136,30 @@ The <tt><em>collection</em>.size</tt> method returns the number of objects in th @order_count = @customer.orders.size </ruby> -h6. <tt><em>collection</em>.find(...)</tt> +h6(#has_many-collection-find). <tt><em>collection</em>.find(...)</tt> The <tt><em>collection</em>.find</tt> method finds objects within the collection. It uses the same syntax and options as +ActiveRecord::Base.find+. <ruby> -@open_orders = @customer.orders.find(:all, :conditions => "open = 1") +@open_orders = @customer.orders.all(:conditions => "open = 1") </ruby> -h6. <tt><em>collection</em>.exists?(...)</tt> +NOTE: Starting Rails 3, supplying options to +ActiveRecord::Base.find+ method is discouraged. Use <tt><em>collection</em>.where</tt> instead when you need to pass conditions. + +h6(#has_many-collection-where). <tt><em>collection</em>.where(...)</tt> + +The <tt><em>collection</em>.where</tt> method finds objects within the collection based on the conditions supplied but the objects are loaded lazily meaning that the database is queried only when the object(s) are accessed. + +<ruby> +@open_orders = @customer.orders.where(:open => true) # No query yet +@open_order = @open_orders.first # Now the database will be queried +</ruby> + +h6(#has_many-collection-exists). <tt><em>collection</em>.exists?(...)</tt> The <tt><em>collection</em>.exists?</tt> method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as +ActiveRecord::Base.exists?+. -h6. <tt><em>collection</em>.build(attributes = {}, ...)</tt> +h6(#has_many-collection-build). <tt><em>collection</em>.build(attributes = {}, ...)</tt> The <tt><em>collection</em>.build</tt> method returns one or more new objects of the associated type. These objects will be instantiated from the passed attributes, and the link through their foreign key will be created, but the associated objects will _not_ yet be saved. @@ -1145,7 +1168,7 @@ The <tt><em>collection</em>.build</tt> method returns one or more new objects of :order_number => "A12345") </ruby> -h6. <tt><em>collection</em>.create(attributes = {})</tt> +h6(#has_many-collection-create). <tt><em>collection</em>.create(attributes = {})</tt> The <tt><em>collection</em>.create</tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through its foreign key will be created, and the associated object _will_ be saved (assuming that it passes any validations). @@ -1193,7 +1216,7 @@ h6(#has_many-as). +:as+ Setting the +:as+ option indicates that this is a polymorphic association, as discussed <a href="#polymorphic-associations">earlier in this guide</a>. -h6. +:autosave+ +h6(#has_many-autosave). +:autosave+ If you set the +:autosave+ option to +true+, Rails will save any loaded members and destroy members that are marked for destruction whenever you save the parent object. @@ -1209,7 +1232,7 @@ end h6(#has_many-conditions). +:conditions+ -The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL +WHERE+ clause). +The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by an SQL +WHERE+ clause). <ruby> class Customer < ActiveRecord::Base @@ -1335,7 +1358,7 @@ The +:offset+ option lets you specify the starting offset for fetching objects v h6(#has_many-order). +:order+ -The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +ORDER BY+ clause). +The +:order+ option dictates the order in which associated objects will be received (in the syntax used by an SQL +ORDER BY+ clause). <ruby> class Customer < ActiveRecord::Base @@ -1367,7 +1390,7 @@ The +:source_type+ option specifies the source association type for a +has_many h6(#has_many-through). +:through+ -The +:through+ option specifies a join model through which to perform the query. +has_many :through+ associations provide a way to implement many-to-many relationships, as discussed <a href="#the-has-many-through-association">earlier in this guide</a>. +The +:through+ option specifies a join model through which to perform the query. +has_many :through+ associations provide a way to implement many-to-many relationships, as discussed <a href="#the-has_many-through-association">earlier in this guide</a>. h6(#has_many-uniq). +:uniq+ @@ -1401,8 +1424,8 @@ person = Person.create(:name => 'honda') post = Post.create(:name => 'a1') person.posts << post person.posts << post -person.posts.inspect # => [#<Post id: 7, name: "a1">] -Reading.all.inspect # => [#<Reading id: 16, person_id: 7, post_id: 7>, #<Reading id: 17, person_id: 7, post_id: 7>] +person.posts.inspect # => [#<Post id: 7, name: "a1">] +Reading.all.inspect # => [#<Reading id: 16, person_id: 7, post_id: 7>, #<Reading id: 17, person_id: 7, post_id: 7>] </ruby> In the above case there are still two readings. However +person.posts+ shows only one post because the collection loads only unique records. @@ -1439,11 +1462,12 @@ When you declare a +has_and_belongs_to_many+ association, the declaring class au * <tt><em>collection</em>.empty?</tt> * <tt><em>collection</em>.size</tt> * <tt><em>collection</em>.find(...)</tt> +* <tt><em>collection</em>.where(...)</tt> * <tt><em>collection</em>.exists?(...)</tt> * <tt><em>collection</em>.build(attributes = {})</tt> * <tt><em>collection</em>.create(attributes = {})</tt> -In all of these methods, <tt><em>collection</em></tt> is replaced with the symbol passed as the first argument to +has_and_belongs_to_many+, and <tt><em>collection_singular</em></tt> is replaced with the singularized version of that symbol.. For example, given the declaration: +In all of these methods, <tt><em>collection</em></tt> is replaced with the symbol passed as the first argument to +has_and_belongs_to_many+, and <tt><em>collection_singular</em></tt> is replaced with the singularized version of that symbol. For example, given the declaration: <ruby> class Part < ActiveRecord::Base @@ -1464,6 +1488,7 @@ assemblies.clear assemblies.empty? assemblies.size assemblies.find(...) +assemblies.where(...) assemblies.exists?(...) assemblies.build(attributes = {}, ...) assemblies.create(attributes = {}) @@ -1476,7 +1501,7 @@ If the join table for a +has_and_belongs_to_many+ association has additional col WARNING: The use of extra attributes on the join table in a +has_and_belongs_to_many+ association is deprecated. If you require this sort of complex behavior on the table that joins two models in a many-to-many relationship, you should use a +has_many :through+ association instead of +has_and_belongs_to_many+. -h6. <tt><em>collection</em>(force_reload = false)</tt> +h6(#has_and_belongs_to_many-collection). <tt><em>collection</em>(force_reload = false)</tt> The <tt><em>collection</em></tt> method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array. @@ -1484,7 +1509,7 @@ The <tt><em>collection</em></tt> method returns an array of all of the associate @assemblies = @part.assemblies </ruby> -h6. <tt><em>collection</em><<(object, ...)</tt> +h6(#has_and_belongs_to_many-collection-lt_lt). <tt><em>collection</em><<(object, ...)</tt> The <tt><em>collection</em><<</tt> method adds one or more objects to the collection by creating records in the join table. @@ -1494,7 +1519,7 @@ The <tt><em>collection</em><<</tt> method adds one or more objects to the collec NOTE: This method is aliased as <tt><em>collection</em>.concat</tt> and <tt><em>collection</em>.push</tt>. -h6. <tt><em>collection</em>.delete(object, ...)</tt> +h6(#has_and_belongs_to_many-collection-delete). <tt><em>collection</em>.delete(object, ...)</tt> The <tt><em>collection</em>.delete</tt> method removes one or more objects from the collection by deleting records in the join table. This does not destroy the objects. @@ -1502,11 +1527,11 @@ The <tt><em>collection</em>.delete</tt> method removes one or more objects from @part.assemblies.delete(@assembly1) </ruby> -h6. <tt><em>collection</em>=objects</tt> +h6(#has_and_belongs_to_many-collection-equal). <tt><em>collection</em>=objects</tt> The <tt><em>collection</em>=</tt> method makes the collection contain only the supplied objects, by adding and deleting as appropriate. -h6. <tt><em>collection_singular</em>_ids</tt> +h6(#has_and_belongs_to_many-collection_singular). <tt><em>collection_singular</em>_ids</tt> The <tt><em>collection_singular</em>_ids</tt> method returns an array of the ids of the objects in the collection. @@ -1514,11 +1539,11 @@ The <tt><em>collection_singular</em>_ids</tt> method returns an array of the ids @assembly_ids = @part.assembly_ids </ruby> -h6. <tt><em>collection_singular</em>_ids=ids</tt> +h6(#has_and_belongs_to_many-collection_singular_ids_ids). <tt><em>collection_singular</em>_ids=ids</tt> The <tt><em>collection_singular</em>_ids=</tt> method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate. -h6. <tt><em>collection</em>.clear</tt> +h6(#has_and_belongs_to_many-collection-clear). <tt><em>collection</em>.clear</tt> The <tt><em>collection</em>.clear</tt> method removes every object from the collection by deleting the rows from the joining table. This does not destroy the associated objects. @@ -1545,15 +1570,25 @@ h6(#has_and_belongs_to_many-collection-find). <tt><em>collection</em>.find(...)< The <tt><em>collection</em>.find</tt> method finds objects within the collection. It uses the same syntax and options as +ActiveRecord::Base.find+. It also adds the additional condition that the object must be in the collection. <ruby> -@new_assemblies = @part.assemblies.find(:all, +@new_assemblies = @part.assemblies.all( :conditions => ["created_at > ?", 2.days.ago]) </ruby> +NOTE: Starting Rails 3, supplying options to +ActiveRecord::Base.find+ method is discouraged. Use <tt><em>collection</em>.where</tt> instead when you need to pass conditions. + +h6(#has_and_belongs_to_many-collection-where). <tt><em>collection</em>.where(...)</tt> + +The <tt><em>collection</em>.where</tt> method finds objects within the collection based on the conditions supplied but the objects are loaded lazily meaning that the database is queried only when the object(s) are accessed. It also adds the additional condition that the object must be in the collection. + +<ruby> +@new_assemblies = @part.assemblies.where("created_at > ?", 2.days.ago) +</ruby> + h6(#has_and_belongs_to_many-collection-exists). <tt><em>collection</em>.exists?(...)</tt> The <tt><em>collection</em>.exists?</tt> method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as +ActiveRecord::Base.exists?+. -h6. <tt><em>collection</em>.build(attributes = {})</tt> +h6(#has_and_belongs_to_many-collection-build). <tt><em>collection</em>.build(attributes = {})</tt> The <tt><em>collection</em>.build</tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through the join table will be created, but the associated object will _not_ yet be saved. @@ -1605,7 +1640,7 @@ The +has_and_belongs_to_many+ association supports these options: * +:uniq+ * +:validate+ -h6. +:association_foreign_key+ +h6(#has_and_belongs_to_many-association_foreign_key). +:association_foreign_key+ By convention, Rails guesses that the column in the join table used to hold the foreign key pointing to the other model is the name of that model with the suffix +_id+ added. The +:association_foreign_key+ option lets you set the name of the foreign key directly: @@ -1635,7 +1670,7 @@ end h6(#has_and_belongs_to_many-conditions). +:conditions+ -The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL +WHERE+ clause). +The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by an SQL +WHERE+ clause). <ruby> class Parts < ActiveRecord::Base @@ -1661,7 +1696,7 @@ Normally Rails automatically generates the proper SQL to count the association m NOTE: If you specify +:finder_sql+ but not +:counter_sql+, then the counter SQL will be generated by substituting +SELECT COUNT(*) FROM+ for the +SELECT ... FROM+ clause of your +:finder_sql+ statement. -h6. +:delete_sql+ +h6(#has_and_belongs_to_many-delete_sql). +:delete_sql+ Normally Rails automatically generates the proper SQL to remove links between the associated classes. With the +:delete_sql+ option, you can specify a complete SQL statement to delete them yourself. @@ -1699,11 +1734,11 @@ h6(#has_and_belongs_to_many-include). +:include+ You can use the +:include+ option to specify second-order associations that should be eager-loaded when this association is used. -h6. +:insert_sql+ +h6(#has_and_belongs_to_many-insert_sql). +:insert_sql+ Normally Rails automatically generates the proper SQL to create links between the associated classes. With the +:insert_sql+ option, you can specify a complete SQL statement to insert them yourself. -h6. +:join_table+ +h6(#has_and_belongs_to_many-join_table). +:join_table+ If the default name of the join table, based on lexical ordering, is not what you want, you can use the +:join_table+ option to override the default. @@ -1724,7 +1759,7 @@ The +:offset+ option lets you specify the starting offset for fetching objects v h6(#has_and_belongs_to_many-order). +:order+ -The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +ORDER BY+ clause). +The +:order+ option dictates the order in which associated objects will be received (in the syntax used by an SQL +ORDER BY+ clause). <ruby> class Parts < ActiveRecord::Base @@ -1760,9 +1795,9 @@ If you want to assign an object to a +has_and_belongs_to_many+ association witho h4. Association Callbacks -Normal callbacks hook into the lifecycle of Active Record objects, allowing you to work with those objects at various points. For example, you can use a +:before_save+ callback to cause something to happen just before an object is saved. +Normal callbacks hook into the life cycle of Active Record objects, allowing you to work with those objects at various points. For example, you can use a +:before_save+ callback to cause something to happen just before an object is saved. -Association callbacks are similar to normal callbacks, but they are triggered by events in the lifecycle of a collection. There are four available association callbacks: +Association callbacks are similar to normal callbacks, but they are triggered by events in the life cycle of a collection. There are four available association callbacks: * +before_add+ * +after_add+ @@ -1821,7 +1856,7 @@ If you have an extension that should be shared by many associations, you can use <ruby> module FindRecentExtension def find_recent - find(:all, :conditions => ["created_at > ?", 5.days.ago]) + where("created_at > ?", 5.days.ago) end end @@ -1851,8 +1886,6 @@ Extensions can refer to the internals of the association proxy using these three h3. Changelog -"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/11 - * April 7, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com * April 19, 2009: Added +:touch+ option to +belongs_to+ associations by "Mike Gunderloy":credits.html#mgunderloy * February 1, 2009: Added +:autosave+ option "Mike Gunderloy":credits.html#mgunderloy diff --git a/railties/guides/source/caching_with_rails.textile b/railties/guides/source/caching_with_rails.textile index 6dee4b9c61..297ba2d661 100644 --- a/railties/guides/source/caching_with_rails.textile +++ b/railties/guides/source/caching_with_rails.textile @@ -65,7 +65,7 @@ end If you want a more complicated expiration scheme, you can use cache sweepers to expire cached objects when things change. This is covered in the section on Sweepers. -Note: Page caching ignores all parameters. For example +/products?page=1+ will be written out to the filesystem as +products.html+ with no reference to the +page+ parameter. Thus, if someone requests +/products?page=2+ later, they will get the cached first page. Be careful when page caching GET parameters in the URL! +NOTE: Page caching ignores all parameters. For example +/products?page=1+ will be written out to the filesystem as +products.html+ with no reference to the +page+ parameter. Thus, if someone requests +/products?page=2+ later, they will get the cached first page. Be careful when page caching GET parameters in the URL! INFO: Page caching runs in an after filter. Thus, invalid requests won't generate spurious cache entries as long as you halt them. Typically, a redirection in some before filter that checks request preconditions does the job. @@ -98,7 +98,7 @@ You can also use +:if+ (or +:unless+) to pass a Proc that specifies when the act You can modify the default action cache path by passing a +:cache_path+ option. This will be passed directly to +ActionCachePath.path_for+. This is handy for actions with multiple possible routes that should be cached differently. If a block is given, it is called with the current controller instance. -Finally, if you are using memcached, you can also pass +:expires_in+. In fact, all parameters not used by +caches_action+ are sent to the underlying cache store. +Finally, if you are using memcached, you can also pass +:expires_in+. In fact, all parameters not used by +caches_action+ are sent to the underlying cache store. INFO: Action caching runs in an after filter. Thus, invalid requests won't generate spurious cache entries as long as you halt them. Typically, a redirection in some before filter that checks request preconditions does the job. @@ -238,86 +238,95 @@ h3. Cache Stores Rails provides different stores for the cached data created by action and fragment caches. Page caches are always stored on disk. -Rails 2.1 and above provide +ActiveSupport::Cache::Store+ which can be used to cache strings. Some cache store implementations, like +MemoryStore+, are able to cache arbitrary Ruby objects, but don't count on every cache store to be able to do that. +h4. Configuration -The default cache stores provided with Rails include: +You can set up your application's default cache store by calling +config.cache_store=+ in the Application definition inside your +config/application.rb+ file or in an Application.configure block in an environment specific configuration file (i.e. +config/environments/*.rb+). The first argument will be the cache store to use and the rest of the argument will be passed as arguments to the cache store constructor. -1) +ActiveSupport::Cache::MemoryStore+: A cache store implementation which stores everything into memory in the same process. If you're running multiple Ruby on Rails server processes (which is the case if you're using mongrel_cluster or Phusion Passenger), then this means that your Rails server process instances won't be able to share cache data with each other. If your application never performs manual cache item expiry (e.g. when you‘re using generational cache keys), then using +MemoryStore+ is ok. Otherwise, consider carefully whether you should be using this cache store. - -+MemoryStore+ is not only able to store strings, but also arbitrary Ruby objects. - -+MemoryStore+ is not thread-safe. Use +SynchronizedMemoryStore+ instead if you need thread-safety. - <ruby> -ActionController::Base.cache_store = :memory_store +config.cache_store = :memory_store </ruby> -2) +ActiveSupport::Cache::FileStore+: Cached data is stored on the disk, this is the default store and the default path for this store is +tmp/cache+. Works well for all types of environments and allows all processes running from the same application directory to access the cached content. If +tmp/cache+ does not exist, the default store becomes +MemoryStore+. +Alternatively, you can call +ActionController::Base.cache_store+ outside of a configuration block. -<ruby> -ActionController::Base.cache_store = :file_store, "/path/to/cache/directory" -</ruby> +You can access the cache by calling +Rails.cache+. -3) +ActiveSupport::Cache::DRbStore+: Cached data is stored in a separate shared DRb process that all servers communicate with. This works for all environments and only keeps one cache around for all processes, but requires that you run and manage a separate DRb process. +h4. ActiveSupport::Cache::Store -<ruby> -ActionController::Base.cache_store = :drb_store, "druby://localhost:9192" -</ruby> +This class provides the foundation for interacting with the cache in Rails. This is an abstract class and you cannot use it on its own. Rather you must use a concrete implementation of the class tied to a storage engine. Rails ships with several implementations documented below. + +The main methods to call are +read+, +write+, +delete+, +exist?+, and +fetch+. The fetch method takes a block and will either return an existing value from the cache, or evaluate the block and write the result to the cache if no value exists. -4) +ActiveSupport::Cache::MemCacheStore+: Works like +DRbStore+, but uses Danga's +memcached+ instead. Rails uses the bundled +memcached-client+ gem by default. This is currently the most popular cache store for production websites. +There are some common options used by all cache implementations. These can be passed to the constructor or the various methods to interact with entries. -Special features: +* +:namespace+ - This option can be used to create a namespace within the cache store. It is especially useful if your application shares a cache with other applications. The default value will include the application name and Rails environment. -* Clustering and load balancing. One can specify multiple memcached servers, and +MemCacheStore+ will load balance between all available servers. If a server goes down, then +MemCacheStore+ will ignore it until it goes back online. -* Time-based expiry support. See +write+ and the +:expires_in+ option. -* Per-request in memory cache for all communication with the +memcached+ server(s). +* +:compress+ - This option can be used to indicate that compression should be used in the cache. This can be useful for transferring large cache entries over a slow network. -It also accepts a hash of additional options: +* +:compress_threshold+ - This options is used in conjunction with the +:compress+ option to indicate a threshold under which cache entries should not be compressed. This defaults to 16 kilobytes. -* +:namespace+: specifies a string that will automatically be prepended to keys when accessing the memcached store. -* +:readonly+: a boolean value that when set to true will make the store read-only, with an error raised on any attempt to write. -* +:multithread+: a boolean value that adds thread safety to read/write operations - it is unlikely you'll need to use this option as the Rails threadsafe! method offers the same functionality. +* +:expires_in+ - This option sets an expiration time in seconds for the cache entry when it will be automatically removed from the cache. -The read and write methods of the +MemCacheStore+ accept an options hash too. When reading you can specify +:raw => true+ to prevent the object being marshaled (by default this is false which means the raw value in the cache is passed to +Marshal.load+ before being returned to you.) +* +:race_condition_ttl+ - This option is used in conjunction with the +:expires_in+ option. It will prevent race conditions when cache entries expire by preventing multiple processes from simultaneously regenerating the same entry (also known as the dog pile effect). This option sets the number of seconds that an expired entry can be reused while a new value is being regenerated. It's a good practice to set this value if you use the +:expires_in+ option. -When writing to the cache it is also possible to specify +:raw => true+ means the value is not passed to +Marshal.dump+ before being stored in the cache (by default this is false). +h4. ActiveSupport::Cache::MemoryStore -The write method also accepts an +:unless_exist+ flag which determines whether the memcached add (when true) or set (when false) method is used to store the item in the cache and an +:expires_in+ option that specifies the time-to-live for the cached item in seconds. +This cache store keeps entries in memory in the same Ruby process. The cache store has a bounded size specified by the +:size+ options to the initializer (default is 32Mb). When the cache exceeds the allotted size, a cleanup will occur and the least recently used entries will be removed. <ruby> -ActionController::Base.cache_store = :mem_cache_store, "localhost" +ActionController::Base.cache_store = :memory_store, :size => 64.megabytes </ruby> -5) +ActiveSupport::Cache::SynchronizedMemoryStore+: Like +MemoryStore+ but thread-safe. +If you're running multiple Ruby on Rails server processes (which is the case if you're using mongrel_cluster or Phusion Passenger), then your Rails server process instances won't be able to share cache data with each other. This cache store is not appropriate for large application deployments, but can work well for small, low traffic sites with only a couple of server processes or for development and test environments. + +This is the default cache store implementation. + +h4. ActiveSupport::Cache::FileStore + +This cache store uses the file system to store entries. The path to the directory where the store files will be stored must be specified when initializing the cache. <ruby> -ActionController::Base.cache_store = :synchronized_memory_store +ActionController::Base.cache_store = :file_store, "/path/to/cache/directory" </ruby> -6) +ActiveSupport::Cache::CompressedMemCacheStore+: Works just like the regular +MemCacheStore+ but uses GZip to decompress/compress on read/write. +With this cache store, multiple server processes on the same host can share a cache. Servers processes running on different hosts could share a cache by using a shared file system, but that set up would not be ideal and is not recommended. The cache store is appropriate for low to medium traffic sites that are served off one or two hosts. + +Note that the cache will grow until the disk is full unless you periodically clear out old entries. + +h4. ActiveSupport::Cache::MemCacheStore + +This cache store uses Danga's +memcached+ server to provide a centralized cache for your application. Rails uses the bundled +memcached-client+ gem by default. This is currently the most popular cache store for production websites. It can be used to provide a single, shared cache cluster with very a high performance and redundancy. + +When initializing the cache, you need to specify the addresses for all memcached servers in your cluster. If none is specified, it will assume memcached is running on the local host on the default port, but this is not an ideal set up for larger sites. + +The +write+ and +fetch+ methods on this cache accept two additional options that take advantage of features specific to memcached. You can specify +:raw+ to send a value directly to the server with no serialization. The value must be a string or number. You can use memcached direct operation like +increment+ and +decrement+ only on raw values. You can also specify +:unless_exist+ if you don't want memcached to overwrite an existing entry. <ruby> -ActionController::Base.cache_store = :compressed_mem_cache_store, "localhost" +ActionController::Base.cache_store = :mem_cache_store, "cache-1.example.com", "cache-2.example.com" </ruby> -7) Custom store: You can define your own cache store (new in Rails 2.1). +h4. Custom Cache Stores + +You can create your own custom cache store by simply extending +ActiveSupport::Cache::Store+ and implementing the appropriate methods. In this way, you can swap in any number of caching technologies into your Rails application. + +To use a custom cache store, simple set the cache store to a new instance of the class. <ruby> -ActionController::Base.cache_store = MyOwnStore.new("parameter") +ActionController::Base.cache_store = MyCacheStore.new </ruby> -NOTE: +config.cache_store+ can be used in place of +ActionController::Base.cache_store+ in your +Rails::Initializer.run+ block in +environment.rb+ +h4. Cache Keys -In addition to all of this, Rails also adds the +ActiveRecord::Base#cache_key+ method that generates a key using the class name, +id+ and +updated_at+ timestamp (if available). +The keys used in a cache can be any object that responds to either +:cache_key+ or to +:to_param+. You can implement the +:cache_key+ method on your classes if you need to generate custom keys. ActiveRecord will generate keys based on the class name and record id. -You can access these cache stores at a low level for storing queries and other objects. Here's an example: +You can use Hashes and Arrays of values as cache keys. <ruby> -Rails.cache.read("city") # => nil -Rails.cache.write("city", "Duckburgh") -Rails.cache.read("city") # => "Duckburgh" +# This is a legal cache key +Rails.cache.read(:site => "mysite", :owners => [owner_1, owner2]) </ruby> +The keys you use on +Rails.cache+ will not be the same as those actually used with the storage engine. They may be modified with a namespace or altered to fit technology backend constraints. This means, for instance, that you can't save values with +Rails.cache+ and then try to pull them out with the +memcache-client+ gem. However, you also don't need to worry about exceeding the memcached size limit or violating syntax rules. + h3. Conditional GET support Conditional GETs are a feature of the HTTP specification that provide a way for web servers to tell browsers that the response to a GET request hasn't changed since the last request and can be safely pulled from the browser cache. @@ -362,25 +371,14 @@ class ProductsController < ApplicationController end </ruby> -h3. Advanced Caching - -Along with the built-in mechanisms outlined above, a number of excellent plugins exist to help with finer grained control over caching. These include Chris Wanstrath's excellent cache_fu plugin (more info "here": http://errtheblog.com/posts/57-kickin-ass-w-cachefu) and Evan Weaver's interlock plugin (more info "here": http://blog.evanweaver.com/articles/2007/12/13/better-rails-caching/). Both of these plugins play nice with memcached and are a must-see for anyone -seriously considering optimizing their caching needs. - -Also the new "Cache money":http://github.com/nkallen/cache-money/tree/master plugin is supposed to be mad cool. - -h3. References +h3. Further reading * "Scaling Rails Screencasts":http://railslab.newrelic.com/scaling-rails -* "RailsEnvy, Rails Caching Tutorial, Part 1":http://www.railsenvy.com/2007/2/28/rails-caching-tutorial -* "RailsEnvy, Rails Caching Tutorial, Part 2":http://www.railsenvy.com/2007/3/20/ruby-on-rails-caching-tutorial-part-2 -* "ActiveSupport::Cache documentation":http://api.rubyonrails.org/classes/ActiveSupport/Cache.html -* "Rails 2.1 integrated caching tutorial":http://thewebfellas.com/blog/2008/6/9/rails-2-1-now-with-better-integrated-caching h3. Changelog -"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/10-guide-to-caching +* Feb 17, 2011: Document 3.0.0 changes to ActiveSupport::Cache * May 02, 2009: Formatting cleanups * April 26, 2009: Clean up typos in submitted patch * April 1, 2009: Made a bunch of small fixes diff --git a/railties/guides/source/command_line.textile b/railties/guides/source/command_line.textile index fb625f7a44..581fece1ab 100644 --- a/railties/guides/source/command_line.textile +++ b/railties/guides/source/command_line.textile @@ -31,11 +31,11 @@ h4. +rails new+ The first thing we'll want to do is create a new Rails application by running the +rails new+ command after installing Rails. -WARNING: You know you need the rails gem installed by typing +gem install rails+ first, if you don't have this installed, follow the instructions in the "Rails 3 Release Notes":/3_0_release_notes.html +WARNING: You can install the rails gem by typing +gem install rails+, if you don't have it already. Follow the instructions in the "Rails 3 Release Notes":/3_0_release_notes.html <shell> $ rails new commandsapp - create + create create README create .gitignore create Rakefile @@ -73,7 +73,7 @@ $ rails server [2010-04-18 03:20:33] INFO WEBrick::HTTPServer#start: pid=26086 port=3000 </shell> -With just three commands we whipped up a Rails server listening on port 3000. Go to your browser and open "http://localhost:3000":http://localhost:3000, you will see a basic rails app running. +With just three commands we whipped up a Rails server listening on port 3000. Go to your browser and open "http://localhost:3000":http://localhost:3000, you will see a basic Rails app running. h4. +rails generate+ @@ -81,7 +81,7 @@ The +rails generate+ command uses templates to create a whole lot of things. You <shell> $ rails generate -Usage: rails generate generator [options] [args] +Usage: rails generate generator [args] [options] ... ... @@ -101,11 +101,11 @@ Using generators will save you a large amount of time by writing *boilerplate co Let's make our own controller with the controller generator. But what command should we use? Let's ask the generator: -INFO: All Rails console utilities have help text. As with most *NIX utilities, you can try adding +--help+ or +-h+ to the end, for example +rails server --help+. +INFO: All Rails console utilities have help text. As with most *nix utilities, you can try adding +--help+ or +-h+ to the end, for example +rails server --help+. <shell> $ rails generate controller -Usage: rails generate controller ControllerName [options] +Usage: rails generate controller NAME [action action] [options] ... ... @@ -122,7 +122,7 @@ Example: Modules Example: rails generate controller 'admin/credit_card' suspend late_fee - Credit card admin controller with URLs /admin/credit_card/suspend. + Credit card admin controller with URLs like /admin/credit_card/suspend. Controller: app/controllers/admin/credit_card_controller.rb Views: app/views/admin/credit_card/debit.html.erb [...] Helper: app/helpers/admin/credit_card_helper.rb @@ -134,25 +134,28 @@ The controller generator is expecting parameters in the form of +generate contro <shell> $ rails generate controller Greetings hello create app/controllers/greetings_controller.rb + route get "greetings/hello" invoke erb create app/views/greetings create app/views/greetings/hello.html.erb - error rspec [not found] + invoke test_unit + create test/functional/greetings_controller_test.rb invoke helper create app/helpers/greetings_helper.rb - error rspec [not found] + invoke test_unit + create test/unit/helpers/greetings_helper_test.rb + </shell> What all did this generate? It made sure a bunch of directories were in our application, and created a controller file, a functional test file, a helper for the view, and a view file. -Check out the controller and modify it a little (in +app/controllers/greetings_controller.rb+):ma +Check out the controller and modify it a little (in +app/controllers/greetings_controller.rb+): <ruby> class GreetingsController < ApplicationController def hello @message = "Hello, how are you today?" end - end </ruby> @@ -163,7 +166,7 @@ Then the view, to display our message (in +app/views/greetings/hello.html.erb+): <p><%= @message %></p> </html> -Deal. Go check it out in your browser. Fire up your server. Remember? +rails server+ at the root of your Rails application should do it. +Deal. Go check it out in your browser. Fire up your server using +rails server+. <shell> $ rails server @@ -180,7 +183,7 @@ Rails comes with a generator for data models too: <shell> $ rails generate model -Usage: rails generate model ModelName [field:type, field:type] +Usage: rails generate model NAME [field:type field:type] [options] ... @@ -197,6 +200,8 @@ Examples: Creates a Post model with a string title, text body, and published flag. </shell> +NOTE: For a list of available field types, refer to the "API documentation":http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/TableDefinition.html#method-i-column for the column method for the +TableDefinition+ class. + But instead of generating a model directly (which we'll be doing later), let's set up a scaffold. A *scaffold* in Rails is a full set of model, database migration for that model, controller to manipulate it, views to view and manipulate the data, and a test suite for each of the above. We will set up a simple resource called "HighScore" that will keep track of our highest score on video games we play. @@ -220,7 +225,7 @@ $ rails generate scaffold HighScore game:string score:integer create app/controllers/high_scores_controller.rb create test/functional/high_scores_controller_test.rb create app/helpers/high_scores_helper.rb - route map.resources :high_scores + route resources :high_scores dependency model exists app/models/ exists test/unit/ @@ -259,6 +264,15 @@ h4. +rails console+ The +console+ command lets you interact with your Rails application from the command line. On the underside, +rails console+ uses IRB, so if you've ever used it, you'll be right at home. This is useful for testing out quick ideas with code and changing data server-side without touching the website. +If you wish to test out some code without changing any data, you can do that by invoking +rails console --sandbox+. + +<shell> +$ rails console --sandbox +Loading development environment in sandbox (Rails 3.0.0) +Any modifications you make will be rolled back on exit +irb(main):001:0> +</shell> + h4. +rails dbconsole+ +rails dbconsole+ figures out which database you're using and drops you into whichever command line interface you would use with it (and figures out the command line parameters to give to it, too!). It supports MySQL, PostgreSQL, SQLite and SQLite3. @@ -272,14 +286,14 @@ Let's say you're creating a website for a client who wants a small accounting sy There is such a thing! The plugin we're installing is called +acts_as_paranoid+, and it lets models implement a +deleted_at+ column that gets set when you call destroy. Later, when calling find, the plugin will tack on a database check to filter out "deleted" things. <shell> -$ rails plugin install http://svn.techno-weenie.net/projects/plugins/acts_as_paranoid +$ rails plugin install https://github.com/technoweenie/acts_as_paranoid.git + ./CHANGELOG + ./MIT-LICENSE ... ... </shell> -h4. +runner+ +h4. +rails runner+ <tt>runner</tt> runs Ruby code in the context of Rails non-interactively. For instance: @@ -287,7 +301,7 @@ h4. +runner+ $ rails runner "Model.long_running_method" </shell> -h4. +destroy+ +h4. +rails destroy+ Think of +destroy+ as the opposite of +generate+. It'll figure out what generate did, and undo it. Believe you-me, the creation of this tutorial used this command many times! @@ -316,7 +330,7 @@ $ rails destroy model Oops notempty app </shell> -h4. +about+ +h4. +rake about+ Check it: Version numbers for Ruby, RubyGems, Rails, the Rails subcomponents, your application's folder, the current Rails environment name, your app's database adapter, and schema version! +about+ is useful when you need to ask for help, check if a security patch might affect you, or when you need some stats for an existing Rails installation. @@ -339,7 +353,7 @@ Environment development h3. The Rails Advanced Command Line -The more advanced uses of the command line are focused around finding useful (even surprising at times) options in the utilities, and fitting utilities to your needs and specific work flow. Listed here are some tricks up Rails' sleeve. +More advanced use of the command line is focused around finding useful (even surprising at times) options in the utilities, and fitting those to your needs and specific work flow. Listed here are some tricks up Rails' sleeve. h4. Rails with Databases and SCM @@ -364,8 +378,8 @@ $ rails new . --git --database=postgresql add 'Rakefile' create README add 'README' - create app/controllers/application_controller_.rb -add 'app/controllers/application_controller_.rb' + create app/controllers/application_controller.rb +add 'app/controllers/application_controller.rb' create app/helpers/application_helper.rb ... create log/test.log @@ -437,7 +451,7 @@ The Rails generator by default looks in these places for available generators, w * Inside any plugin with a directory like "generators" or "rails_generators" * ~/.rails/generators * Inside any Gem you have installed with a name ending in "_generator" -* Inside *any* Gem installed with a "rails_generators" path, and a file ending in "_generator.rb" +* Inside any Gem installed with a "rails_generators" path, and a file ending in "_generator.rb" * Finally, the builtin Rails generators (controller, model, mailer, etc.) Let's try the fourth option (in our home directory), which will be easy to clean up later: @@ -472,7 +486,7 @@ We take whatever args are supplied, save them to an instance variable, and liter * Check there's a *public* directory. You bet there is. * Run the ERb template called "tutorial.erb". * Save it into "Rails.root/public/tutorial.txt". -* Pass in the arguments we saved through the +:assign+ parameter. +* Pass in the arguments we saved through the +:assigns+ parameter. Next we'll build the template: @@ -525,7 +539,7 @@ Rake is a standalone Ruby utility that replaces the Unix utility 'make', and use You can get a list of Rake tasks available to you, which will often depend on your current directory, by typing +rake --tasks+. Each task has a description, and should help you find the thing you need. <shell> - rake --tasks +$ rake --tasks (in /home/foobar/commandsapp) rake db:abort_if_pending_migrations # Raises an error if there are pending migrations rake db:charset # Retrieves the charset for the current environment's database @@ -538,8 +552,6 @@ rake tmp:sessions:clear # Clears all files in tmp/sessions rake tmp:sockets:clear # Clears all files in tmp/sockets </shell> -Let's take a look at some of these 80 or so rake tasks. - h5. +db:+ Database The most common tasks of the +db:+ Rake namespace are +migrate+ and +create+, and it will pay off to try out all of the migration rake tasks (+up+, +down+, +redo+, +reset+). +rake db:version+ is useful when troubleshooting, telling you the current version of the database. @@ -548,29 +560,15 @@ h5. +doc:+ Documentation If you want to strip out or rebuild any of the Rails documentation (including this guide!), the +doc:+ namespace has the tools. Stripping documentation is mainly useful for slimming your codebase, like if you're writing a Rails application for an embedded platform. -h5. +gems:+ Ruby gems - -You can specify which gems your application uses, and +rake gems:install+ will install them for you. Look at your environment.rb to learn how with the *config.gem* directive. - -NOTE: +gems:unpack+ will unpack, that is internalize your application's Gem dependencies by copying the Gem code into your vendor/gems directory. By doing this you increase your codebase size, but simplify installation on new hosts by eliminating the need to run +rake gems:install+, or finding and installing the gems your application uses. - h5. +notes:+ Code note enumeration These tasks will search through your code for commented lines beginning with "FIXME", "OPTIMIZE", "TODO", or any custom annotation (like XXX) and show you them. -h5. +rails:+ Rails-specific tasks - -In addition to the +gems:unpack+ task above, you can also unpack the Rails backend specific gems into vendor/rails by calling +rake rails:freeze:gems+, to unpack the version of Rails you are currently using, or +rake rails:freeze:edge+ to unpack the most recent (cutting, bleeding edge) version. - -When you have frozen the Rails gems, Rails will prefer to use the code in vendor/rails instead of the system Rails gems. You can "thaw" by running +rake rails:unfreeze+. - -After upgrading Rails, it is useful to run +rails:update+, which will update your config and scripts directories, and upgrade your Rails-specific javascript (like Scriptaculous). - h5. +test:+ Rails tests INFO: A good description of unit testing in Rails is given in "A Guide to Testing Rails Applications":testing.html -Rails comes with a test suite called Test::Unit. It is through the use of tests that Rails itself is so stable, and the slew of people working on Rails can prove that everything works as it should. +Rails comes with a test suite called Test::Unit. It is through the use of tests that Rails itself is so stable, and the slew of people working on Rails can prove that everything works as it should. The +test:+ namespace helps in running the different tests you will (hopefully!) write. @@ -580,16 +578,13 @@ You can list all the timezones Rails knows about with +rake time:zones:all+, whi h5. +tmp:+ Temporary files -The tmp directory is, like in the *nix /tmp directory, the holding place for temporary files like sessions (if you're using a file store for files), process id files, and cached actions. The +tmp:+ namespace tasks will help you clear them if you need to if they've become overgrown, or create them in case of an +rm -rf *+ gone awry. +The tmp directory is, like in the *nix /tmp directory, the holding place for temporary files like sessions (if you're using a file store for files), process id files, and cached actions. The +tmp:+ namespace tasks will help you clear them if you need to if they've become overgrown, or create them in case of deletions gone awry. h5. Miscellaneous Tasks +rake stats+ is great for looking at statistics on your code, displaying things like KLOCs (thousands of lines of code) and your code to test ratio. - +rake secret+ will give you a psuedo-random key to use for your session secret. + +rake secret+ will give you a pseudo-random key to use for your session secret. +rake routes+ will list all of your defined routes, which is useful for tracking down routing problems in your app, or giving you a good overview of the URLs in an app you're trying to get familiar with. -h3. Changelog - -"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213/tickets/29 diff --git a/railties/guides/source/configuring.textile b/railties/guides/source/configuring.textile index 9e0c7cd060..62b846e871 100644 --- a/railties/guides/source/configuring.textile +++ b/railties/guides/source/configuring.textile @@ -13,7 +13,7 @@ Rails offers (at least) four good spots to place initialization code: * application.rb * Environment-specific Configuration Files -* Initializers (load_application_initializers) +* Initializers * After-Initializers h3. Running Code Before Rails @@ -23,65 +23,178 @@ To run some code before Rails itself is loaded, simply put it above the call to h3. Configuring Rails Components -In general, the work of configuring Rails means configuring the components of Rails, as well as configuring Rails itself. The +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. For example, the default Rails 2.3 +application.rb+ file includes one setting: +In general, the work of configuring Rails means configuring the components of Rails, as well as configuring Rails itself. The +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. For example, the default Rails 3.0 +application.rb+ file includes this setting: <ruby> -config.filter_parameters << :password + config.filter_parameters += [:password] </ruby> 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: <ruby> -config.active_record.colorize_logging = false + config.active_record.timestamped_migrations = false </ruby> Rails will use that particular setting to configure Active Record. h4. Rails General Configuration -* +config.routes_configuration_file+ overrides the default path for the routes configuration file. This defaults to +config/routes.rb+. +* +config.after_initialize+ takes a block which will be ran _after_ Rails has finished initializing. Useful for configuring values set up by other initializers: -* +config.cache_classes+ controls whether or not application classes should be reloaded on each request. +<ruby> +config.after_initialize do + ActionView::Base.sanitized_allowed_tags.delete 'div' +end +</ruby> + +* +config.allow_concurrency+ should be set to +true+ to allow concurrent (threadsafe) action processing. Set to +false+ by default. You probably don't want to call this one directly, though, because a series of other adjustments need to be made for threadsafe mode to work properly. Can also be enabled with +threadsafe!+. + +* +config.asset_host+ sets the host for the assets. Useful when CDNs are used for hosting assets rather than the application server itself. Shorter version of +config.action_controller.asset_host+. -* +config.cache_store+ configures which cache store to use for Rails caching. Options include +:memory_store+, +:file_store+, +:mem_cache_store+ or the name of your own custom class. +* +config.asset_path+ takes a block which configures where assets can be found. Shorter version of +config.action_controller.asset_path+. -* +config.controller_paths+ accepts an array of paths that will be searched for controllers. Defaults to +app/controllers+. +<ruby> + config.asset_path = proc { |asset_path| "assets/#{asset_path}" } +</ruby> -* +config.database_configuration_file+ overrides the default path for the database configuration file. Default to +config/database.yml+. +* +config.autoload_once_paths+ accepts an array of paths from which Rails will automatically load from only once. All elements of this array must also be in +autoload_paths+. -* +config.dependency_loading+ enables or disables dependency loading during the request cycle. Setting dependency_loading to _true_ will allow new classes to be loaded during a request and setting it to _false_ will disable this behavior. +* +config.autoload_paths+ accepts an array of additional paths to prepend to the load path. By default, all app, lib, vendor and mock paths are included in this list. -* +config.eager_load_paths+ accepts an array of paths from which Rails will eager load on boot if cache classes is enabled. All elements of this array must also be in +load_paths+. +* +config.cache_classes+ controls whether or not application classes should be reloaded on each request. Defaults to _true_ in development, _false_ in test and production. Can also be enabled with +threadsafe!+. -* +config.load_once_paths+ accepts an array of paths from which Rails will automatically load from only once. All elements of this array must also be in +load_paths+. +* +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.load_paths+ accepts an array of additional paths to prepend to the load path. By default, all app, lib, vendor and mock paths are included in this list. +* +config.cache_store+ configures which cache store to use for Rails caching. Options include +:memory_store+, +:file_store+, +:mem_cache_store+ or the name of your own custom class. Defaults to +:file_store+. -* +config.log_level+ defines the verbosity of the Rails logger. In production mode, this defaults to +:info+. In development mode, it defaults to +:debug+. +* +config.colorize_logging+ specifies whether or not to use ANSI color codes when logging information. Defaults to _true_. -* +config.log_path+ overrides the path to the log file to use. Defaults to +log/#{environment}.log+ (e.g. log/development.log or log/production.log). +* +config.consider_all_requests_local+ is generally set to +true+ during development and +false+ during production; if it is set to +true+, then any error will cause detailed debugging information to be dumped in the HTTP response. For finer-grained control, set this to +false+ and implement +local_request?+ in controllers to specify which requests should provide debugging information on errors. -* +config.logger+ accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, which is then used to log information from Action Controller. Set to nil to disable logging. +* +config.controller_paths+ configures where Rails can find controllers for this application. + +* +config.dependency_loading+ enables or disables dependency loading during the request cycle. Setting dependency_loading to _true_ will allow new classes to be loaded during a request and setting it to _false_ will disable this behavior. Can also be enabled with +threadsafe!+. + +* +config.eager_load_paths+ accepts an array of paths from which Rails will eager load on boot if cache classes is enabled. Defaults to every folder in the +app+ directory of the application. All elements of this array must also be in +load_paths+. + +* +config.encoding+ sets up the application-wide encoding. Defaults to UTF-8. -* +config.plugin_loader+ overrides the class that handles loading each plugin. Defaults to +Rails::Plugin::Loader+. +* +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.plugin_locators+ overrides the class that handle finding the desired plugins that you‘d like to load for your application. By default it is the +Rails::Plugin::FileSystemLocator+. +* +config.helper_paths+ configures where Rails can find helpers for this application. -* +config.plugin_paths+ overrides the path to the root of the plugins directory. Defaults to +vendor/plugins+. +* +config.log_level+ defines the verbosity of the Rails logger. In production mode, this defaults to +:info+. In development mode, it defaults to +:debug+. + +* +config.log_path+ overrides the path to the log file to use. Defaults to +log/#{environment}.log+ (e.g. log/development.log or log/production.log). + +* +config.logger+ accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, which is then used to log information from Action Controller. Set to nil to disable logging. + +* +config.middleware+ allows you to configure the application's middleware. This is covered in depth in the "Configuring Middleware" section below. * +config.plugins+ accepts the list of plugins to load. If this is set to nil, all plugins will be loaded. If this is set to [], no plugins will be loaded. Otherwise, plugins will be loaded in the order specified. -* +config.preload_frameworks+ enables or disables preloading all frameworks at startup. +* +config.preload_frameworks+ enables or disables preloading all frameworks at startup. Can also be enabled with +threadsafe!+. Defaults to +nil+, so is disabled. + +* +config.reload_plugins+ enables or disables plugin reloading. + +* +config.root+ configures the root path of the application. -* +config.reload_plugins+ enables or disables plugin reloading. +* +config.secret_token+ used for specifying a key which allows sessions for the application to be verified against a known secure key to prevent tampering. + +* +config.serve_static_assets+ configures Rails to serve static assets. Defaults to _true_, but in the production environment is turned off. The server software used to run the application should be used to serve the assets instead. + +* +config.session_store+ is usually set up in +config/initializers/session_store.rb+ and specifies what class to use to store the session. Custom session stores can be specified like so: + +<ruby> + config.session_store = :my_custom_store +</ruby> -* +config.root_path+ configures the root path of the application. +This custom store must be defined as +ActionDispatch::Session::MyCustomStore+. + +* +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.view_path+ sets the path of the root of an application's views. Defaults to +app/views+. +* +config.whiny_nils+ enables or disables warnings when any methods of nil are invoked. Defaults to _true_ in development and test environments. + +h4. Configuring Generators + +Rails 3 allows you to alter what generators are used with the +config.generators+ method. This method takes a block: + +<ruby> + config.generators do |g| + g.orm :active_record + g.test_framework :test_unit + end +</ruby> + +The full set of methods that can be used in this block are as follows: + +* +force_plural+ allows pluralized model names. Defaults to _false_. +* +helper+ defines whether or not to generate helpers. Defaults to _true_. +* +orm+ defines which orm to use. Defaults to _nil_, so will use Active Record by default. +* +integration_tool+ defines which integration tool to use. Defaults to _nil_. +* +performance_tool+ defines which performance tool to use. Defaults to _nil_. +* +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. +* +test_framework+ defines which test framework to use. Defaults to _nil_, so will use Test::Unit by default. +* +template_engine+ defines which template engine to use, such as ERB or Haml. Defaults to +:erb+. + +h4. Configuring Middleware + +Every Rails application comes with a standard set of middleware which it uses in this order in the development environment: + +* +ActionDispatch::Static+ is used to serve static assets. Disabled if +config.serve_static_assets+ is _true_. +* +Rack::Lock+ Will wrap 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+ Will notify the logs that the request has began. After request is complete, flushes all the logs. +* +ActionDispatch::ShowExceptions+ rescues any exception returned by the application and renders nice exception pages if the request is local or if +config.consider_all_requests_local+ is set to _true_. If +config.action_dispatch.show_exceptions+ is set to _false_, exceptions will be raised regardless. +* +ActionDispatch::RemoteIp+ checks for IP spoofing attacks. Configurable with the +config.action_dispatch.ip_spoofing_check+ and +config.action_dispatch.trusted_proxies+ settings. +* +Rack::Sendfile+ The Sendfile middleware intercepts responses whose body is being served from a file and replaces it with a server specific X-Sendfile header. Configurable with +config.action_dispatch.x_sendfile_header+ +* +ActionDispatch::Callbacks+ Runs the prepare callbacks before serving the request. +* +ActiveRecord::ConnectionAdapters::ConnectionManagement+ cleans active connections after each request, unless the +rack.test+ key in the request environment is set to _true_. +* +ActiveRecord::QueryCache+ caches all +SELECT+ queries generated in a request. If an +INSERT+ or +UPDATE+ takes place then the cache is cleaned. +* +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 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: + +<ruby> + config.middleware.use Magical::Unicorns +</ruby> + +This will put the +Magical::Unicorns+ middleware on the end of the stack. If you wish to put this middleware before another use +insert_before+: + +<ruby> + config.middleware.insert_before ActionDispatch::Head, Magical::Unicorns +</ruby> + +There's also +insert_after+ which will insert a middleware _after_ another: + +<ruby> + config.middleware.insert_after ActionDispatch::Head, Magical::Unicorns +</ruby> + +Middlewares can also be completely swapped out and replaced with others: + +<ruby> + config.middleware.swap ActionDispatch::BestStandardsSupport, Magical::Unicorns +</ruby> + +They can also be removed from the stack completely: -* +config.whiny_nils+ enables or disabled warnings when an methods of nil are invoked. Defaults to _false_. +<ruby> + config.middleware.delete ActionDispatch::BestStandardsSupport +</ruby> h4. Configuring i18n @@ -105,9 +218,7 @@ h4. Configuring Active Record * +config.active_record.pluralize_table_names+ specifies whether Rails will look for singular or plural table names in the database. If set to +true+ (the default), then the Customer class will use the +customers+ table. If set to +false+, then the Customers class will use the +customer+ table. -* +config.active_record.colorize_logging+ (true by default) specifies whether or not to use ANSI color codes when logging information from ActiveRecord. - -* +config.active_record.default_timezone+ determines whether to use +Time.local+ (if set to +:local+) or +Time.utc+ (if set to +:utc+) when pulling dates and times from the database. The default is +:local+. +* +config.active_record.default_timezone+ determines whether to use +Time.local+ (if set to +:local+) or +Time.utc+ (if set to +:utc+) when pulling dates and times from the database. The default is +:utc+ for Rails, although ActiveRecord defaults to +:local+ when used outside of Rails. * +config.active_record.schema_format+ controls the format for dumping the database schema to a file. The options are +:ruby+ (the default) for a database-independent version that depends on migrations, or +:sql+ for a set of (potentially database-dependent) SQL statements. @@ -127,41 +238,29 @@ h4. Configuring Action Controller <tt>config.action_controller</tt> includes a number of configuration settings: -* +config.action_controller.asset_host+ provides a string that is prepended to all of the URL-generating helpers in +AssetHelper+. This is designed to allow moving all javascript, CSS, and image files to a separate asset host. +* +config.action_controller.asset_host+ sets the host for the assets. Useful when CDNs are used for hosting assets rather than the application server itself. -* +config.action_controller.asset_path+ allows you to override the default asset path generation by providing your own instructions. +* +config.action_controller.asset_path+ takes a block which configures where assets can be found. Shorter version of +config.action_controller.asset_path+. -* +config.action_controller.consider_all_requests_local+ is generally set to +true+ during development and +false+ during production; if it is set to +true+, then any error will cause detailed debugging information to be dumped in the HTTP response. For finer-grained control, set this to +false+ and implement +local_request?+ to specify which requests should provide debugging information on errors. +* +config.action_controller.page_cache_directory+ should be the document root for the web server and is set using <tt>Base.page_cache_directory = "/document/root"</tt>. For Rails, this directory has already been set to +Rails.public_path+ (which is usually set to <tt>Rails.root + "/public"</tt>). Changing this setting can be useful to avoid naming conflicts with files in <tt>public/</tt>, but doing so will likely require configuring your web server to look in the new location for cached files. -* +config.action_controller.allow_concurrency+ should be set to +true+ to allow concurrent (threadsafe) action processing. Set to +false+ by default. You probably don't want to call this one directly, though, because a series of other adjustments need to be made for threadsafe mode to work properly. Instead, you should simply call +config.threadsafe!+ inside your +production.rb+ file, which makes all the necessary adjustments. +* +config.action_controller.page_cache_extension+ configures the extension used for cached pages saved to +page_cache_directory+. Defaults to +.html+ -WARNING: Threadsafe operation is incompatible with the normal workings of development mode Rails. In particular, automatic dependency loading and class reloading are automatically disabled when you call +config.threadsafe!+. - -* +config.action_controller.param_parsers+ provides an array of handlers that can extract information from incoming HTTP requests and add it to the +params+ hash. By default, parsers for multipart forms, URL-encoded forms, XML, and JSON are active. +* +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 1.8+ Logger class, which is then used to log information from Action Controller. Set to nil to disable logging. -* +config.action_controller.resource_action_separator+ gives the token to be used between resources and actions when building or interpreting RESTful URLs. By default, this is "/". - -* +config.action_controller.resource_path_names+ is a hash of default names for several RESTful actions. By default, the new action is named +new+ and the edit action is named +edit+. - * +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.optimise_named_routes+ turns on some optimizations in generating the routing table. It is set to +true+ by default. - -* +config.action_controller.use_accept_header+ sets the rules for determining the response format. If this is set to +true+ (the default) then +respond_to+ and +Request#format+ will take the Accept header into account. If it is set to false then the request format will be determined solely by examining +params[:format]+. If there is no +format+ parameter, then the response format will be either HTML or Javascript depending on whether the request is an AJAX request. - * +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']+. -* +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. - The caching code adds two additional settings: -* +ActionController::Base.page_cache_directory+ sets the directory where Rails will create cached pages for your web server. The default is +Rails.public_path+ (which is usually set to +Rails.root + "/public"+). +* +ActionController::Base.page_cache_directory+ sets the directory where Rails will create cached pages for your web server. The default is +Rails.public_path+ (which is usually set to <tt>Rails.root + "/public"</tt>). * +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+. @@ -173,13 +272,23 @@ The Active Record session store can also be configured: * +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 four on +ActionView::Base+: -* +config.action_view.debug_rjs+ specifies whether RJS responses should be wrapped in a try/catch block that alert()s the caught exception (and then re-raises it). The default is +false+. - -* +config.action_view.warn_cache_misses+ tells Rails to display a warning whenever an action results in a cache miss on your view paths. The default is +false+. +* +config.action_view.debug_rjs+ specifies whether RJS responses should be wrapped in a try/catch block that alerts the caught exception (and then re-raises it). The default is +false+. * +config.action_view.field_error_proc+ provides an HTML generator for displaying errors that come from Active Record. The default is <tt>Proc.new{ |html_tag, instance| %Q(%<div class="field_with_errors">#{html_tag}</div>).html_safe }</tt> @@ -189,12 +298,36 @@ There are only a few configuration options for Action View, starting with four o * +config.action_view.erb_trim_mode+ gives the trim mode to be used by ERB. It defaults to +'-'+. See the "ERB documentation":http://www.ruby-doc.org/stdlib/libdoc/erb/rdoc/ for more information. +* +config.action_view.javascript_expansions+ is a hash containing expansions that can be used for the JavaScript include tag. By default, this is defined as: + +<ruby> + config.action_view.javascript_expansions = { :defaults => ['prototype', 'effects', 'dragdrop', 'controls', 'rails'] } +</ruby> + +However, you may add to this by defining others: + +<ruby> + config.action_view.javascript_expansions[:jquery] = ["jquery", "jquery-ui"] +</ruby> + +And can reference in the view with the following code: + +<ruby> + <%= javascript_include_tag :jquery %> +</ruby> + +* +config.action_view.stylesheet_expansions+ works in much the same way as +javascript_expansions+, but has no default key. Keys defined for this hash can be referenced in the view like such: + +<ruby> + <%= stylesheet_link_tag :special %> +</ruby> + +* +ActionView::Helpers::AssetTagHelper::AssetPaths.cache_asset_ids+ With the cache enabled, the asset tag helper methods will make fewer expensive file system calls (the default implementation checks the file system timestamp). However this prevents you from modifying any asset files while the server is running. + h4. Configuring Action Mailer There are a number of settings available on +config.action_mailer+: -* +config.action_mailer.template_root+ gives the root folder for Action Mailer templates. - * +config.action_mailer.logger+ accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, which is then used to log information from Action 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: @@ -215,15 +348,13 @@ There are a number of settings available on +config.action_mailer+: * +config.action_mailer.perform_deliveries+ specifies whether mail will actually be delivered. By default this is +true+; it can be convenient to set it to +false+ for testing. -* +config.action_mailer.default_charset+ tells Action Mailer which character set to use for the body and for encoding the subject. It defaults to +utf-8+. - -* +config.action_mailer.default_content_type+ specifies the default content type used for the main part of the message. It defaults to "text/plain" - -* +config.action_mailer.default_mime_version+ is the default MIME version for the message. It defaults to +1.0+. - -* +config.action_mailer.default_implicit_parts_order+ - When a message is built implicitly (i.e. multiple parts are assembled from templates -which specify the content type in their filenames) this variable controls how the parts are ordered. Defaults to +["text/html", "text/enriched", "text/plain"]+. Items that appear first in the array have higher priority in the mail client -and appear last in the mime encoded message. +* +config.action_mailer.default+ configures Action Mailer defaults. These default to: +<ruby> + :mime_version => "1.0", + :charset => "UTF-8", + :content_type => "text/plain", + :parts_order => [ "text/plain", "text/enriched", "text/html" ] +</ruby> h4. Configuring Active Resource @@ -235,6 +366,8 @@ h4. Configuring Active Support There are a few configuration options available in Active Support: +* +config.active_support.bare+ enables or disables the loading of +active_support/all+ when booting Rails. Defaults to +nil+, which means +active_support/all+ is loaded. + * +config.active_support.escape_html_entities_in_json+ enables or disables the escaping of HTML entities in JSON serialization. Defaults to +true+. * +config.active_support.use_standard_json_time_format+ enables or disables serializing dates to ISO 8601 format. Defaults to +false+. @@ -243,46 +376,196 @@ There are a few configuration options available in Active Support: * +ActiveSupport::Cache::Store.logger+ specifies the logger to use within cache store operations. +* +ActiveSupport::Deprecation.behavior+ alternative setter to +config.active_support.deprecation+ which configures the behavior of deprecation warnings for Rails. + +* +ActiveSupport::Deprecation.silence+ takes a block in which all deprecation warnings are silenced. + +* +ActiveSupport::Deprecation.silenced+ sets whether or not to display deprecation warnings. + * +ActiveSupport::Logger.silencer+ is set to +false+ to disable the ability to silence logging in a block. The default is +true+. -h3. Using Initializers -After loading the framework and any gems and plugins in your application, Rails turns to loading initializers. An initializer is any file of Ruby code stored under +config/initializers+ in your application. You can use initializers to hold configuration settings that should be made after all of the frameworks and plugins are loaded. +h3. Rails Environment Settings -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. +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 and plugins in your application, Rails turns to loading initializers. An initializer is any file of Ruby code stored under +config/initializers+ in your application. You can use initializers to hold configuration settings that should be made after all of the frameworks, plugins and gems are loaded, such as options to configure settings for these parts. + +NOTE: You can use subfolders to organize your initializers if you like, because Rails will look into the whole file hierarchy from the initializers folder on down. TIP: If you have any ordering dependency in your initializers, you can control the load order by naming. For example, +01_critical.rb+ will be loaded before +02_normal.rb+. -h3. Using an After-Initializer +h3. Initialization events + +Rails has 5 initialization events which can be hooked into (listed in order that they are ran): + +* +before_configuration+: This is run as soon as the application constant inherits from +Rails::Application+. The +config+ calls are evaluated before this happens. + +* +before_initialize+: This is run directly before the initialization process of the application occurs with the +:bootstrap_hook+ initializer near the beginning of the Rails initialization process. + +* +to_prepare+: Run after the initializers are ran for all Railties (including the application itself), but before eager loading and the middleware stack is built. + +* +before_eager_load+: This is run directly before eager loading occurs, which is the default behaviour for the _production_ environment and not for the +development+ enviroment. + +* +after_initialize+: Run directly after the initialization of the application, but before the application initializers are run. -After-initializers are run (as you might guess) after any initializers are loaded. You can supply an +after_initialize+ block (or an array of such blocks) by setting up +config.after_initialize+ in any of the Rails configuration files: + +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: <ruby> -config.after_initialize do - SomeClass.init +initializer "active_support.initialize_whiny_nils" do |app| + require 'active_support/whiny_nil' if app.config.whiny_nils end </ruby> -WARNING: Some parts of your application, notably observers and routing, are not yet set up at the point where the +after_initialize+ block is called. +The +initializer+ method takes three arguments with the first being the name for the initializer and the second being an options hash (not shown here) and the third being a block. The +:before+ key in the options hash can be specified to specify which initializer this new initializer must run before, and the +:after+ key will specify which initializer to run this initializer _after_. -h3. Rails Environment Settings +Initializers defined using the +initializer+ method will be ran in the order they are defined in, with the exception of ones that use the +:before+ or +:after+ methods. -Some parts of Rails can also be configured externally by supplying environment variables. The following environment variables are recognized by various parts of Rails: +WARNING: You may put your initializer before or after any other initializer in the chain, as long as it is logical. Say you have 4 initializers called "one" through "four" (defined in that order) and you define "four" to go _before_ "four" but _after_ "three", that just isn't logical and Rails will not be able to determine your initializer order. -* +ENV['RAILS_ENV']+ defines the Rails environment (production, development, test, and so on) that Rails will run under. +The block's argument of the +initialize+ is the instance of the application itself, and so we can access the configuration on it by using the +config+ method as this initializer does. -* +ENV['RAILS_RELATIVE_URL_ROOT']+ is used by the routing code to recognize URLs when you deploy your application to a subdirectory. +Because +Rails::Application+ inherits from +Rails::Railtie+ (indirectly), you can use the +initializer+ method in +config/application.rb+ to define initializers for the application. -* +ENV["RAILS_ASSET_ID"]+ will override the default cache-busting timestamps that Rails generates for downloadable assets. +h4. Initializers -* +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. +Below is a comprehensive list of all the initializers found in Rails in the order that they are defined (and therefore run in, unless otherwise stated). -* +ENV['RAILS_GEM_VERSION']+ defines the version of the Rails gems to use, if +RAILS_GEM_VERSION+ is not defined in your +environment.rb+ file. +*+load_environment_hook+* +Serves as a placeholder so that +:load_environment_config+ can be defined to run before it. -h3. Changelog +*+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+* Will load all autoload dependencies of Rails automatically if +config.preload_frameworks+ is +true+ or "truthful". By default this configuration option is disabled. In Rails, when internal classes are referenced for the first time they are autoloaded. +:preload_frameworks+ loads all of this at once on initialization. + +*+initialize_logger+* Initializes the logger (an +ActiveSupport::BufferedLogger+ object) for the application and makes it accessible at +Rails.logger+, providing that there's no initializer inserted before this point that has defined +Rails.logger+. + +*+initialize_cache+* If +RAILS_CACHE+ isn't yet set, initializes the cache by referencing the value in +config.cache_store+ and stores the outcome as +RAILS_CACHE+. If this object responds to the +middleware+ method, its middleware is inserted before +Rack::Runtime+ in the middleware stack. + +*+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 set to +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+* Will require +active_support/whiny_nil+ if +config.whiny_nils+ is set to +true+. This file will output errors such as: + +<plain> + Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id +</plain> + +And: + +<plain> +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 +</plain> -"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/28 +*+active_support.deprecation_behavior+* Sets up deprecation reporting for environments, defaulting to +:log+ for development, +:notify+ for production and +:stderr+ for test. If a value isn't set for +config.active_support.deprecation+ then this initializer will prompt the user to configure this line in the current environment's +config/environments+ file. Can be set to an array of values. + +*+active_support.initialize_time_zone+* Sets the default time zone for the application based off the +config.time_zone+ setting, which defaults to "UTC". + +*+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+* Will set +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 recognised 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 length of time Active Record calls took for the request back to the logger. + +*+active_record.set_dispatch_hooks+* If +config.cache_classes+ is set to false, all reloadable connections to the database will be reset. + +*+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. + +*+active_resource.set_configs+* Sets up Active Resource by using the settings in +config.active_resource+ by +send+'ing the method names as setters to +ActiveResource::Base+ and passing the values through. + +*+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_path+* This initializer runs before +bootstrap_hook+. Adds all sub-directories of +app+ and paths specified by +config.autoload_paths+ to +ActiveSupport::Dependencies.autoload_paths+. + +*+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 and plugins are loaded. + +NOTE: You can use subfolders to organize your initializers if you like, because Rails will look into the whole file hierarchy from the +initializers+ folder on down. + +TIP: If you have any ordering dependency in your initializers, you can control the load order by naming. For example, +01_critical.rb+ will be loaded before +02_normal.rb+. + +*+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. Changelog +* December 3, 2010: Added initialization events for Rails 3 ("Ryan Bigg":http://ryanbigg.com) +* November 26, 2010: Removed all config settings not available in Rails 3 ("Ryan Bigg":http://ryanbigg.com) * August 13, 2009: Updated with config syntax and added general configuration options by "John Pignata" * January 3, 2009: First reasonably complete draft by "Mike Gunderloy":credits.html#mgunderloy * November 5, 2008: Rough outline by "Mike Gunderloy":credits.html#mgunderloy diff --git a/railties/guides/source/contribute.textile b/railties/guides/source/contribute.textile index 88c5c79e9d..4bd527d4c7 100644 --- a/railties/guides/source/contribute.textile +++ b/railties/guides/source/contribute.textile @@ -1,20 +1,20 @@ h2. Contribute to the Rails Guides -Rails Guides aim to improve the Rails documentation and to make the barrier to entry as low as possible. A reasonably experienced developer should be able to use the Guides to come up to speed on Rails quickly. You can track the overall effort at the "Rails Guides Lighthouse":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets. Our sponsors have contributed prizes for those who write an entire guide, but there are many other ways to contribute. +Rails Guides aim to improve the Rails documentation and to make the barrier to entry as low as possible. A reasonably experienced developer should be able to use the guides to come up to speed on Rails quickly. Our sponsors have contributed prizes for those who write an entire guide, but there are many other ways to contribute. endprologue. h3. How to Contribute? * We have an open commit policy: anyone is welcome to contribute and to review contributions. -* "docrails is hosted on GitHub":http://github.com/lifo/docrails and has public write access. +* "docrails is hosted on GitHub":https://github.com/lifo/docrails and has public write access. * Guides are written in Textile, and reside at +railties/guides/source+ in the docrails project. -* Follow the "Rails Guides Conventions":http://wiki.github.com/lifo/docrails/rails-guides-conventions. +* Follow the "Rails Guides Conventions":https://wiki.github.com/lifo/docrails/rails-guides-conventions. * Assets are stored in the +railties/guides/assets+ directory. -* Sample format : "Active Record Associations":http://github.com/lifo/docrails/blob/3e56a3832415476fdd1cb963980d0ae390ac1ed3/railties/guides/source/association_basics.textile. +* Sample format : "Active Record Associations":https://github.com/lifo/docrails/blob/3e56a3832415476fdd1cb963980d0ae390ac1ed3/railties/guides/source/association_basics.textile. * Sample output : "Active Record Associations":association_basics.html. -* You can build the Guides during testing by running +rake generate_guides+ in the +railties+ directory. -* You're encouraged to validate XHTML for the generated guides before commiting your changes by running +rake validate_guides+ in the +railties+ directory. +* You can build the Guides during testing by running +bundle exec rake generate_guides+ in the +railties+ directory. +* You're encouraged to validate XHTML for the generated guides before commiting your changes by running +bundle exec rake validate_guides+ in the +railties+ directory. * Edge guides "can be consulted online":http://edgeguides.rubyonrails.org/. That website is generated periodically from docrails. h3. What to Contribute? @@ -53,11 +53,11 @@ h3. Rules * If the same guide writer wants to write multiple guides, that's ideally the situation we'd love to be in! However, that guide writer will only receive the cash prize for all the subsequent guides (and not the GitHub or RPM prizes). * Our review team will have the final say on whether the guide is complete and of good enough quality. -All authors should read and follow the "Rails Guides Conventions":http://wiki.github.com/lifo/docrails/rails-guides-conventions and the "Rails API Documentation Conventions":http://wiki.github.com/lifo/docrails/rails-api-documentation-conventions. +All authors should read and follow the "Rails Guides Conventions":https://wiki.github.com/lifo/docrails/rails-guides-conventions and the "Rails API Documentation Conventions":https://wiki.github.com/lifo/docrails/rails-api-documentation-conventions. h3. Translations -The translation effort for the Rails Guides is just getting underway. We know about projects to translate the Guides into Spanish, Portuguese, Polish, and French. For more details or to get involved see the "Translating Rails Guides":http://wiki.github.com/lifo/docrails/translating-rails-guides page. +The translation effort for the Rails Guides is just getting underway. We know about projects to translate the Guides into Spanish, Portuguese, Polish, and French. For more details or to get involved see the "Translating Rails Guides":https://wiki.github.com/lifo/docrails/translating-rails-guides page. h3. Mailing List diff --git a/railties/guides/source/contributing_to_rails.textile b/railties/guides/source/contributing_to_rails.textile deleted file mode 100644 index fb81bab98d..0000000000 --- a/railties/guides/source/contributing_to_rails.textile +++ /dev/null @@ -1,308 +0,0 @@ -h2. Contributing to Rails - -This guide covers ways in which _you_ can become a part of the ongoing development of Rails. After reading it, you should be familiar with: - -* Using Lighthouse to report issues with Rails -* Cloning edge Rails and running the test suite -* Helping to resolve existing issues -* Contributing to the Rails documentation -* Contributing to the Rails code - -Rails is not "someone else's framework." Over the years, hundreds of people have contributed code ranging from a single character to massive architectural changes, all with the goal of making Rails better for everyone. Even if you don't feel up to writing code yet, there are a variety of other ways that you can contribute, from reporting issues to testing patches to contributing documentation. - -endprologue. - -h3. Reporting a Rails Issue - -Rails uses a "Lighthouse project":http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/ to track issues (primarily bugs and contributions of new code). If you've found a bug in Rails, this is the place to start. You'll need to create a (free) Lighthouse account in order to comment on issues or to upload tests or patches. - -NOTE: Bugs in the most recent released version of Rails are likely to get the most attention. Also, the Rails core team is always interested in feedback from those who can take the time to test _edge Rails_ (the code for the version of Rails that is currently under development). Later in this Guide you'll find out how to get edge Rails for testing. - -h4. Creating a Bug Report - -If you've found a problem in Rails, you can start by "adding a new ticket":http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/new to the Rails Lighthouse. At the minimum, your ticket needs a title and descriptive text. But that's only a minimum. You should include as much relevant information as possible. You need to at least post the code sample that has the issue. Even better is to include a unit test that shows how the expected behavior is not occurring. Your goal should be to make it easy for yourself - and others - to replicate the bug and figure out a fix. - -You shouldn't assign the bug to a particular core developer (through the *Who's Responsible* select list) unless you know for sure which developer will be handling any patch. The core team periodically reviews issues and assigns developers and milestones to them. - -You should set tags for your issue. Use the "bug" tag for a bug report, and add the "patch" tag if you are attaching a patch. Try to find some relevant tags from the existing tag list (which will appear as soon as you start typing in the *Choose some tags* textbox), rather than creating new tags. - -Then don't get your hopes up. Unless you have a "Code Red, Mission Critical, The World is Coming to an End" kind of bug, you're creating this ticket in the hope that others with the same problem will be able to collaborate with you on solving it. Do not expect that the ticket automatically will see any activity or that others will jump to fix it. Creating a ticket like this is mostly to help yourself start on the path of fixing the problem and for others to confirm it with a "I'm having this problem too" comment. - -h4. Special Treatment for Security Issues - -If you've found a security vulnerability in Rails, please do *not* report it via a Lighthouse ticket. Lighthouse tickets are public as soon as they are entered. Instead, you should use the dedicated email address "security@rubyonrails.org":mailto:security@rubyonrails.org to report any vulnerabilities. This alias is monitored and the core team will work with you to quickly and completely address any such vulnerabilities. - -WARNING: Just to emphasize the point, _please do not report security vulnerabilities on public Lighthouse tickets_. This will only expose your fellow Rails developers to needless risks. - -You should receive an acknowledgement and detailed response to any reported security issue within 48 hours. If you don't think you're getting adequate response from the security alias, refer to the "Rails security policy page":http://rubyonrails.org/security for direct emails for the current Rails security coordinators. - -h4. What About Feature Requests? - -Please don't put "feature request" tickets into Lighthouse. If there's a new feature that you want to see added to Rails, you'll need to write the code yourself - or convince someone else to partner with you to write the code. Later in this guide you'll find detailed instructions for proposing a patch to Rails. If you enter a wishlist item in Lighthouse with no code, you can expect it to be marked "invalid" as soon as it's reviewed. - -h3. Running the Rails Test Suite - -To move on from submitting bugs to helping resolve existing issues or contributing your own code to Rails, you _must_ be able to run the Rails test suite. In this section of the guide you'll learn how to set up the tests on your own computer. - -h4. Install git - -Rails uses git for source code control. You won’t be able to do anything without the Rails source code, and this is a prerequisite. The "git homepage":http://git-scm.com/ has installation instructions. If you’re on OS X, use the "Git for OS X":http://code.google.com/p/git-osx-installer/ installer. If you're unfamiliar with git, there are a variety of resources on the net that will help you learn more: - -* "Everyday Git":http://www.kernel.org/pub/software/scm/git/docs/everyday.html will teach you just enough about git to get by. -* The "PeepCode screencast":https://peepcode.com/products/git on git ($9) is easier to follow. -* "GitHub":http://github.com/guides/home offers links to a variety of git resources. -* "Pro Git":http://progit.org/book/ is an entire book about git with a Creative Commons license. - -h4. Get the Rails Source Code - -Don’t fork the main Rails repository. Instead, you want to clone it to your own computer. Navigate to the folder where you want the source code (it will create its own /rails subdirectory) and run: - -<shell> -git clone git://github.com/rails/rails.git -cd rails -</shell> - -h4. Set up and Run the Tests - -All of the Rails tests must pass with any code you submit, otherwise you have no chance of getting code accepted. This means you need to be able to run the tests. First, you need to install all Rails dependencies with bundler: - -NOTE: Ensure you install bundler v1.0 - -<shell> -gem install -v=1.0.0.rc.2 bundler -bundle install --without db -</shell> - -The second command will install all dependencies, except MySQL and PostgreSQL. We will come back at these soon. With dependencies installed, you can run the whole Rails test suite with: - -<shell> -rake test -</shell> - -You can also run tests for an specific framework, like Action Pack, by going into its directory and executing the same command: - -<shell> -cd actionpack -rake test -</shell> - -h4. Testing Active Record - -By default, when you run Active Record tests, it will execute the test suite three times, one for each of the main databases: SQLite3, MySQL and PostgreSQL. If you are adding a feature that is not specific to the database, you can run the test suite (or just one file) for just one of them. Here is an example for SQLite3: - -<shell> -cd activerecord -rake test_sqlite3 -rake test_sqlite3 TEST=test/cases/validations_test.rb -</shell> - -If you want to use another database, as MySQL, you need to create a user named +rails+ with privileges on the test databases. - -<shell> -mysql> GRANT ALL PRIVILEGES ON activerecord_unittest.* - to 'rails'@'localhost'; -mysql> GRANT ALL PRIVILEGES ON activerecord_unittest2.* - to 'rails'@'localhost'; -</shell> - -Then ensure you run bundle install without the +--without db+ option: - -<shell> -bundle install -</shell> - -Finally, enter this from the +activerecord+ directory to create the test databases: - -<shell> -rake mysql:build_databases -</shell> - -NOTE: Using the rake task to create the test databases ensures they have the correct character set and collation. - -If you’re using another database, check the files under +activerecord/test/connections+ in the Rails source code for default connection information. You can edit these files if you _must_ on your machine to provide different credentials, but obviously you should not push any such changes back to Rails. - -You can now run tests as you did for +sqlite3+: - -<shell> -rake test_mysql -</shell> - -You can also +myqsl+ with +postgresql+, +jdbcmysql+, +jdbcsqlite3+ or +jdbcpostgresql+. Check out the file +activerecord/RUNNING_UNIT_TESTS+ for information on running more targeted database tests, or the file +ci/ci_build.rb+ to see the test suite that the Rails continuous integration server runs. - -NOTE: If you're working with Active Record code, you _must_ ensure that the tests pass for at least MySQL, PostgreSQL, and SQLite 3. Subtle differences between the various Active Record database adapters have been behind the rejection of many patches that looked OK when tested only against MySQL. - -h4. Older versions of Rails - -If you want to work add a fix to older versions of Rails, you'll need to set up and switch to your own local tracking branch. Here is an example to switch to Rails 2.3 branch: - -<shell> -git branch --track 2-3-stable origin/2-3-stable -git checkout 2-3-stable -</shell> - -TIP: You may want to "put your git branch name in your shell prompt":http://github.com/guides/put-your-git-branch-name-in-your-shell-prompt to make it easier to remember which version of the code you're working with. - -h3. Helping to Resolve Existing Issues - -As a next step beyond reporting issues, you can help the core team resolve existing issues. If you check the "open tickets":https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets?q=state%3Aopen list in Lighthouse, you'll find hundreds of issues already requiring attention. What can you do for these? Quite a bit, actually: - -h4. Verifying Bug Reports - -For starters, it helps to just verify bug reports. Can you reproduce the reported issue on your own computer? If so, you can add a comment to the ticket saying that you're seeing the same thing. - -If something is very vague, can you help squish it down into something specific? Maybe you can provide additional information to help reproduce a bug, or eliminate needless steps that aren't required to help demonstrate the problem. - -If you find a bug report without a test, it's very useful to contribute a failing test. This is also a great way to get started exploring the Rails source: looking at the existing test files will teach you how to write more tests for Rails. New tests are best contributed in the form of a patch, as explained later on in the "Contributing to the Rails Code" section. - -Anything you can do to make bug reports more succinct or easier to reproduce is a help to folks trying to write code to fix those bugs - whether you end up writing the code yourself or not. - -h4. Testing Patches - -You can also help out by examining patches that have been submitted to Rails via Lighthouse. To apply someone's changes you need to first create a branch of the Rails source code: - -<shell> -git checkout -b testing_branch -</shell> - -Then you can apply their patch: - -<shell> -git apply their-patch-file.diff -</shell> - -After applying a patch, test it out! Here are some things to think about: - -* Does the patch actually work? -* Are you happy with the tests? Can you follow what they're testing? Are there any tests missing? -* Does the documentation still seem right to you? -* Do you like the implementation? Can you think of a nicer or faster way to implement a part of their change? - -Once you're happy that the patch contains a good change, comment on the Lighthouse ticket indicating your approval. Your comment should indicate that you like the change and what you like about it. Something like: - -<blockquote> -I like the way you've restructured that code in generate_finder_sql, much nicer. The tests look good too. -</blockquote> - -If your comment simply says "+1", then odds are that other reviewers aren't going to take it too seriously. Show that you took the time to review the patch. Once three people have approved it, add the "verified" tag. This will bring it to the attention of a core team member who will review the changes looking for the same kinds of things. - -h3. Contributing to the Rails Documentation - -Another area where you can help out if you're not yet ready to take the plunge to writing Rails core code is with Rails documentation. You can help with the Rails Guides or the Rails API documentation. - -TIP: "docrails":http://github.com/lifo/docrails/tree/master is the documentation branch for Rails with an *open commit policy*. You can simply PM "lifo":http://github.com/lifo on Github and ask for the commit rights. Documentation changes made as part of the "docrails":http://github.com/lifo/docrails/tree/master project are merged back to the Rails master code from time to time. Check out the "original announcement":http://weblog.rubyonrails.org/2008/5/2/help-improve-rails-documentation-on-git-branch for more details. - -h4. The Rails Guides - -The "Rails Guides":http://guides.rubyonrails.org/ are a set of online resources that are designed to make people productive with Rails and to understand how all of the pieces fit together. These guides (including this one!) are written as part of the "docrails":http://github.com/lifo/docrails/tree/master project. If you have an idea for a new guide, or improvements for an existing guide, you can refer to the "contribution page":contribute.html for instructions on getting involved. - -h4. The Rails API Documentation - -The "Rails API documentation":http://api.rubyonrails.org/ is automatically generated from the Rails source code via "RDoc":http://rdoc.rubyforge.org/. If you find some part of the documentation to be incomplete, confusing, or just plain wrong, you can step in and fix it. - -To contribute an update to the API documentation, you can contact "lifo":http://github.com/lifo on GitHub and ask for commit rights to the docrails repository and push your changes to the docrails repository. Please follow the "docrails RDoc conventions":http://wiki.github.com/lifo/docrails/rails-api-documentation-conventions when contributing the changes. - -h3. The Rails Wiki - -The "Rails wiki":http://wiki.rubyonrails.org/ is a collection of user-generated and freely-editable information about Rails. It covers everything from getting started to FAQs to how-tos and popular plugins. To contribute to the wiki, just find some useful information that isn't there already and add it. There are style guidelines to help keep the wiki a coherent resources; see the section on "contributing to the wiki":http://wiki.rubyonrails.org/#contributing_to_the_wiki for more details. - -h3. Contributing to the Rails Code - -When you're ready to take the plunge, one of the most helpful ways to contribute to Rails is to actually submit source code. Here's a step-by-step listing of the things you need to do to make this a successful experience. - -h4. Learn the Language and the Framework - -Learn at least _something_ about Ruby and Rails. If you don’t understand the syntax of the language, common Ruby idioms, and the code that already exists in Rails, you’re unlikely to be able to build a good patch (that is, one that will get accepted). You don’t have to know every in-and-out of the language and the framework; some of the Rails code is fiendishly complex. But Rails is probably not appropriate as the first place that you ever write Ruby code. You should at least understand (though not necessarily memorize) "The Ruby Programming Language":http://www.amazon.com/gp/product/0596516177?ie=UTF8&linkCode=as2&camp=1789&creative=390957&creativeASIN=0596516177 and have browsed the Rails source code. - -h4. Fork the Rails Source Code - -Fork Rails. You’re not going to put your patches right into the master branch, OK? This is where you need that copy of Rails that you cloned earlier. Think of a name for your new branch and run - -<shell> -git checkout -b my_new_branch -</shell> - -It doesn’t really matter what name you use, because this branch will only exist on your local computer. - -h4. Write Your Code - -Now get busy and add your code to Rails (or edit the existing code). You’re on your branch now, so you can write whatever you want (you can check to make sure you’re on the right branch with +git branch -a+). But if you’re planning to submit your change back for inclusion in Rails, keep a few things in mind: - -* Get the code right -* Use Rails idioms and helpers -* Include tests that fail without your code, and pass with it -* Update the documentation - -h4. Follow the Coding Conventions - -Rails follows a simple set of coding style conventions. - -* Two spaces, no tabs -* Prefer +&&+/+||+ over +and+/+or+ -* +MyClass.my_method(my_arg)+ not +my_method( my_arg )+ or +my_method my_arg+ -* Follow the conventions you see used in the source already - -h4. Sanity Check - -You should not be the only person who looks at the code before you submit it. You know at least one other Rails developer, right? Show them what you’re doing and ask for feedback. Doing this in private before you push a patch out publicly is the “smoke test” for a patch: if you can’t convince one other developer of the beauty of your code, you’re unlikely to convince the core team either. - -You might also want to check out the "RailsBridge BugMash":http://wiki.railsbridge.org/projects/railsbridge/wiki/BugMash as a way to get involved in a group effort to improve Rails. This can help you get started and help check your code when you're writing your first patches. - -h4. Commit Your Changes - -When you're happy with the code on your computer, you need to commit the changes to git: - -<shell> -git commit -a -m "Here is a commit message" -</shell> - -h4. Update Rails - -Update your copy of Rails. It’s pretty likely that other changes to core Rails have happened while you were working. Go get them: - -<shell> -git checkout master -git pull -</shell> - -Now reapply your patch on top of the latest changes: - -<shell> -git checkout my_new_branch -git rebase master -</shell> - -No conflicts? Tests still pass? Change still seems reasonable to you? Then move on. - -h4. Create a Patch - -Now you can create a patch file to share with other developers (and with the Rails core team). Still in your branch, run - -<shell> -git commit -a -git format-patch master --stdout > my_new_patch.diff -</shell> - -Sanity check the results of this operation: open the diff file in your text editor of choice and make sure that no unintended changes crept in. - -h4. Create a Lighthouse Ticket - -Now create a ticket with your patch. Go to the "new ticket":http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/new page at Lighthouse. Fill in a reasonable title and description, remember to attach your patch file, and tag the ticket with the ‘patch’ tag and whatever other subject area tags make sense. - -h4. Get Some Feedback - -Now you need to get other people to look at your patch, just as you've looked at other people's patches. You can use the rubyonrails-core mailing list or the #rails-contrib channel on IRC freenode for this. You might also try just talking to Rails developers that you know. - -h4. Iterate as Necessary - -It’s entirely possible that the feedback you get will suggest changes. Don’t get discouraged: the whole point of contributing to an active open source project is to tap into community knowledge. If people are encouraging you to tweak your code, then it’s worth making the tweaks and resubmitting. If the feedback is that your code doesn’t belong in the core, you might still think about releasing it as a plugin. - -And then...think about your next contribution! - -h3. Changelog - -"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/64 - -* April 6, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com -* August 1, 2009: Updates/amplifications by "Mike Gunderloy":credits.html#mgunderloy -* March 2, 2009: Initial draft by "Mike Gunderloy":credits.html#mgunderloy - diff --git a/railties/guides/source/contributing_to_ruby_on_rails.textile b/railties/guides/source/contributing_to_ruby_on_rails.textile new file mode 100644 index 0000000000..1fcc4fd7e3 --- /dev/null +++ b/railties/guides/source/contributing_to_ruby_on_rails.textile @@ -0,0 +1,392 @@ +h2. Contributing to Ruby on Rails + +This guide covers ways in which _you_ can become a part of the ongoing development of Ruby on Rails. After reading it, you should be familiar with: + +* Using Lighthouse to report issues +* Cloning master and running the test suite +* Helping to resolve existing issues +* Contributing to the Ruby on Rails documentation +* Contributing to the Ruby on Rails code + +Ruby on Rails is not "someone else's framework." Over the years, hundreds of people have contributed to Ruby on Rails ranging from a single character to massive architectural changes or significant documentation. All with the goal of making Ruby on Rails better for everyone. Even if you don't feel up to writing code or documentation yet, there are a variety of other ways that you can contribute, from reporting issues to testing patches. + +endprologue. + +h3. Reporting an Issue + +Ruby on Rails uses a "Lighthouse project":http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/ to track issues (primarily bugs and contributions of new code). If you've found a bug in Ruby on Rails, this is the place to start. You'll need to create a (free) Lighthouse account in order to comment on issues or to upload patches. + +NOTE: Bugs in the most recent released version of Ruby on Rails are likely to get the most attention. Also, the Rails core team is always interested in feedback from those who can take the time to test _edge Rails_ (the code for the version of Rails that is currently under development). Later in this guide you'll find out how to get edge Rails for testing. + +h4. Creating a Bug Report + +If you've found a problem in Ruby on Rails which is not a security risk do a search in Lighthouse in case it was already reported. If you find no ticket addressing it you can "add a new one":http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/new. (See the next section for reporting security issues.) + +At the minimum, your ticket needs a title and descriptive text. But that's only a minimum. You should include as much relevant information as possible. You need to at least post the code sample that has the issue. Even better is to include a unit test that shows how the expected behavior is not occurring. Your goal should be to make it easy for yourself - and others - to replicate the bug and figure out a fix. + +You shouldn't assign the bug to a particular core developer unless you know for sure which developer will be handling that issue. The core team periodically reviews issues and assigns developers and milestones to them. + +You should set tags for your issue. Use the "bug" tag for a bug report, and add the "patch" tag if you are attaching a patch. Try to find some relevant tags from the existing tag list (which will appear as soon as you start typing in the "Choose some tags" textbox), rather than creating new tags. + +Then don't get your hopes up. Unless you have a "Code Red, Mission Critical, The World is Coming to an End" kind of bug, you're creating this ticket in the hope that others with the same problem will be able to collaborate with you on solving it. Do not expect that the ticket automatically will see any activity or that others will jump to fix it. Creating a ticket like this is mostly to help yourself start on the path of fixing the problem and for others to confirm it with a "I'm having this problem too" comment. + +h4. Special Treatment for Security Issues + +WARNING: Please do not report security vulnerabilities on public Lighthouse tickets. The "Rails security policy page":http://rubyonrails.org/security details the procedure to follow for security issues. + +h4. What About Feature Requests? + +Please don't put "feature request" tickets into Lighthouse. If there's a new feature that you want to see added to Ruby on Rails, you'll need to write the code yourself - or convince someone else to partner with you to write the code. Later in this guide you'll find detailed instructions for proposing a patch to Ruby on Rails. If you enter a wishlist item in Lighthouse with no code, you can expect it to be marked "invalid" as soon as it's reviewed. + +h3. Running the Test Suite + +To move on from submitting bugs to helping resolve existing issues or contributing your own code to Ruby on Rails, you _must_ be able to run its test suite. In this section of the guide you'll learn how to set up the tests on your own computer. + +h4. Install git + +Ruby on Rails uses git for source code control. The "git homepage":http://git-scm.com/ has installation instructions. There are a variety of resources on the net that will help you get familiar with git: + +* "Everyday Git":http://www.kernel.org/pub/software/scm/git/docs/everyday.html will teach you just enough about git to get by. +* The "PeepCode screencast":https://peepcode.com/products/git on git ($9) is easier to follow. +* "GitHub":https://github.com/guides/home offers links to a variety of git resources. +* "Pro Git":http://progit.org/book/ is an entire book about git with a Creative Commons license. + +h4. Clone the Ruby on Rails Repository + +Navigate to the folder where you want the Ruby on Rails source code (it will create its own +rails+ subdirectory) and run: + +<shell> +$ git clone git://github.com/rails/rails.git +$ cd rails +</shell> + +h4. Set up and Run the Tests + +The test suite must pass with any submitted code. No matter whether you are writing a new patch, or evaluating someone else's, you need to be able to run the tests. + +Install first libxml2 and libxslt together with their development files for Nokogiri. In Ubuntu that's + +<shell> +$ sudo apt-get install libxml2 libxml2-dev libxslt1-dev +</shell> + +Also, SQLite3 and its development files for the +sqlite3-ruby+ gem, in Ubuntu you're done with + +<shell> +$ sudo apt-get install sqlite3 libsqlite3-dev +</shell> + +Get a recent version of "Bundler":http://gembundler.com/: + +<shell> +$ gem install bundler +</shell> + +and run: + +<shell> +$ bundle install --without db +</shell> + +This command will install all dependencies except the MySQL and PostgreSQL Ruby drivers. We will come back at these soon. With dependencies installed, you can run the test suite with: + +<shell> +$ rake test +</shell> + +You can also run tests for an specific framework, like Action Pack, by going into its directory and executing the same command: + +<shell> +$ cd actionpack +$ rake test +</shell> + +If you want to run tests from the specific directory use the +TEST_DIR+ environment variable. For example, this will run tests inside +railties/test/generators+ directory only: + +<shell> +$ cd railties +$ TEST_DIR=generators rake test +</shell> + + +h4. Warnings + +The test suite runs with warnings enabled. Ideally Ruby on Rails should issue no warning, but there may be a few, and also some from third-party libraries. Please ignore (or fix!) them if any, and submit patches that do not issue new warnings. + +As of this writing they are specially noisy with Ruby 1.9. If you are sure about what you are doing and would like to have a more clear output, there's a way to override the flag: + +<shell> +$ RUBYOPT=-W0 rake test +</shell> + +h4. Testing Active Record + +The test suite of Active Record attempts to run four times, once for SQLite3, once for each of the two MySQL gems (+mysql+ and +mysql2+), and once for PostgreSQL. We are going to see now how to setup the environment for them. + +WARNING: If you're working with Active Record code, you _must_ ensure that the tests pass for at least MySQL, PostgreSQL, and SQLite3. Subtle differences between the various adapters have been behind the rejection of many patches that looked OK when tested only against MySQL. + +h5. SQLite3 + +The gem +sqlite3-ruby+ does not belong to the "db" group indeed, if you followed the instructions above you're ready. This is how you run the Active Record test suite only for SQLite3: + +<shell> +$ cd activerecord +$ rake test_sqlite3 +</shell> + +h5. MySQL and PostgreSQL + +To be able to run the suite for MySQL and PostgreSQL we need their gems. Install first the servers, their client libraries, and their development files. In Ubuntu just run + +<shell> +$ sudo apt-get install mysql-server libmysqlclient15-dev +$ sudo apt-get install postgresql postgresql-client postgresql-contrib libpq-dev +</shell> + +After that run: + +<shell> +$ rm .bundle/config +$ bundle install +</shell> + +We need first to delete +.bundle/config+ because Bundler remembers in that file that we didn't want to install the "db" group (alternatively you can edit the file). + +In order to be able to run the test suite against MySQL you need to create a user named +rails+ with privileges on the test databases: + +<shell> +mysql> GRANT ALL PRIVILEGES ON activerecord_unittest.* + to 'rails'@'localhost'; +mysql> GRANT ALL PRIVILEGES ON activerecord_unittest2.* + to 'rails'@'localhost'; +</shell> + +and create the test databases: + +<shell> +$ cd activerecord +$ rake mysql:build_databases +</shell> + +PostgreSQL's authentication works differently. A simple way to setup the development environment for example is to run with your development account + +<shell> +$ sudo -u postgres createuser --superuser $USER +</shell> + +and after that create the test databases with + +<shell> +$ cd activerecord +$ rake postgresql:build_databases +</shell> + +NOTE: Using the rake task to create the test databases ensures they have the correct character set and collation. + +If you’re using another database, check the files under +activerecord/test/connections+ for default connection information. You can edit these files if you _must_ on your machine to provide different credentials, but obviously you should not push any such changes back to Rails. + +You can now run tests as you did for +sqlite3+, the tasks are + +<shell> +test_mysql +test_mysql2 +test_postgresql +</shell> + +respectively. As we mentioned before + +<shell> +$ rake test +</shell> + +will now run the four of them in turn. + +You can also invoke +test_jdbcmysql+, +test_jdbcsqlite3+ or +test_jdbcpostgresql+. Check out the file +activerecord/RUNNING_UNIT_TESTS+ for information on running more targeted database tests, or the file +ci/ci_build.rb+ to see the test suite that the continuous integration server runs. + +h4. Older versions of Ruby on Rails + +If you want to add a fix to older versions of Ruby on Rails, you'll need to set up and switch to your own local tracking branch. Here is an example to switch to the 2-3-stable branch: + +<shell> +$ git branch --track 2-3-stable origin/2-3-stable +$ git checkout 2-3-stable +</shell> + +TIP: You may want to "put your git branch name in your shell prompt":http://qugstart.com/blog/git-and-svn/add-colored-git-branch-name-to-your-shell-prompt/ to make it easier to remember which version of the code you're working with. + +h3. Helping to Resolve Existing Issues + +As a next step beyond reporting issues, you can help the core team resolve existing issues. If you check the "open tickets":https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets?q=state%3Aopen list in Lighthouse, you'll find lots of issues already requiring attention. What can you do for these? Quite a bit, actually: + +h4. Verifying Bug Reports + +For starters, it helps to just verify bug reports. Can you reproduce the reported issue on your own computer? If so, you can add a comment to the ticket saying that you're seeing the same thing. + +If something is very vague, can you help squish it down into something specific? Maybe you can provide additional information to help reproduce a bug, or eliminate needless steps that aren't required to help demonstrate the problem. + +If you find a bug report without a test, it's very useful to contribute a failing test. This is also a great way to get started exploring the source code: looking at the existing test files will teach you how to write more tests. New tests are best contributed in the form of a patch, as explained later on in the "Contributing to the Rails Code" section. + +Anything you can do to make bug reports more succinct or easier to reproduce is a help to folks trying to write code to fix those bugs - whether you end up writing the code yourself or not. + +h4. Testing Patches + +You can also help out by examining patches that have been submitted to Ruby on Rails via Lighthouse. To apply someone's changes you need to first create a dedicated branch: + +<shell> +$ git checkout -b testing_branch +</shell> + +Then you can apply their patch: + +<shell> +$ git am their-patch-file.diff +</shell> + +After applying a patch, test it out! Here are some things to think about: + +* Does the patch actually work? +* Are you happy with the tests? Can you follow what they're testing? Are there any tests missing? +* Does it have proper documentation coverage? Should documentation elsewhere be updated? +* Do you like the implementation? Can you think of a nicer or faster way to implement a part of their change? + +Once you're happy that the patch contains a good change, comment on the Lighthouse ticket indicating your approval. Your comment should indicate that you like the change and what you like about it. Something like: + +<blockquote> +I like the way you've restructured that code in generate_finder_sql, much nicer. The tests look good too. +</blockquote> + +If your comment simply says "+1", then odds are that other reviewers aren't going to take it too seriously. Show that you took the time to review the patch. Once three people have approved it, add the "verified" tag. This will bring it to the attention of a core team member who will review the changes looking for the same kinds of things. + +h3. Contributing to the Rails Documentation + +Ruby on Rails has two main sets of documentation: The guides help you to learn Ruby on Rails, and the API is a reference. + +You can create a ticket in Lighthouse to fix or expand documentation. However, if you're confident about your changes you can push them yourself directly via "docrails":https://github.com/lifo/docrails/tree/master. docrails is a branch with an *open commit policy* and public write access. Commits to docrails are still reviewed, but that happens after they are pushed. docrails is merged with master regularly, so you are effectively editing the Ruby on Rails documentation. + +When working with documentation, please take into account the "API Documentation Guidelines":api_documentation_guidelines.html and the "Ruby on Rails Guides Guidelines":ruby_on_rails_guides_guidelines.html. + +NOTE: As explained above, ordinary code patches should have proper documentation coverage. docrails is only used for isolated documentation improvements. + +WARNING: docrails has a very strict policy: no code can be touched whatsoever, no matter how trivial or small the change. Only RDoc and guides can be edited via docrails. + +If you have an idea for a new guide you can refer to the "contribution page":contribute.html for instructions on getting involved. + +h3. Contributing to the Rails Code + +h4. Clone the Rails Repository + +The first thing you need to do to be able to contribute code is to clone the repository: + +<shell> +$ git clone git://github.com/rails/rails.git +</shell> + +and create a dedicated branch: + +<shell> +$ cd rails +$ git checkout -b my_new_branch +</shell> + +It doesn’t really matter what name you use, because this branch will only exist on your local computer. + +h4. Write Your Code + +Now get busy and add or edit code. You’re on your branch now, so you can write whatever you want (you can check to make sure you’re on the right branch with +git branch -a+). But if you’re planning to submit your change back for inclusion in Rails, keep a few things in mind: + +* Get the code right +* Use Rails idioms and helpers +* Include tests that fail without your code, and pass with it +* Update the documentation, the surrounding one, examples elsewhere, guides, whatever is affected by your contribution + +h4. Follow the Coding Conventions + +Rails follows a simple set of coding style conventions. + +* Two spaces, no tabs +* Prefer +&&+/+||+ over +and+/+or+ +* +MyClass.my_method(my_arg)+ not +my_method( my_arg )+ or +my_method my_arg+ +* Follow the conventions you see used in the source already + +h4. Sanity Check + +You should not be the only person who looks at the code before you submit it. You know at least one other Rails developer, right? Show them what you’re doing and ask for feedback. Doing this in private before you push a patch out publicly is the “smoke test” for a patch: if you can’t convince one other developer of the beauty of your code, you’re unlikely to convince the core team either. + +You might also want to check out the "RailsBridge BugMash":http://wiki.railsbridge.org/projects/railsbridge/wiki/BugMash as a way to get involved in a group effort to improve Rails. This can help you get started and help check your code when you're writing your first patches. + +h4. Commit Your Changes + +When you're happy with the code on your computer, you need to commit the changes to git: + +<shell> +$ git commit -a -m "Here is a commit message" +</shell> + +h4. Update master + +It’s pretty likely that other changes to master have happened while you were working. Go get them: + +<shell> +$ git checkout master +$ git pull +</shell> + +Now reapply your patch on top of the latest changes: + +<shell> +$ git checkout my_new_branch +$ git rebase master +</shell> + +No conflicts? Tests still pass? Change still seems reasonable to you? Then move on. + +h4. Create a Patch + +Now you can create a patch file to share with other developers (and with the core team). Still in your branch, run + +<shell> +$ git commit -a +$ git format-patch master --stdout > my_new_patch.diff +</shell> + +Open the diff file in your text editor of choice to sanity check the results, and make sure that no unintended changes crept in. + +You can also perform an extra check by applying the patch to a different dedicated branch: + +<shell> +$ git checkout -b testing_branch +$ git apply --check my_new_patch.diff +</shell> + +Please make sure the patch does not introduce whitespace errors: + +<shell> +$ git apply --whitespace=error-all mynew_patch.diff +</shell> + + +h4. Create a Lighthouse Ticket + +Now create a ticket with your patch. Go to the "new ticket":http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/new page at Lighthouse. Fill in a reasonable title and description, remember to attach your patch file, and tag the ticket with the ‘patch’ tag and whatever other subject area tags make sense. + +h4. Get Some Feedback + +Now you need to get other people to look at your patch, just as you've looked at other people's patches. You can use the "rubyonrails-core mailing list":http://groups.google.com/group/rubyonrails-core/ or the #rails-contrib channel on IRC freenode for this. You might also try just talking to Rails developers that you know. + +h4. Iterate as Necessary + +It’s entirely possible that the feedback you get will suggest changes. Don’t get discouraged: the whole point of contributing to an active open source project is to tap into community knowledge. If people are encouraging you to tweak your code, then it’s worth making the tweaks and resubmitting. If the feedback is that your code doesn’t belong in the core, you might still think about releasing it as a plugin. + +And then...think about your next contribution! + +h3. Rails Contributors + +All contributions, either via master or docrails, get credit in "Rails Contributors":http://contributors.rubyonrails.org. + +h3. Changelog + +* December 28, 2010: Complete revision by "Xavier Noria":credits.html#fxn +* April 6, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com +* August 1, 2009: Updates/amplifications by "Mike Gunderloy":credits.html#mgunderloy +* March 2, 2009: Initial draft by "Mike Gunderloy":credits.html#mgunderloy + diff --git a/railties/guides/source/credits.html.erb b/railties/guides/source/credits.html.erb index 825e042628..65e396be95 100644 --- a/railties/guides/source/credits.html.erb +++ b/railties/guides/source/credits.html.erb @@ -20,7 +20,7 @@ Ruby on Rails Guides: Credits <% end %> <%= author('Xavier Noria', 'fxn', 'fxn.png') do %> - Xavier has been into Rails since 2005, he is currently a Rails consultant. Xavier is Rails committer and enjoys combining his passion for Rails and his past life as a proofreader of math textbooks. Oh, he also <a href="http://twitter.com/fxn">tweets</a> and can be found everywhere as "fxn". + Xavier Noria has been into Ruby on Rails since 2005. He is a Rails committer and enjoys combining his passion for Rails and his past life as a proofreader of math textbooks. Xavier is currently a Ruby on Rails consultant. Oh, he also <a href="http://twitter.com/fxn">tweets</a> and can be found everywhere as "fxn". <% end %> <h3 class="section">Rails Guides Designers</h3> @@ -44,7 +44,7 @@ Ruby on Rails Guides: Credits <% end %> <%= author('Mikel Lindsaar', 'raasdnil') do %> - Mikel Lindsaar has been working with Rails since 2006 and is the author of the Ruby <a href="http://github.com/mikel/mail">Mail gem</a> and core contributor (he helped re-write Action Mailer's API). Mikel is the founder of <a href="http://rubyx.com/">RubyX</a>, has a <a href="http://lindsaar.net/">blog</a> and <a href="http://twitter.com/raasdnil">tweets</a>. + Mikel Lindsaar has been working with Rails since 2006 and is the author of the Ruby <a href="https://github.com/mikel/mail">Mail gem</a> and core contributor (he helped re-write Action Mailer's API). Mikel is the founder of <a href="http://rubyx.com/">RubyX</a>, has a <a href="http://lindsaar.net/">blog</a> and <a href="http://twitter.com/raasdnil">tweets</a>. <% end %> <%= author('Cássio Marques', 'cmarques') do %> @@ -52,7 +52,7 @@ Ruby on Rails Guides: Credits <% end %> <%= author('James Miller', 'bensie') do %> - James Miller is a software developer for <a href="http://www.jk-tech.com">JK Tech</a> in San Diego, CA. Find me on GitHub, Gmail, Twitter, and Freenode as "bensie". + James Miller is a software developer for <a href="http://www.jk-tech.com">JK Tech</a> in San Diego, CA. You can find James on GitHub, Gmail, Twitter, and Freenode as "bensie". <% end %> <%= author('Emilio Tagua', 'miloops') do %> diff --git a/railties/guides/source/debugging_rails_applications.textile b/railties/guides/source/debugging_rails_applications.textile index 26aee82ae1..045b8823ca 100644 --- a/railties/guides/source/debugging_rails_applications.textile +++ b/railties/guides/source/debugging_rails_applications.textile @@ -48,7 +48,7 @@ Title: Rails debugging guide h4. +to_yaml+ -Displaying an instance variable, or any other object or method, in yaml format can be achieved this way: +Displaying an instance variable, or any other object or method, in YAML format can be achieved this way: <html> <%= simple_format @post.to_yaml %> @@ -96,23 +96,25 @@ Will be rendered as follows: Title: Rails debugging guide </pre> -h4. Debugging JavaScript +h4. Debugging RJS -Rails has built-in support to debug RJS, to active it, set +ActionView::Base.debug_rjs+ to _true_, this will specify whether RJS responses should be wrapped in a try/catch block that alert()s the caught exception (and then re-raises it). +Rails has optional built-in support to debug RJS. When enabled, responses are wrapped in a try/catch block that displays the caught exception using +alert()+, and then re-raises it. -To enable it, add the following in the +Rails::Initializer do |config|+ block inside +environment.rb+: +The flag to enable RJS debugging in your configuration files is +config.action_view.debug_rjs+: <ruby> -config.action_view[:debug_rjs] = true +config.action_view.debug_rjs = true </ruby> -Or, at any time, setting +ActionView::Base.debug_rjs+ to _true_: +or at any time setting +ActionView::Base.debug_rjs+: <ruby> ActionView::Base.debug_rjs = true </ruby> -TIP: For more information on debugging javascript refer to "Firebug":http://getfirebug.com/, the popular debugger for Firefox. +It is enabled by default in development mode, and disabled in the rest. + +TIP: For more information on debugging JavaScript, refer to "Firebug":http://getfirebug.com/, the popular debugger for Firefox. h3. The Logger @@ -120,13 +122,13 @@ It can also be useful to save information to log files at runtime. Rails maintai h4. What is the Logger? -Rails makes use of Ruby's standard +logger+ to write log information. You can also substitute another logger such as +Log4R+ if you wish. +Rails makes use of Ruby's standard +logger+ to write log information. You can also substitute another logger such as +Log4r+ if you wish. You can specify an alternative logger in your +environment.rb+ or any environment file: <ruby> -ActiveRecord::Base.logger = Logger.new(STDOUT) -ActiveRecord::Base.logger = Log4r::Logger.new("Application Log") +Rails.logger = Logger.new(STDOUT) +Rails.logger = Log4r::Logger.new("Application Log") </ruby> Or in the +Initializer+ section, add _any_ of the following @@ -140,13 +142,13 @@ TIP: By default, each log is created under +Rails.root/log/+ and the log file na h4. Log Levels -When something is logged it's printed into the corresponding log if the log level of the message is equal or higher than the configured log level. If you want to know the current log level you can call the +ActiveRecord::Base.logger.level+ method. +When something is logged it's printed into the corresponding log if the log level of the message is equal or higher than the configured log level. If you want to know the current log level you can call the +Rails.logger.level+ method. 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 -ActiveRecord::Base.logger.level = 0 # at any time +Rails.logger.level = 0 # at any time </ruby> This is useful when you want to log under development or staging, but you don't want to flood your production log with unnecessary information. @@ -176,7 +178,7 @@ class PostsController < ApplicationController if @post.save flash[:notice] = 'Post was successfully created.' - logger.debug "The post was saved and now is the user is going to be redirected..." + logger.debug "The post was saved and now the user is going to be redirected..." redirect_to(@post) else render :action => "new" @@ -202,7 +204,7 @@ Post should be valid: true Post Create (0.000443) INSERT INTO "posts" ("updated_at", "title", "body", "published", "created_at") VALUES('2008-09-08 14:52:54', 'Debugging Rails', 'I''m learning how to print in logs!!!', 'f', '2008-09-08 14:52:54') -The post was saved and now is the user is going to be redirected... +The post was saved and now the user is going to be redirected... Redirected to #<Post:0x20af760> Completed in 0.01224 (81 reqs/sec) | DB: 0.00044 (3%) | 302 Found [http://localhost/posts] </shell> @@ -223,6 +225,8 @@ The debugger used by Rails, +ruby-debug+, comes as a gem. To install it, just ru $ sudo gem install ruby-debug </shell> +TIP: If you are using Ruby 1.9, you can install a compatible version of +ruby-debug+ by running +sudo gem install ruby-debug19+ + In case you want to download a particular version or get the source code, refer to the "project's page on rubyforge":http://rubyforge.org/projects/ruby-debug/. Rails has had built-in support for ruby-debug since Rails 2.0. Inside any Rails application you can invoke the debugger by calling the +debugger+ method. @@ -247,8 +251,8 @@ If you see the message in the console or logs: Make sure you have started your web server with the option +--debugger+: <shell> -~/PathTo/rails_project$ rails server --debugger -=> Booting Mongrel (use 'rails server webrick' to force WEBrick) +$ rails server --debugger +=> Booting WEBrick => Rails 3.0.0 application starting on http://0.0.0.0:3000 => Debugger enabled ... @@ -256,8 +260,6 @@ Make sure you have started your web server with the option +--debugger+: TIP: In development mode, you can dynamically +require \'ruby-debug\'+ instead of restarting the server, if it was started without +--debugger+. -In order to use Rails debugging you'll need to be running either *WEBrick* or *Mongrel*. For the moment, no alternative servers are supported. - h4. The Shell As soon as your application calls the +debugger+ method, the debugger will be started in a debugger shell inside the terminal window where you launched your application server, and you will be placed at ruby-debug's prompt +(rdb:n)+. The _n_ is the thread number. The prompt will also show you the next line of code that is waiting to run. @@ -267,7 +269,7 @@ If you got there by a browser request, the browser tab containing the request wi For example: <shell> -@posts = Post.find(:all) +@posts = Post.all (rdb:7) </shell> @@ -300,7 +302,7 @@ This command shows you where you are in the code by printing 10 lines centered a 3 # GET /posts.xml 4 def index 5 debugger -=> 6 @posts = Post.find(:all) +=> 6 @posts = Post.all 7 8 respond_to do |format| 9 format.html # index.html.erb @@ -378,7 +380,7 @@ Any expression can be evaluated in the current context. To evaluate an expressio This example shows how you can print the instance_variables defined within the current context: <shell> -@posts = Post.find(:all) +@posts = Post.all (rdb:11) instance_variables ["@_response", "@action_name", "@url", "@_session", "@_cookies", "@performed_render", "@_flash", "@template", "@_params", "@before_filter_chain_aborted", "@request_origin", "@_headers", "@performed_redirect", "@_request"] </shell> @@ -475,7 +477,7 @@ end TIP: You can use ruby-debug while using +rails console+. Just remember to +require "ruby-debug"+ before calling the +debugger+ method. <shell> -/PathTo/project $ rails console +$ rails console Loading development environment (Rails 2.1.0) >> require "ruby-debug" => [] @@ -599,7 +601,7 @@ There are some settings that can be configured in ruby-debug to make it easier t You can see the full list by using +help set+. Use +help set _subcommand_+ to learn about a particular +set+ command. -TIP: You can include any number of these configuration lines inside a +.rdebugrc+ file in your HOME directory. ruby-debug will read this file every time it is loaded. and configure itself accordingly. +TIP: You can include any number of these configuration lines inside a +.rdebugrc+ file in your HOME directory. ruby-debug will read this file every time it is loaded and configure itself accordingly. Here's a good start for an +.rdebugrc+: @@ -613,18 +615,18 @@ h3. Debugging Memory Leaks A Ruby application (on Rails or not), can leak memory - either in the Ruby code or at the C code level. -In this section, you will learn how to find and fix such leaks by using Bleak House and Valgrind debugging tools. +In this section, you will learn how to find and fix such leaks by using tools such as BleakHouse and Valgrind. h4. BleakHouse -"BleakHouse":http://github.com/fauna/bleak_house/tree/master is a library for finding memory leaks. +"BleakHouse":https://github.com/fauna/bleak_house/tree/master is a library for finding memory leaks. If a Ruby object does not go out of scope, the Ruby Garbage Collector won't sweep it since it is referenced somewhere. Leaks like this can grow slowly and your application will consume more and more memory, gradually affecting the overall system performance. This tool will help you find leaks on the Ruby heap. To install it run: <shell> -sudo gem install bleak_house +$ sudo gem install bleak_house </shell> Then setup your application for profiling. Then add the following at the bottom of config/environment.rb: @@ -636,7 +638,7 @@ require 'bleak_house' if ENV['BLEAK_HOUSE'] Start a server instance with BleakHouse integration: <shell> -RAILS_ENV=production BLEAK_HOUSE=1 ruby-bleak-house rails server +$ RAILS_ENV=production BLEAK_HOUSE=1 ruby-bleak-house rails server </shell> Make sure to run a couple hundred requests to get better data samples, then press +CTRL-C+. The server will stop and Bleak House will produce a dumpfile in +/tmp+: @@ -666,7 +668,7 @@ To analyze it, just run the listed command. The top 20 leakiest lines will be li This way you can find where your application is leaking memory and fix it. -If "BleakHouse":http://github.com/fauna/bleak_house/tree/master doesn't report any heap growth but you still have memory growth, you might have a broken C extension, or real leak in the interpreter. In that case, try using Valgrind to investigate further. +If "BleakHouse":https://github.com/fauna/bleak_house/tree/master doesn't report any heap growth but you still have memory growth, you might have a broken C extension, or real leak in the interpreter. In that case, try using Valgrind to investigate further. h4. Valgrind @@ -680,12 +682,12 @@ h3. Plugins for Debugging There are some Rails plugins to help you to find errors and debug your application. Here is a list of useful plugins for debugging: -* "Footnotes":http://github.com/josevalim/rails-footnotes: Every Rails page has footnotes that give request information and link back to your source via TextMate. -* "Query Trace":http://github.com/ntalbott/query_trace/tree/master: Adds query origin tracing to your logs. -* "Query Stats":http://github.com/dan-manges/query_stats/tree/master: A Rails plugin to track database queries. +* "Footnotes":https://github.com/josevalim/rails-footnotes: Every Rails page has footnotes that give request information and link back to your source via TextMate. +* "Query Trace":https://github.com/ntalbott/query_trace/tree/master: Adds query origin tracing to your logs. +* "Query Stats":https://github.com/dan-manges/query_stats/tree/master: A Rails plugin to track database queries. * "Query Reviewer":http://code.google.com/p/query-reviewer/: This rails plugin not only runs "EXPLAIN" before each of your select queries in development, but provides a small DIV in the rendered output of each page with the summary of warnings for each query that it analyzed. -* "Exception Notifier":http://github.com/rails/exception_notification/tree/master: Provides a mailer object and a default set of templates for sending email notifications when errors occur in a Rails application. -* "Exception Logger":http://github.com/defunkt/exception_logger/tree/master: Logs your Rails exceptions in the database and provides a funky web interface to manage them. +* "Exception Notifier":https://github.com/smartinez87/exception_notification/tree/master: Provides a mailer object and a default set of templates for sending email notifications when errors occur in a Rails application. +* "Exception Logger":https://github.com/defunkt/exception_logger/tree/master: Logs your Rails exceptions in the database and provides a funky web interface to manage them. h3. References @@ -702,8 +704,6 @@ h3. References h3. Changelog -"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/5 - * April 4, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com * November 3, 2008: Accepted for publication. Added RJS, memory leaks and plugins chapters by "Emilio Tagua":credits.html#miloops * October 19, 2008: Copy editing pass by "Mike Gunderloy":credits.html#mgunderloy diff --git a/railties/guides/source/form_helpers.textile b/railties/guides/source/form_helpers.textile index 146b75da3f..1f21c27ae6 100644 --- a/railties/guides/source/form_helpers.textile +++ b/railties/guides/source/form_helpers.textile @@ -9,6 +9,7 @@ In this guide you will: * Generate select boxes from multiple types of data * Understand the date and time helpers Rails provides * Learn what makes a file upload form different +* Learn some cases of building forms to external resources * Find out where to look for complex forms endprologue. @@ -31,17 +32,18 @@ When called without arguments like this, it creates a form element that has the Sample output from +form_tag+: <html> -<form action="/home/index" method="post"> +<form accept-charset="UTF-8" action="/home/index" method="post"> <div style="margin:0;padding:0"> + <input name="utf8" type="hidden" value="✓" /> <input name="authenticity_token" type="hidden" value="f755bb0ed134b76c432144748a6d4b7a7ddf2b71" /> </div> Form contents </form> </html> -If you carefully observe this output, you can see that the helper generated something you didn't specify: a +div+ element with a hidden input inside. This is a security feature of Rails called *cross-site request forgery protection* and form helpers generate it for every form whose action is not "get" (provided that this security feature is enabled). You can read more about this in the "Ruby On Rails Security Guide":./security.html#_cross_site_reference_forgery_csrf. +If you carefully observe this output, you can see that the helper generated something you didn't specify: a +div+ element with two hidden input elements inside. The first input element with name +utf8+ enforces browsers to properly respect your form's character encoding and is generated for all forms whether action is "get" or "post". Second input element with name +authenticity_token+ is a security feature of Rails called *cross-site request forgery protection* and form helpers generate it for every form whose action is not "get" (provided that this security feature is enabled). You can read more about this in the "Ruby On Rails Security Guide":./security.html#_cross_site_reference_forgery_csrf. -NOTE: Throughout this guide, this +div+ with the hidden input will be stripped away to have clearer code samples. +NOTE: Throughout this guide, this +div+ with the hidden input elements will be stripped away to have clearer code samples. h4. A Generic Search Form @@ -58,20 +60,20 @@ To create this form you will use +form_tag+, +label_tag+, +text_field_tag+, and A basic search form -<html> +<erb> <%= form_tag(search_path, :method => "get") do %> <%= label_tag(:q, "Search for:") %> <%= text_field_tag(:q) %> <%= submit_tag("Search") %> <% end %> -</html> +</erb> -TIP: +search_path+ can be a named route specified in "routes.rb": <br /><tt>map.search "search", :controller => "search"</tt> +TIP: +search_path+ can be a named route specified in "routes.rb" as: <br /><code>match "search" => "search"</code> This declares that path "/search" will be handled by action "search" belonging to controller "search". The above view code will result in the following markup: <html> -<form action="/search" method="get"> +<form accept-charset="UTF-8" action="/search" method="get"> <label for="q">Search for:</label> <input id="q" name="q" type="text" /> <input name="commit" type="submit" value="Search" /> @@ -90,14 +92,14 @@ As with the +link_to+ helper, the path argument doesn't have to be given a strin <ruby> form_tag(:controller => "people", :action => "search", :method => "get", :class => "nifty_form") -# => <form action="/people/search?method=get&class=nifty_form" method="post"> +# => <form accept-charset="UTF-8" action="/people/search?method=get&class=nifty_form" method="post"> </ruby> Here you wanted to pass two hashes, but the Ruby interpreter sees only one hash, so Rails will construct a URL with extraneous parameters. The correct way of passing multiple hashes as arguments is to delimit the first hash (or both hashes) with curly brackets: <ruby> form_tag({:controller => "people", :action => "search"}, :method => "get", :class => "nifty_form") -# => <form action="/people/search" method="get" class="nifty_form"> +# => <form accept-charset="UTF-8" action="/people/search" method="get" class="nifty_form"> </ruby> This is a common pitfall when using form helpers, since many of them accept multiple hashes. So in future, if a helper produces unexpected output, make sure that you have delimited the hash parameters properly. @@ -106,7 +108,7 @@ WARNING: Do not delimit the second hash without doing so with the first hash, ot h4. Helpers for Generating Form Elements -Rails provides a series of helpers for generating form elements such as checkboxes, text fields, radio buttons, and so on. These basic helpers, with names ending in <notextile>_tag</notextile> such as +text_field_tag+, +check_box_tag+, etc., generate just a single +<input>+ element. The first parameter to these is always the name of the input. In the controller this name will be the key in the +params+ hash used to get the value entered by the user. For example, if the form contains +Rails provides a series of helpers for generating form elements such as checkboxes, text fields and radio buttons. These basic helpers, with names ending in <notextile>_tag</notextile> such as +text_field_tag+ and +check_box_tag+ generate just a single +<input>+ element. The first parameter to these is always the name of the input. In the controller this name will be the key in the +params+ hash used to get the value entered by the user. For example, if the form contains <erb> <%= text_field_tag(:query) %> @@ -126,17 +128,19 @@ Checkboxes are form controls that give the user a set of options they can enable <erb> <%= check_box_tag(:pet_dog) %> - <%= label_tag(:pet_dog, "I own a dog") %> +<%= label_tag(:pet_dog, "I own a dog") %> <%= check_box_tag(:pet_cat) %> - <%= label_tag(:pet_cat, "I own a cat") %> +<%= label_tag(:pet_cat, "I own a cat") %> +</erb> output: +<html> <input id="pet_dog" name="pet_dog" type="checkbox" value="1" /> - <label for="pet_dog">I own a dog</label> +<label for="pet_dog">I own a dog</label> <input id="pet_cat" name="pet_cat" type="checkbox" value="1" /> - <label for="pet_cat">I own a cat</label> -</erb> +<label for="pet_cat">I own a cat</label> +</html> The second parameter to +check_box_tag+ is the value of the input. This is the value that will be submitted by the browser if the checkbox is ticked (i.e. the value that will be present in the +params+ hash). With the above form you would check the value of +params[:pet_dog]+ and +params[:pet_cat]+ to see which pets the user owns. @@ -146,17 +150,19 @@ Radio buttons, while similar to checkboxes, are controls that specify a set of o <erb> <%= radio_button_tag(:age, "child") %> - <%= label_tag(:age_child, "I am younger than 21") %> +<%= label_tag(:age_child, "I am younger than 21") %> <%= radio_button_tag(:age, "adult") %> - <%= label_tag(:age_adult, "I'm over 21") %> +<%= label_tag(:age_adult, "I'm over 21") %> +</erb> output: +<html> <input id="age_child" name="age" type="radio" value="child" /> - <label for="age_child">I am younger than 21</label> +<label for="age_child">I am younger than 21</label> <input id="age_adult" name="age" type="radio" value="adult" /> - <label for="age_adult">I'm over 21</label> -</erb> +<label for="age_adult">I'm over 21</label> +</html> As with +check_box_tag+ the second parameter to +radio_button_tag+ is the value of the input. Because these two radio buttons share the same name (age) the user will only be able to select one and +params[:age]+ will contain either "child" or "adult". @@ -170,17 +176,19 @@ Other form controls worth mentioning are the text area, password input and hidde <%= text_area_tag(:message, "Hi, nice site", :size => "24x6") %> <%= password_field_tag(:password) %> <%= hidden_field_tag(:parent_id, "5") %> +</erb> output: +<html> <textarea id="message" name="message" cols="24" rows="6">Hi, nice site</textarea> <input id="password" name="password" type="password" /> <input id="parent_id" name="parent_id" type="hidden" value="5" /> -</erb> +</html> Hidden inputs are not shown to the user, but they hold data like any textual input. Values inside them can be changed with JavaScript. -TIP: If you're using password input fields (for any purpose), you might want to prevent their values showing up in application logs by activating +filter_parameter_logging(:password)+ in your ApplicationController. +TIP: If you're using password input fields (for any purpose), you might want to configure your application to prevent those parameters from being logged. h3. Dealing with Model Objects @@ -222,16 +230,16 @@ end The corresponding view +app/views/articles/new.html.erb+ using +form_for+ looks like this: <erb> -<%= form_for :article, @article, :url => { :action => "create" }, :html => {:class => "nifty_form"} do |f| %> +<%= form_for @article, :url => { :action => "create" }, :html => {:class => "nifty_form"} do |f| %> <%= f.text_field :title %> <%= f.text_area :body, :size => "60x12" %> - <%= submit_tag "Create" %> + <%= f.submit "Create" %> <% end %> </erb> There are a few things to note here: -# +:article+ is the name of the model and +@article+ is the actual object being edited. +# +@article+ is the actual object being edited. # There is a single hash of options. Routing options are passed in the +:url+ hash, HTML options are passed in the +:html+ hash. # The +form_for+ method yields a *form builder* object (the +f+ variable). # Methods to create form controls are called *on* the form builder object +f+ @@ -239,7 +247,7 @@ There are a few things to note here: The resulting HTML is: <html> -<form action="/articles/create" method="post" class="nifty_form"> +<form accept-charset="UTF-8" action="/articles/create" method="post" class="nifty_form"> <input id="article_title" name="article[title]" size="30" type="text" /> <textarea id="article_body" name="article[body]" cols="60" rows="12"></textarea> <input name="commit" type="submit" value="Create" /> @@ -253,7 +261,7 @@ The helper methods called on the form builder are identical to the model object You can create a similar binding without actually creating +<form>+ tags with the +fields_for+ helper. This is useful for editing additional model objects with the same form. For example if you had a Person model with an associated ContactDetail model you could create a form for creating both like so: <erb> -<%= form_for :person, @person, :url => { :action => "create" } do |person_form| %> +<%= form_for @person, :url => { :action => "create" } do |person_form| %> <%= person_form.text_field :name %> <%= fields_for @person.contact_detail do |contact_details_form| %> <%= contact_details_form.text_field :phone_number %> @@ -264,7 +272,7 @@ You can create a similar binding without actually creating +<form>+ tags which produces the following output: <html> -<form action="/people/create" class="new_person" id="new_person" method="post"> +<form accept-charset="UTF-8" action="/people/create" class="new_person" id="new_person" method="post"> <input id="person_name" name="person[name]" size="30" type="text" /> <input id="contact_detail_phone_number" name="contact_detail[phone_number]" size="30" type="text" /> </form> @@ -277,7 +285,7 @@ h4. Relying on Record Identification The Article model is directly available to users of the application, so -- following the best practices for developing with Rails -- you should declare it *a resource*: <ruby> -map.resources :articles +resources :articles </ruby> TIP: Declaring a resource has a number of side-affects. See "Rails Routing From the Outside In":routing.html#resource-routing-the-rails-default for more information on setting up and using resources. @@ -287,13 +295,13 @@ When dealing with RESTful resources, calls to +form_for+ can get significantly e <ruby> ## Creating a new article # long-style: -form_for(:article, @article, :url => articles_path) +form_for(@article, :url => articles_path) # same thing, short-style (record identification gets used): form_for(@article) ## Editing an existing article # long-style: -form_for(:article, @article, :url => article_path(@article), :html => { :method => "put" }) +form_for(@article, :url => article_path(@article), :html => { :method => "put" }) # short-style: form_for(@article) </ruby> @@ -334,9 +342,10 @@ form_tag(search_path, :method => "put") output: <html> -<form action="/search" method="post"> +<form accept-charset="UTF-8" action="/search" method="post"> <div style="margin:0;padding:0"> <input name="_method" type="hidden" value="put" /> + <input name="utf8" type="hidden" value="✓" /> <input name="authenticity_token" type="hidden" value="f755bb0ed134b76c432144748a6d4b7a7ddf2b71" /> </div> ... @@ -466,7 +475,7 @@ To leverage time zone support in Rails, you have to ask your users what time zon There is also +time_zone_options_for_select+ helper for a more manual (therefore more customizable) way of doing this. Read the API documentation to learn about the possible arguments for these two methods. -Rails _used_ to have a +country_select+ helper for choosing countries, but this has been extracted to the "country_select plugin":http://github.com/rails/country_select/tree/master. When using this, be aware that the exclusion or inclusion of certain names from the list can be somewhat controversial (and was the reason this functionality was extracted from Rails). +Rails _used_ to have a +country_select+ helper for choosing countries, but this has been extracted to the "country_select plugin":https://github.com/chrislerum/country_select. When using this, be aware that the exclusion or inclusion of certain names from the list can be somewhat controversial (and was the reason this functionality was extracted from Rails). h3. Using Date and Time Form Helpers @@ -549,7 +558,7 @@ will produce the same output if the current year is 2009 and the value chosen by h3. Uploading Files -A common task is uploading some sort of file, whether it's a picture of a person or a CSV file containing data to process. The most important thing to remember with file uploads is that the form's encoding *MUST* be set to "multipart/form-data". If you forget to do this the file will not be uploaded. This can be done by passing +:multi_part => true+ as an HTML option. This means that in the case of +form_tag+ it must be passed in the second options hash and in the case of +form_for+ inside the +:html+ hash. +A common task is uploading some sort of file, whether it's a picture of a person or a CSV file containing data to process. The most important thing to remember with file uploads is that the rendered form's encoding *MUST* be set to "multipart/form-data". If you use +form_for+, this is done automatically. If you use +form_tag+, you must set it yourself, as per the following example. The following two forms both upload a file. @@ -558,11 +567,13 @@ The following two forms both upload a file. <%= file_field_tag 'picture' %> <% end %> -<%= form_for @person, :html => {:multipart => true} do |f| %> +<%= form_for @person do |f| %> <%= f.file_field :picture %> <% end %> </erb> +NOTE: Since Rails 3.1, forms rendered using +form_for+ have their encoding set to <tt>multipart/form-data</tt> automatically once a +file_field+ is used inside the block. Previous versions required you to set this explicitly. + Rails provides the usual pair of helpers: the barebones +file_field_tag+ and the model oriented +file_field+. The only difference with other helpers is that you cannot set a default value for file inputs as this would have no meaning. As you would expect in the first case the uploaded file is in +params[:picture]+ and in the second case in +params[:person][:picture]+. h4. What Gets Uploaded @@ -578,13 +589,13 @@ 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":http://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 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. NOTE: If the user has not selected a file the corresponding parameter will be an empty string. h4. Dealing with Ajax -Unlike other forms making an asynchronous file upload form is not as simple as replacing +form_for+ with +remote_form_for+. With an Ajax form the serialization is done by JavaScript running inside the browser and since JavaScript cannot read files from your hard drive the file cannot be uploaded. The most common workaround is to use an invisible iframe that serves as the target for the form submission. +Unlike other forms making an asynchronous file upload form is not as simple as providing +form_for+ with <tt>:remote => true</tt>. With an Ajax form the serialization is done by JavaScript running inside the browser and since JavaScript cannot read files from your hard drive the file cannot be uploaded. The most common workaround is to use an invisible iframe that serves as the target for the form submission. h3. Customizing Form Builders @@ -631,7 +642,12 @@ action for a Person model, +params[:model]+ would usually be a hash of all the a Fundamentally HTML forms don't know about any sort of structured data, all they generate is name–value pairs, where pairs are just plain strings. The arrays and hashes you see in your application are the result of some parameter naming conventions that Rails uses. -TIP: You may find you can try out examples in this section faster by using the console to directly invoke Rails' parameter parser. For example <tt> ActionController::UrlEncodedPairParser.parse_query_parameters "name=fred&phone=0123456789" # => {"name"=>"fred", "phone"=>"0123456789"} </tt> +TIP: You may find you can try out examples in this section faster by using the console to directly invoke Rails' parameter parser. For example, + +<ruby> +ActionController::UrlEncodedPairParser.parse_query_parameters "name=fred&phone=0123456789" +# => {"name"=>"fred", "phone"=>"0123456789"} +</ruby> h4. Basic Structures @@ -707,7 +723,7 @@ You might want to render a form with a set of edit fields for each of a person's Assuming the person had two addresses, with ids 23 and 45 this would create output similar to this: <html> -<form action="/people/1" class="edit_person" id="edit_person_1" method="post"> +<form accept-charset="UTF-8" action="/people/1" class="edit_person" id="edit_person_1" method="post"> <input id="person_name" name="person[name]" size="30" type="text" /> <input id="person_address_23_city" name="person[address][23][city]" size="30" type="text" /> <input id="person_address_45_city" name="person[address][45][city]" size="30" type="text" /> @@ -748,6 +764,40 @@ As a shortcut you can append [] to the name and omit the +:index+ option. This i produces exactly the same output as the previous example. +h3. Forms to external resources + +If you need to post some data to an external resource it is still great to build your from using rails form helpers. But sometimes you need to set an +authenticity_token+ for this resource. You can do it by passing an +:authenticity_token => 'your_external_token'+ parameter to the +form_tag+ options: + +<erb> +<%= form_tag 'http://farfar.away/form', :authenticity_token => 'external_token') do %> + Form contents +<% end %> +</erb> + +Sometimes when you submit data to an external resource, like payment gateway, fields you can use in your form are limited by an external API. So you may want not to generate an +authenticity_token+ hidden field at all. For doing this just pass +false+ to the +:authenticity_token+ option: + +<erb> +<%= form_tag 'http://farfar.away/form', :authenticity_token => 'external_token') do %> + Form contents +<% end %> +</erb> + +The same technique is available for the +form_for+ too: + +<erb> +<%= form_for @invoice, :url => external_url, :authenticity_token => 'external_token' do |f| + Form contents +<% end %> +</erb> + +Or if you don't want to render an +authenticity_token+ field: + +<erb> +<%= form_for @invoice, :url => external_url, :authenticity_token => false do |f| + Form contents +<% end %> +</erb> + h3. Building Complex Forms Many apps grow beyond simple forms editing a single object. For example when creating a Person you might want to allow the user to (on the same form) create multiple address records (home, work, etc.). When later editing that person the user should be able to add, remove or amend addresses as necessary. While this guide has shown you all the pieces necessary to handle this, Rails does not yet have a standard end-to-end way of accomplishing this, but many have come up with viable approaches. These include: @@ -755,14 +805,13 @@ Many apps grow beyond simple forms editing a single object. For example when cre * As of Rails 2.3, Rails includes "Nested Attributes":./2_3_release_notes.html#nested-attributes and "Nested Object Forms":./2_3_release_notes.html#nested-object-forms * Ryan Bates' series of Railscasts on "complex forms":http://railscasts.com/episodes/75 * Handle Multiple Models in One Form from "Advanced Rails Recipes":http://media.pragprog.com/titles/fr_arr/multiple_models_one_form.pdf -* Eloy Duran's "complex-forms-examples":http://github.com/alloy/complex-form-examples/ application -* Lance Ivy's "nested_assignment":http://github.com/cainlevy/nested_assignment/tree/master plugin and "sample application":http://github.com/cainlevy/complex-form-examples/tree/cainlevy -* James Golick's "attribute_fu":http://github.com/jamesgolick/attribute_fu plugin +* Eloy Duran's "complex-forms-examples":https://github.com/alloy/complex-form-examples/ application +* Lance Ivy's "nested_assignment":https://github.com/cainlevy/nested_assignment/tree/master plugin and "sample application":https://github.com/cainlevy/complex-form-examples/tree/cainlevy +* James Golick's "attribute_fu":https://github.com/jamesgolick/attribute_fu plugin h3. Changelog -"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/1 - +* February 5, 2011: Added 'Forms to external resources' section. Timothy N. Tsvetkov <timothy.tsvetkov@gmail.com> * April 6, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com h3. Authors diff --git a/railties/guides/source/generators.textile b/railties/guides/source/generators.textile index c5b41673e1..d32ba48003 100644 --- a/railties/guides/source/generators.textile +++ b/railties/guides/source/generators.textile @@ -1,6 +1,6 @@ -h2. Creating and Customizing Rails Generators +h2. Creating and Customizing Rails Generators & Templates -Rails generators are an essential tool if you plan to improve your workflow and in this guide you will learn how to create and customize already existing generators. +Rails generators are an essential tool if you plan to improve your workflow. With this guide you will learn how to create generators and customize existing ones. In this guide you will: @@ -10,10 +10,11 @@ In this guide you will: * Customize your scaffold by creating new generators * Customize your scaffold by changing generator templates * Learn how to use fallbacks to avoid overwriting a huge set of generators +* Learn how to create an application template endprologue. -NOTE: This guide is about Rails generators for versions >= 3.0. Rails generators from previous versions are not supported. +NOTE: This guide is about generators in Rails 3, previous versions are not covered. h3. First Contact @@ -33,9 +34,9 @@ $ rails generate helper --help h3. Creating Your First Generator -Since Rails 3.0, generators are built on top of "Thor":http://github.com/wycats/thor. Thor provides powerful options parsing and a great API for manipulating files. For instance, let's build a generator that creates an initializer file named +initializer.rb+ inside +config/initializers+. +Since Rails 3.0, generators are built on top of "Thor":https://github.com/wycats/thor. Thor provides powerful options parsing and a great API for manipulating files. For instance, let's build a generator that creates an initializer file named +initializer.rb+ inside +config/initializers+. -The first step is to create a file at +RAILS_APP/lib/generators/initializer_generator.rb+ with the following content: +The first step is to create a file at +lib/generators/initializer_generator.rb+ with the following content: <ruby> class InitializerGenerator < Rails::Generators::Base @@ -45,6 +46,8 @@ class InitializerGenerator < Rails::Generators::Base end </ruby> +NOTE: +create_file+ is a method provided by +Thor::Actions+ and the documentation for it and its brethren can be found at "rdoc.info":http://rdoc.info/github/wycats/thor/master/Thor/Actions. + Our new generator is quite simple: it inherits from +Rails::Generators::Base+ and has one method definition. Each public method in the generator is executed when a generator is invoked. Finally, we invoke the +create_file+ method that will create a file at the given destination with the given content. If you are familiar with the Rails Application Templates API, you'll feel right at home with the new generators API. To invoke our new generator, we just need to do: @@ -74,7 +77,7 @@ Now we can see the new description by invoking +--help+ on the new generator. Th h3. Creating Generators with Generators -A faster way to create a generator is using the generator's generator: +Generators themselves have a generator: <shell> $ rails generate generator initializer @@ -84,7 +87,7 @@ $ rails generate generator initializer create lib/generators/initializer/templates </shell> -And it will create a new generator as follows: +This is the generator just created: <ruby> class InitializerGenerator < Rails::Generators::NamedBase @@ -92,7 +95,7 @@ class InitializerGenerator < Rails::Generators::NamedBase end </ruby> -First, notice that we are inheriting from +Rails::Generators::NamedBase+ instead of +Rails::Generators::Base+. This means that our generator expects as least one argument, which will be the name of the initializer. +First, notice that we are inheriting from +Rails::Generators::NamedBase+ instead of +Rails::Generators::Base+. This means that our generator expects at least one argument, which will be the name of the initializer, and will be available in our code in the variable +name+. We can see that by invoking the description of this new generator (don't forget to delete the old generator file): @@ -102,7 +105,9 @@ Usage: rails generate initializer NAME [options] </shell> -We can also see in our new generator that it has a class method called +source_root+. This method points to where our generator templates will be placed and by default it points to the created directory under +RAILS_APP/lib/generators/initializer/templates+. In order to understand what a generator template means, let's create a file at +RAILS_APP/lib/generators/initializer/templates/initializer.rb+ with the following content: +We can also see that our new generator has a class method called +source_root+. This method points to where our generator templates will be placed, if any, and by default it points to the created directory +lib/generators/initializer/templates+. + +In order to understand what a generator template means, let's create the file +lib/generators/initializer/templates/initializer.rb+ with the following content: <ruby> # Add initialization content here @@ -124,16 +129,16 @@ end And let's execute our generator: <shell> -$ rails generate initializer foo +$ rails generate initializer core_extensions </shell> -We can see that now a initializer named foo was created at +config/initializers/foo.rb+ with the contents of our template. That means that +copy_file+ copied a file in our source root to the destination path we gave. The method +file_name+ is automatically created when we inherit from +Rails::Generators::NamedBase+. +We can see that now a initializer named core_extensions was created at +config/initializers/core_extensions.rb+ with the contents of our template. That means that +copy_file+ copied a file in our source root to the destination path we gave. The method +file_name+ is automatically created when we inherit from +Rails::Generators::NamedBase+. -h3. Generators Lookup +The methods that are available for generators are covered in the "final section":#generator-methods of this guide. -Now that we've created our first generator, we need to briefly discuss generator lookup. The way Rails finds generators is exactly the same way Ruby find files, i.e. using +$LOAD_PATHS+. +h3. Generators Lookup -For instance, when you say +rails generate initializer foo+, Rails knows you want to invoke the initializer generator and then search for the following generators in the $LOAD_PATHS: +When you run +rails generate initializer core_extensions+ Rails requires these files in turn until one is found: <shell> rails/generators/initializer/initializer_generator.rb @@ -142,11 +147,13 @@ rails/generators/initializer_generator.rb generators/initializer_generator.rb </shell> -If none of them is found, it raises an error message. +If none is found you get an error message. + +INFO: The examples above put files under the application's +lib+ because said directory belongs to +$LOAD_PATH+. h3. Customizing Your Workflow -Rails generators are flexible enough to let you customize your scaffold the way you want. In your +config/application.rb+ there is a section just for generators: +Rails own generators are flexible enough to let you customize scaffolding. They can be configured in +config/application.rb+, these are some defaults: <ruby> config.generators do |g| @@ -166,7 +173,7 @@ $ rails generate scaffold User name:string invoke test_unit create test/unit/user_test.rb create test/fixtures/users.yml - route map.resources :users + route resources :users invoke scaffold_controller create app/controllers/users_controller.rb invoke erb @@ -186,9 +193,9 @@ $ rails generate scaffold User name:string create public/stylesheets/scaffold.css </shell> -Looking at this output, it's easy to understand how generators work on Rails 3.0 and above. The scaffold generator doesn't actually generate anything, it just invokes others to do the work. This allows us to add/replace/remove any of those invocations. For instance, the scaffold generator invokes the scaffold_controller generator, which invokes erb, test_unit and helper generators. Since each generator has a single responsibility, they are easy to reuse, avoiding code duplication. +Looking at this output, it's easy to understand how generators work in Rails 3.0 and above. The scaffold generator doesn't actually generate anything, it just invokes others to do the work. This allows us to add/replace/remove any of those invocations. For instance, the scaffold generator invokes the scaffold_controller generator, which invokes erb, test_unit and helper generators. Since each generator has a single responsibility, they are easy to reuse, avoiding code duplication. -Our first customization on the workflow will be to stop generating stylesheets and test fixtures on scaffold. We can achieve that by changing our application to the following: +Our first customization on the workflow will be to stop generating stylesheets and test fixtures for scaffolds. We can achieve that by changing our configuration to the following: <ruby> config.generators do |g| @@ -199,18 +206,18 @@ config.generators do |g| end </ruby> -If we generate another resource on scaffold, we can notice that neither stylesheets nor fixtures are created anymore. If you want to customize it further, for example to use +Datamapper+ and +RSpec+ instead of +ActiveRecord+ and +TestUnit+, it's just a matter of adding their gems to your application and configuring your generators. +If we generate another resource with the scaffold generator, we can see that neither stylesheets nor fixtures are created anymore. If you want to customize it further, for example to use DataMapper and RSpec instead of Active Record and TestUnit, it's just a matter of adding their gems to your application and configuring your generators. -To demonstrate this, we are going to create a new helper generator that simply adds some instance variable readers. First, we create a generator: +To demonstrate this, we are going to create a new helper generator that simply adds some instance variable readers. First, we create a generator within the rails namespace, as this is where rails searches for generators used as hooks: <shell> -$ rails generate generator my_helper +$ rails generate generator rails/my_helper </shell> After that, we can delete both the +templates+ directory and the +source_root+ class method from our new generators, because we are not going to need them. So our new generator looks like the following: <ruby> -class MyHelperGenerator < Rails::Generators::NamedBase +class Rails::MyHelperGenerator < Rails::Generators::NamedBase def create_helper_file create_file "app/helpers/#{file_name}_helper.rb", <<-FILE module #{class_name}Helper @@ -224,18 +231,18 @@ end We can try out our new generator by creating a helper for users: <shell> -$ rails generate my_helper users +$ rails generate my_helper products </shell> And it will generate the following helper file in +app/helpers+: <ruby> -module UsersHelper - attr_reader :users, :user +module ProductsHelper + attr_reader :products, :product end </ruby> -Which is what we expected. We can now tell scaffold to use our new helper generator by configuring +config/application.rb+ once again: +Which is what we expected. We can now tell scaffold to use our new helper generator by editing +config/application.rb+ once again: <ruby> config.generators do |g| @@ -247,7 +254,7 @@ config.generators do |g| end </ruby> -And see it in action when invoking generator once again: +and see it in action when invoking the generator: <shell> $ rails generate scaffold Post body:text @@ -260,10 +267,10 @@ We can notice on the output that our new helper was invoked instead of the Rails Since Rails 3.0, this is easy to do due to the hooks concept. Our new helper does not need to be focused in one specific test framework, it can simply provide a hook and a test framework just needs to implement this hook in order to be compatible. -To do that, we can change your generator to the following: +To do that, we can change the generator this way: <ruby> -class MyHelperGenerator < Rails::Generators::NamedBase +class Rails::MyHelperGenerator < Rails::Generators::NamedBase def create_helper_file create_file "app/helpers/#{file_name}_helper.rb", <<-FILE module #{class_name}Helper @@ -276,7 +283,7 @@ end end </ruby> -Now, when the helper generator is invoked and TestUnit is configured as the test framework, it will try to invoke both +MyHelper::Generators::TestUnitGenerator+ and +TestUnit::Generators::MyHelperGenerator+. Since none of those are defined, we can tell our generator to invoke +TestUnit::Generators::HelperGenerator+ instead, which is defined since it's a Rails generator. To do that, we just need to add: +Now, when the helper generator is invoked and TestUnit is configured as the test framework, it will try to invoke both +Rails::TestUnitGenerator+ and +TestUnit::MyHelperGenerator+. Since none of those are defined, we can tell our generator to invoke +TestUnit::Generators::HelperGenerator+ instead, which is defined since it's a Rails generator. To do that, we just need to add: <ruby> # Search for :helper instead of :my_helper @@ -287,9 +294,9 @@ And now you can re-run scaffold for another resource and see it generating tests h3. Customizing Your Workflow by Changing Generators Templates -In the step above, we simply wanted to add a line to the generated helper, without adding any extra functionality. There is a simpler way to do that, and it's by replacing the templates of already existing generators. +In the step above we simply wanted to add a line to the generated helper, without adding any extra functionality. There is a simpler way to do that, and it's by replacing the templates of already existing generators, in that case +Rails::Generators::HelperGenerator+. -In Rails 3.0 and above, generators don't just look in the source root for templates, they also search for templates in other paths. And one of them is inside +RAILS_APP/lib/templates+. Since we want to customize +Rails::Generators::HelperGenerator+, we can do that by simply making a template copy inside +RAILS_APP/lib/templates/rails/helper+ with the name +helper.rb+. So let's create that file with the following content: +In Rails 3.0 and above, generators don't just look in the source root for templates, they also search for templates in other paths. And one of them is +lib/templates+. Since we want to customize +Rails::Generators::HelperGenerator+, we can do that by simply making a template copy inside +lib/templates/rails/helper+ with the name +helper.rb+. So let's create that file with the following content: <erb> module <%= class_name %>Helper @@ -297,7 +304,7 @@ module <%= class_name %>Helper end </erb> -So now we can revert the changes in +config/application.rb+: +and revert the last change in +config/application.rb+: <ruby> config.generators do |g| @@ -308,11 +315,11 @@ config.generators do |g| end </ruby> -If you generate another resource, you can see that we got exactly the same result! This is useful if you want to customize your scaffold templates and/or layout by just creating +edit.html.erb+, +index.html.erb+ and so on inside +RAILS_APP/lib/templates/erb/scaffold+. +If you generate another resource, you can see that we get exactly the same result! This is useful if you want to customize your scaffold templates and/or layout by just creating +edit.html.erb+, +index.html.erb+ and so on inside +lib/templates/erb/scaffold+. h3. Adding Generators Fallbacks -One last feature about generators which is quite useful for plugin generators is fallbacks. For example, imagine that you want to add a feature on top of TestUnit test framework, like "shoulda":http://github.com/thoughtbot/shoulda does. Since TestUnit already implements all generators required by Rails and shoulda just wants to overwrite part of it, there is no need for shoulda to reimplement some generators again, it can simply tell Rails to use a +TestUnit+ generator if none was found under the +Shoulda+ namespace. +One last feature about generators which is quite useful for plugin generators is fallbacks. For example, imagine that you want to add a feature on top of TestUnit like "shoulda":https://github.com/thoughtbot/shoulda does. Since TestUnit already implements all generators required by Rails and shoulda just wants to overwrite part of it, there is no need for shoulda to reimplement some generators again, it can simply tell Rails to use a +TestUnit+ generator if none was found under the +Shoulda+ namespace. We can easily simulate this behavior by changing our +config/application.rb+ once again: @@ -328,7 +335,7 @@ config.generators do |g| end </ruby> -Now, if you create a Comment scaffold, you will see that the shoulda generators are being invoked, and at the end, they are just falling back to test unit generators: +Now, if you create a Comment scaffold, you will see that the shoulda generators are being invoked, and at the end, they are just falling back to TestUnit generators: <shell> $ rails generate scaffold Comment body:text @@ -338,7 +345,7 @@ $ rails generate scaffold Comment body:text invoke shoulda create test/unit/comment_test.rb create test/fixtures/comments.yml - route map.resources :comments + route resources :comments invoke scaffold_controller create app/controllers/comments_controller.rb invoke erb @@ -359,9 +366,258 @@ $ rails generate scaffold Comment body:text Fallbacks allow your generators to have a single responsibility, increasing code reuse and reducing the amount of duplication. +h3. Application templates + +Now that you've seen how generators can be used _inside_ an application, did you know they can also be used to _generate_ applications too? This kind of generator is referred as a "template". + +<ruby> +gem("rspec-rails", :group => "test") +gem("cucumber-rails", :group => "test") + +if yes?("Would you like to install Devise?") + gem("devise") + generate("devise:install") + model_name = ask("What would you like the user model to be called? [user]") + model_name = "user" if model_name.blank? + generate("devise", model_name) +end +</ruby> + +In the above template we specify that the application relies on the +rspec-rails+ and +cucumber-rails+ gem so these two will be added to the +test+ group in the +Gemfile+. Then we pose a question to the user about whether or not they would like to install Devise. If the user replies "y" or "yes" to this question, then the template will add Devise to the +Gemfile+ outside of any group and then runs the +devise:install+ generator. This template then takes the users input and runs the +devise+ generator, with the user's answer from the last question being passed to this generator. + +Imagine that this template was in a file called +template.rb+. We can use it to modify the outcome of the +rails new+ command by using the +-m+ option and passing in the filename: + +<shell> +$ rails new thud -m template.rb +</shell> + +This command will generate the +Thud+ application, and then apply the template to the generated output. + +Templates don't have to be stored on the local system, the +-m+ option also supports online templates: + +<shell> +$ rails new thud -m https://gist.github.com/722911.txt +</shell> + +Whilst the final section of this guide doesn't cover how to generate the most awesome template known to man, it will take you through the methods available at your disposal so that you can develop it yourself. These same methods are also available for generators. + +h3. Generator methods + +The following are methods available for both generators and templates for Rails. + +NOTE: Methods provided by Thor are not covered this guide and can be found in "Thor's documentation":http://rdoc.info/github/wycats/thor/master/Thor/Actions.html + +h4. +plugin+ + ++plugin+ will install a plugin into the current application. + +<ruby> + plugin("dynamic-form", :git => "git://github.com/rails/dynamic-form.git") +</ruby> + +Available options are: + +* +:git+ - Takes the path to the git repository where this plugin can be found. +* +:branch+ - The name of the branch of the git repository where the plugin is found. +* +:submodule+ - Set to +true+ for the plugin to be installed as a submodule. Defaults to +false+. +* +:svn+ - Takes the path to the svn repository where this plugin can be found. +* +:revision+ - The revision of the plugin in an SVN repository. + +h4. +gem+ + +Specifies a gem dependency of the application. + +<ruby> +gem("rspec", :group => "test", :version => "2.1.0") +gem("devise", "1.1.5") +</ruby> + +Available options are: + +* +:group+ - The group in the +Gemfile+ where this gem should go. +* +:version+ - The version string of the gem you want to use. Can also be specified as the second argument to the method. +* +:git+ - The URL to the git repository for this gem. + +Any additional options passed to this method are put on the end of the line: + +<ruby> + gem("devise", :git => "git://github.com/plataformatec/devise", :branch => "master") +</ruby> + +The above code will put the following line into +Gemfile+: + +<ruby> + gem "devise", :git => "git://github.com/plataformatec/devise", :branch => "master" +</ruby> + + +h4. +add_source+ + +Adds a specified source to +Gemfile+: + +<ruby> + add_source "http://gems.github.com" +</ruby> + +h4. +application+ + +Adds a line to +config/application.rb+ directly after the application class definition. + +<ruby> + application "config.asset_host = 'http://example.com'" +</ruby> + +This method can also take a block: + +<ruby> +application do + "config.asset_host = 'http://example.com'" +end +</ruby> + +Available options are: + +* +:env+ - Specify an environment for this configuration option. If you wish to use this option with the block syntax the recommended syntax is as follows: + +<ruby> +application(nil, :env => "development") do + "config.asset_host = 'http://localhost:3000'" +end +</ruby> + +h4. +git+ + +Runs the specified git command: + +<ruby> + git :init + git :add => "." + git :commit => "-m First commit!" + git :add => "onefile.rb", :rm => "badfile.cxx" +</ruby> + +The values of the hash here being the arguments or options passed to the specific git command. As per the final example shown here, multiple git commands can be specified at a time, but the order of their running is not guaranteed to be the same as the order that they were specified in. + +h4. +vendor+ + +Places a file into +vendor+ which contains the specified code. + +<ruby> + vendor("sekrit.rb", '#top secret stuff') +</ruby> + +This method also takes a block: + +<ruby> + vendor("seeds.rb") do + "puts 'in ur app, seeding ur database'" + end +</ruby> + +h4. +lib+ + +Places a file into +lib+ which contains the specified code. + +<ruby> + lib("special.rb", 'p Rails.root') +</ruby> + +This method also takes a block: + +<ruby> +lib("super_special.rb") do + puts "Super special!" +end +</ruby> + +h4. +rakefile+ + +Creates a Rake file in the +lib/tasks+ directory of the application. + +<ruby> + rakefile("test.rake", 'hello there') +</ruby> + +This method also takes a block: + +<ruby> +rakefile("test.rake") do + %Q{ + task :rock => :environment do + puts "Rockin'" + end + } +end +</ruby> + +h4. +initializer+ + +Creates an initializer in the +config/initializers+ directory of the application: + +<ruby> + initializer("begin.rb", "puts 'this is the beginning'") +</ruby> + +This method also takes a block: + +<ruby> +initializer("begin.rb") do + puts "Almost done!" +end +</ruby> + +h4. +generate+ + +Runs the specified generator where the first argument is the generator name and the remaining arguments are passed directly to the generator. + +<ruby> + generate("scaffold", "forums title:string description:text") +</ruby> + + +h4. +rake+ + +Runs the specified Rake task. + +<ruby> + rake("db:migrate") +</ruby> + +Available options are: + +* +:env+ - Specifies the environment in which to run this rake task. +* +:sudo+ - Whether or not to run this task using +sudo+. Defaults to +false+. + +h4. +capify!+ + +Runs the +capify+ command from Capistrano at the root of the application which generates Capistrano configuration. + +<ruby> + capify! +</ruby> + +h4. +route+ + +Adds text to the +config/routes.rb+ file: + +<ruby> + route("resources :people") +</ruby> + +h4. +readme+ + +Output the contents of a file in the template's +source_path+, usually a README. + +<ruby> + readme("README") +</ruby> + h3. Changelog -"Lighthouse Ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/102 +* December 1, 2010: Documenting the available methods and options for generators and templates by "Ryan Bigg":http://ryanbigg.com +* December 1, 2010: Addition of Rails application templates by "Ryan Bigg":http://ryanbigg.com + +* August 23, 2010: Edit pass by "Xavier Noria":credits.html#fxn * April 30, 2010: Reviewed by José Valim diff --git a/railties/guides/source/getting_started.textile b/railties/guides/source/getting_started.textile index ffb0310816..0661549644 100644 --- a/railties/guides/source/getting_started.textile +++ b/railties/guides/source/getting_started.textile @@ -110,7 +110,7 @@ Active Resource provides a framework for managing the connection between busines h5. Active Support -Active Support is an extensive collection of utility classes and standard Ruby library extensions that are used in the Rails, both by the core code and by your applications. +Active Support is an extensive collection of utility classes and standard Ruby library extensions that are used in Rails, both by the core code and by your applications. h5. Railties @@ -149,13 +149,11 @@ Usually run this as the root user: # gem install rails </shell> -NOTE. In the Rails 3.0.0-beta, you will need to manually install the dependencies for Rails itself as a bug in rubygems will cause these to not be installed, see the "3.0 Release Notes":3_0_release_notes.html for the commands to run. - -TIP. If you're working on Windows, you may find it easier to install "Instant Rails":http://instantrails.rubyforge.org/wiki/wiki.pl. Be aware, though, that Instant Rails releases tend to lag seriously behind the actual Rails version. Also, you will find that Rails development on Windows is overall less pleasant than on other operating systems. If at all possible, we suggest that you install a Linux virtual machine and use that for Rails development, instead of using Windows. +TIP. If you're working on Windows, you can quickly install Ruby and Rails with "Rails Installer":http://railsinstaller.org. h4. Creating the Blog Application -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. If you need to see the completed code, you can download it from "Getting Started Code":http://github.com/mikel/getting-started-code. +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. If you need to see the completed code, you can download it from "Getting Started Code":https://github.com/mikel/getting-started-code. To begin, open a terminal, navigate to a folder where you have rights to create files, and type: @@ -165,7 +163,7 @@ $ rails new blog This will create a Rails application called Blog in a directory called blog. -TIP: You can see all of the switches that the Rails application builder accepts by running <tt>rails -h</tt>. +TIP: You can see all of the switches that the Rails application builder accepts by running <tt>rails new -h</tt>. After you create the blog application, switch to its folder to continue work directly in that application: @@ -177,7 +175,7 @@ In any case, Rails will create a folder in your working directory called <tt>blo |_.File/Folder|_.Purpose| |Gemfile|This file allows you to specify what gem dependencies are needed for your Rails application.| -|README.rdoc|This is a brief instruction manual for your application. Use it to tell others what your application does, how to set it up, and so on.| +|README|This is a brief instruction manual for your application. Use it to tell others what your application does, how to set it up, and so on.| |Rakefile|This file contains batch jobs that can be run from the terminal.| |app/|Contains the controllers, models, and views 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.| @@ -186,7 +184,7 @@ In any case, Rails will create a folder in your working directory called <tt>blo |doc/|In-depth documentation for your application.| |lib/|Extended modules for your application (not covered in this guide).| |log/|Application log files.| -|public/|The only folder seen to the world as-is. This is where your images, javascript, stylesheets (CSS), and other static files go.| +|public/|The only folder seen to the world as-is. This is where your images, JavaScript files, stylesheets (CSS), and other static files go.| |script/|Contains the rails script that starts your app and can contain other scripts you use to deploy or run your application.| |test/|Unit tests, fixtures, and other test apparatus. These are covered in "Testing Rails Applications":testing.html| |tmp/|Temporary files| @@ -194,15 +192,13 @@ In any case, Rails will create a folder in your working directory called <tt>blo h4. Installing the Required Gems -Rails uses the "Bundler":http://www.github.com/carlhuda/bundler gem to populate the +vendor+ directory with all the gems your application depends on. As we don't need any special gems beyond the default, we just need to do the following: +Rails applications manage gem dependencies with "Bundler":http://gembundler.com/v1.0/index.html by default. As we don't need any other gems beyond the ones in the generated +Gemfile+ we can directly run <shell> -As the root user: -# gem install bundler -# bundle install +$ bundle install </shell> -This will copy down the versions of all the gems you need to start a rails application. +to have them ready. h4. Configuring a Database @@ -231,11 +227,11 @@ NOTE: In this guide we are using an SQLite3 database for data storage, because i h5. Configuring a MySQL Database -If you choose to use MySQL instead of the shipped Sqlite3 database, your +config/database.yml+ will look a little different. Here's the development section: +If you choose to use MySQL instead of the shipped SQLite3 database, your +config/database.yml+ will look a little different. Here's the development section: <yaml> development: - adapter: mysql + adapter: mysql2 encoding: utf8 database: blog_development pool: 5 @@ -262,6 +258,8 @@ development: Change the username and password in the +development+ section as appropriate. +TIP: You don't have to update the database configurations manually. If you had a look at the options of application generator, you have seen that one of them is named <tt>--database</tt>. It lets you choose an adapter for couple of most used relational databases. You can even run the generator repeatedly: <tt>cd .. && rails new blog --database=mysql</tt>. When you confirm the overwriting of the +config/database.yml+ file, your application will be configured for MySQL instead of SQLite. + h4. Creating the Database Now that you have your database configured, it's time to have Rails create an empty database for you. You can do this by running a rake command: @@ -276,7 +274,7 @@ TIP: Rake is a general-purpose command-runner that Rails uses for many things. Y h3. Hello, Rails! -One of the traditional places to start with a new language is by getting some text up on screen quickly, to do this, you need to get your Rails application server running. +One of the traditional places to start with a new language is by getting some text up on screen quickly. To do this, you need to get your Rails application server running. h4. Starting up the Web Server @@ -286,7 +284,7 @@ You actually have a functional Rails application already. To see it, you need to $ rails server </shell> -This will fire up an instance of the Mongrel web server by default (Rails can also use several other web servers). 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 the WEBrick web server by default (Rails can also use several other web servers). 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: !images/rails_welcome.png(Welcome Aboard screenshot)! @@ -302,7 +300,7 @@ To get Rails saying "Hello", you need to create at minimum a controller and a vi $ rails generate controller home index </shell> -TIP: If you're on Windows, or your Ruby is set up in some non-standard fashion, you may need to explicitly pass Rails +rails+ commands to Ruby: +ruby \path\to\rails controller home index+. +TIP: If you're on Windows, or your Ruby is set up in some non-standard fashion, you may need to explicitly pass Rails +rails+ commands to Ruby: <tt>ruby \path\to\your\application\script\rails generate controller home index</tt>. Rails will create several files for you, including +app/views/home/index.html.erb+. This is the template that will be used to display the results of the +index+ action (method) in the +home+ controller. Open this file in your text editor and edit it to contain a single line of code: @@ -320,9 +318,9 @@ The first step to doing this is to delete the default page from your application $ rm public/index.html </shell> -We need to do this as Rails will deliver any static file in the +public+ directory in preference to any dynamic contact we generate from the controllers. +We need to do this as Rails will deliver any static file in the +public+ directory in preference to any dynamic content we generate from the controllers. -Now, you have to tell Rails where your actual home page is located. Open the file +config/routes.rb+ in your editor. This is your application's _routing file_ which holds entries in a special DSL (domain-specific language) that tells Rails how to connect incoming requests to controllers and actions. This file contains many sample routes on commented lines, and one of them actually shows you how to connect the root of your site to a specific controller and action. Find the line beginning with +:root to+, uncomment it and change it like the following: +Now, you have to tell Rails where your actual home page is located. Open the file +config/routes.rb+ in your editor. This is your application's _routing file_ which holds entries in a special DSL (domain-specific language) that tells Rails how to connect incoming requests to controllers and actions. This file contains many sample routes on commented lines, and one of them actually shows you how to connect the root of your site to a specific controller and action. Find the line beginning with +root :to+, uncomment it and change it like the following: <ruby> Blog::Application.routes.draw do @@ -351,12 +349,12 @@ In the case of the blog application, you can start by generating a scaffolded Po $ rails generate scaffold Post name:string title:string content:text </shell> -NOTE. While scaffolding will get you up and running quickly, the "one size fits all" code that it generates is unlikely to be a perfect fit for your application. In most cases, you'll need to customize the generated code. Many experienced Rails developers avoid scaffolding entirely, preferring to write all or most of their source code from scratch. +NOTE. While scaffolding will get you up and running quickly, the code it generates is unlikely to be a perfect fit for your application. You'll most probably want to customize the generated code. Many experienced Rails developers avoid scaffolding entirely, preferring to write all or most of their source code from scratch. Rails, however, makes it really simple to customize templates for generated models, controllers, views and other source files. You'll find more information in the "Creating and Customizing Rails Generators & Templates":generators.html guide. The scaffold generator will build 15 files in your application, along with some folders, and edit one more. Here's a quick overview of what it creates: |_.File |_.Purpose| -|db/migrate/20100207214725_create_posts.rb.rb |Migration to create the posts table in your database (your name will include a different timestamp)| +|db/migrate/20100207214725_create_posts.rb |Migration to create the posts table in your database (your name will include a different timestamp)| |app/models/post.rb |The Post model| |test/fixtures/posts.yml |Dummy posts for use in testing| |app/controllers/posts_controller.rb |The Posts controller| @@ -413,7 +411,7 @@ Rails will execute this migration command and tell you it created the Posts tabl == CreatePosts: migrated (0.0020s) =========================================== </shell> -NOTE. Because you're working in the development environment by default, this command will apply to the database defined in the +development+ section of your +config/database.yml+ file. +NOTE. Because you're working in the development environment by default, this command will apply to the database defined in the +development+ section of your +config/database.yml+ file. If you would like to execute migrations in other environment, for instance in production, you must explicitly pass it when invoking the command: <tt>rake db:migrate RAILS_ENV=production</tt>. h4. Adding a Link @@ -471,28 +469,32 @@ To see your validations in action, you can use the console. The console is a com $ rails console </shell> +TIP: The default console will make changes to your database. You can instead open a console that will roll back any changes you make by using +rails console --sandbox+. + After the console loads, you can use it to work with your application's models: <shell> >> p = Post.new(:content => "A new post") -=> #<Post id: nil, name: nil, title: nil, +=> #<Post id: nil, name: nil, title: nil, content: "A new post", created_at: nil, updated_at: nil> >> p.save => false >> p.errors -=> #<OrderedHash { :title=>["can't be blank", +=> #<OrderedHash { :title=>["can't be blank", "is too short (minimum is 5 characters)"], :name=>["can't be blank"] }> </shell> This code shows creating a new +Post+ instance, attempting to save it and getting +false+ for a return value (indicating that the save failed), and inspecting the +errors+ of the post. +When you're finished, type +exit+ and hit +return+ to exit the console. + TIP: Unlike the development web server, the console does not automatically load your code afresh for each line. If you make changes to your models while the console is open, type +reload!+ at the console prompt to load them. h4. Listing All Posts -The easiest place to start looking at functionality is with the code that lists all posts. Open the file +app/controllers/posts_controller.rb + and look at the +index+ action: +The easiest place to start looking at functionality is with the code that lists all posts. Open the file +app/controllers/posts_controller.rb+ and look at the +index+ action: <ruby> def index @@ -505,7 +507,7 @@ def index end </ruby> -+Post.all+ calls the +Post+ model to return all of the posts currently in the database. The result of this call is an array containing the posts which has been saved in an instance variable called +@posts+. ++Post.all+ calls the +Post+ model to return all of the posts currently in the database. The result of this call is an array of posts that we store in a instance variable called +@posts+. TIP: For more information on finding records with Active Record, see "Active Record Query Interface":active_record_querying.html. @@ -552,7 +554,7 @@ TIP: For more details on the rendering process, see "Layouts and Rendering in Ra h4. Customizing the Layout -The view is only part of the story of how HTML is displayed in your web browser. Rails also has the concept of +layouts+, which are containers for views. When Rails renders a view to the browser, it does so by putting the view's HTML into a layout's HTML. In previous versions of Rails, the +rails generate scaffold+ command would automatically create a controller specific layout, like +app/views/layouts/posts.html.erb+, for the posts controller. However this has been changed in Rails 3.0. A application specific +layout+ is used for all the controllers and can be found in +app/views/layouts/application.html.erb+. Open this layout in your editor and modify the +body+ tag: +The view is only part of the story of how HTML is displayed in your web browser. Rails also has the concept of +layouts+, which are containers for views. When Rails renders a view to the browser, it does so by putting the view's HTML into a layout's HTML. In previous versions of Rails, the +rails generate scaffold+ command would automatically create a controller specific layout, like +app/views/layouts/posts.html.erb+, for the posts controller. However this has been changed in Rails 3.0. An application specific +layout+ is used for all the controllers and can be found in +app/views/layouts/application.html.erb+. Open this layout in your editor and modify the +body+ tag: <erb> <!DOCTYPE html> @@ -561,7 +563,7 @@ The view is only part of the story of how HTML is displayed in your web browser. <title>Blog</title> <%= stylesheet_link_tag :all %> <%= javascript_include_tag :defaults %> - <%= csrf_meta_tag %> + <%= csrf_meta_tags %> </head> <body style="background: #EEEEEE;"> @@ -668,7 +670,7 @@ The +create+ action instantiates a new Post object from the data supplied by the If the post was not successfully saved, due to a validation error, then the controller returns the user back to the +new+ action with any error messages so that the user has the chance to fix the error and try again. -The "Post was successfully created" message is stored inside of the Rails +flash+ hash, (usually just called the Flash) so that messages can be carried over to another action, providing the user with useful information on the status of their request. In the case of +create+, the user never actually sees any page rendered during the Post creation process, because it immediately redirects to the new Post as soon Rails saves the record. The Flash carries over a message to the next action, so that when the user is redirected back to the +show+ action, they are presented with a message saying "Post was successfully created." +The "Post was successfully created." message is stored inside of the Rails +flash+ hash, (usually just called _the flash_) so that messages can be carried over to another action, providing the user with useful information on the status of their request. In the case of +create+, the user never actually sees any page rendered during the Post creation process, because it immediately redirects to the new Post as soon Rails saves the record. The Flash carries over a message to the next action, so that when the user is redirected back to the +show+ action, they are presented with a message saying "Post was successfully created." h4. Showing an Individual Post @@ -729,7 +731,6 @@ After finding the requested post, Rails uses the +edit.html.erb+ view to display <%= link_to 'Show', @post %> | <%= link_to 'Back', posts_path %> -<% end %> </erb> Again, as with the +new+ action, the +edit+ action is using the +form+ partial, this time however, the form will do a PUT action to the PostsController and the submit button will display "Update Post" @@ -742,7 +743,7 @@ def update respond_to do |format| if @post.update_attributes(params[:post]) - format.html { redirect_to(@post, + format.html { redirect_to(@post, :notice => 'Post was successfully updated.') } format.xml { head :ok } else @@ -814,6 +815,8 @@ class CreateComments < ActiveRecord::Migration t.timestamps end + + add_index :comments, :post_id end def self.down @@ -822,7 +825,7 @@ class CreateComments < ActiveRecord::Migration end </ruby> -The +t.references+ line sets up a foreign key column for the association between the two models. Go ahead and run the migration: +The +t.references+ line sets up a foreign key column for the association between the two models. And the +add_index+ line sets up an index for this association column. Go ahead and run the migration: <shell> $ rake db:migrate @@ -922,8 +925,6 @@ So first, we'll wire up the Post show template (+/app/views/posts/show.html.erb+ <h2>Add a comment:</h2> <%= form_for([@post, @post.comments.build]) do |f| %> - <%= f.error_messages %> - <div class="field"> <%= f.label :commenter %><br /> <%= f.text_field :commenter %> @@ -992,8 +993,6 @@ Once we have made the new comment, we send the user back to the original post us <h2>Add a comment:</h2> <%= form_for([@post, @post.comments.build]) do |f| %> - <%= f.error_messages %> - <div class="field"> <%= f.label :commenter %><br /> <%= f.text_field :commenter %> @@ -1015,7 +1014,7 @@ Once we have made the new comment, we send the user back to the original post us Now you can add posts and comments to your blog and have them show up in the right places. -h3. Refactorization +h3. Refactoring Now that we have Posts and Comments working, if we take a look at the +app/views/posts/show.html.erb+ template, it's getting long and awkward. We can use partials to clean this up. @@ -1056,13 +1055,10 @@ Then in the +app/views/posts/show.html.erb+ you can change it to look like the f </p> <h2>Comments</h2> -<%= render :partial => "comments/comment", - :collection => @post.comments %> +<%= render @post.comments %> <h2>Add a comment:</h2> <%= form_for([@post, @post.comments.build]) do |f| %> - <%= f.error_messages %> - <div class="field"> <%= f.label :commenter %><br /> <%= f.text_field :commenter %> @@ -1090,8 +1086,6 @@ Lets also move that new comment section out to it's own partial, again, you crea <erb> <%= form_for([@post, @post.comments.build]) do |f| %> - <%= f.error_messages %> - <div class="field"> <%= f.label :commenter %><br /> <%= f.text_field :commenter %> @@ -1127,8 +1121,7 @@ Then you make the +app/views/posts/show.html.erb+ look like the following: </p> <h2>Comments</h2> -<%= render :partial => "comments/comment", - :collection => @post.comments %> +<%= render @post.comments %> <h2>Add a comment:</h2> <%= render "comments/form" %> @@ -1139,7 +1132,7 @@ Then you make the +app/views/posts/show.html.erb+ look like the following: <%= link_to 'Back to Posts', posts_path %> | </erb> -The second render just defines the partial template we want to render, <tt>comments/form</tt>, Rails is smart enough to spot the forward slash in that string and realise that you want to render the <tt>_form.html.erb</tt> file in the <tt>app/views/comments</tt> directory. +The second render just defines the partial template we want to render, <tt>comments/form</tt>, Rails is smart enough to spot the forward slash in that string and realize that you want to render the <tt>_form.html.erb</tt> file in the <tt>app/views/comments</tt> directory. The +@post+ object is available to any partials rendered in the view because we defined it as an instance variable. @@ -1213,15 +1206,15 @@ Rails provides a very simple HTTP authentication system that will work nicely in <ruby> class ApplicationController < ActionController::Base protect_from_forgery - + private - + def authenticate authenticate_or_request_with_http_basic do |user_name, password| user_name == 'admin' && password == 'password' end end - + end </ruby> @@ -1277,7 +1270,7 @@ Again, run the migration to create the database table: $ rake db:migrate </shell> -Next, edit the +post.rb+ file to create the other side of the association, and to tell Rails (via the +accepts_nested_attributes+ macro) that you intend to edit tags via posts: +Next, edit the +post.rb+ file to create the other side of the association, and to tell Rails (via the +accepts_nested_attributes_for+ macro) that you intend to edit tags via posts: <ruby> class Post < ActiveRecord::Base @@ -1381,8 +1374,7 @@ Finally, we will edit the <tt>app/views/posts/show.html.erb</tt> template to sho </p> <h2>Comments</h2> -<%= render :partial => "comments/comment", - :collection => @post.comments %> +<%= render @post.comments %> <h2>Add a comment:</h2> <%= render "comments/form" %> @@ -1405,7 +1397,7 @@ Open up <tt>app/helpers/posts_helper.rb</tt> and add the following: <erb> module PostsHelper def join_tags(post) - post.tags.map { |t| t.name }.join(", ") + post.tags.map { |t| t.name }.join(", ") end end </erb> @@ -1436,8 +1428,7 @@ Now you can edit the view in <tt>app/views/posts/show.html.erb</tt> to look like </p> <h2>Comments</h2> -<%= render :partial => "comments/comment", - :collection => @post.comments %> +<%= render @post.comments %> <h2>Add a comment:</h2> <%= render "comments/form" %> @@ -1451,7 +1442,8 @@ h3. What's Next? Now that you've seen your first Rails application, you should feel free to update it and experiment on your own. But you don't have to do everything without help. As you need assistance getting up and running with Rails, feel free to consult these support resources: -* The "Ruby On Rails guides":index.html +* The "Ruby on Rails guides":index.html +* The "Ruby on Rails Tutorial":http://railstutorial.org/book * The "Ruby on Rails mailing list":http://groups.google.com/group/rubyonrails-talk * The "#rubyonrails":irc://irc.freenode.net/#rubyonrails channel on irc.freenode.net * The "Rails Wiki":http://wiki.rubyonrails.org/ @@ -1483,8 +1475,7 @@ Two very common sources of data that are not UTF-8: h3. Changelog -"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/2 - +* August 30, 2010: Minor editing after Rails 3 release by "Joost Baaij":http://www.spacebabies.nl * July 12, 2010: Fixes, editing and updating of code samples by "Jaime Iniesta":http://jaimeiniesta.com * May 16, 2010: Added a section on configuration gotchas to address common encoding problems that people might have by "Yehuda Katz":http://www.yehudakatz.com * April 30, 2010: Fixes, editing and updating of code samples by "Rohit Arondekar":http://rohitarondekar.com diff --git a/railties/guides/source/i18n.textile b/railties/guides/source/i18n.textile index 63d22db485..3e7e396e8d 100644 --- a/railties/guides/source/i18n.textile +++ b/railties/guides/source/i18n.textile @@ -1,4 +1,4 @@ -h2. Rails Internationalization (I18n) API +lh2. Rails Internationalization (I18n) API The Ruby I18n (shorthand for _internationalization_) gem which is shipped with Ruby on Rails (starting from Rails 2.2) provides an easy-to-use and extensible framework for *translating your application to a single custom language* other than English or for *providing multi-language support* in your application. @@ -10,7 +10,7 @@ So, in the process of _internationalizing_ your Rails application you have to: * Tell Rails where to find locale dictionaries * Tell Rails how to set, preserve and switch locale -In the process of _localizing_ your application you'll probably want to do following three things: +In the process of _localizing_ your application you'll probably want to do the following three things: * Replace or supplement Rails' default locale -- e.g. date and time formats, month names, Active Record model names, etc * Abstract strings in your application into keyed dictionaries -- e.g. flash messages, static text in your views, etc. @@ -87,11 +87,11 @@ en: hello: "Hello world" </ruby> -This means, that in the +:en+ locale, the key _hello_ will map to the _Hello world_ string. Every string inside Rails is internationalized in this way, see for instance Active Record validation messages in the "+activerecord/lib/active_record/locale/en.yml+":http://github.com/rails/rails/blob/master/activerecord/lib/active_record/locale/en.yml file or time and date formats in the "+activesupport/lib/active_support/locale/en.yml+":http://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml file. You can use YAML or standard Ruby Hashes to store translations in the default (Simple) backend. +This means, that in the +:en+ locale, the key _hello_ will map to the _Hello world_ string. Every string inside Rails is internationalized in this way, see for instance Active Record validation messages in the "+activerecord/lib/active_record/locale/en.yml+":https://github.com/rails/rails/blob/master/activerecord/lib/active_record/locale/en.yml file or time and date formats in the "+activesupport/lib/active_support/locale/en.yml+":https://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml file. You can use YAML or standard Ruby Hashes to store translations in the default (Simple) backend. The I18n library will use *English* as a *default locale*, i.e. if you don't set a different locale, +:en+ will be used for looking up translations. -NOTE: The i18n library takes a *pragmatic approach* to locale keys (after "some discussion":http://groups.google.com/group/rails-i18n/browse_thread/thread/14dede2c7dbe9470/80eec34395f64f3c?hl=en), including only the _locale_ ("language") part, like +:en+, +:pl+, not the _region_ part, like +:en-US+ or +:en-UK+, which are traditionally used for separating "languages" and "regional setting" or "dialects". Many international applications use only the "language" element of a locale such as +:cz+, +:th+ or +:es+ (for Czech, Thai and Spanish). However, there are also regional differences within different language groups that may be important. For instance, in the +:en-US+ locale you would have $ as a currency symbol, while in +:en-UK+, you would have £. Nothing stops you from separating regional and other settings in this way: you just have to provide full "English - United Kingdom" locale in a +:en-UK+ dictionary. Various "Rails I18n plugins":http://rails-i18n.org/wiki such as "Globalize2":http://github.com/joshmh/globalize2/tree/master may help you implement it. +NOTE: The i18n library takes a *pragmatic approach* to locale keys (after "some discussion":http://groups.google.com/group/rails-i18n/browse_thread/thread/14dede2c7dbe9470/80eec34395f64f3c?hl=en), including only the _locale_ ("language") part, like +:en+, +:pl+, not the _region_ part, like +:en-US+ or +:en-UK+, which are traditionally used for separating "languages" and "regional setting" or "dialects". Many international applications use only the "language" element of a locale such as +:cz+, +:th+ or +:es+ (for Czech, Thai and Spanish). However, there are also regional differences within different language groups that may be important. For instance, in the +:en-US+ locale you would have $ as a currency symbol, while in +:en-UK+, you would have £. Nothing stops you from separating regional and other settings in this way: you just have to provide full "English - United Kingdom" locale in a +:en-UK+ dictionary. Various "Rails I18n plugins":http://rails-i18n.org/wiki such as "Globalize2":https://github.com/joshmh/globalize2/tree/master may help you implement it. The *translations load path* (+I18n.load_path+) is just a Ruby Array of paths to your translation files that will be loaded automatically and available in your application. You can pick whatever directory and translation file naming scheme makes sense for you. @@ -127,7 +127,7 @@ If you want to translate your Rails application to a *single language other than However, you would probably like to *provide support for more locales* in your application. In such case, you need to set and pass the locale between requests. -WARNING: You may be tempted to store the chosen locale in a _session_ or a _cookie_. *Do not do so*. The locale should be transparent and a part of the URL. This way you don't break people's basic assumptions about the web itself: if you send a URL of some page to a friend, she should see the same page, same content. A fancy word for this would be that you're being "_RESTful_":http://en.wikipedia.org/wiki/Representational_State_Transfer. Read more about the RESTful approach in "Stefan Tilkov's articles":http://www.infoq.com/articles/rest-introduction. There may be some exceptions to this rule, which are discussed below. +WARNING: You may be tempted to store the chosen locale in a _session_ or a <em>cookie</em>. *Do not do so*. The locale should be transparent and a part of the URL. This way you don't break people's basic assumptions about the web itself: if you send a URL of some page to a friend, she should see the same page, same content. A fancy word for this would be that you're being "<em>RESTful</em>":http://en.wikipedia.org/wiki/Representational_State_Transfer. Read more about the RESTful approach in "Stefan Tilkov's articles":http://www.infoq.com/articles/rest-introduction. There may be some exceptions to this rule, which are discussed below. The _setting part_ is easy. You can set the locale in a +before_filter+ in the +ApplicationController+ like this: @@ -231,6 +231,17 @@ end Now, when you call the +books_path+ method you should get +"/en/books"+ (for the default locale). An URL like +http://localhost:3001/nl/books+ should load the Netherlands locale, then, and following calls to +books_path+ should return +"/nl/books"+ (because the locale changed). +If you don't want to force the use of a locale in your routes you can use an optional path scope (donated by the use brackets) like so: + +<ruby> +# config/routes.rb +scope "(:locale)", :locale => /en|nl/ do + resources :books +end +</ruby> + +With this approach you will not get a +Routing Error+ when accessing your resources such as +http://localhost:3001/books+ without a locale. This is useful for when you want to use the default locale when one is not specified. + Of course, you need to take special care of the root URL (usually "homepage" or "dashboard") of your application. An URL like +http://localhost:3001/nl+ will not work automatically, because the +root :to => "books#index"+ declaration in your +routes.rb+ doesn't take locale into account. (And rightly so: there's only one "root" URL.) You would probably need to map URLs like these: @@ -242,7 +253,7 @@ match '/:locale' => 'dashboard#index' Do take special care about the *order of your routes*, so this route declaration does not "eat" other ones. (You may want to add it directly before the +root :to+ declaration.) -IMPORTANT: This solution has currently one rather big *downside*. Due to the _default_url_options_ implementation, you have to pass the +:id+ option explicitly, like this: +link_to 'Show', book_url(:id => book)+ and not depend on Rails' magic in code like +link_to 'Show', book+. If this should be a problem, have a look at two plugins which simplify work with routes in this way: Sven Fuchs's "routing_filter":http://github.com/svenfuchs/routing-filter/tree/master and Raul Murciano's "translate_routes":http://github.com/raul/translate_routes/tree/master. See also the page "How to encode the current locale in the URL":http://rails-i18n.org/wiki/wikipages/how-to-encode-the-current-locale-in-the-url in the Rails i18n Wiki. +NOTE: Have a look at two plugins which simplify work with routes in this way: Sven Fuchs's "routing_filter":https://github.com/svenfuchs/routing-filter/tree/master and Raul Murciano's "translate_routes":https://github.com/raul/translate_routes/tree/master. h4. Setting the Locale from the Client Supplied Information @@ -267,7 +278,7 @@ def extract_locale_from_accept_language_header end </ruby> -Of course, in a production environment you would need much more robust code, and could use a plugin such as Iain Hecker's "http_accept_language":http://github.com/iain/http_accept_language/tree/master or even Rack middleware such as Ryan Tomayko's "locale":http://github.com/rtomayko/rack-contrib/blob/master/lib/rack/locale.rb. +Of course, in a production environment you would need much more robust code, and could use a plugin such as Iain Hecker's "http_accept_language":https://github.com/iain/http_accept_language/tree/master or even Rack middleware such as Ryan Tomayko's "locale":https://github.com/rack/rack-contrib/blob/master/lib/rack/contrib/locale.rb. h5. Using GeoIP (or Similar) Database @@ -294,12 +305,12 @@ end # app/controllers/home_controller.rb class HomeController < ApplicationController def index - flash[:notice] = "Hello flash!" + flash[:notice] = "Hello Flash" end end # app/views/home/index.html.erb -<h1>Hello world!</h1> +<h1>Hello World</h1> <p><%= flash[:notice] %></p> </ruby> @@ -333,8 +344,8 @@ So let's add the missing translations into the dictionary files (i.e. do the "lo <ruby> # config/locales/en.yml en: - hello_world: Hello World - hello_flash: Hello Flash + hello_world: Hello world! + hello_flash: Hello flash! # config/locales/pirate.yml pirate: @@ -379,7 +390,7 @@ So that would give you: !images/i18n/demo_localized_pirate.png(rails i18n demo localized time to pirate)! -TIP: Right now you might need to add some more date/time formats in order to make the I18n backend work as expected (at least for the 'pirate' locale). Of course, there's a great chance that somebody already did all the work by *translating Rails' defaults for your locale*. See the "rails-i18n repository at Github":http://github.com/svenfuchs/rails-i18n/tree/master/rails/locale for an archive of various locale files. When you put such file(s) in +config/locales/+ directory, they will automatically be ready for use. +TIP: Right now you might need to add some more date/time formats in order to make the I18n backend work as expected (at least for the 'pirate' locale). Of course, there's a great chance that somebody already did all the work by *translating Rails' defaults for your locale*. See the "rails-i18n repository at Github":https://github.com/svenfuchs/rails-i18n/tree/master/rails/locale for an archive of various locale files. When you put such file(s) in +config/locales/+ directory, they will automatically be ready for use. h4. Localized Views @@ -453,24 +464,24 @@ I18n.t 'message' The +translate+ method also takes a +:scope+ option which can contain one or more additional keys that will be used to specify a “namespace” or scope for a translation key: <ruby> -I18n.t :invalid, :scope => [:activerecord, :errors, :messages] +I18n.t :record_invalid, :scope => [:activerecord, :errors, :messages] </ruby> -This looks up the +:invalid+ message in the Active Record error messages. +This looks up the +:record_invalid+ message in the Active Record error messages. Additionally, both the key and scopes can be specified as dot-separated keys as in: <ruby> -I18n.translate :"activerecord.errors.messages.invalid" +I18n.translate "activerecord.errors.messages.record_invalid" </ruby> Thus the following calls are equivalent: <ruby> -I18n.t 'activerecord.errors.messages.invalid' -I18n.t 'errors.messages.invalid', :scope => :active_record -I18n.t :invalid, :scope => 'activerecord.errors.messages' -I18n.t :invalid, :scope => [:activerecord, :errors, :messages] +I18n.t 'activerecord.errors.messages.record_invalid' +I18n.t 'errors.messages.record_invalid', :scope => :active_record +I18n.t :record_invalid, :scope => 'activerecord.errors.messages' +I18n.t :record_invalid, :scope => [:activerecord, :errors, :messages] </ruby> h5. Defaults @@ -518,7 +529,7 @@ es: title: "Título" </yaml> -you can look up the +books.index.title+ value *inside* +app/views/books/index.html.erb+ template like this (note the dot): +you can look up the +books.index.title+ value *inside* +app/views/books/index.html.erb+ template like this (note the dot): <ruby> <%= t '.title' %> @@ -575,7 +586,7 @@ I18n.t :foo I18n.l Time.now </ruby> -Explicitely passing a locale: +Explicitly passing a locale: <ruby> I18n.t :foo, :locale => :de @@ -612,7 +623,7 @@ pt: bar: baz </ruby> -As you see, in both cases the toplevel key is the locale. +:foo+ is a namespace key and +:bar+ is the key for the translation "baz". +As you see, in both cases the top level key is the locale. +:foo+ is a namespace key and +:bar+ is the key for the translation "baz". Here is a "real" example from the Active Support +en.yml+ translations YAML file: @@ -638,7 +649,7 @@ Generally we recommend using YAML as a format for storing translations. There ar h4. Translations for Active Record Models -You can use the methods +Model.human_name+ and +Model.human_attribute_name(attribute)+ to transparently look up translations for your model and attribute names. +You can use the methods +Model.model_name.human+ and +Model.human_attribute_name(attribute)+ to transparently look up translations for your model and attribute names. For example when you add the following translations: @@ -653,7 +664,7 @@ en: # will translate User attribute "login" as "Handle" </ruby> -Then +User.human_name+ will return "Dude" and +User.human_attribute_name("login")+ will return "Handle". +Then +User.model_name.human+ will return "Dude" and +User.human_attribute_name("login")+ will return "Handle". h5. Error Message Scopes @@ -661,11 +672,11 @@ Active Record validation error messages can also be translated easily. Active Re This gives you quite powerful means to flexibly adjust your messages to your application's needs. -Consider a User model with a +validates_presence_of+ validation for the name attribute like this: +Consider a User model with a validation for the name attribute like this: <ruby> class User < ActiveRecord::Base - validates_presence_of :name + validates :name, :presence => true end </ruby> @@ -675,6 +686,8 @@ The key for the error message in this case is +:blank+. Active Record will look activerecord.errors.models.[model_name].attributes.[attribute_name] activerecord.errors.models.[model_name] activerecord.errors.messages +errors.attributes.[attribute_name] +errors.messages </ruby> Thus, in our example it will try the following keys in this order and return the first result: @@ -683,6 +696,8 @@ Thus, in our example it will try the following keys in this order and return the activerecord.errors.models.user.attributes.name.blank activerecord.errors.models.user.blank activerecord.errors.messages.blank +errors.attributes.name.blank +errors.messages.blank </ruby> When your models are additionally using inheritance then the messages are looked up in the inheritance chain. @@ -691,18 +706,20 @@ For example, you might have an Admin model inheriting from User: <ruby> class Admin < User - validates_presence_of :name + validates :name, :presence => true end </ruby> Then Active Record will look for messages in this order: <ruby> -activerecord.errors.models.admin.attributes.title.blank +activerecord.errors.models.admin.attributes.name.blank activerecord.errors.models.admin.blank -activerecord.errors.models.user.attributes.title.blank +activerecord.errors.models.user.attributes.name.blank activerecord.errors.models.user.blank activerecord.errors.messages.blank +errors.attributes.name.blank +errors.messages.blank </ruby> This way you can provide special translations for various error messages at different points in your models inheritance chain and in the attributes, models, or default scopes. @@ -716,27 +733,27 @@ So, for example, instead of the default error message +"can not be blank"+ you c * +count+, where available, can be used for pluralization if present: |_. validation |_.with option |_.message |_.interpolation| -| validates_confirmation_of | - | :confirmation | -| -| validates_acceptance_of | - | :accepted | -| -| validates_presence_of | - | :blank | -| -| validates_length_of | :within, :in | :too_short | count| -| validates_length_of | :within, :in | :too_long | count| -| validates_length_of | :is | :wrong_length | count| -| validates_length_of | :minimum | :too_short | count| -| validates_length_of | :maximum | :too_long | count| -| validates_uniqueness_of | - | :taken | -| -| validates_format_of | - | :invalid | -| -| validates_inclusion_of | - | :inclusion | -| -| validates_exclusion_of | - | :exclusion | -| -| validates_associated | - | :invalid | -| -| validates_numericality_of | - | :not_a_number | -| -| validates_numericality_of | :greater_than | :greater_than | count| -| validates_numericality_of | :greater_than_or_equal_to | :greater_than_or_equal_to | count| -| validates_numericality_of | :equal_to | :equal_to | count| -| validates_numericality_of | :less_than | :less_than | count| -| validates_numericality_of | :less_than_or_equal_to | :less_than_or_equal_to | count| -| validates_numericality_of | :odd | :odd | -| -| validates_numericality_of | :even | :even | -| +| confirmation | - | :confirmation | -| +| acceptance | - | :accepted | -| +| presence | - | :blank | -| +| length | :within, :in | :too_short | count| +| length | :within, :in | :too_long | count| +| length | :is | :wrong_length | count| +| length | :minimum | :too_short | count| +| length | :maximum | :too_long | count| +| uniqueness | - | :taken | -| +| format | - | :invalid | -| +| inclusion | - | :inclusion | -| +| exclusion | - | :exclusion | -| +| associated | - | :invalid | -| +| numericality | - | :not_a_number | -| +| numericality | :greater_than | :greater_than | count| +| numericality | :greater_than_or_equal_to | :greater_than_or_equal_to | count| +| numericality | :equal_to | :equal_to | count| +| numericality | :less_than | :less_than | count| +| numericality | :less_than_or_equal_to | :less_than_or_equal_to | count| +| numericality | :odd | :odd | -| +| numericality | :even | :even | -| h5. Translations for the Active Record +error_messages_for+ Helper @@ -761,23 +778,23 @@ Rails uses fixed strings and other localizations, such as format strings and oth h5. Action View Helper Methods -* +distance_of_time_in_words+ translates and pluralizes its result and interpolates the number of seconds, minutes, hours, and so on. See "datetime.distance_in_words":http://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L51 translations. +* +distance_of_time_in_words+ translates and pluralizes its result and interpolates the number of seconds, minutes, hours, and so on. See "datetime.distance_in_words":https://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L51 translations. -* +datetime_select+ and +select_month+ use translated month names for populating the resulting select tag. See "date.month_names":http://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L15 for translations. +datetime_select+ also looks up the order option from "date.order":http://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L18 (unless you pass the option explicitely). All date selection helpers translate the prompt using the translations in the "datetime.prompts":http://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L83 scope if applicable. +* +datetime_select+ and +select_month+ use translated month names for populating the resulting select tag. See "date.month_names":https://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L15 for translations. +datetime_select+ also looks up the order option from "date.order":https://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L18 (unless you pass the option explicitly). All date selection helpers translate the prompt using the translations in the "datetime.prompts":https://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L83 scope if applicable. -* The +number_to_currency+, +number_with_precision+, +number_to_percentage+, +number_with_delimiter+, and +number_to_human_size+ helpers use the number format settings located in the "number":http://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L2 scope. +* The +number_to_currency+, +number_with_precision+, +number_to_percentage+, +number_with_delimiter+, and +number_to_human_size+ helpers use the number format settings located in the "number":https://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L2 scope. h5. Active Record Methods -* +human_name+ and +human_attribute_name+ use translations for model names and attribute names if available in the "activerecord.models":http://github.com/rails/rails/blob/master/activerecord/lib/active_record/locale/en.yml#L29 scope. They also support translations for inherited class names (e.g. for use with STI) as explained above in "Error message scopes". +* +model_name.human+ and +human_attribute_name+ use translations for model names and attribute names if available in the "activerecord.models":https://github.com/rails/rails/blob/master/activerecord/lib/active_record/locale/en.yml#L29 scope. They also support translations for inherited class names (e.g. for use with STI) as explained above in "Error message scopes". -* +ActiveRecord::Errors#generate_message+ (which is used by Active Record validations but may also be used manually) uses +human_name+ and +human_attribute_name+ (see above). It also translates the error message and supports translations for inherited class names as explained above in "Error message scopes". +* +ActiveRecord::Errors#generate_message+ (which is used by Active Record validations but may also be used manually) uses +model_name.human+ and +human_attribute_name+ (see above). It also translates the error message and supports translations for inherited class names as explained above in "Error message scopes". -*+ ActiveRecord::Errors#full_messages+ prepends the attribute name to the error message using a separator that will be looked up from "activerecord.errors.format.separator":http://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L91 (and which defaults to +' '+). +*+ ActiveRecord::Errors#full_messages+ prepends the attribute name to the error message using a separator that will be looked up from "activerecord.errors.format.separator":https://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L91 (and which defaults to +' '+). h5. Active Support Methods -* +Array#to_sentence+ uses format settings as given in the "support.array":http://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L30 scope. +* +Array#to_sentence+ uses format settings as given in the "support.array":https://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L30 scope. h3. Customize your I18n Setup @@ -792,6 +809,12 @@ That does not mean you're stuck with these limitations, though. The Ruby I18n ge I18n.backend = Globalize::Backend::Static.new </ruby> +You can also use the Chain backend to chain multiple backends together. This is useful when you want to use standard translations with a Simple backend but store custom application translations in a database or other backends. For example, you could use the ActiveRecord backend and fall back to the (default) Simple backend: + +<ruby> +I18n.backend = I18n::Backend::Chain.new(I18n::Backend::ActiveRecord.new, I18n.backend) +</ruby> + h4. Using Different Exception Handlers The I18n API defines the following exceptions that will be raised by backends when the corresponding unexpected conditions occur: @@ -813,7 +836,7 @@ In other contexts you might want to change this behaviour, though. E.g. the defa <ruby> module I18n - def just_raise_that_exception(*args) + def self.just_raise_that_exception(*args) raise args.first end end @@ -835,7 +858,7 @@ h3. Conclusion At this point you should have a good overview about how I18n support in Ruby on Rails works and are ready to start translating your project. -If you find anything missing or wrong in this guide please file a ticket on "our issue tracker":http://i18n.lighthouseapp.com/projects/14948-rails-i18n/overview. If you want to discuss certain portions or have questions please sign up to our "mailinglist":http://groups.google.com/group/rails-i18n. +If you find anything missing or wrong in this guide, please file a ticket on our "issue tracker":http://i18n.lighthouseapp.com/projects/14948-rails-i18n/overview. If you want to discuss certain portions or have questions, please sign up to our "mailing list":http://groups.google.com/group/rails-i18n. h3. Contributing to Rails I18n @@ -844,16 +867,16 @@ I18n support in Ruby on Rails was introduced in the release 2.2 and is still evo Thus we encourage everybody to experiment with new ideas and features in plugins or other libraries and make them available to the community. (Don't forget to announce your work on our "mailing list":http://groups.google.com/group/rails-i18n!) -If you find your own locale (language) missing from our "example translations data":http://github.com/svenfuchs/rails-i18n/tree/master/rails/locale repository for Ruby on Rails, please "_fork_":http://github.com/guides/fork-a-project-and-submit-your-modifications the repository, add your data and send a "pull request":http://github.com/guides/pull-requests. +If you find your own locale (language) missing from our "example translations data":https://github.com/svenfuchs/rails-i18n/tree/master/rails/locale repository for Ruby on Rails, please "_fork_":https://github.com/guides/fork-a-project-and-submit-your-modifications the repository, add your data and send a "pull request":https://github.com/guides/pull-requests. h3. Resources * "rails-i18n.org":http://rails-i18n.org - Homepage of the rails-i18n project. You can find lots of useful resources on the "wiki":http://rails-i18n.org/wiki. -* "rails-i18n Google group":http://groups.google.com/group/rails-i18n - The project's mailing list. -* "Github: rails-i18n":http://github.com/svenfuchs/rails-i18n/tree/master - Code repository for the rails-i18n project. Most importantly you can find lots of "example translations":http://github.com/svenfuchs/rails-i18n/tree/master/rails/locale for Rails that should work for your application in most cases. +* "Google group: rails-i18n":http://groups.google.com/group/rails-i18n - The project's mailing list. +* "Github: rails-i18n":https://github.com/svenfuchs/rails-i18n/tree/master - Code repository for the rails-i18n project. Most importantly you can find lots of "example translations":https://github.com/svenfuchs/rails-i18n/tree/master/rails/locale for Rails that should work for your application in most cases. +* "Github: i18n":https://github.com/svenfuchs/i18n/tree/master - Code repository for the i18n gem. * "Lighthouse: rails-i18n":http://i18n.lighthouseapp.com/projects/14948-rails-i18n/overview - Issue tracker for the rails-i18n project. -* "Github: i18n":http://github.com/svenfuchs/i18n/tree/master - Code repository for the i18n gem. * "Lighthouse: i18n":http://i18n.lighthouseapp.com/projects/14947-ruby-i18n/overview - Issue tracker for the i18n gem. @@ -862,7 +885,7 @@ h3. Authors * "Sven Fuchs":http://www.workingwithrails.com/person/9963-sven-fuchs (initial author) * "Karel Minařík":http://www.workingwithrails.com/person/7476-karel-mina-k -If you found this guide useful please consider recommending its authors on "workingwithrails":http://www.workingwithrails.com. +If you found this guide useful, please consider recommending its authors on "workingwithrails":http://www.workingwithrails.com. h3. Footnotes @@ -872,8 +895,3 @@ fn1. Or, to quote "Wikipedia":http://en.wikipedia.org/wiki/Internationalization_ fn2. Other backends might allow or require to use other formats, e.g. a GetText backend might allow to read GetText files. fn3. One of these reasons is that we don't want to imply any unnecessary load for applications that do not need any I18n capabilities, so we need to keep the I18n library as simple as possible for English. Another reason is that it is virtually impossible to implement a one-fits-all solution for all problems related to I18n for all existing languages. So a solution that allows us to exchange the entire implementation easily is appropriate anyway. This also makes it much easier to experiment with custom features and extensions. - - -h3. Changelog - -"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213/tickets/23 diff --git a/railties/guides/source/index.html.erb b/railties/guides/source/index.html.erb index a0db87c188..af46beee56 100644 --- a/railties/guides/source/index.html.erb +++ b/railties/guides/source/index.html.erb @@ -3,19 +3,23 @@ Ruby on Rails Guides <% end %> <% content_for :header_section do %> -<h2>Ruby on Rails Guides</h2> +<h2>Ruby on Rails Guides (<%= ENV['RAILS_VERSION'] || 'edge' %>)</h2> <% if @edge %> <p> These are <b>Edge Guides</b>, based on the current - <a href="http://github.com/rails/rails/tree/master">master branch</a>. + <a href="https://github.com/rails/rails/tree/master">master branch</a>. </p> <p> If you are looking for the ones for the stable version please check <a href="http://guides.rubyonrails.org">http://guides.rubyonrails.org</a> instead. </p> +<% else %> +<p> + These are the new guides for Rails 3. The guides for Rails 2.3 are still available + at <a href="http://guides.rubyonrails.org/v2.3.8/">http://guides.rubyonrails.org/v2.3.8/</a>. +</p> <% end %> - <p> These guides are designed to make you immediately productive with Rails, and to help you understand how all of the pieces fit together. @@ -27,7 +31,7 @@ Ruby on Rails Guides <div id="subCol"> <dl> <dd class="warning">Rails Guides are a result of the ongoing <a href="http://hackfest.rubyonrails.org">Guides hackfest</a>, and a work in progress.</dd> - <dd class="ticket">Guides marked with this icon are currently being worked on. While they might still be useful to you, they may contain incomplete information and even errors. You can help by reviewing them and posting your comments and corrections at the respective Lighthouse ticket.</dd> + <dd class="work-in-progress">Guides marked with this icon are currently being worked on. While they might still be useful to you, they may contain incomplete information and even errors. You can help by reviewing them and posting your comments and corrections to the author.</dd> </dl> </div> <% end %> @@ -67,7 +71,7 @@ Ruby on Rails Guides <p>This guide covers the basic layout features of Action Controller and Action View, including rendering and redirecting, using content_for blocks, and working with partials.</p> <% end %> -<%= guide("Action View Form Helpers", 'form_helpers.html', :ticket => 1) do %> +<%= guide("Action View Form Helpers", 'form_helpers.html', :work_in_progress => true) do %> <p>Guide to using built-in Form helpers.</p> <% end %> </dl> @@ -96,11 +100,11 @@ Ruby on Rails Guides <p>This guide covers how to add internationalization to your applications. Your application will be able to translate content to different languages, change pluralization rules, use correct date formats for each country and so on.</p> <% end %> -<%= guide("Action Mailer Basics", 'action_mailer_basics.html', :ticket => 25) do %> +<%= guide("Action Mailer Basics", 'action_mailer_basics.html', :work_in_progress => true) do %> <p>This guide describes how to use Action Mailer to send and receive emails.</p> <% end %> -<%= guide("Testing Rails Applications", 'testing.html', :ticket => 8) do %> +<%= guide("Testing Rails Applications", 'testing.html', :work_in_progress => true) do %> <p>This is a rather comprehensive guide to doing both unit and functional tests in Rails. It covers everything from "What is a test?" to the testing APIs. Enjoy.</p> <% end %> @@ -120,11 +124,11 @@ Ruby on Rails Guides <p>This guide covers the basic configuration settings for a Rails application.</p> <% end %> -<%= guide("Rails Command Line Tools and Rake tasks", 'command_line.html', :ticket => 29) do %> +<%= guide("Rails Command Line Tools and Rake tasks", 'command_line.html', :work_in_progress => true) do %> <p>This guide covers the command line tools and rake tasks provided by Rails.</p> <% end %> -<%= guide("Caching with Rails", 'caching_with_rails.html', :ticket => 10) do %> +<%= guide("Caching with Rails", 'caching_with_rails.html', :work_in_progress => true) do %> <p>Various caching techniques provided by Rails.</p> <% end %> </dl> @@ -132,7 +136,7 @@ Ruby on Rails Guides <h3>Extending Rails</h3> <dl> - <%= guide("The Basics of Creating Rails Plugins", 'plugins.html', :ticket => 32) do %> + <%= guide("The Basics of Creating Rails Plugins", 'plugins.html', :work_in_progress => true) do %> <p>This guide covers how to build a plugin to extend the functionality of Rails.</p> <% end %> @@ -140,23 +144,27 @@ Ruby on Rails Guides <p>This guide covers Rails integration with Rack and interfacing with other Rack components.</p> <% end %> - <%= guide("Adding Generators", 'generators.html') do %> + <%= guide("Creating and Customizing Rails Generators", 'generators.html') do %> <p>This guide covers the process of adding a brand new generator to your extension or providing an alternative to an element of a built-in Rails generator (such as providing alternative test stubs for the scaffold generator).</p> <% end %> </dl> -<h3>Contributing to Rails</h3> +<h3>Contributing to Ruby on Rails</h3> <dl> - <%= guide("Contributing to Rails", 'contributing_to_rails.html') do %> + <%= guide("Contributing to Ruby on Rails", 'contributing_to_ruby_on_rails.html') do %> <p>Rails is not "somebody else's framework." This guide covers a variety of ways that you can get involved in the ongoing development of Rails.</p> <% end %> <%= guide('API Documentation Guidelines', 'api_documentation_guidelines.html') do %> <p>This guide documents the Ruby on Rails API documentation guidelines.</p> <% end %> + + <%= guide('Ruby on Rails Guides Guidelines', 'ruby_on_rails_guides_guidelines.html') do %> + <p>This guide documents the Ruby on Rails guides guidelines.</p> + <% end %> </dl> <h3>Release Notes</h3> diff --git a/railties/guides/source/initialization.textile b/railties/guides/source/initialization.textile index f80c00b280..0cbbe1f389 100644 --- a/railties/guides/source/initialization.textile +++ b/railties/guides/source/initialization.textile @@ -1,2012 +1,425 @@ h2. The Rails Initialization Process -This guide explains how the initialization process in Rails works as of Rails 3. +This guide explains the internals of the initialization process in Rails works as of Rails 3.1. It is an extremely in-depth guide and recommended for advanced Rails developers. * Using +rails server+ * Using Passenger endprologue. -This guide first describes the process of +rails server+ then explains the Passenger + Rack method, before delving into the common initialize pattern these two go through. +This guide goes through every single file, class and method call that is required to boot up the Ruby on Rails stack for a default Rails 3.1 application, explaining each part in detail a long the way. For this guide, we will be focusing on how the two most common methods (+rails server+ and Passenger) boot a Rails application. + +NOTE: Paths in this guide are relative to Rails or a Rails application unless otherwise specified. h3. Launch! As of Rails 3, +script/server+ has become +rails server+. This was done to centralize all rails related commands to one common file. -The actual +rails+ command is kept in _railties/bin/rails_ and goes like this: - -<ruby> - require 'rbconfig' - - module Rails - module ScriptRailsLoader - RUBY = File.join(*RbConfig::CONFIG.values_at("bindir", "ruby_install_name")) + RbConfig::CONFIG["EXEEXT"] - SCRIPT_RAILS = File.join('script', 'rails') - - def self.exec_script_rails! - cwd = Dir.pwd - exec RUBY, SCRIPT_RAILS, *ARGV if File.exists?(SCRIPT_RAILS) - Dir.chdir("..") do - # Recurse in a chdir block: if the search fails we want to be sure - # the application is generated in the original working directory. - exec_script_rails! unless cwd == Dir.pwd - end - rescue SystemCallError - # could not chdir, no problem just return - end - end - end - - Rails::ScriptRailsLoader.exec_script_rails! - - railties_path = File.expand_path('../../lib', __FILE__) - $:.unshift(railties_path) if File.directory?(railties_path) && !$:.include?(railties_path) +h4. +bin/rails+ - require 'rails/ruby_version_check' - Signal.trap("INT") { puts; exit } - - require 'rails/commands/application' -</ruby> - -The +Rails::ScriptRailsLoader+ module here defines two constants: +RUBY+ and +SCRIPT_RAILS+. +RUBY+ is the full path to your ruby executable, on a Snow Leopard system it's _/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby_. +SCRIPT_RAILS+ is simply _script/rails_. When +exec_script_rails+ is invoked, this will attempt to +exec+ the _rails_ file in the _script_ directory using the path to your Ruby executable, +RUBY+. If +exec+ is invoked, the program will stop at this point. If the _script/rails_ file doesn't exist in the current directory, Rails will recurse upwards until it finds it by calling +exec_script_rails+ from inside the +Dir.chdir("..")+. This is handy if you're currently in one of the sub-directories of the rails application and wish to launch a server or a console. - -If Rails cannot execute _script/rails_ then it will fall back to the standard +rails+ command task of generating an application. - -In +script/rails+ we see the following: +The actual +rails+ command is kept in _bin/rails_ at the and goes like this: <ruby> #!/usr/bin/env ruby - # This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application. - - APP_PATH = File.expand_path('../../config/application', __FILE__) - require File.expand_path('../../config/boot', __FILE__) - require 'rails/commands' -</ruby> -This obviously defines a couple of constants to some pretty important files, _config/environment.rb_, _config/boot.rb_ and _config/application.rb_ all within the context of +__FILE__+ which is of course +script/rails+ in the root of your application. Then it goes on to +require BOOT_PATH+ which leads us onto _config/boot.rb_. - -h3. Passenger - -Before we dive into what _config/boot.rb_ encompasses, we'll just glimpse at what Passenger does enough to get an understanding of how it requires a Rails application. - -Passenger will require _config/environment.rb_ by way of its +PhusionPassenger::Railz::ApplicationSpawner#preload_application+ method. _config/environment.rb_ requires _config/application.rb_ which requires _config/boot.rb_. That's how the Rails boot process begins with Passenger in a nutshell. - -h3. _config/boot.rb_ - -_config/boot.rb_ is the first stop for everything for initializing your application. This boot process does quite a bit of work for you and so this section attempts to go in-depth enough to explain what each of the pieces does. - -<ruby> - require 'rubygems' - - # Set up gems listed in the Gemfile. - gemfile = File.expand_path('../../Gemfile', __FILE__) begin - ENV['BUNDLE_GEMFILE'] = gemfile - require 'bundler' - Bundler.setup - rescue Bundler::GemNotFound => e - STDERR.puts e.message - STDERR.puts "Try running `bundle install`." - exit! - end if File.exist?(gemfile) -</ruby> - -h3. Bundled Rails (3.x) - - -Rails 3 now uses Bundler and the README for the project explains it better than I could: - -> "Bundler is a tool that manages gem dependencies for your ruby application. It takes a gem manifest file and is able to fetch, download, and install the gems and all child dependencies specified in this manifest. It can manage any update to the gem manifest file and update the bundle's gems accordingly. It also lets you run any ruby code in context of the bundle's gem environment." - -Now with Rails 3 we have a Gemfile which defines the basics our application needs to get going: - -<ruby> - source 'http://rubygems.org' - - gem 'rails', '3.0.0.beta4' - - # Bundle edge Rails instead: - # gem 'rails', :git => 'git://github.com/rails/rails.git' - - gem 'sqlite3-ruby', :require => 'sqlite3' - - # Use unicorn as the web server - # gem 'unicorn' - - # Deploy with Capistrano - # gem 'capistrano' - - # Bundle the extra gems: - # gem 'bj' - # gem 'nokogiri' - # gem 'sqlite3-ruby', :require => 'sqlite3' - # gem 'aws-s3', :require => 'aws/s3' - - # Bundle gems for certain environments: - # gem 'rspec', :group => :test - # group :test do - # gem 'webrat' - # end - -</ruby> - -Here the only two gems we need are +rails+ and +sqlite3-ruby+, so it seems. This is until you run +bundle pack+. This command freezes all the gems required by your application into _vendor/cache_. The gems installed by default are: - -* abstract-1.0.0.gem -* actionmailer-3.0.0.beta4.gem -* actionpack-3.0.0.beta4.gem -* activemodel-3.0.0.beta4.gem -* activerecord-3.0.0.beta4.gem -* activeresource-3.0.0.beta4.gem -* activesupport-3.0.0.beta4.gem -* arel-0.4.0.gem -* builder-2.1.2.gem -* bundler-1.0.0.rc.2.gem -* erubis-2.6.6.gem -* i18n-0.4.1.gem -* mail-2.2.5.gem -* memcache-client-1.8.5.gem -* mime-types-1.16.gem -* nokogiri-1.4.3.1.gem -* polyglot-0.3.1.gem -* rack-1.2.1.gem -* rack-mount-0.6.9.gem -* rack-test-0.5.4.gem -* rails-3.0.0.beta4.gem -* railties-3.0.0.beta4.gem -* rake-0.8.7.gem -* sqlite3-ruby-1.3.1.gem -* text-format-1.0.0.gem -* text-hyphen-1.0.0.gem -* thor-0.13.7.gem -* treetop-1.4.8.gem -* tzinfo-0.3.22.gem - -TODO: Prettify when it becomes more stable. - -I won't go into what each of these gems are, as that is really something that needs covering on a case-by-case basis. We will however just dig a little under the surface of Bundler. - -Back in _config/boot.rb_, we call +Bundler.setup+ which will load and parse the +Gemfile+ and add the _lib_ directory of the gems mentioned **and** their dependencies (**and** their dependencies' dependencies, and so on) to the +$LOAD_PATH+. - -h3. Requiring Rails - -After _config/boot.rb_ is loaded, there's this +require+: - -<ruby> - require 'rails/commands' -</ruby> - -In this file, _railties/lib/rails/commands.rb_, there is a case statement for +ARGV.shift+: - -<ruby> - case ARGV.shift - ... - when 's', 'server' - require 'rails/commands/server' - # Initialize the server first, so environment options are set - server = Rails::Server.new - require APP_PATH - ... - end -</ruby> - -We're running +rails server+ and this means it will make a require out to _rails/commands/server_ (_railties/lib/rails/commands/server.rb_). Firstly, this file makes a couple of requires of its own: - -<ruby> - require 'fileutils' - require 'optparse' - require 'action_dispatch' -</ruby> - -The first two are Ruby core and this guide does not cover what they do, but _action_dispatch_ (_actionpack/lib/action_dispatch.rb_) is important. This file firstly make a require to _active_support_ (_activesupport/lib/active_support.rb_) which defines the +ActiveSupport+ module. - -h4. +require 'active_support'+ - -_activesupport/lib/active_support.rb_ sets up +module ActiveSupport+: - -<ruby> - module ActiveSupport - class << self - attr_accessor :load_all_hooks - def on_load_all(&hook) load_all_hooks << hook end - def load_all!; load_all_hooks.each { |hook| hook.call } end - end - self.load_all_hooks = [] - - on_load_all do - [Dependencies, Deprecation, Gzip, MessageVerifier, Multibyte, SecureRandom] - end - end -</ruby> - -This defines two methods on the module itself by using the familiar +class << self+ syntax. This allows you to call them as if they were class methods: +ActiveSupport.on_load_all+ and +ActiveSupport.load_all!+ respectively. The first method simply adds loading hooks to save them up for loading later on when +load_all!+ is called. By +call+'ing the block, the classes will be loaded. (NOTE: kind of guessing, I feel 55% about this). - -The +on_load_all+ method is called later with the +Dependencies+, +Deprecation+, +Gzip+, +MessageVerifier+, +Multibyte+ and +SecureRandom+. What each of these modules do will be covered later. - -This file goes on to define some classes that will be automatically loaded using Ruby's +autoload+ method, but not before including Rails's own variant of the +autoload+ method from _active_support/dependencies/autoload.rb_: - - -<ruby> - require "active_support/inflector/methods" - require "active_support/lazy_load_hooks" - - module ActiveSupport - module Autoload - def self.extended(base) - base.extend(LazyLoadHooks) - end - - @@autoloads = {} - @@under_path = nil - @@at_path = nil - @@eager_autoload = false - - def autoload(const_name, path = @@at_path) - full = [self.name, @@under_path, const_name.to_s, path].compact.join("::") - location = path || Inflector.underscore(full) - - if @@eager_autoload - @@autoloads[const_name] = location - end - super const_name, location - end - - ... - end - end -</ruby> - -h4. Lazy Hooks - -+ActiveSupport::LazyLoadHooks+ is responsible for defining methods used for running hooks that are defined during the initialization process, such as the one defined inside the +active_record.initialize_timezone+ initializer: - -<ruby> - initializer "active_record.initialize_timezone" do - ActiveSupport.on_load(:active_record) do - self.time_zone_aware_attributes = true - self.default_timezone = :utc - end - end -</ruby> - -When the initializer runs it invokes method +on_load+ for +ActiveRecord+ and the block passed to it would be called only when +run_load_hooks+ is called. -When the entirety of +activerecord/lib/active_record/base.rb+ has been evaluated then +run_load_hooks+ is invoked. The very last line of +activerecord/lib/active_record/base.rb+ is: - -<ruby> -ActiveSupport.run_load_hooks(:active_record, ActiveRecord::Base) -</ruby> - -h4. +require 'active_support'+ cont'd. - -This file also uses the method +eager_autoload+ also defined in _active_support/dependencies/autoload.rb_: - -<ruby> - def eager_autoload - old_eager, @@eager_autoload = @@eager_autoload, true - yield - ensure - @@eager_autoload = old_eager - end -</ruby> - -As you can see for the duration of the +eager_autoload+ block the class variable +@@eager_autoload+ is set to +true+, which has the consequence of when +autoload+ is called that the location of the file for that specific +autoload+'d constant is added to the +@@autoloads+ hash initialized at the beginning of this module declaration. So now that you have part of the context, here's the other, the code from _activesupport/lib/active_support.rb_: - -<ruby> - require "active_support/dependencies/autoload" - - module ActiveSupport - extend ActiveSupport::Autoload - - autoload :DescendantsTracker - autoload :FileUpdateChecker - autoload :LogSubscriber - autoload :Notifications - - # TODO: Narrow this list down - eager_autoload do - autoload :BacktraceCleaner - autoload :Base64 - autoload :BasicObject - autoload :Benchmarkable - autoload :BufferedLogger - autoload :Cache - autoload :Callbacks - autoload :Concern - autoload :Configurable - autoload :Deprecation - autoload :Gzip - autoload :Inflector - autoload :JSON - autoload :Memoizable - autoload :MessageEncryptor - autoload :MessageVerifier - autoload :Multibyte - autoload :OptionMerger - autoload :OrderedHash - autoload :OrderedOptions - autoload :Rescuable - autoload :SecureRandom - autoload :StringInquirer - autoload :XmlMini - end - - autoload :SafeBuffer, "active_support/core_ext/string/output_safety" - autoload :TestCase - end - - autoload :I18n, "active_support/i18n" -</ruby> - -So we know the ones in +eager_autoload+ are eagerly loaded and it does this by storing them in an +@@autoloads+ hash object and then loading them via +eager_autoload!+ which is called via the +preload_frameworks+ initializer defined in _railties/lib/rails/application/bootstrap.rb_. - -The classes and modules that are not +eager_autoload+'d are automatically loaded as they are references - -Note: What does it means to be autoloaded? An example of this would be calling the +ActiveSupport::TestCase+ class which hasn't yet been initialized. Because it's been specified as an +autoload+ Ruby will require the file that it's told to. The file it requires is not defined in the +autoload+ call here but, as you may have seen, in the +ActiveSupport::Autoload.autoload+ definition. So once that file has been required Ruby will try again and then if it still can't find it it will throw the all-too-familiar +uninitialized constant+ error. - -h4. +require 'action_dispatch'+ - -Back in _actionpack/lib/action_dispatch.rb_, the next require after _active_support_ is to _active_support/dependencies/autoload_ but this file has already been loaded by _activesupport/lib/active_support.rb_ and so will not be loaded again. The next require is to Rack itself: - -<ruby> - require 'rack' -</ruby> - -As mentioned previously, Bundler has added the gems' _lib_ directories to the load path so this _rack_ file that is referenced lives in the Rack gem: _lib/rack.rb_. This loads Rack so we can use it later on when we define +Rails::Server+ to descend from +Rack::Server+. - -This file then goes on to define the +ActionDispatch+ module and it's related autoloads: - -<ruby> - module Rack - autoload :Test, 'rack/test' - end - - module ActionDispatch - extend ActiveSupport::Autoload - - autoload_under 'http' do - autoload :Request - autoload :Response - end - - autoload_under 'middleware' do - autoload :Callbacks - autoload :Cascade - autoload :Cookies - autoload :Flash - autoload :Head - autoload :ParamsParser - autoload :RemoteIp - autoload :Rescue - autoload :ShowExceptions - autoload :Static - end - - autoload :MiddlewareStack, 'action_dispatch/middleware/stack' - autoload :Routing - - module Http - extend ActiveSupport::Autoload - - autoload :Cache - autoload :Headers - autoload :MimeNegotiation - autoload :Parameters - autoload :FilterParameters - autoload :Upload - autoload :UploadedFile, 'action_dispatch/http/upload' - autoload :URL - end - - module Session - autoload :AbstractStore, 'action_dispatch/middleware/session/abstract_store' - autoload :CookieStore, 'action_dispatch/middleware/session/cookie_store' - autoload :MemCacheStore, 'action_dispatch/middleware/session/mem_cache_store' - end - - autoload_under 'testing' do - autoload :Assertions - autoload :Integration - autoload :PerformanceTest - autoload :TestProcess - autoload :TestRequest - autoload :TestResponse - end - end - - autoload :Mime, 'action_dispatch/http/mime_type' -</ruby> - -h4. +require "rails/commands/server"+ - -Now that Rails has required Action Dispatch and it has required Rack, Rails can now go about defining the +Rails::Server+ class: - -<ruby> - module Rails - class Server < ::Rack::Server - - ... - - def initialize(*) - super - set_environment - end - - ... - - def set_environment - ENV["RAILS_ENV"] ||= options[:environment] - end - ... - end - end -</ruby> - -h4. +require "rails/commands"+ - -Back in _rails/commands_ Rails calls +Rails::Server.new+ which calls the +initialize+ method on the +Rails::Server+ class, which calls +super+, meaning it's actually calling +Rack::Server#initialize+, with it being defined like this: - -<ruby> - def initialize(options = nil) - @options = options - end -</ruby> - -The +options+ method like this: - -<ruby> - def options - @options ||= parse_options(ARGV) - end -</ruby> - -The +parse_options+ method like this: - -<ruby> - def parse_options(args) - options = default_options - - # Don't evaluate CGI ISINDEX parameters. - # http://hoohoo.ncsa.uiuc.edu/cgi/cl.html - args.clear if ENV.include?("REQUEST_METHOD") - - options.merge! opt_parser.parse! args - options - end -</ruby> - -And +default_options+ like this: - -<ruby> - def default_options - { - :environment => "development", - :pid => nil, - :Port => 9292, - :Host => "0.0.0.0", - :AccessLog => [], - :config => "config.ru" - } - end -</ruby> - -Here it is important to note that the default environment is _development_. After +Rack::Server#initialize+ has done its thing it returns to +Rails::Server#initialize+ which calls +set_environment+: - -<ruby> - def set_environment - ENV["RAILS_ENV"] ||= options[:environment] + require "rails/cli" + rescue LoadError + railties_path = File.expand_path('../../railties/lib', __FILE__) + $:.unshift(railties_path) + require "rails/cli" end </ruby> -From the information given we can determine that +ENV["RAILS_ENV"]+ will be set to _development_ if no other environment is specified. - -Finally, after +Rails::Server.new+ has executed, there is one more require: - -<ruby> - require APP_PATH -</ruby> - -+APP_PATH+ was previously defined as _config/application.rb_ in the application's root, and so that is where Rails will go next. - -h4. +require APP_PATH+ - -This file is _config/application.rb_ in your application and makes two requires to begin with: - -<ruby> - require File.expand_path('../boot', __FILE__) - require 'rails/all' -</ruby> - -The +../boot+ file it references is +config/boot.rb+, which was loaded earlier in the initialization process and so will not be loaded again. - -If you generate the application with the +-O+ option this will put a couple of pick-and-choose requirements at the top of your _config/application.rb_ instead: - -<ruby> - # Pick the frameworks you want: - # require "active_record/railtie" - require "action_controller/railtie" - require "action_mailer/railtie" - require "active_resource/railtie" - require "rails/test_unit/railtie" -</ruby> - -For the purposes of this guide, will will assume only: +This file will attempt to load +rails/cli+ and if it cannot find it then add the +railties/lib+ path to the load path (+$:+) and will then try to require it again. -<ruby> - require 'rails/all' -</ruby> - -h4. +require "rails/all"+ - -Now we'll dive into the internals of the pre-initialization stage of Rails. The file that is being required is _railties/lib/rails/all.rb_. The first line in this file is: - -<ruby> - require 'rails' -</ruby> - -h4. +require 'rails'+ +h4. +railites/lib/rails/cli.rb+ -This file (_railties/lib/rails.rb_) requires the very, very basics that Rails needs to get going. I'm not going to delve into these areas yet, just cover them briefly for now. Later on we will go through the ones that are important to the boot procedure. +This file looks like this: <ruby> - require 'pathname' + require 'rbconfig' + require 'rails/script_rails_loader' - require 'active_support' - require 'active_support/core_ext/kernel/reporting' - require 'active_support/core_ext/logger' + # If we are inside a Rails application this method performs an exec and thus + # the rest of this script is not run. + Rails::ScriptRailsLoader.exec_script_rails! - require 'rails/application' - require 'rails/version' - require 'rails/deprecation' - require 'rails/log_subscriber' require 'rails/ruby_version_check' + Signal.trap("INT") { puts; exit } - require 'active_support/railtie' - require 'action_dispatch/railtie' -</ruby> - -+require 'pathname'+ requires the Pathname class which is used for returning a Pathname object for +Rails.root+. Although is coming to use this path name to generate paths as below: - -<ruby> - Rails.root.join("app/controllers") -</ruby> - -Pathname can also be converted to string, so the following syntax is preferred: - -<ruby> - "#{Rails.root}/app/controllers" -</ruby> - - -This works because Ruby automatically handles file path conversions. Although this is not new to Rails 3 (it was available in 2.3.5), it is something worthwhile pointing out. - -Inside this file there are other helpful helper methods defined, such as +Rails.root+, +Rails.env+, +Rails.logger+ and +Rails.application+. - -The first require: - -<ruby> - require 'active_support' -</ruby> - -Is not ran as this was already required by _actionpack/lib/action_dispatch.rb_. - - -h4. +require 'active_support/core_ext/kernel/reporting'+ - -This file extends the +Kernel+ module, providing the methods +silence_warnings+, +enable_warnings+, +with_warnings+, +silence_stderr+, +silence_stream+ and +suppress+. The API documentation on these overridden methods is fairly good and if you wish to know more "have a read.":http://api.rubyonrails.org/classes/Kernel.html - -For information on this file see the "Core Extensions" guide. TODO: link to guide. - -h4. +require 'active_support/core_ext/logger'+ - -For information on this file see the "Core Extensions" guide. TODO: link to guide. - -h4. +require 'rails/application'+ - -Here's where +Rails::Application+ is defined. This is the superclass of +YourApp::Application+ from _config/application.rb_ and the subclass of +Rails::Engine+ This is the main entry-point into the Rails initialization process as when your application is initialized, your class is the basis of its configuration. - -This file requires three important files before +Rails::Application+ is defined: _rails/railties_path.rb_, _rails/plugin.rb_ and _rails/engine.rb_. - - -h4. +require 'rails/railties_path'+ - -This file serves one purpose: - -<ruby> - RAILTIES_PATH = File.expand_path(File.join(File.dirname(__FILE__), '..', '..')) -</ruby> - -Helpful, hey? One must wonder why they just didn't define it outright. - - -h4. +require 'rails/plugin'+ - -Firstly this file requires _rails/engine.rb_, which defines our +Rails::Engine+ class, explained in the very next section. - -This file defines a class called +Rails::Plugin+ which descends from +Rails::Engine+. - -This defines the first few initializers for the Rails stack: - -* load_init_rb -* sanity_check_railties_collisons - -These are explained in the Initialization section. TODO: First write initialization section then come back here and link. -TODO: Expand. - -h4. +require 'rails/engine'+ - -This file requires _rails/railtie.rb_ which defines +Rails::Railtie+. - -+Rails::Engine+ defines a couple of further initializers for your application: - -* set_load_path -* set_autoload_paths -* add_routing_paths -* add_routing_namespaces -* add_locales -* add_view_paths -* add_generator_templates -* load_application_initializers -* load_application_classes - -These are explained in the Initialization section. TODO: First write initialization section then come back here and link. - -Also in here we see that a couple of methods are +delegate+'d: - -<ruby> - delegate :middleware, :paths, :root, :to => :config -</ruby> - -This means when you call either the +middleware+, +paths+ or +root+ methods you are in reality calling +config.middleware+, +config.paths+ and +config.root+ respectively. - -+Rails::Engine+ descends from +Rails::Railtie+. - -h4. +require 'rails/railtie'+ - -+Rails::Railtie+ (_pronounced Rail-tie, as in a bowtie_), provides a method of classes to hook into Rails, providing them with methods to add generators, rake tasks and subscribers. All of the facets of Rails are their own Railtie. and as you've probably already figured out, the engines that you use are railties too. Plugins also can be railties, but they do not have to be. - -Here there's requires to _rails/initializable.rb_ and and _rails/configurable.rb_. - -h4. +require 'rails/initializable'+ - -The +Rails::Initializable+ module includes methods helpful for the initialization process in rails, such as the method to define initializers: +initializer+. This is included into +Rails::Railtie+ so it's available there as well as +Rails::Engine+, +Rails::Application+ and +YourApp::Application+. In here we also see the class definition for +Rails::Initializer+, the class for all initializer objects. - -h4. +require 'rails/configuration'+ - -The +Rails::Configuration+ module sets up shared configuration for applications, engines and plugins alike. - -At the top of this file there are three +require+s: - -<ruby> - require 'active_support/ordered_options' - require 'rails/paths' - require 'rails/rack' -</ruby> - -h4. +require 'active_support/ordered_options'+ - -+ActiveSupport::OrderedOptions+ is a special-purpose +OrderedHash+, used for keeping track of the options specified in the configuration of your application. - -TODO: expand. - -h4. +require 'rails/paths'+ - -This file is used to set up the +Rails::Paths+ module which is used to set up helpers for referencing paths to the folders of your Rails application, such as in _railties/lib/rails/engine/configuration.rb_ where it is used to firstly define them: - -<ruby> - def paths - @paths ||= begin - paths = Rails::Paths::Root.new(@root) - paths.app "app", :eager_load => true, :glob => "*" - paths.app.controllers "app/controllers", :eager_load => true - paths.app.helpers "app/helpers", :eager_load => true - paths.app.models "app/models", :eager_load => true - paths.app.mailers "app/mailers", :eager_load => true - paths.app.views "app/views", :eager_load => true - paths.lib "lib", :load_path => true - paths.lib.tasks "lib/tasks", :glob => "**/*.rake" - paths.lib.templates "lib/templates" - paths.config "config" - paths.config.initializers "config/initializers", :glob => "**/*.rb" - paths.config.locales "config/locales", :glob => "*.{rb,yml}" - paths.config.routes "config/routes.rb" - paths.public "public" - paths.public.javascripts "public/javascripts" - paths.public.stylesheets "public/stylesheets" - paths - end - end -</ruby> - -You can then get to these helper methods by calling +YourApp::Application.config.paths+. - -h4. +require 'rails/rack'+ - -This file sets up some +autoload+'d constants for +Rails::Rack+: - -<ruby> - module Rails - module Rack - autoload :Debugger, "rails/rack/debugger" - autoload :Logger, "rails/rack/logger" - autoload :LogTailer, "rails/rack/log_tailer" - autoload :Static, "rails/rack/static" - end + if ARGV.first == 'plugin' + ARGV.shift + require 'rails/commands/plugin_new' + else + require 'rails/commands/application' end </ruby> -h4. +require 'rails/version'+ - -Now we're back to _rails.rb_. The line after +require 'rails/application'+ in _rails.rb_ is: +The +rbconfig+ file here is out of Ruby's standard library and provides us with the +RbConfig+ class which contains useful information dependent on how Ruby was compiled. We'll see this in use in +railties/lib/rails/script_rails_loader+. <ruby> - require 'rails/version' -</ruby> - -The code in this file declares +Rails::VERSION+ so that the version number can easily be accessed. It stores it in constants, with the final version number being attainable by calling +Rails::VERSION::STRING+. - -h4. +require 'rails/deprecation'+ - -This sets up a couple of familiar constants: +RAILS_ENV+, +RAILS_ROOT+ and +RAILS_DEFAULT_LOGGER+ to still be usable, but raise a deprecation warning when they are. Their alternatives are now +Rails.env+, +Rails.root+ and +Rails.logger+ respectively. - -If you wish to know more about how they're deprecated see the +require 'active_support/deprecation/proxy_wrappers'+ section. TODO: link to section. - -h4. +require 'rails/log_subscriber'+ - -The +Rails::LogSubscriber+ provides a central location for logging in Rails 3 so as to not slow down the main thread. When you call one of the logging methods (+info+, +debug+, +warn+, +error+, +fatal+ or +unknown+) from the +Rails::LogSubscriber+ class or one of its subclasses this will notify the Rails logger to log this call in the fashion you specify, but will not write it to the file. The file writing is done at the end of the request, courtesy of the +Rails::Rack::Logger+ middleware. - -Each Railtie defines its own class that descends from +Rails::LogSubscriber+ with each defining its own methods for logging individual tasks. - -h4. +require 'rails/ruby_version_check'+ - -This file ensures that you're running a minimum of 1.8.7. If you're running an older version, it will tell you: - -<pre> - Rails requires Ruby version 1.8.7 or later. - You're running [your Ruby version here]; please upgrade to continue. -</pre> - -h4. +require 'activesupport/railtie'+ - -This file declares two Railties, one for ActiveSupport and the other for I18n. In these Railties there's the following initializers defined: - -* active_support.initialize_whiny_nils -* active_support.initialize_time_zone - -* i18n.initialize - -This Railtie also defines an an +after_initialize+ block, which will (as the name implies) be ran after the initialization process. More on this later. TODO: When you write the section you can link to it. - -h4. +require 'action_dispatch/railtie'+ - -This file is explained in the ActionDispatch Railtie Section. TODO: link - -h4. Return to _rails/all.rb_ - -Now that we've covered the extensive process of what the first line does in this file, lets cover the remainder: - -<ruby> - %w( - active_record - action_controller - action_mailer - active_resource - rails/test_unit - ).each do |framework| - begin - require "#{framework}/railtie" - rescue LoadError - end - end -</ruby> - -As you may be able to tell from the code, this is going through and loading all the Railties for Active Record, Action Controller, Action Mailer, Active Resource. Two other Railties, one for Active Support and one for Action Dispatch were required earlier, but are still covered in this section for continuity reasons. TODO: link. - -h4. ActiveSupport Railtie - -From Active Support's README: - -Active Support is a collection of various utility classes and standard library extensions that were found useful for Rails. - -TODO: Quotify. - -h5. +require 'active_support/railtie'+ - +require 'pathname' -h4. Active Record Railtie - -The Active Record Railtie takes care of hooking Active Record into Rails. This depends on Active Support, Active Model and Arel. From Active Record's readme: - -TODO: Quotify. - -<plain> - Active Record connects business objects and database tables to create a persistable domain model where logic and data are presented in one wrapping. It's an implementation of the object-relational mapping (ORM) pattern by the same name as described by Martin Fowler: - - "An object that wraps a row in a database table or view, encapsulates - the database access, and adds domain logic on that data." - - Active Record's main contribution to the pattern is to relieve the original of two stunting problems: - lack of associations and inheritance. By adding a simple domain language-like set of macros to describe - the former and integrating the Single Table Inheritance pattern for the latter, Active Record narrows the - gap of functionality between the data mapper and active record approach. -</plain> - -h5. +require "active_record/railtie"+ - -The _activerecord/lib/active_record/railtie.rb_ file defines the Railtie for Active Record. - -This file first requires Active Record, the _railties/lib/rails.rb_ file which has already been required and so will be ignored, and the Active Model Railtie: - -<ruby> - require "active_record" - require "rails" - require "active_model/railtie" -</ruby> - -Active Model's Railtie is covered in the next section. TODO: Section. - -h5. +require "active_record"+ - -TODO: Why are +activesupport_path+ and +activemodel_path+ defined here? - -The first three requires require ActiveSupport, Active Model and ARel in that order: - -<ruby> - require 'active_support' - require 'active_model' - require 'arel' -</ruby> - - -h5. +require "active_support"+ - -This was loaded earlier by _railties/lib/rails.rb_. This line is here as a safeguard for when Active Record is loaded outside the scope of Rails. - -h5. +require "active_model"+ - -TODO: Again with the +activesupport_path+! - -Here we see another +require "active_support"+ this is again, a safeguard for when Active Model is loaded outside the scope of Rails. - -This file defines a few +autoload+'d modules for Active Model, requires +active_support/i18n+ and adds the default translation file for Active Model to +I18n.load_path+. - -The +require 'active_support/i18n'+ just loads I18n and adds Active Support's default translations file to +I18n.load_path+ too: - -<ruby> - require 'i18n' - I18n.load_path << "#{File.dirname(__FILE__)}/locale/en.yml -</ruby> - - -h5. +require "arel"+ - -This file in _arel/lib/arel.rb_ loads a couple of Active Support things first: - -<ruby> - require 'active_support/inflector' - require 'active_support/core_ext/module/delegation' - require 'active_support/core_ext/class/attribute_accessors' -</ruby> - -These files are explained in the "Common Includes" section. - -h5. +require 'arel'+ - -Back in _arel/lib/arel.rb_, the next two lines require Active Record parts: - -<ruby> - require 'active_record' - require 'active_record/connection_adapters/abstract/quoting' -</ruby> - -Because we're currently loading _active_record.rb_, it skips right over it. - -h5. +require 'active_record/connection_adapters/abstract/quoting'+ - -_activerecord/lib/active_record/connection_adapters/abstract/quoting.rb_ defines methods used for quoting fields and table names in Active Record. - -TODO: Explain why this is loaded especially. - -h5. +require 'active_record'+ - -Back the initial require from the _railtie.rb_. - -The _active_support_ and _active_model_ requires are again just an insurance for if we're loading Active Record outside of the scope of Rails. In _active_record.rb_ the ActiveRecord +Module+ is initialized and in it there is defined a couple of +autoloads+ and +eager_autoloads+. - -There's a new method here called +autoload_under+ which is defined in +ActiveSupport::Autoload+. This sets the autoload path to temporarily be the specified path, in this case +relation+ for the +autoload+'d classes inside the block. - -Inside this file the +AttributeMethods+, +Locking+ and +ConnectionAdapter+ modules are defined inside the +ActiveRecord+ module. The second to last line tells Arel what SQL engine we want to use. In this case it's +ActiveRecord::Base+. The final line adds in the translations for Active Record which are only for if a record is invalid or non-unique. - -h5. +require 'rails'+ - -As mentioned previously this is skipped over as it has been already loaded. If you'd still like to see what this file does go to section TODO: section. - -h5. +require 'active_model/railtie'+ - -This is covered in the Active Model Railtie section. TODO: link there. - -h5. +require 'action_controller/railtie'+ - -This is covered in the Action Controller Railtie section. TODO: link there. - -h5. The Active Record Railtie - -Inside the Active Record Railtie the +ActiveRecord::Railtie+ class is defined: - -<ruby> - module ActiveRecord - class Railtie < Rails::Railtie - +module Rails + module ScriptRailsLoader + RUBY = File.join(*RbConfig::CONFIG.values_at("bindir", "ruby_install_name")) + RbConfig::CONFIG["EXEEXT"] + SCRIPT_RAILS = File.join('script', 'rails') ... - end - end -</ruby> - -TODO: Explain the logger. - -By doing this the +ActiveRecord::Railtie+ class gains access to the methods contained within +Rails::Railtie+ such as +rake_tasks+, +log_subscriber+ and +initiailizer+, all of which the Railtie is using in this case. The initializers defined here are: - -* active_record.initialize_timezone -* active_record.logger -* active_record.set_configs -* active_record.initialize_database -* active_record.log_runtime -* active_record.initialize_database_middleware -* active_record.load_observers -* active_record.set_dispatch_hooks - -As with the engine initializers, these are explained later. - - -h4. Active Model Railtie - -This Railtie is +require+'d by Active Record's Railtie. - -From the Active Model readme: - -<plain> - Prior to Rails 3.0, if a plugin or gem developer wanted to be able to have an object interact with Action Pack helpers, it was required to either copy chunks of code from Rails, or monkey patch entire helpers to make them handle objects that did not look like Active Record. This generated code duplication and fragile applications that broke on upgrades. - - Active Model is a solution for this problem. - - Active Model provides a known set of interfaces that your objects can implement to then present a common interface to the Action Pack helpers. -</plain> - - -h5. +require "active_model/railtie"+ - -This Railtie file, _activemodel/lib/active_model/railtie.rb_ is quite small and only requires in +active_model+. As mentioned previously, the require to _rails_ is skipped over as it has been already loaded. If you'd still like to see what this file does go to section TODO: section. - -<ruby> - require "active_model" - require "rails" -</ruby> - -h5. +require "active_model"+ - -Active Model depends on Active Support and ensures it is required by making a +require 'active_support'+ call. It has already been loaded from _railties/lib/rails.rb_ so will not be reloaded for us here. The file goes on to define the +ActiveModel+ module and all of its autoloaded classes. This file also defines the english translations for some of the validation messages provided by Active Model, such as "is not included in the list" and "is reserved". - -h4. Action Controller Railtie - -The Action Controller Railtie takes care of all the behind-the-scenes code for your controllers; it puts the C into MVC; and does so by implementing the +ActionController::Base+ class which you may recall is where your +ApplicationController+ class descends from. - -h5. +require 'action_controller/railtie'+ - -This first makes a couple of requires: - -<ruby> - require "action_controller" - require "rails" - require "action_view/railtie" -</ruby> - -The _action_controller_ file is explained in the very next section. The require to _rails_ is requiring the already-required _railties/lib/rails.rb_. If you wish to know about the require to _action_view/railtie_ this is explained in the Action View Railtie section. - -h5. +require 'action_controller+ - -This file, _actionpack/lib/action_controller.rb_, defines the Action Controller module and its relative autoloads. Before it does any of that it makes two requires: one to _abstract_controller_, explored next, and the other to _action_dispatch_, explored directly after that. - -h5. +require 'abstract_controller'+ - -+AbstractController+ provides the functionality of TODO. - -This file is in _actionpack/lib/abstract_controller.rb_ and begins by attempting to add the path to Active Support to the load path, which it would succeed in if it wasn't already set by anything loaded before it. In this case, it's not going to be set due to Arel already loading it in (TODO: right?). - -The next thing in this file four +require+ calls: - -<ruby> - require 'active_support/ruby/shim' - require 'active_support/dependencies/autoload' - require 'active_support/core_ext/module/attr_internal' - require 'active_support/core_ext/module/delegation' -</ruby> - -After these require calls the +AbstractController+ module is defined with some standard +autoload+'d classes. - - -h5. +require 'active_support/ruby/shim'+ - -This file is explained in the "Common Includes" section beneath. - -h5. +require 'active_support/dependencies/autoload+ - -This file was loaded upon the first require of +active_support+ and is not included. If you wish to be refreshed on what this file performs visit TODO: link to section. - -h5. +require 'active_support/core_ext/module/attr_internal'+ - -This file is explained in the "Common Includes" section as it is required again later on. See the TODO: section. I also think this may be explained in the Active Support Core Extensions guide. - -h5. +require 'active_support/core_ext/module/delegation'+ - -This file is explained in the "Common Includes" section as it has already been required by Arel at this point in the initialization process (see: section TODO: LINK!). - -h5. +require 'action_controller'+ - -Back to _actionpack/lib/action_controller.rb_. - -After the initial call to +require 'abstract_controller'+, this calls +require 'action_dispatch'+ which was required earlier by _railties/lib/rails.rb_. The purpose of this file is explained in the ActionDispatch Railtie section. - -This file defines the +ActionController+ module and its autoloaded classes. - -Here we have a new method called +autoload_under+. This was covered in the Active Record Railtie but it is covered here also just in case you missed or skimmed over it. The +autoload_under+ method is defined in +ActiveSupport::Autoload+ and it sets the autoload path to temporarily be the specified path, in this case by specifying _metal_ it will load the specified +autoload+'d classes from _lib/action_controller/metal_ inside the block. - -Another new method we have here is called +autoload_at+: - -<ruby> - autoload_at "action_controller/metal/exceptions" do - autoload :ActionControllerError - autoload :RenderError - autoload :RoutingError - autoload :MethodNotAllowed - autoload :NotImplemented - autoload :UnknownController - autoload :MissingFile - autoload :RenderError - autoload :SessionOverflowError - autoload :UnknownHttpMethod - end -</ruby> - -This defines the path of which to find these classes defined at and is most useful for if you have multiple classes defined in a single file, as is the case for this block; all of those classes are defined inside _action_controller/metal/exceptions.rb_ and when Active Support goes looking for them it will look in that file. - -At the end of this file there are a couple more requires: - -<ruby> - # All of these simply register additional autoloads - require 'action_view' - require 'action_controller/vendor/html-scanner' - - # Common Active Support usage in ActionController - require 'active_support/concern' - require 'active_support/core_ext/class/attribute_accessors' - require 'active_support/core_ext/load_error' - require 'active_support/core_ext/module/attr_internal' - require 'active_support/core_ext/module/delegation' - require 'active_support/core_ext/name_error' - require 'active_support/inflector' -</ruby> - -h5. +require 'action_view'+ - -This is best covered in the Action View Railtie section, so skip there by TODO: Link / page? - -h5. +require 'action_controller/vendor/html-scanner'+ - -TODO: What is the purpose of this? Find out. - -h5. +require 'active_support/concern'+ - -TODO: I can kind of understand the purpose of this.. need to see where @_dependencies is used however. - -h5. +require 'active_support/core_ext/class/attribute_accessors'+ - -This file defines, as the path implies, attribute accessors for class. These are +cattr_reader+, +cattr_writer+, +cattr_accessor+. - -h5. +require 'active_support/core_ext/load_error'+ - -The Active Support Core Extensions (TODO: LINK!) guide has a great coverage of what this file precisely provides. - -h5. +require 'active_support/core_ext/module/attr_internal'+ - -This file is explained in the "Core Extension" guide. - -This file was required through the earlier _abstract_controller.rb_ require. - -h5. +require 'active_support/core_ext/module/delegation'+ - -This file is explained in the "Common Includes" section. - -This file was required earlier by Arel and so is not required again. - -h5. +require 'active_support/core_ext/name_error'+ - -This file includes extensions to the +NameError+ class, providing the +missing_name+ and +missing_name?+ methods. For more information see the Active Support Core Extensions guide. - -h5. +require 'active_support/inflector'+ - -This file is explained in the "Common Includes" section. - -This file was earlier required by Arel and so is not required again. - -h5. Action Controller Railtie - -So now we come back to the Action Controller Railtie with a couple more requires to go before +ActionController::Railtie+ is defined: - -<ruby> - require "action_view/railtie" - require "active_support/core_ext/class/subclasses" - require "active_support/deprecation/proxy_wrappers" - require "active_support/deprecation" -</ruby> - -As explained previously the +action_view/railtie+ file will be explained in the Action View Railtie section. TODO: link to it. - -h5. +require 'active_support/core_ext/class/subclasses'+ - -For an explanation of this file _activesupport/lib/active_support/core_ext/class/subclasses_, see the Active Support Core Extension guide. - -h5. +require 'active_support/deprecation/proxy_wrappers'+ - -This file, _activesupport/lib/active_support/deprecation/proxy_wrappers.rb_, defines a couple of deprecation classes, which are +DeprecationProxy+, +DeprecationObjectProxy+, +DeprecationInstanceVariableProxy+, +DeprecationConstantProxy+ which are all namespaced into +ActiveSupport::Deprecation+. These last three are all subclasses of +DeprecationProxy+. - -Why do we mention them here? Beside the obvious-by-now fact that we're covering just about everything about the initialization process in this guide, if you're deprecating something in your library and you use Active Support, you too can use the +DeprecationProxy+ class (and it's subclasses) too. - - -h6. +DeprecationProxy+ - -This class is used only in _railties/lib/rails/deprecation.rb_, loaded further on in the initialization process. It's used in this way: - -<ruby> - RAILS_ROOT = (Class.new(ActiveSupport::Deprecation::DeprecationProxy) do - cattr_accessor :warned - self.warned = false - - def target - Rails.root - end - - def replace(*args) - warn(caller, :replace, *args) - end - - def warn(callstack, called, args) - unless warned - ActiveSupport::Deprecation.warn("RAILS_ROOT is deprecated! Use Rails.root instead", callstack) - self.warned = true - end - end - end).new -</ruby> - -There is similar definitions for the other constants of +RAILS_ENV+ and +RAILS_DEFAULT_LOGGER+. All three of these constants are in the midst of being deprecated (most likely in Rails 3.1) so Rails will tell you if you reference them that they're deprecated using the +DeprecationProxy+ class. Whenever you call +RAILS_ROOT+ this will raise a warning, telling you: "RAILS_ROOT is deprecated! Use Rails.root instead".... TODO: investigate if simply calling it does raise this warning. This same rule applies to +RAILS_ENV+ and +RAILS_DEFAULT_LOGGER+, their new alternatives are +Rails.env+ and +Rails.logger+ respectively. - -h6. +DeprecatedObjectProxy+ - -This is used in one place _actionpack/lib/action_controller/railtie.rb_, which you may remember is how we got to the +DeprecationProxy+ section: - -<ruby> - ActiveSupport::Deprecation::DeprecatedObjectProxy.new(app.routes, message) -</ruby> - -This makes more sense in the wider scope of the initializer: - -<ruby> - initializer "action_controller.url_helpers" do |app| - ActionController.base_hook do - extend ::ActionController::Railtie::UrlHelpers.with(app.routes) - end - message = "ActionController::Routing::Routes is deprecated. " \ - "Instead, use Rails.application.routes" - - proxy = ActiveSupport::Deprecation::DeprecatedObjectProxy.new(app.routes, message) - ActionController::Routing::Routes = proxy end +end </ruby> -+ActionController::Routing::Routes+ was the previous constant used in defining routes in Rails 2 applications, now it's simply a method on +Rails.application+ rather than it's own individual class: +Rails.application.routes+. Both of these still call the +draw+ method on the returned object to end up defining the routes. - - -h6. +DeprecatedInstanceVariableProxy+ - -This isn't actually used anywhere in Rails anymore. It was used previously for when +@request+ and +@params+ were deprecated in Rails 2. It has been kept around as it could be useful for the same purposes in libraries that use Active Support. - -h6. +DeprecatedConstantProxy+ - -This method is used in a couple of places, _activesupport/lib/active_support/json/encoding.rb_ and _railties/lib/rails/rack.rb_. - -In _encoding.rb_ it's used to define a constant that's now been deprecated: - -<ruby> - CircularReferenceError = Deprecation::DeprecatedConstantProxy.new('ActiveSupport::JSON::CircularReferenceError', Encoding::CircularReferenceError) -</ruby> - +The +rails/script_rails_loader+ file uses +RbConfig::Config+ to gather up the +bin_dir+ and +ruby_install_name+ values for the configuration which will result in a path such as +/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby+, which is the default path on Mac OS X. If you're running Windows the path may be something such as +C:/Ruby192/bin/ruby+. Anyway, the path on your system may be different, but the point of this is that it will point at the known ruby executable location for your install. The +RbConfig::CONFIG["EXEEXT"]+ will suffix this path with ".exe" if the script is running on Windows. This constant is used later on in +exec_script_rails!+. As for the +SCRIPT_RAILS+ console, we'll see that when we get to the +in_rails_application?+ method. -Now when you reference +ActiveSupport::JSON::CircularReferenceError+ you'll receive a warning: - -<plain> - ActiveSupport::JSON::CircularReferenceError is deprecated! Use Encoding::CircularReferenceError instead. -</plain> - -h5. +require "active_support/deprecation"+ - -This re-opens the +ActiveSupport::Deprecation+ module which was already defined by our deprecation proxies. Before this happens however we have 4 requires: +Back in +rails/cli+, the next line is this: <ruby> - require 'active_support/deprecation/behaviors' - require 'active_support/deprecation/reporting' - require 'active_support/deprecation/method_wrappers' - require 'active_support/deprecation/proxy_wrappers' + Rails::ScriptRailsLoader.exec_script_rails! </ruby> -The remainder of this file goes about setting up the +silenced+ and +debug+ accessors: +This method is defined in +rails/script_rails_loader+ like this: <ruby> - module ActiveSupport - module Deprecation #:nodoc: - class << self - # The version the deprecated behavior will be removed, by default. - attr_accessor :deprecation_horizon - end - self.deprecation_horizon = '3.0' - - # By default, warnings are not silenced and debugging is off. - self.silenced = false - self.debug = false + def self.exec_script_rails! + cwd = Dir.pwd + return unless in_rails_application? || in_rails_application_subdirectory? + exec RUBY, SCRIPT_RAILS, *ARGV if in_rails_application? + Dir.chdir("..") do + # Recurse in a chdir block: if the search fails we want to be sure + # the application is generated in the original working directory. + exec_script_rails! unless cwd == Dir.pwd end + rescue SystemCallError + # could not chdir, no problem just return end </ruby> -h5. +require "active_support/deprecation/behaviors"+ - -This sets up some default behavior for the warnings raised by +ActiveSupport::Deprecation+, defining different ones for _development_ and _test_ and nothing for production, as we never want deprecation warnings in production: - -<ruby> - # Default warning behaviors per Rails.env. Ignored in production. - DEFAULT_BEHAVIORS = { - 'test' => Proc.new { |message, callstack| - $stderr.puts(message) - $stderr.puts callstack.join("\n ") if debug - }, - 'development' => Proc.new { |message, callstack| - logger = - if defined?(Rails) && Rails.logger - Rails.logger - else - require 'logger' - Logger.new($stderr) - end - logger.warn message - logger.debug callstack.join("\n ") if debug - } - } -</ruby> - -In the _test_ environment, we will see the deprecation errors displayed in +$stderr+ and in _development_ mode, these are sent to +Rails.logger+ if it exists, otherwise it is output to +$stderr+ in a very similar fashion to the _test_ environment. These are both defined as procs, so Active Support can pass arguments to the +call+ method we call on it when Active Support +warn+. - -h5. +require 'active_support/deprecation/reporting'+ - -This file defines further extensions to the +ActiveSupport::Deprecation+ module, including the +warn+ method which is used from Active Support's +DeprecationProxy+ class and an +attr_accessor+ on the class called +silenced+. This checks that we have a behavior defined, which we do in the _test_ and _development_ environments, and that we're not +silenced+ before warning about deprecations by +call+'ing the +Proc+ time. - -This file also defines a +silence+ method on the module also which you can pass a block to temporarily silence errors: +This method will first check if the current working directory (+cwd+) is a Rails application or is a subdirectory of one. The way to determine this is defined in the +in_rails_application?+ method like this: <ruby> - ActiveSupport::Deprecation.silence do - puts "YOU CAN FIND ME HERE: #{RAILS_ROOT}" + def self.in_rails_application? + File.exists?(SCRIPT_RAILS) end </ruby> -TODO: may have to correct this example. - -h5. +require 'active_support/deprecation/method_wrappers'+ - -This file defines a class method on +ActiveSupport::Deprecation+ called +deprecate_methods+. This method is used in _activesupport/lib/active_support/core_ext/module/deprecation.rb_ to allow you to declare deprecated methods on modules: +The +SCRIPT_RAILS+ constant defined earlier is used here, with +File.exists?+ checking for its presence in the current directory. If this method returns +false+, then +in_rails_application_subdirectory?+ will be used: <ruby> - class Module - # Declare that a method has been deprecated. - # deprecate :foo - # deprecate :bar => 'message' - # deprecate :foo, :bar, :baz => 'warning!', :qux => 'gone!' - def deprecate(*method_names) - ActiveSupport::Deprecation.deprecate_methods(self, *method_names) - end + def self.in_rails_application_subdirectory?(path = Pathname.new(Dir.pwd)) + File.exists?(File.join(path, SCRIPT_RAILS)) || !path.root? && in_rails_application_subdirectory?(path.parent) end </ruby> -h5. +require 'action_controller/railtie'+ - -Inside +ActionController::Railtie+ there are another two requires: +This climbs the directory tree until it reaches a path which contains a +script/rails+ file. If a directory is reached which contains this file then this line will run: <ruby> - require "action_controller/railties/log_subscriber" - require "action_controller/railties/url_helpers" + exec RUBY, SCRIPT_RAILS, *ARGV if in_rails_application? </ruby> +This is effectively the same as doing +ruby script/rails [arguments]+. Where +[arguments]+ at this point in time is simply "server". -h5. +require 'action_controller/railties/log_subscriber'+ - -+ActionController::Railties::LogSubscriber+ inherits from +Rails::LogSubscriber+ and defines methods for logging such things as action processing and file sending. - -h5. +require 'action_controller/railties/url_helpers'+ - -This file defines a +with+ method on +ActionController::Railtie::UrlHelpers+ which is later used in the +action_controller.url_helpers+ initializer. For more information see the +action_controller.url_helpers+ initializer section. - -h5. Action Controller Railtie - -After these requires it deprecates a couple of ex-Action Controller methods and points whomever references them to their ActionDispatch equivalents. These methods are +session+, +session=+, +session_store+ and +session_store=+. - -After the deprecations, Rails defines the +log_subscriber+ to be a new instance of +ActionController::Railties::LogSubscriber+ and then go about defining the following initializers, keeping in mind that these are added to the list of initializers defined before hand: - -* action_controller.logger -* action_controller.set_configs -* action_controller.initialize_framework_caches -* action_controller.set_helpers_path -* action_controller.url_helpers - -h4. Action View Railtie +h4. +script/rails+ -The Action View Railtie provides the backend code for your views and it puts the C into MVC. This implements the +ActionView::Base+ of which all views and partials are objects of. - -h5. +require 'action_view/railtie'+ - -The Railtie is defined in a file called _actionpack/lib/action_view/railtie.rb_ and initially makes a call to +require 'action_view'+. - -h5. +require 'action_view'+ - -Here again we have the addition of the path to Active Support to the load path attempted, but because it's already in the load path it will not be added. Similarly, we have two requires: - -<ruby> - require 'active_support/ruby/shim' - require 'active_support/core_ext/class/attribute_accessors' -</ruby> - -And these have already been required. If you wish to know what these files do go to the explanation of each in the "Common Includes" section. TODO: link to them! - -This file goes on to +require 'action_pack'+ which consists of all this code (comments stripped): +This file looks like this: <ruby> - require 'action_pack/version' + APP_PATH = File.expand_path('../../config/application', __FILE__) + require File.expand_path('../../config/boot', __FILE__) + require 'rails/commands' </ruby> -the _version_ file contains this code (comments stripped): +The +APP_PATH+ constant here will be used later in +rails/commands+. The +config/boot+ file that +script/rails+ references is the +config/boot.rb+ file in our application which is responsible for loading Bundler and setting it up. -<ruby> - module ActionPack #:nodoc: - module VERSION #:nodoc: - MAJOR = 3 - MINOR = 0 - TINY = "0.beta1" - - STRING = [MAJOR, MINOR, TINY].join('.') - end - end -</ruby> - -TODO: Why?! +h4. +config/boot.rb+ -This file goes on to define the +ActionView+ module and its +autoload+'d modules and then goes on to make two more requires: ++config/boot.rb+ contains this: <ruby> - require 'active_support/core_ext/string/output_safety' - require 'action_view/base' -</ruby> - -h5. +require 'active_support/core_ext/string/output_safety'+ - -The _actionpack/lib/active_support/core_ext/string/output_saftey.rb_ file is responsible for the code used in escaping HTML and JSON, namely the +html_escape+ and +json_escape+ methods. It does this by overriding these methods in +Erb::Util+ which is later included into +ActionView::Base+. This also defines +ActiveSupport::SafeBuffer+ which descends from +String+ and is used for concatenating safe output from your views to ERB templates. - -h5. +require 'action_view/base'+ - -This file initially makes requires to the following files: + require 'rubygems' -<ruby> - require 'active_support/core_ext/module/attr_internal' - require 'active_support/core_ext/module/delegation' - require 'active_support/core_ext/class/attribute' + # Set up gems listed in the Gemfile. + gemfile = File.expand_path('../../Gemfile', __FILE__) + begin + ENV['BUNDLE_GEMFILE'] = gemfile + require 'bundler' + Bundler.setup + rescue Bundler::GemNotFound => e + STDERR.puts e.message + STDERR.puts "Try running `bundle install`." + exit! + end if File.exist?(gemfile) </ruby> -These are explained in their relevant areas inside the "Common Includes" section. - -The remainder of this file sets up the +ActionView+ module and the +ActionView::Base+ class which is the class of all view templates. Inside of +ActionView::Base+ it makes an include to several helper modules: +In a standard Rails application, there's a +Gemfile+ which declares all dependencies of the application. +config/boot.rb+ sets +ENV["BUNDLE_GEMFILE"]+ to the location of this file, then requires Bundler and calls +Bundler.setup+ which adds the dependencies of the application (including all the Rails parts) to the load path, making them available for the application to load. The gems that a Rails 3.1 application depends on are as follows: + +* abstract (1.0.0) +* actionmailer (3.1.0.beta) +* actionpack (3.1.0.beta) +* activemodel (3.1.0.beta) +* activerecord (3.1.0.beta) +* activeresource (3.1.0.beta) +* activesupport (3.1.0.beta) +* arel (2.0.7) +* builder (3.0.0) +* bundler (1.0.6) +* erubis (2.6.6) +* i18n (0.5.0) +* mail (2.2.12) +* mime-types (1.16) +* polyglot (0.3.1) +* rack (1.2.1) +* rack-cache (0.5.3) +* rack-mount (0.6.13) +* rack-test (0.5.6) +* rails (3.1.0.beta) +* railties (3.1.0.beta) +* rake (0.8.7) +* sqlite3-ruby (1.3.2) +* thor (0.14.6) +* treetop (1.4.9) +* tzinfo (0.3.23) + +h4. +rails/commands.rb+ + +Once +config/boot.rb+ has finished, the next file that is required is +rails/commands+ which will execute a command based on the arguments passed in. In this case, the +ARGV+ array simply contains +server+ which is extracted into the +command+ variable using these lines: + +<ruby> + aliases = { + "g" => "generate", + "c" => "console", + "s" => "server", + "db" => "dbconsole" + } -<ruby> - include Helpers, Rendering, Partials, Layouts, ::ERB::Util, Context + command = ARGV.shift + command = aliases[command] || command </ruby> -h5. +ActionView::Helpers+ - -This module, from _actionpack/lib/action_view/helpers.rb_, initially sets up the +autoload+'s for the various +ActionView::Helpers+ modules (TODO: mysteriously not using +autoload_under+). This also sets up a +ClassMethods+ module which is included automatically into wherever +ActionView::Helpers+ is included by defining a +self.included+ method: +If we used <tt>s</tt> rather than +server+, Rails will use the +aliases+ defined in the file and match them to their respective commands. With the +server+ command, Rails will run this code: <ruby> - def self.included(base) - base.extend(ClassMethods) - end - - module ClassMethods - include SanitizeHelper::ClassMethods - end -</ruby> - -Inside of +SanitizeHelper::ClassMethods+ it defines, of course, methods for assisting with sanitizing in Rails such as +link_sanitizer+ which is used by the +strip_links+ method. + when 'server' + # Change to the application's path if there is no config.ru file in current dir. + # This allows us to run script/rails server from other directories, but still get + # the main config.ru and properly set the tmp directory. + Dir.chdir(File.expand_path('../../', APP_PATH)) unless File.exists?(File.expand_path("config.ru")) -Afterwards this includes the +ActiveSupport::Benchmarkable+ which is used for benchmarking how long a specific thing takes in a view. The method is simply +benchmark+ and can be used like this: - -<ruby> - benchmark("potentially long running thing") do - Post.count - end + require 'rails/commands/server' + Rails::Server.new.tap { |server| + # We need to require application after the server sets environment, + # otherwise the --environment option given to the server won't propagate. + require APP_PATH + Dir.chdir(Rails.application.root) + server.start + } </ruby> -The "documentation":http://api.rails.info/classes/ActiveSupport/Benchmarkable.html#M000607 is great about explaining what precisely this does. (TODO: replace link with real documentation link when it becomes available.) - -This module is also included into Active Record and +AbstractController+, meaning you can also use the +benchmark+ method in these methods. +This file will change into the root of the directory (a path two directories back from +APP_PATH+ which points at +config/application.rb+), but only if the +config.ru+ file isn't found. This then requires +rails/commands/server+ which requires +action_dispatch+ and sets up the +Rails::Server+ class. -After including +ActiveSupport::Benchmarkable+, the helpers which we have declared to be +autoload+'d are included. I will not go through and cover what each of these helpers do, as their names should be fairly explicit about it, and it's not really within the scope of this guide. +h4. +actionpack/lib/action_dispatch.rb+ -h5. +ActionView::Rendering+ +Action Dispatch is the routing component of the Rails framework. It depends on Active Support, +actionpack/lib/action_pack.rb+ and +Rack+ being available. The first thing required here is +active_support+. -This module, from _actionpack/lib/action_view/render/rendering.rb_ defines a method you may be a little too familiar with: +render+. This is the +render+ use for rendering all kinds of things, such as partials, templates and text. +h4. +activesupport/lib/active_support.rb+ -h5. +ActionView::Partials+ +This file begins with requiring +active_support/lib/active_support/dependencies/autoload.rb+ which redefines Ruby's +autoload+ method to have a little more extra behaviour especially in regards to eager autoloading. Eager autoloading is the loading of all required classes and will happen when the +config.cache_classes+ setting is +true+. The required file also requires another file: +active_support/lazy_load_hooks+ -This module, from _actionpack/lib/action_view/render/partials.rb_, defines +ActionView::Partials::PartialRenderer+ which you can probably guess is used for rendering partials. +h4. +activesupport/lib/active_support/lazy_load_hooks.rb+ -h5. +ActionView::Layouts+ +This file defines the +ActiveSupport.on_load+ hook which is used to execute code when specific parts are loaded. We'll see this in use a little later on. -This module, from _actionpack/lib/action_view/render/layouts.rb_, defines +ActionView::Layouts+ which defines methods such as +find_layout+ for locating layouts. +This file begins with requiring +active_support/inflector/methods+. -h5. +ERB::Util+ +h4. +activesupport/lib/active_support/inflector/methods.rb+ -The +ERB::Util+ module from Ruby core, as the document describes it: "A utility module for conversion routines, often handy in HTML generation". It offers two methods +html_escape+ and +url_encode+, with a third called +json_escape+ being added in by the requirement of _actionpack/lib/active_support/core_ext/string/output_saftey.rb_ earlier. As explained earlier, +html_escape+ is overridden to return a string marked as safe. - -h5. +ActionView::Context+ - -TODO: Not entirely sure what this is all about. Something about the context of view rendering... can't work it out. - -h5. Action View Railtie - -Now that _actionpack/lib/action_view.rb_ has been required, the next step is to +require 'rails'+, but this will be skipped as the file was required by _railties/lib/rails/all.rb_ way back in the beginnings of the initialization process. - -Next, the Railtie itself is defined: +The +methods.rb+ file is responsible for defining methods such as +camelize+, +underscore+ and +dasherize+ as well as a slew of others. The "+ActiveSupport::Inflector+ documentation":http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html covers them all pretty decently. +In this file there are a lot of lines such as this inside the +ActiveSupport+ module: <ruby> - module ActionView - class Railtie < Rails::Railtie - railtie_name :action_view - - require "action_view/railties/log_subscriber" - log_subscriber ActionView::Railties::LogSubscriber.new - - initializer "action_view.cache_asset_timestamps" do |app| - unless app.config.cache_classes - ActionView.base_hook do - ActionView::Helpers::AssetTagHelper.cache_asset_timestamps = false - end - end - end - end - end -</ruby> - -The +ActionView::LogSubscriber+ sets up a method called +render_template+ which is called when a template is rendered. TODO: Templates only or partials and layouts also? I would imagine these fall under the templates category, but there needs to research to ensure this is correct. - -The sole initializer defined here, _action_view.cache_asset_timestamps_ is responsible for caching the timestamps on the ends of your assets. If you've ever seen a link generated by +image_tag+ or +stylesheet_link_tag+ you would know that I mean that this timestamp is the number after the _?_ in this example: _/javascripts/prototype.js?1265442620_. This initializer will do nothing if +cache_classes+ is set to false in any of your application's configuration. TODO: Elaborate. - -h4. Action Mailer Railtie - -The Action Mailer Railtie is responsible for including all the emailing functionality into Rails by way of the Action Mailer gem itself. Action Mailer is: - -Action Mailer is a framework for designing email-service layers. These layers -are used to consolidate code for sending out forgotten passwords, welcome -wishes on signup, invoices for billing, and any other use case that requires -a written notification to either a person or another system. - -Action Mailer is in essence a wrapper around Action Controller and the -Mail gem. It provides a way to make emails using templates in the same -way that Action Controller renders views using templates. - -TODO: Quotify. - -h5. +require 'action_mailer/railtie'+ - -This file first makes two requires: - -<ruby> - require "action_mailer" - require "rails" -</ruby> - -The requires in +action_mailer+ are already loaded or are core extensions: - -<ruby> - require 'abstract_controller' - require 'action_view' - - # Common Active Support usage in Action Mailer - require 'active_support/core_ext/class' - require 'active_support/core_ext/object/blank' - require 'active_support/core_ext/array/uniq_by' - require 'active_support/core_ext/module/attr_internal' - require 'active_support/core_ext/module/delegation' - require 'active_support/core_ext/string/inflections' - require 'active_support/lazy_load_hooks' + autoload :Inflector </ruby> -_abstract_controller_ is covered in the "Action Controller Railtie" section. TODO: Cover AbstractController there and link to it. -_action_view_ was required by the Action View Railtie and will not be required again. - -For the core extensions you may reference the "Core Extensions" guide. TODO: Link to guide. - -_active_support/lazy_load_hooks_ was covered earlier in the guide and since it has already been required at this point in the initialization process, it will not be required again. - -The +require "rails"+ is referencing the _railties/lib/rails.rb_ file which was included back in TODO: link to section. - -_actionmailer/lib/action_mailer.rb_ then goes on to define the +ActionMailer+ module: - -<ruby> - module ActionMailer - extend ::ActiveSupport::Autoload - - autoload :AdvAttrAccessor - autoload :Collector - autoload :Base - autoload :DeliveryMethods - autoload :DeprecatedApi - autoload :MailHelper - autoload :OldApi - autoload :Quoting - autoload :TestCase - autoload :TestHelper - end -</ruby> - -And a +Text+ module too: - -<ruby> - module Text - extend ActiveSupport::Autoload - - autoload :Format, 'text/format' - end -</ruby> - -which is used by the +ActionMailer::MailerHelper+ method +block_format+: - -<ruby> - def block_format(text) - formatted = text.split(/\n\r\n/).collect { |paragraph| - Text::Format.new( - :columns => 72, :first_indent => 2, :body_indent => 2, :text => paragraph - ).format - }.join("\n") - - # Make list points stand on their own line - formatted.gsub!(/[ ]*([*]+) ([^*]*)/) { |s| " #{$1} #{$2.strip}\n" } - formatted.gsub!(/[ ]*([#]+) ([^#]*)/) { |s| " #{$1} #{$2.strip}\n" } - - formatted - end -</ruby> +Due to the overriding of the +autoload+ method, Ruby will know to look for this file at +activesupport/lib/active_support/inflector.rb+ when the +Inflector+ class is first referenced. -h5. Action Mailer Railtie +The +active_support/lib/active_support/version.rb+ that is also required here simply defines an +ActiveSupport::VERSION+ constant which defines a couple of constants inside this module, the main constant of this is +ActiveSupport::VERSION::STRING+ which returns the current version of ActiveSupport. -The Railtie defines the +log_subscriber+ as +ActionMailer::Railties::LogSubscriber.new+, with this class having two logging methods: one for delivery called +deliver+ and one for receipt called +receive+. +The +active_support/lib/active_support.rb+ file simply defines the +ActiveSupport+ module and some autoloads (eager and of the normal variety) for it. -The initializers defined in this Railtie are: +h4. +actionpack/lib/action_dispatch.rb+ cont'd. -* action_mailer.url_for -* action_mailer.logger -* action_mailer.set_configs +Now back to +action_pack/lib/action_dispatch.rb+. The next +require+ in this file is one for +action_pack+, which simply calls +action_pack/version.rb+ which defines +ActionPack::VERSION+ and the constants, much like +ActiveSpport+ does. -These are covered later on the Initialization section. TODO: first write then link to Initialization section. +After this line, there's a require to +active_model+ which simply defines autoloads for the +ActiveModel+ part of Rails and sets up the +ActiveModel+ module which is used later on. -h4. Active Resource Railtie +The last of the requires is to +rack+, which like the +active_model+ and +active_support+ requires before it, sets up the +Rack+ module as well as the autoloads for constants within it. -The Active Resource Railtie is responsible for creating an interface into remote sites that offer a REST API. The Active Resource Railtie depends on Active Support and Active Model. +Finally in +action_dispatch.rb+ the +ActionDispatch+ module and *its* autoloads are declared. -h5. +require 'active_resource/railtie'+ +h4. +rails/commands/server.rb+ -This file defines the Active Resource Railtie: +The +Rails::Server+ class is defined in this file as inheriting from +Rack::Server+. When +Rails::Server.new+ is called, this calls the +initialize+ method in +rails/commands/server.rb+: <ruby> - require "active_resource" - require "rails" - - module ActiveResource - class Railtie < Rails::Railtie - railtie_name :active_resource - - require "active_resource/railties/log_subscriber" - log_subscriber ActiveResource::Railties::LogSubscriber.new - - initializer "active_resource.set_configs" do |app| - app.config.active_resource.each do |k,v| - ActiveResource::Base.send "#{k}=", v - end - end - end + def initialize(*) + super + set_environment end </ruby> -The +require 'rails'+ has already been done back in TODO: link to section. - -h5. +require 'active_resource'+ +Firstly, +super+ is called which calls the +initialize+ method on +Rack::Server+. -This file, _activeresource/lib/active_resource.rb_, defines the +ActiveResource+ module, first off this will add the path to Active Support and Active Model to the load path if it's not already there, then require both +active_support+ (_activesupport/lib/active_support.rb_) and +active_model+ (_activemodel/lib/active_model.rb_) +h4. Rack: +lib/rack/server.rb+ -<ruby> - activesupport_path = File.expand_path('../../../activesupport/lib', __FILE__) - $:.unshift(activesupport_path) if File.directory?(activesupport_path) && !$:.include?(activesupport_path) - - activemodel_path = File.expand_path('../../../activemodel/lib', __FILE__) - $:.unshift(activemodel_path) if File.directory?(activemodel_path) && !$:.include?(activemodel_path) - - require 'active_support' - require 'active_model' - - module ActiveResource - extend ActiveSupport::Autoload - - autoload :Base - autoload :Connection - autoload :CustomMethods - autoload :Formats - autoload :HttpMock - autoload :Observing - autoload :Schema - autoload :Validations - end -</ruby> ++Rack::Server+ is responsible for providing a common server interface for all Rack-based applications, which Rails is now a part of. -h5. Active Resource Railtie - -The Railtie itself is fairly short as Active Resource is the smallest component of Rails. +The +initialize+ method in +Rack::Server+ simply sets a couple of variables: <ruby> - module ActiveResource - class Railtie < Rails::Railtie - railtie_name :active_resource - - require "active_resource/railties/log_subscriber" - log_subscriber ActiveResource::Railties::LogSubscriber.new - - initializer "active_resource.set_configs" do |app| - app.config.active_resource.each do |k,v| - ActiveResource::Base.send "#{k}=", v - end - end - end + def initialize(options = nil) + @options = options + @app = options[:app] if options && options[:app] end </ruby> -The Railtie defines the +log_subscriber+ as +ActiveResource::Railties::LogSubscriber.new+ which has one method defined: +request+. +request+ is used whenever a request is made to an external service. - -There is only one initializer defined here: +set_configs+. This is covered later in the Initialization section. - - -h4. ActionDispatch Railtie - -ActionDispatch handles all dispatch work for Rails. It interfaces with Action Controller to determine what action to undertake when a request comes in. TODO: I would quote the README but it is strangely absent. Flyin' blind here! - -The ActionDispatch Railtie was previously required when we called +require 'rails'+, but we will cover the Railtie here too. +In this case, +options+ will be +nil+ so nothing happens in this method. -ActionDispatch depends on Active Support. - -h5. +require 'action_dispatch/railtie'+ - -This file defines the ActionDispatch Railtie: +After +super+ has finished in +Rack::Server+, we jump back to +rails/commands/server.rb+. At this point, +set_environment+ is called within the context of the +Rails::Server+ object and this method doesn't appear to do much at first glance: <ruby> - require "action_dispatch" - require "rails" - - module ActionDispatch - class Railtie < Rails::Railtie - railtie_name :action_dispatch - - config.action_dispatch.x_sendfile_header = "X-Sendfile" - config.action_dispatch.ip_spoofing_check = true - - # Prepare dispatcher callbacks and run 'prepare' callbacks - initializer "action_dispatch.prepare_dispatcher" do |app| - # TODO: This used to say unless defined?(Dispatcher). Find out why and fix. - require 'rails/dispatcher' - ActionDispatch::Callbacks.to_prepare { app.routes_reloader.reload_if_changed } - end - end + def set_environment + ENV["RAILS_ENV"] ||= options[:environment] end </ruby> -The +require 'rails'+ has already been done back in TODO: link to section. - - - - -h5. +require 'action_dispatch'+ - -This file was already loaded earlier in the initialization process. TODO: link to it. - -h5. ActionDispatch Railtie - -The ActionDispatch Railtie is almost as short as the Active Resource Railtie: +In fact, the +options+ method here does quite a lot. This method is defined in +Rack::Server+ like this: <ruby> - require "action_dispatch" - require "rails" - - module ActionDispatch - class Railtie < Rails::Railtie - railtie_name :action_dispatch - - config.action_dispatch.x_sendfile_header = "X-Sendfile" - config.action_dispatch.ip_spoofing_check = true - - # Prepare dispatcher callbacks and run 'prepare' callbacks - initializer "action_dispatch.prepare_dispatcher" do |app| - # TODO: This used to say unless defined?(Dispatcher). Find out why and fix. - require 'rails/dispatcher' - ActionDispatch::Callbacks.to_prepare { app.routes_reloader.reload_if_changed } - end - end + def options + @options ||= parse_options(ARGV) end </ruby> -The +config+ method here is from +Rails::Railtie+ and pertains to your application's configuration. In this case, it is setting up some defaults which you can later override in _config/application.rb_. - -This Railtie does not define a +log_subscriber+ and only defines one initializer: +prepare_dispatcher+. - -h3. Return to _config/application.rb_ - -Now that Rails has finished loading all the Railties by way of +require 'rails/all'+ Rails can now move on to the next line: - -<ruby> - Bundler.require :default, Rails.env -</ruby> - -NOTE: It is worth mentioning here that you are not tied to using Bundler with Rails 3, but it is (of course) advised that you do. To "turn off" Bundler, comment out or remove the corresponding lines in _config/application.rb_ and _config/boot.rb_. - -Bundler was +require+'d back in _config/boot.rb_, and so that is what makes it available here. This guide does not dive into the internals of Bundler; it's really it's own separate guide. - -The +Bundler.require+ method adds all the gems not specified inside a +group+ in the +Gemfile+ and the ones specified in groups for the +Rails.env+ (in this case, _development_), to the load path. This is how an application is able to find them. - -The rest of this file is spent defining your application's main class. This is it without the comments: +Then +parse_options+ is defined like this: <ruby> - module YourApp - class Application < Rails::Application - config.encoding = "utf-8" - config.filter_parameters += [:password] - end - end -</ruby> - -h3. Return to Rails + def parse_options(args) + options = default_options -On the surface, this looks like a simple class inheritance. There's more underneath though. back in +Rails::Application+, the +inherited+ method is defined: + # Don't evaluate CGI ISINDEX parameters. + # http://hoohoo.ncsa.uiuc.edu/cgi/cl.html + args.clear if ENV.include?("REQUEST_METHOD") -<ruby> - def inherited(base) - raise "You cannot have more than one Rails::Application" if Rails.application - super - Rails.application = base.instance + options.merge! opt_parser.parse! args + options[:config] = ::File.expand_path(options[:config]) + ENV["RACK_ENV"] = options[:environment] + options end </ruby> -We do not already have a +Rails.application+, so instead this resorts to calling +super+. +Rails::Application+ descends from +Rails::Engine+ and so will call the +inherited+ method in +Rails::Engine+ (in _railties/lib/rails/engine.rb_), but before that it's important to note that +called_from+ is defined an +attr_accessor+ on +Rails::Engine+ and that +YourApp::Application+ is not an +abstract_railtie+: +With the +default_options+ set to this: <ruby> - def inherited(base) - unless base.abstract_railtie? - base.called_from = begin - # Remove the line number from backtraces making sure we don't leave anything behind - call_stack = caller.map { |p| p.split(':')[0..-2].join(':') } - File.dirname(call_stack.detect { |p| p !~ %r[railties[\w\-\.]*/lib/rails|rack[\w\-\.]*/lib/rack] }) - end - end - - super + def default_options + { + :environment => ENV['RACK_ENV'] || "development", + :pid => nil, + :Port => 9292, + :Host => "0.0.0.0", + :AccessLog => [], + :config => "config.ru" + } end </ruby> -This +called_from+ setting looks a little overwhelming to begin with, but the short end of it is that it returns your application's root, something like: _/home/you/yourapp_. After +called_from+ has been set, +super+ is again called and this means the +Rails::Railtie#inherited+ method (in _railties/lib/rails/railtie.rb_): - -<ruby> - def inherited(base) - unless base.abstract_railtie? - base.send(:include, self::Configurable) - subclasses << base - end - end -</ruby> - -Again, +YourApp::Application+ will return false for +abstract_railtie+ and so the code inside the +unless+ will be ran. The first line: +There is no +REQUEST_METHOD+ key in +ENV+ so we can skip over that line. The next line merges in the options from +opt_parser+ which is defined plainly in +Rack::Server+ <ruby> - base.send(:include, self::Configurable) -</ruby> - -includes the +self::Configurable+ module, with self being +Rails::Application+ in this context: - -<ruby> - module Rails - class Application - module Configurable - def self.included(base) - base.extend ClassMethods - end - - module ClassMethods - def inherited(base) - raise "You cannot inherit from a Rails::Application child" - end - end - - def config - @config ||= Application::Configuration.new(self.class.find_root_with_flag("config.ru", Dir.pwd)) - end - end - end + def opt_parser + Options.new end </ruby> -The inclusion of the +Rails::Application::Configurable+ module triggers the +included+ method in here which extends +YourApp::Application+ with the +Rails::Application::Configurable::ClassMethods+. - -Now that the chain of +super+ calls is done, we'll go back to the original +inherited+ method in +Rails::Application+ and the final line in this method: +The class *is* defined in +Rack::Server+, but is overwritten in +Rails::Server+ to take different arguments. Its +parse!+ method begins like this: <ruby> - Rails.application = base.instance -</ruby> + def parse!(args) + args, options = args.dup, {} -+base+ in this case is +YourApp::Application+ and calling +instance+ on this will return an instance of +YourApp::Application+ through the +instance+ method defined here: - -<ruby> - def instance - if self == Rails::Application - Rails.application - else - @@instance ||= new - end - end + opt_parser = OptionParser.new do |opts| + opts.banner = "Usage: rails server [mongrel, thin, etc] [options]" + opts.on("-p", "--port=port", Integer, + "Runs Rails on the specified port.", "Default: 3000") { |v| options[:Port] = v } + ... </ruby> -+self+ in this case is +YourApp::Application+, so it won't match to +Rails::Application+ so instead the +new+ method is called which calls the +initialize+ method. - - - +This method will set up keys for the +options+ which Rails will then be able to use to determine how its server should run. After +initialize+ has finished, then the +start+ method will launch the server. -h3. Firing it up! +h4. +Rails::Server#start+ -Now that we've covered the boot process of Rails the next line best to cover would be what happens after _script/rails_ has loaded _config/boot.rb_. That's quite simply that it then +require 'rails/commands'+ which is located at _railties/lib/rails/commands.rb_. Remember how +exec+ passed the arguments to +script/rails+? This is where they're used. _rails/commands.rb_ is quite a large file in Rails 3, as it contains all the Rails commands like console, about, generate and, of course, server. Because we've called +rails server+ the first argument in +ARGV+ is of course +"server"+. So assuming this we can determine that the +ARGV.shift+ in _commands.rb_ is going to return +"server"+, therefore it'll match this +when+: - -<ruby> - when 's', 'server' - require 'rails/commands/server' - Dir.chdir(ROOT_PATH) - Rails::Server.start -</ruby> - -The keen-eyed observer will note that this +when+ also specifies the argument could also be simply +'s'+ thereby making the full command +rails s+. This is the same with the other commands with +generate+ becoming +g+, +console+ becoming +c+ and +dbconsole+ becoming +db+. - -This code here ensures we are at the +ROOT_PATH+ of our application (this constant was defined in _script/rails_) and then calls +Rails::Server.start+. +Rails::Server+ descends from +Rack::Server+ which is defined in the rack gem. The +Rails::Server.start+ method is defined like this: +This method is defined like this: <ruby> def start - ENV["RAILS_ENV"] = options[:environment] - puts "=> Booting #{ActiveSupport::Inflector.demodulize(server)}" puts "=> Rails #{Rails.version} application starting in #{Rails.env} on http://#{options[:Host]}:#{options[:Port]}" puts "=> Call with -d to detach" unless options[:daemonize] trap(:INT) { exit } puts "=> Ctrl-C to shutdown server" unless options[:daemonize] + #Create required tmp directories if not found + %w(cache pids sessions sockets).each do |dir_to_make| + FileUtils.mkdir_p(Rails.root.join('tmp', dir_to_make)) + end + super ensure - puts 'Exiting' unless options[:daemonize] + # The '-h' option calls exit before @options is set. + # If we call 'options' with it unset, we get double help banners. + puts 'Exiting' unless @options && options[:daemonize] end </ruby> -We can see here that there is usual output indicating that the server is booting up. - -How the +options+ variable gets set and how Rack starts the server up is covered in the next section. - -h3. Racking it up! - - -This +Rack::Server.start+ method is defined like this: - -<ruby> - def self.start - new.start - end -</ruby> - -+new+ as you know calls +initialize+ in a class, and that is defined like this: - -<ruby> - def initialize(options = nil) - @options = options - end -</ruby> - -And then +options+, which are the options referenced by the +start+ method in +Rails::Server+. - -<ruby> - def options - @options ||= parse_options(ARGV) - end -</ruby> - -And +parse_options+: - -<ruby> - def parse_options(args) - options = default_options - - # Don't evaluate CGI ISINDEX parameters. - # http://hoohoo.ncsa.uiuc.edu/cgi/cl.html - args.clear if ENV.include?("REQUEST_METHOD") - - options.merge! opt_parser.parse! args - options - end -</ruby> - -And +default_options+: - -<ruby> - def default_options - { - :environment => "development", - :pid => nil, - :Port => 9292, - :Host => "0.0.0.0", - :AccessLog => [], - :config => "config.ru" - } - end -</ruby> - -Finally! We've arrived at +default_options+ which leads into our next point quite nicely. After the object has been +initialize+'d, +start+ is called: +This is where the first output of the Rails initialization happens. This method creates a trap for +INT+ signals, so if you +CTRL+C+ the server, it will exit the process. As we can see from the code here, it will create the +tmp/cache+, +tmp/pids+, +tmp/sessions+ and +tmp/sockets+ directories if they don't already exist prior to calling +super+. The +super+ method will call +Rack::Server.start+ which begins its definition like this: <ruby> def start - if options[:debug] - $DEBUG = true - require 'pp' - p options[:server] - pp wrapped_app - pp app - end - if options[:warn] $-w = true end if includes = options[:include] - $LOAD_PATH.unshift *includes + $LOAD_PATH.unshift(*includes) end if library = options[:require] require library end - daemonize_app if options[:daemonize] - write_pid if options[:pid] - server.run wrapped_app, options - end + if options[:debug] + $DEBUG = true + require 'pp' + p options[:server] + pp wrapped_app + pp app + end </ruby> -We're not debugging anything, so there goes the first 7 lines, we're not warning, nor are we including, requiring, daemonising or writing out a pid file. That's everything except the final line, which calls +run+ with the +wrapped_app+ which is then defined like this: +In a Rails application, these options are not set at all and therefore aren't used at all. The first line of code that's executed in this method is a call to this method: <ruby> - def wrapped_app - @wrapped_app ||= build_app app - end + wrapped_app </ruby> -and +build_app+'s first and only argument is +app+ which is defined like this: +This method calls another method: +<ruby> + @wrapped_app ||= build_app app +</ruby> + +Then the +app+ method here is defined like so: <ruby> def app @@ -2022,1744 +435,678 @@ and +build_app+'s first and only argument is +app+ which is defined like this: end </ruby> -+options+ is a method we talked about a short while ago, which is just the set of default options. +options[:config]+ in this context is therefore _config.ru_ which coincidentally we have in our application! To get an application instance from this method +Rack::Builder+ joins the fray with a call to +parse_file+ on our _config.ru_: - -<ruby> - def self.parse_file(config, opts = Server::Options.new) - options = {} - if config =~ /\.ru$/ - cfgfile = ::File.read(config) - if cfgfile[/^#\\(.*)/] && opts - options = opts.parse! $1.split(/\s+/) - end - cfgfile.sub!(/^__END__\n.*/, '') - app = eval "Rack::Builder.new {( " + cfgfile + "\n )}.to_app", - TOPLEVEL_BINDING, config - else - require config - app = Object.const_get(::File.basename(config, '.rb').capitalize) - end - return app, options - end -</ruby> - -First this reads your config file and checks it for +#\+ at the beginning. This is supported if you want to pass options into the +Rack::Server+ instance that you have and can be used like this: +The +options[:config]+ value defaults to +config.ru+ which contains this: <ruby> - #\\ -E production # This file is used by Rack-based servers to start the application. require ::File.expand_path('../config/environment', __FILE__) - run YourApp::Application.instance - + run YourApp::Application </ruby> -TODO: Is the above correct? I am simply guessing! - -After that it removes all the content after any +__END__+ in your _config.ru_ (TODO: because? Is this so it doesn't get eval'd?) and then evals the content of this file which, as you've seen is quite simple. The code that's first evaluated would be the require to the _config/environment.rb_ file, which leads into the next section. -h3. _config/environment.rb_ - -Now that we've seen that _rails/server_ gets to _config/environment.rb_ via Rack's requiring of it and Passenger requires it straight off the line. We've covered the boot process of Rails and covered the beginnings of a Rack server starting up. We have reached a common path for both _rails/server_ and Passenger now, so let's investigate what _config/environment.rb_ does. +The +Rack::Builder.parse_file+ method here takes the content from this +config.ru+ file and parses it using this code: <ruby> - # Load the rails application - require File.expand_path('../application', __FILE__) - - # Initialize the rails application - YourApp::Application.initialize! - + app = eval "Rack::Builder.new {( " + cfgfile + "\n )}.to_app", + TOPLEVEL_BINDING, config </ruby> -As you can see, there's a require in here for _config/application.rb_, and this file looks like this: - +The <ruby>initialize</ruby> method will take the block here and execute it within an instance of +Rack::Builder+. This is where the majority of the initialization process of Rails happens. The chain of events that this simple line sets off will be the focus of a large majority of this guide. The +require+ line for +config/environment.rb+ in +config.ru+ is the first to run: <ruby> - module YourApp - class Application < Rails::Application - # Settings in config/environments/* take precedence over those specified here. - # Application configuration should go into files in config/initializers - # -- all .rb files in that directory are automatically loaded. - - # Add additional load paths for your own custom dirs - # config.load_paths += %W( #{config.root}/extras ) - - # Only load the plugins named here, in the order given (default is alphabetical). - # :all can be used as a placeholder for all plugins not explicitly named - # config.plugins = [ :exception_notification, :ssl_requirement, :all ] - - # Activate observers that should always be running - # config.active_record.observers = :cacher, :garbage_collector, :forum_observer - - # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. - # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. - # config.time_zone = 'Central Time (US & Canada)' - - # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. - # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')] - # config.i18n.default_locale = :de - - # Configure generators values. Many other options are available, be sure to check the documentation. - # config.generators do |g| - # g.orm :active_record - # g.template_engine :erb - # g.test_framework :test_unit, :fixture => true - # end - end - end -</ruby> - -These options (and their siblings) are explained in a later section. What's important to note for this file currently is that this is where the +YourApp::Application+ class is initialized and that it's a subclass of +Rails::Application+. This is the first point where your application begins to initialize Rails and as you can see all of this is configuration stuff which your initializers and really, the rest of your application will depend on. These options and what they do will be covered later. - - -h3. Rails Initialization Process - -Now begins the actual initialization of Rails. Previously we have covered how _rails server_ and Passenger get to this stage and the parts of Rails that they have both loaded. - -h3. +Rails::Application+ - -The first steps for the initialization process of Rails begins when +YourApp::Application+ descends from +Rails::Application+. The +Rails::Application+ class descends from +Rails::Engine+ class which itself descends from +Rails::Railtie+ defined in _railties/lib/rails/railtie.rb_. Along this fantastical chain of superclasses, there's defined a couple of inherited class methods. These methods just so happen to be called when a class inherits from (aka: is made a subclass of) this class. This first one is for +Rails::Application+: - -<ruby> - def inherited(base) - raise "You cannot have more than one Rails::Application" if Rails.application - super - Rails.application = base.instance - end -</ruby> - -This goes up the chain by using +super+ to calling +Rails::Engine.inherited+: - -<ruby> - def inherited(base) - unless abstract_railtie?(base) - base.called_from = begin - call_stack = caller.map { |p| p.split(':').first } - File.dirname(call_stack.detect { |p| p !~ %r[railties/lib/rails|rack/lib/rack] }) - end - end - - super - end + require ::File.expand_path('../config/environment', __FILE__) </ruby> -+called_from+ references where this code was called from. This is covered later on in the "Bootstrap Initializers" section. +h4. +config/environment.rb+ -Which then calls +Rails::Railtie.inherited+: +This file is the common file required by +config.ru+ (+rails server+) and Passenger. This is where these two ways to run the server meet; everything before this point has been Rack and Rails setup. -<ruby> - def inherited(base) - unless abstract_railtie?(base) - base.send(:include, self::Configurable) - subclasses << base - end - end -</ruby> +This file begins with requiring +config/application.rb+. -This +inherited+ first includes the +Rails::Configurable+ module on +base+, which is +YourApp::Application+. This module defines the +config+ method on +YourApp::Application+, and now it's starting to come together. You may notice that in your +config/application.rb+ file there's a +config+ method called there. This is the method from +Rails::Configurable+. +h4. +config/application.rb+ -Then this adds to +Rails::Railtie.subclasses+ your application's class because... TODO: explain. +This file requires +config/boot.rb+, but only if it hasn't been required before, which would be the case in +rails server+ but *wouldn't* be the case with Passenger. -With +Rails::Railtie.inherited+ out of the way, and that being the last thing to do in +Rails::Engine.inherited+ we return to +Rails::Application.inherited+ which calls the following: +Then the fun begins! -<ruby> - Rails.application = base.instance -</ruby> +h3. Loading Rails -As you already know, +base+ is +YourApp::Application+ and now it's calling the +instance+ method on it. This method is defined in +Rails::Application+ like this: +The next line in +config/application.rb+ is: <ruby> - def instance - if self == Rails::Application - Rails.application - else - @@instance ||= new - end - end + require 'rails/all' </ruby> -The +new+ method here simply creates a new +Rails::Application+ and sets it to the +@@instance+ class variable. No magic. +h4 +railties/lib/rails/all.rb+ -h3. Your Application's Configuration -Now that +inherited+ has finished doing its job, next up in _config/application.rb_ is the call to the +config+ object's methods. As explained before, this +config+ object is an instance of +Rails::Railtie::Configuration+, put into place by the call of +include Rails::Configurable+ back in +Rails::Railtie.inherited+. This defined it as such: +This file is responsible for requiring all the individual parts of Rails like so: <ruby> - def config - @config ||= Railtie::Configuration.new - end -</ruby> - -All the methods for +Rails::Railtie::Configuration+ are defined like this in _railties/lib/rails/railtie/configuration.rb_: - -<ruby> - require 'rails/configuration' + require "rails" - module Rails - class Railtie - class Configuration - include Rails::Configuration::Shared - end + %w( + active_record + action_controller + action_mailer + active_resource + rails/test_unit + ).each do |framework| + begin + require "#{framework}/railtie" + rescue LoadError end end </ruby> -As you can probably guess here, the +Rails::Configuration+ module is defined by _rails/configuration_ (_railties/lib/rails/configuration.rb_). - -h3. +Rails::Configuration::Shared+ +First off the line is the +rails+ require itself. -In a standard application, the +application.rb+ looks like this with all the comments stripped out: +h4. +railties/lib/rails.rb+ -<ruby> - require File.expand_path('../boot', __FILE__) +This file is responsible for the initial definition of the +Rails+ module and, rather than defining the autoloads like +ActiveSupport+, +ActionDispatch+ and so on, it actually defines other functionality. Such as the +root+, +env+ and +application+ methods which are extremely useful in Rails 3 applications. - module YourApp - class Application < Rails::Application - config.filter_parameters << :password - end - end -</ruby> - -The +config+ method being the one defined on +Rails::Application::Configurable+: - -<ruby> - def config - @config ||= Application::Configuration.new(self.class.find_root_with_flag("config.ru", Dir.pwd)) - end -</ruby> +However, before all that takes place the +rails/ruby_version_check+ file is required first. -The method +find_with_root_flag+ is defined on +Rails::Engine+ (the superclass of +Rails::Application+) and it will find the directory containing a certain flag. In this case it's the +config.ru+ file: +h4. +railties/lib/rails/ruby_version_check.rb+ -<ruby> - def find_root_with_flag(flag, default=nil) - root_path = self.called_from +This file simply checks if the Ruby version is less than 1.8.7 or is 1.9.1 and raises an error if that is the case. Rails 3 simply will not run on earlier versions of Ruby than 1.8.7 or 1.9.1. - while root_path && File.directory?(root_path) && !File.exist?("#{root_path}/#{flag}") - parent = File.dirname(root_path) - root_path = parent != root_path && parent - end +NOTE: You should always endeavour to run the latest version of Ruby with your Rails applications. The benefits are many, including security fixes and the like, and very often there is a speed increase associated with it. The caveat is that you could have code that potentially breaks on the latest version, which should be fixed to work on the latest version rather than kept around as an excuse not to upgrade. - root = File.exist?("#{root_path}/#{flag}") ? root_path : default - raise "Could not find root path for #{self}" unless root +h4. +active_support/core_ext/kernel/reporting.rb+ - RUBY_PLATFORM =~ /(:?mswin|mingw)/ ? - Pathname.new(root).expand_path : Pathname.new(root).realpath - end -</ruby> - -+called_from+ goes through the +caller+ which is the stacktrace of the current thread, in the case of your application it would go a little like this: - -<pre> - /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.0.0.beta1/lib/rails/application.rb:30:in `inherited' - /home/you/yourapp/config/application.rb:4:in `<module:TestApp>' - /home/you/yourapp/config/application.rb:3:in `<top (required)>' - /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0.beta1/lib/active_support/dependencies.rb:167:in `require' - /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0.beta1/lib/active_support/dependencies.rb:167:in `block in require' - /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0.beta1/lib/active_support/dependencies.rb:537:in `new_constants_in' - /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0.beta1/lib/active_support/dependencies.rb:167:in `require' - /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.0.0.beta1/lib/rails/commands.rb:33:in `<top (required)>' - /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0.beta1/lib/active_support/dependencies.rb:167:in `require' - /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0.beta1/lib/active_support/dependencies.rb:167:in `block in require' - /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0.beta1/lib/active_support/dependencies.rb:537:in `new_constants_in' - /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0.beta1/lib/active_support/dependencies.rb:167:in `require' - /var/www/rboard/script/rails:10:in `<main>' -</pre> - -+called_from+ is defined in the +inherited+ method for +Rails::Engine+ which looks like this: +This is the first of the many Active Support core extensions that come with Rails. This one in particular defines methods in the +Kernel+ module which is mixed in to the +Object+ class so the methods are available on +main+ and can therefore be called like this: <ruby> - base.called_from = begin - call_stack = caller.map { |p| p.split(':').first } - File.dirname(call_stack.detect { |p| p !~ %r[railties/lib/rails|rack/lib/rack] }) + silence_warnings do + # some code end </ruby> -The +call_stack+ here is the +caller+ output shown previously, minus everything after the first +:+ on all the lines. The first path that matches this is _/usr/local/lib/ruby/gems/1.9.1/gems/railties-3.0.0.beta1/lib/rails_. Yours may vary slightly, but should always end in _railties-x.x.x/lib/rails_. +These methods can be used to silence STDERR responses and the +silence_stream+ allows you to also silence other streams. Additionally, this mixin allows you to suppress exceptions and capture streams. For more information see the "Silencing Warnings, Streams, and Exceptions":http://guides.rubyonrails.org/active_support_core_extensions.html#silencing-warnings-streams-and-exceptions section from the Active Support Core Extensions Guide. -The code in +find_root_with_flag+ will go up this directory structure until it reaches the top, which in this case is +/+. +h4. +active_support/core_ext/logger.rb+ -<ruby> - while root_path && File.directory?(root_path) && !File.exist?("#{root_path}/#{flag}") - parent = File.dirname(root_path) - root_path = parent != root_path && parent - end +The next file that is required is another Active Support core extension, this time to the +Logger+ class. This begins by defining the +around_[level]+ helpers for the +Logger+ class as well as other methods such as a +datetime_format+ getter and setter for the +formatter+ object tied to a +Logger+ object. - root = File.exist?("#{root_path}/#{flag}") ? root_path : default - raise "Could not find root path for #{self}" unless root -</ruby> +For more information see the "Extensions to Logger":http://guides.rubyonrails.org/active_support_core_extensions.html#extensions-to-logger section from the Active Support Core Extensions Guide. -TODO: What is all this for? +h4. +railties/lib/rails/application.rb+ -At the root of the system it looks for +config.ru+. TODO: Why? Obviously it's not going to find it, so it uses the +default+ option we've specified which is +Dir.pwd+ which will default to the root folder of your Rails application. This path is then passed to +Rails::Application::Configuration.new+. +Rails::Application::Configuration+ descends from +Rails::Engine::Configuration+ and the +initialize+ method goes like this: +The next file required by +railties/lib/rails.rb+ is +application.rb+. This file defines the +Rails::Application+ constant which the application's class defined in +config/application.rb+ in a standard Rails application depends on. Before the +Rails::Application+ class is defined however, there's some other files that get required first. -<ruby> - def initialize(*) - super - @allow_concurrency = false - @colorize_logging = true - @filter_parameters = [] - @dependency_loading = true - @serve_static_assets = true - @time_zone = "UTC" - @consider_all_requests_local = true - end -</ruby> +The first of these is +active_support/core_ext/hash/reverse_merge+ which can be "read about in the Active Support Core Extensions guide":http://guides.rubyonrails.org/active_support_core_extensions.html#merging under the "Merging" section. -The +super+ method here is the +initialize+ method in +Rails::Engine::Configuration+: +h4. +active_support/file_update_checker.rb+ -<ruby> - def initialize(root=nil) - @root = root - end -</ruby> +The +ActiveSupport::FileUpdateChecker+ class defined within this file is responsible for checking if a file has been updated since it was last checked. This is used for monitoring the routes file for changes during development environment runs. -Here, the +@root+ variable is assigned the path of your application and then the remainder of +Rails::Application::Configuration.initialize+ is ran, setting up a few instance variables for basic configuration, including one for +@filter_parameters+. +h4. +railties/lib/rails/plugin.rb+ -Now with the +config+ option set up, we can go onwards and call +filter_parameters+ on it. This +filter_parameters+ method is not defined on +Rails::Configuration::Shared+ and actually falls to the +method_missing+ defined there instead: +This file defines +Rails::Plugin+ which inherits from +Rails::Engine+. Unlike +Rails::Engine+ and +Rails::Railtie+ however, this class is not designed to be inherited from. Instead, this is used simply for loading plugins from within an application and an engine. -<ruby> - def method_missing(name, *args, &blk) - if name.to_s =~ config_key_regexp - return $2 == '=' ? options[$1] = args.first : options[$1] - end - super - end -</ruby> +This file begins by requiring +rails/engine.rb+ -We're not calling +filter_parameters=+, we're calling +filter_parameters+, therefore it'll be the second part of this ternary argument: +options[$1]+. The options method is defined like this: +h4. +railties/lib/rails/engine.rb+ -<ruby> - def options - @@options ||= Hash.new { |h,k| h[k] = ActiveSupport::OrderedOptions.new } - end -</ruby> +The +rails/engine.rb+ file defines the +Rails::Engine+ class which inherits from +Rails::Railtie+. The +Rails::Engine+ class defines much of the functionality found within a standard application class such as the +routes+ and +config+ methods. -OrderedOptions exists... TODO: explain. +The "API documentation":http://api.rubyonrails.org/classes/Rails/Engine.html for +Rails::Engine+ explains the function of this class pretty well. +This file's first line requires +rails/railtie.rb+. -So from this we can determine that our +options+ hash now has a key for +filter_parameters+ which's value is an array consisting of a single symbol: +:password+. How this option manages to get into the +@filter_parameters+ variable defined on the +Rails::Application::Configuration.initialize+ method is explained later. +h4. +railties/lib/rails/railtie.rb+ -h3. Application Configured! +The +rails/railtie.rb+ file is responsible for defining +Rails::Railtie+, the underlying class for all ties to Rails now. Gems that want to have their own initializers or rake tasks and hook into Rails should have a +GemName::Railtie+ class that inherits from +Rails::Railtie+. -Now your application has finished being configured (at least in the sense of _config/application.rb_, there's more to come!) in _config/environment.rb_ the final line calls +YourApp::Application.initalize!+. +The "API documentation":http://api.rubyonrails.org/classes/Rails/Railtie.html for +Rails::Railtie+, much like +Rails::Engine+, explains this class exceptionally well. -h3. Initialization begins +The first require in this file is +rails/initializable.rb+. -This is one of those magical uses of +method_missing+ which, for the purposes of debugging, is something that you don't expect to come across as often as you do and as a consequence you'll spend a good portion of an hour looking for method definitions that don't exist because +method_missing+ is taking care of it. There's some pretty crafty use of +method_missing+ all over Rails and it's encouraged to take note of its power. +h4. +railties/lib/rails/initializable.rb+ -+Rails::Application+ has a +method_missing+ definition which does this: +Now we reach the end of this particular rabbit hole as +rails/initializable.rb+ doesn't require any more Rails files, only +tsort+ from the Ruby standard library. -<ruby> - def method_missing(*args, &block) - instance.send(*args, &block) - end -</ruby> +This file defines the +Rails::Initializable+ module which contains the +Initializer+ class, the basis for all initializers in Rails. This module also contains a +ClassMethods+ class which will be included into the +Rails::Railtie+ class when these requires have finished. -With our +instance+ being our already initialized by the +inherited+ method, this will just return the value of the +@@instance+ variable, a +Rails::Application+ object. Calling +initialize!+ on this method does this: +Now that +rails/initializable.rb+ has finished being required from +rails/railtie.rb+, the next require is for +rails/configuration+. -<ruby> - def initialize! - run_initializers(self) - self - end -</ruby> +h4. +railties/lib/rails/configuration.rb+ -The initializers it is talking about running here are the initializers for our application. The object passed in to +run_initializers+ is +YourApp::Application+. +This file defines the +Rails::Configuration+ module, containing the +MiddlewareStackProxy+ class as well as the +Generators+ class. The +MiddlewareStackProxy+ class is used for managing the middleware stack for an application, which we'll see later on. The +Generators+ class provides the functionality used for configuring what generators an application uses through the "+config.generators+ option":http://guides.rubyonrails.org/configuring.html#configuring-generators. +The first file required in this file is +activesupport/deprecation+. -h3. +run_initializers+ +h4. +activesupport/lib/active_support/deprecation.rb+ -This method begins the running of all the defined initializers. In the section "The Boot Process" we covered the loading sequence of Rails before any initialization happens and during this time we saw that the +Rails::Railtie+ class includes the +Initializable+ module. As we've also seen +YourApp::Application+ is a descendant of this class, so it too has these methods. +This file, and the files it requires, define the basic deprecation warning features found in Rails. This file is responsible for setting defaults in the +ActiveSupport::Deprecation+ module for the +deprecation_horizon+, +silenced+ and +debug+ values. The files that are required before this happens are: -+run_initializers+ looks like this: +* +active_support/deprecation/behaviors+ +* +active_support/deprecation/reporting+ +* +active_support/deprecation/method_wrappers+ +* +active_support/deprecation/proxy_wrappers+ -<ruby> - def run_initializers(*args) - return if instance_variable_defined?(:@ran) - initializers.each do |initializer| - initializer.run(*args) - end - @ran = true - end -</ruby> +h4. +activesupport/lib/active_support/deprecation/behaviors.rb+ -Here the +initializers+ method is defined in _railties/lib/rails/application.rb_: +This file defines the behavior of the +ActiveSupport::Deprecation+ module, setting up the +DEFAULT_BEHAVIORS+ hash constant which contains the three defaults to outputting deprecation warnings: +:stderr+, +:log+ and +:notify+. This file begins by requiring +activesupport/notifications+ and +activesupport/core_ext/array/wrap+. -<ruby> - def initializers - initializers = Bootstrap.initializers_for(self) - railties.all { |r| initializers += r.initializers } - initializers += super - initializers += Finisher.initializers_for(self) - initializers - end -</ruby> - -h3. +Bootstrap+ initializers +h4 +activesupport/lib/active_support/notifications.rb+ -The first line here references a +Bootstrap+ class we haven't seen before. Or have we? The keen-eyed observer would have spotted an +autoload+ for it at the top of +Rails::Application+: - -<ruby> - autoload :Bootstrap, 'rails/application/bootstrap' -</ruby> +TODO: document +ActiveSupport::Notifications+. -Now that we've referenced that class, it will be required for us. You'll notice inside this class that there's an +include Initializable+, providing the afore-mentioned methods from this module. Inside this class a number of initializers are defined. +h4. +activesupport/core_ext/array/wrap+ -* load_environment_config -* load_all_active_support -* preload_frameworks -* initialize_logger -* initialize_cache -* initialize_subscriber -* set_clear_dependencies_hook -* initialize_dependency_mechanism +As this file comprises of a core extension, it is covered exclusively in "the Active Support Core Extensions guide":http://guides.rubyonrails.org/active_support_core_extensions.html#wrapping -These are all defined using the +initializer+ method: - -<ruby> - def initializer(name, opts = {}, &blk) - raise ArgumentError, "A block must be passed when defining an initializer" unless blk - opts[:after] ||= initializers.last.name unless initializers.empty? || initializers.find { |i| i.name == opts[:before] } - initializers << Initializer.new(name, nil, opts, &blk) - end -</ruby> +h4. +activesupport/lib/active_support/deprecation/reporting.rb+ -The +initializers+ method defined here just references an +@initializers+ variable: +This file is responsible for defining the +warn+ and +silence+ methods for +ActiveSupport::Deprecation+ as well as additional private methods for this module. -<ruby> - def initializers - @initializers ||= [] - end -</ruby> +h4. +activesupport/lib/active_support/deprecation/method_wrappers.rb+ -As you can see from this method it will set +opts[:after]+ if there are previously defined initializers. So we can determine from this that the order our initializers are defined in is the same order that they run in, but only by default. It is possible to change this by specifying an +:after+ or +:before+ option as we will see later on. Each initializer is its own instance of the +Initializer+ class: +This file defines a +deprecate_methods+ which is primarily used by the +module/deprecation+ core extension required by the first line of this file. Other core extensions required by this file are the +module/aliasing+ and +array/extract_options+ files. -<ruby> - class Initializer - attr_reader :name, :block +h4. +activesupport/lib/active_support/deprecation/proxy_wrappers.rb+ - def initialize(name, context, options, &block) - @name, @context, @options, @block = name, context, options, block - end ++proxy_wrappers.rb+ defines deprecation wrappers for methods, instance variables and constants. Previously, this was used for the +RAILS_ENV+ and +RAILS_ROOT+ constants for 3.0 but since then these constants have been removed. The deprecation message that would be raised from these would be something like: - def before - @options[:before] - end +<plain> + BadConstant is deprecated! Use GoodConstant instead. +</plain> - def after - @options[:after] - end +h4. +active_support/ordered_options+ - def run(*args) - @context.instance_exec(*args, &block) - end +This file is the next file required from +rails/configuration.rb+ is the file that defines +ActiveSupport::OrderedOptions+ which is used for configuration options such as +config.active_support+ and the like. - def bind(context) - return self if @context - Initializer.new(@name, context, @options, &block) - end - end -</ruby> +The next file required is +active_support/core_ext/hash/deep_dup+ which is covered in "Active Support Core Extensions guide":http://guides.rubyonrails.org/active_support_core_extensions.html#deep_dup -Now that +Rails::Application::Bootstrap+ has finished loading, we can continue on with our initialization. We saw that it called this: +The file that is required next from is +rails/paths+ -<ruby> - initializers = Bootstrap.initializers_for(self) -</ruby> +h4. +railties/lib/rails/paths.rb+ -Calling +initializers_for+, defined like this: +This file defines the +Rails::Paths+ module which allows paths to be configured for a Rails application or engine. Later on in this guide when we cover Rails configuration during the initialization process we'll see this used to set up some default paths for Rails and some of them will be configured to be eager loaded. -<ruby> - def initializers_for(binding) - Collection.new(initializers_chain.map { |i| i.bind(binding) }) - end -</ruby> +h4. +railties/lib/rails/rack.rb+ -The +binding+ argument here is +YourApp::Application+ and this will return a new +Initializer+ object for all the initializers in +initializers_chain+ for this particular context. +initializers_chain+ goes like this: +The final file to be loaded by +railties/lib/rails/configuration.rb+ is +rails/rack+ which defines some simple autoloads: <ruby> - def initializers_chain - initializers = Collection.new - ancestors.reverse_each do |klass| - next unless klass.respond_to?(:initializers) - initializers = initializers + klass.initializers + module Rails + module Rack + autoload :Debugger, "rails/rack/debugger" + autoload :Logger, "rails/rack/logger" + autoload :LogTailer, "rails/rack/log_tailer" + autoload :Static, "rails/rack/static" end - initializers end </ruby> -The ancestors list is relatively short for +Rails::Application::Bootstrap+, consisting of itself and +Rails::Initializable+. Rails will go through these ancestors in reverse and check them all if they +respond_to?(:initializers)+. +Rails::Initializable+ does not and so it's skipped. +Rails::Application::Bootstrap+ of course does, and this is the list of initializers we covered earlier. +Once this file is finished loading, then the +Rails::Configuration+ class is initialized. This completes the loading of +railties/lib/rails/configuration.rb+ and now we jump back to the loading of +railties/lib/rails/railtie.rb+, where the next file loaded is +active_support/inflector+. -After +initializers_chain+ is finished, then they are +map+'d like this, with the +binding+ of course being +YourApp::Application+ as explained previously. +h4. +activesupport/lib/active_support/inflector.rb+ -<ruby> - def initializers_for(binding) - Collection.new(initializers_chain.map { |i| i.bind(binding) }) - end -</ruby> - -Wow. All that to cover just the first line in the +initializers+ method for +Rails::Application+. - -h3. Railties Initializers - -This section covers the loading of the initializers and we will go into depth for each initializer in the next section, as they make more sense explained in their chain. - -The second line in +Rails::Application#initializers+: ++active_support/inflector.rb+ requires a series of file which are responsible for setting up the basics for knowing how to pluralize and singularize words. These files are: <ruby> - def initializers - railties.all { |r| initializers += r.initializers } - end -</ruby> - -calls +railties+, which is defined like this: + require 'active_support/inflector/inflections' + require 'active_support/inflector/transliterate' + require 'active_support/inflector/methods' -<ruby> - def railties - @railties ||= Railties.new(config) - end + require 'active_support/inflections' + require 'active_support/core_ext/string/inflections' </ruby> -This sets up a new +Rails::Application::Railties+ object like this: +The +active_support/inflector/methods+ file has already been required by +active_support/autoload+ and so won't be loaded again here. -<ruby> - def initialize(config) - @config = config - end -</ruby> +h4. +activesupport/lib/active_support/inflector/inflections.rb+ -And calls +all+ on it: +This file references the +ActiveSupport::Inflector+ constant which isn't loaded by this point. But there were autoloads set up in +activesupport/lib/active_support.rb+ which will load the file which loads this constant and so then it will be defined. Then this file defines pluralization and singularization rules for words in Rails. This is how Rails knows how to pluralize "tomato" to "tomatoes". -<ruby> - def all(&block) - @all ||= railties + engines + plugins - @all.each(&block) if block - @all - end -</ruby> +h4. +activesupport/lib/active_support/inflector/transliterate.rb+ -This +all+ method executes code on all the +Rails::Railtie+ and +Rails::Engine+ subclasses, retreived by the +railties+ and +engines+ methods defined right after +all+: +In this file is where the "+transliterate+":http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-transliterate and +parameterize+:http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-parameterize methods are defined. The documentation for both of these methods is very much worth reading. -<ruby> - def railties - @railties ||= ::Rails::Railtie.subclasses.map(&:new) - end +h4. Back to +railties/lib/rails/railtie.rb+ - def engines - @engines ||= ::Rails::Engine.subclasses.map(&:new) - end -</ruby> +Once the inflector files have been loaded, the +Rails::Railtie+ class is defined. This class includes a module called +Initializable+, which is actually +Rails::Initializable+. This module includes the +initializer+ method which is used later on for setting up initializers, amongst other methods. -By default, the railties are: +h4. +railties/lib/rails/initializable.rb+ -* +ActiveSupport::Railtie+ -* +I18n::Railtie+ -* +ActionDispatch::Railtie+ -* +ActionController::Railtie+ -* +ActiveRecord::Railtie+ -* +ActionView::Railtie+ -* +ActionMailer::Railtie+ -* +ActiveResource::Railtie+ -* +Rails::TestUnitRailtie+ +When the module from this file (+Rails::Initializable+) is included, it extends the class it's included into with the +ClassMethods+ module inside of it. This module defines the +initializer+ method which is used to define initializers throughout all of the railties. This file completes the loading of +railties/lib/rails/railtie.rb+. Now we go back to +rails/engine.rb+. -And these all descend from +Rails::Railtie+. +h4. +railties/lib/rails/engine.rb+ -The default +engines+ are +[]+. +The next file required in +rails/engine.rb+ is +active_support/core_ext/module/delegation+ which is documented in the "Active Support Core Extensions Guide":http://guides.rubyonrails.org/active_support_core_extensions.html#method-delegation. -The +plugins+ method it calls is a little more complex: +The next two files after this are Ruby standard library files: +pathname+ and +rbconfig+. The file after these is +rails/engine/railties+. -<ruby> - def plugins - @plugins ||= begin - plugin_names = (@config.plugins || [:all]).map { |p| p.to_sym } - Plugin.all(plugin_names, @config.paths.vendor.plugins) - end - end -</ruby> +h4. +railties/lib/rails/engine/railties.rb+ -+@config.paths+ is defined in the +Rails::Application::Configuration+ like this: +This file defines the +Rails::Engine::Railties+ class which provides the +engines+ and +railties+ methods which are used later on for defining rake tasks and other functionality for engines and railties. -<ruby> - def paths - @paths ||= begin - paths = super - paths.app.controllers << builtin_controller if builtin_controller - paths.config.database "config/database.yml" - paths.config.environment "config/environments", :glob => "#{Rails.env}.rb" - paths.log "log/#{Rails.env}.log" - paths.tmp "tmp" - paths.tmp.cache "tmp/cache" - paths.vendor "vendor", :load_path => true - paths.vendor.plugins "vendor/plugins" - - if File.exists?("#{root}/test/mocks/#{Rails.env}") - ActiveSupport::Deprecation.warn "\"RAILS_ROOT/test/mocks/#{Rails.env}\" won't be added " << - "automatically to load paths anymore in future releases" - paths.mocks_path "test/mocks", :load_path => true, :glob => Rails.env - end +h4. Back to +railties/lib/rails/engine.rb+ - paths - end - end -</ruby> +Once +rails/engine/railties.rb+ has finished loading the +Rails::Engine+ class gets its basic functionality defined, such as the +inherited+ method which will be called when this class is inherited from. -When we call +@config.paths.vendor.plugins+ it will return +"vendor/plugins"+. - +Once this file has finished loading we jump back to +railties/lib/rails/plugin.rb+ -If you've defined specific plugin requirements for your application in _config/application.rb_ by using this code: +h4. Back to +railties/lib/rails/plugin.rb+ -<ruby> - config.plugins = [:will_paginate, :by_star] -</ruby> +The next file required in this is a core extension from Active Support called +array/conversions+ which is covered in "this section":http://guides.rubyonrails.org/active_support_core_extensions.html#array-conversions of the Active Support Core Extensions Guide. -or specific plugin loading using a similar statement such as this next one: +Once that file has finished loading, the +Rails::Plugin+ class is defined. -<ruby> - config.plugins = [:will_paginate, :by_star, :all] -</ruby> +h4. Back to +railties/lib/rails/application.rb+ +Jumping back to +rails/application.rb+ now. This file defines the +Rails::Application+ class where the application's class inherits from. This class (and its superclasses) define the basic behaviour on the application's constant such as the +config+ method used for configuring the application. -Then this is where the +@config.plugins+ comes from. If you wish to load only certain plugins for your application, use the first example. If you wish to load certain plugins before the rest then the second example is what you would use. +Once this file's done then we go back to the +railties/lib/rails.rb+ file, which next requires +rails/version+. -If +config.plugins+ is not defined then +:all+ is specified in its place. Whatever the +plugin_names+ is specified as, is passed to +Plugin.all+ along with the path to the plugins, +@config.path.vendor.plugins+ (which defaults to _vendor/plugins_): +h4. +railties/lib/rails/version.rb+ -<ruby> - def self.all(list, paths) - plugins = [] - paths.each do |path| - Dir["#{path}/*"].each do |plugin_path| - plugin = new(plugin_path) - next unless list.include?(plugin.name) || list.include?(:all) - plugins << plugin - end - end +Much like +active_support/version+, this file defines the +VERSION+ constant which has a +STRING+ constant on it which returns the current version of Rails. - plugins.sort_by do |p| - [list.index(p.name) || list.index(:all), p.name.to_s] - end - end -</ruby> +Once this file has finished loading we go back to +railties/lib/rails.rb+ which then requires +active_support/railtie.rb+. -As we can see here it will go through the paths and for every folder in _vendor/plugins_ and +initialize+ a new +Rails::Plugin+ object for each: +h4. +activesupport/lib/active_support/railtie.rb+ -<ruby> - def initialize(root) - @name = File.basename(root).to_sym - config.root = root - end -</ruby> +This file requires +active_support+ and +rails+ which have already been required so these two lines are effectively ignored. The third require in this file is to +active_support/i18n_railtie.rb+. -This sets the plugin name to be the same name as the folder so the plugin located at _vendor/plugins/by\_star_'s name is +by_star+. After that, the +config+ object is initialized: +h4. +activesupport/lib/active_support/i18n_railtie.rb+ -<ruby> - def config - @config ||= Engine::Configuration.new - end -</ruby> - -and the root of the plugin defined as that folder. The reasoning for defining a +root+ is so that the initializer called +load_init_rb+ has some place to look for this file: +This file is the first file that sets up configuration with these lines inside the class: <ruby> - initializer :load_init_rb, :before => :load_application_initializers do |app| - file = Dir["#{root}/{rails/init,init}.rb"].first - config = app.config - eval(File.read(file), binding, file) if file && File.file?(file) - end + class Railtie < Rails::Railtie + config.i18n = ActiveSupport::OrderedOptions.new + config.i18n.railties_load_path = [] + config.i18n.load_path = [] + config.i18n.fallbacks = ActiveSupport::OrderedOptions.new </ruby> -A little more on that later, however. - -If the plugin is not included in the list then it moves on to the next one. For all plugins included in the list (or if +:all+ is specified in the list) they are put into a +plugins+ local variable which is then sorted: +By inheriting from +Rails::Railtie+ the +Rails::Railtie#inherited+ method is called: <ruby> - plugins.sort_by do |p| - [list.index(p.name) || list.index(:all), p.name.to_s] - end -</ruby> - -The sort order is the same order as which they appear in the +config.plugins+ setting, or in alphabetical order if there is no setting specified. - -Now that we have our railties, engines, and plugins in a line we can finally get back to the +all+ code: - -<ruby> - def initializers - railties.all { |r| initializers += r.initializers } - end -</ruby> - -This block will gather add the railties' initializers to it. - -h3. Engine Initializers - -The third line in this +initializers+ method: - -<ruby> - initializers += super -</ruby> - -The +super+ method it's referring to is of course +Rails::Engine.initializers+, which isn't defined on the class but, as we have seen before, is defined on the +Rails::Railtie+ class it inherits from through the +Rails::Initializable+ module. Therefore we can determine the initializers to be added are now the ones defined in +Rails::Engine+. - -h3. Finisher Initializers - -The final set of initializers in this chain are those in +Rails::Finisher+. This involves running any after initialize code, building the middleware stack and adding the route for _rails/info/properties_. - -h3. Running the Initializers - -Now that we have all the initializers we can go back to the +run_initializers+ in +Rails::Initializable+: - -<ruby> - def run_initializers(*args) - return if instance_variable_defined?(:@ran) - initializers.each do |initializer| - initializer.run(*args) + def inherited(base) + unless base.abstract_railtie? + base.send(:include, Railtie::Configurable) + subclasses << base end - @ran = true - end -</ruby> - -Now we finally have all the +initializers+ we can go through them and call +run+: - -<ruby> - def run(*args) - @context.instance_exec(*args, &block) end </ruby> -You may remember that the +@context+ in this code is +YourApp::Application+ and calling +instance_exec+ on this class will make a new instance of it and execute the code within the +&block+ passed to it. This code within the block is the code from all the initializers. - -h3. Bootstrap Initializers - -These initializers are the very first initializers that will be used to get your application going. - -h4. +load_environment_config+ +This first checks if the Railtie that's inheriting it is a component of Rails itself: <ruby> - initializer :load_environment_config do - require_environment! - end -</ruby> +ABSTRACT_RAILTIES = %w(Rails::Railtie Rails::Plugin Rails::Engine Rails::Application) -This quite simply makes a call to +require_environment!+ which is defined like this in +Rails::Application+: +... -<ruby> - def require_environment! - environment = config.paths.config.environment.to_a.first - require environment if environment - end -</ruby> - -We've seen +config.paths+ before when loading the plugins and they're explained in more detail in the Bonus section at the end of this guide. +config.enviroment+ for +paths+ is defined like this: - -<ruby> - paths.config.environment "config/environments", :glob => "#{Rails.env}.rb" -</ruby> - -+Rails.env+ was defined way back in the boot process when +railties/lib/rails.rb+ was required: - -<ruby> -module Rails - class << self - - ... - - def env - @_env ||= ActiveSupport::StringInquirer.new(ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development") - end - - ... - - end +def abstract_railtie? + ABSTRACT_RAILTIES.include?(name) end </ruby> -With +ENV["RAILS_ENV"]+ and +ENV["RACK_ENV"]+ not set to anything for our server booting process, this will default to +"development"+. - -Therefore the path to this config file line would look like this with a substitution made: - -<ruby> - paths.config.environment "config/environments", :glob => "development.rb" -</ruby> - -This method returns a +Path+ object (which acts as an +Enumerable+). - -Back to +require_environment+ now: +Because +I18n::Railtie+ isn't in this list, +abstract_railtie?+ returns +false+. Therefore the +Railtie::Configurable+ module is included into this class and the +subclasses+ method is called and +I18n::Railtie+ is added to this new array. <ruby> - def require_environment! - environment = config.paths.config.environment.to_a.first - require environment if environment - end +def subclasses + @subclasses ||= [] +end </ruby> -And we've determined that +config.paths.config.environment+ is +Path+ object, and calling +to_a+ on that object calls +paths+ because it's +alias+'d at the bottom of the +Path+ class definition: -<ruby> - alias to_a paths -</ruby> +The +config+ method used at the top of +I18n::Railtie+ is defined on +Rails::Railtie+ and is defined like this: <ruby> - def paths - raise "You need to set a path root" unless @root.path - result = @paths.map do |p| - path = File.expand_path(p, @root.path) - @glob ? Dir[File.join(path, @glob)] : path - end - result.flatten! - result.uniq! - result + def config + @config ||= Railtie::Configuration.new end </ruby> -This returns an array of files according to our +path+ and +@glob+ which are +config/environments+ and +development.rb+ respectively, therefore we can determine that: +At this point, that +Railtie::Configuration+ constant is automatically loaded which causes the +rails/railties/configuration+ file to be loaded. The line for this is this particular line in +railties/lib/rails/railtie.rb+: <ruby> - Dir[File.join(path, @glob)] + autoload :Configuration, "rails/railtie/configuration" </ruby> -will return an +Array+ containing one element, +"config/enviroments/development.rb"+. Of course when we call +first+ on this Array we'll get the first element and because that exists, we now +require "config/environments/development.rb"+. - -This file contains the following by default: - -<ruby> - YourApp::Application.configure do - # Settings specified here will take precedence over those in config/environment.rb - - # In the development environment your application's code is reloaded on - # every request. This slows down response time but is perfect for development - # since you don't have to restart the webserver when you make code changes. - config.cache_classes = false - - # Log error messages when you accidentally call methods on nil. - config.whiny_nils = true +h4. +railties/lib/rails/railtie/configuration.rb+ - # Show full error reports and disable caching - config.consider_all_requests_local = true - config.action_view.debug_rjs = true - config.action_controller.perform_caching = false - - # Don't care if the mailer can't send - config.action_mailer.raise_delivery_errors = false - end -</ruby> +This file begins with a require out to +rails/configuration+ which has already been required earlier in the process and so isn't required again. -This +configure+ method is an +alias+ of +class_eval+ on +Rails::Application+: - -<ruby> - alias :configure :class_eval -</ruby> - -therefore, the code inside of the +configure+ is evaluated within the context of +YourApp::Application+. - -The +config+ object here is the same one that was set up when _config/application.rb_ was loaded, therefore the methods called in this object will fall to the +method_missing+ defined in +Rails::Configuration::Shared+: +This file defines the +Rails::Railtie::Configuration+ class which is responsible for providing a way to easily configure railties and it's the +initialize+ method here which is called by the +config+ method back in the +i18n_railtie.rb+ file. The methods on this object don't exist, and so are rescued by the +method_missing+ defined further down in +configuration.rb+: <ruby> def method_missing(name, *args, &blk) - if name.to_s =~ config_key_regexp - return $2 == '=' ? options[$1] = args.first : options[$1] + if name.to_s =~ /=$/ + @@options[$`.to_sym] = args.first + elsif @@options.key?(name) + @@options[name] + else + super end - super end </ruby> -This time we are using methods ending in +\=+, so it will set the key in the +options+ to be the value specified. The first couple of options, +cache_classes+, +whiny_nils+, +consider_all_requests_local+ are just simple keys on the +options+. If you recall how options were setup then you may be able to work out how the remaining +action_view+, +action_controller+ and +action_mailer+ methods work. - -Firstly, we'll cover how +config_key_regexp+ is defined: - -<ruby> - def config_key_regexp - bits = config_keys.map { |n| Regexp.escape(n.to_s) }.join('|') - /^(#{bits})(?:=)?$/ - end -</ruby> - -And also +config_keys+: - -<ruby> - def config_keys - (Railtie.railtie_names + Engine.engine_names).map { |n| n.to_s }.uniq - end -</ruby> - -+config_keys+ in here returns: - -<ruby> - [:active_support, :i18n, :action_dispatch, :action_view, :action_controller, :active_record, :action_mailer, :active_resource, :test_unit] -</ruby> - -With all of those keys coming from +Railtie::railtie_names+. If you've elected to not load some of the frameworks here they won't be available as configuration keys, so you'll need to remove them too. +So therefore when an option is referred to it simply stores the value as the key if it's used in a setter context, or retrieves it if used in a getter context. Nothing fancy going on there. -Now a reminder of how the +options+ key is defined: +h4. Back to +activesupport/lib/active_support/i18n_railtie.rb+ -<ruby> - def options - @@options ||= Hash.new { |h,k| h[k] = ActiveSupport::OrderedOptions.new } - end -</ruby> - -The values for these framework keys are +ActiveSupport::OrderedOptions+ objects, with the class defined like this: +After the configuration method the +reloader+ method is defined, and then the first of of Railties' initializers is defined: +i18n.callbacks+. <ruby> - module ActiveSupport #:nodoc: - class OrderedOptions < OrderedHash - def []=(key, value) - super(key.to_sym, value) - end - - def [](key) - super(key.to_sym) - end - - def method_missing(name, *args) - if name.to_s =~ /(.*)=$/ - self[$1.to_sym] = args.first - else - self[name] - end - end + initializer "i18n.callbacks" do + ActionDispatch::Reloader.to_prepare do + I18n::Railtie.reloader.execute_if_updated end end </ruby> -We can determine when we call +config.action_view.debug_rjs+ it's falling back to the +method_missing+ defined on +ActiveSupport::OrderedOptions+, which ends up either setting or retrieving a key. In this case because we're using a setter, it will set the key for this hash. This completes the loading of _config/environments/development.rb_. - -h4. +load_all_active_support+ - -This initializer does exactly what it says: +The +initializer+ method (from the +Rails::Initializable+ module) here doesn't run the block, but rather stores it to be run later on: <ruby> - initializer :load_all_active_support do - require "active_support/all" unless config.active_support.bare + def initializer(name, opts = {}, &blk) + raise ArgumentError, "A block must be passed when defining an initializer" unless blk + opts[:after] ||= initializers.last.name unless initializers.empty? || initializers.find { |i| i.name == opts[:before] } + initializers << Initializer.new(name, nil, opts, &blk) end </ruby> -If you don't want this to happen you can specify the +config.active_support.bare+ option to +true+ in either _config/application.rb_ or any of your environment files. - -h4. +preload_frameworks+ - -Remember earlier how we had all that stuff +eager_autoload+'d for Active Support? +An initializer can be configured to run before or after another initializer, which we'll see a couple of times throughout this initialization process. Anything that inherits from +Rails::Railtie+ may also make use of the +initializer+ method, something which is covered in the "Configuration guide":[http://ryanbigg.com/guides/configuring.html#rails-railtie-initializer]. -<ruby> - initializer :preload_frameworks do - require 'active_support/dependencies' - ActiveSupport::Autoload.eager_autoload! if config.preload_frameworks - end -</ruby> - -This is where it gets loaded. The +eager_autoload!+ method is defined like this: +The +Initializer+ class here is defined within the +Rails::Initializable+ module and its +initialize+ method is defined to just set up a couple of variables: <ruby> - def self.eager_autoload! - @@autoloads.values.each { |file| require file } + def initialize(name, context, options, &block) + @name, @context, @options, @block = name, context, options, block end </ruby> -With +@@autoloads+ being - - -* load_all_active_support -* preload_frameworks -* initialize_logger -* initialize_cache -* initialize_subscriber -* set_clear_dependencies_hook -* initialize_dependency_mechanism - -h4. Active Support Initializers - -Active Support - -**Active Support Initializers** - -* active_support.initialize_whiny_nils -* active_support.initialize_time_zone - -**I18n Initializers** - -* i18n.initialize - -The +I18n::Railtie+ also defines an +after_initialize+ which we will return to later when discussing the initializers in detail. - -**Action Dispatch Initializers** - -* action_dispatch.prepare_dispatcher - -**Action Controller Initializers** - -* action_controller.logger -* action_controller.set_configs -* action_controller.initialize_framework_caches -* action_controller.set_helpers_path - -**Active Record Initializers** - -* active_record.initialize_time_zone -* active_record.logger -* active_record.set_configs -* active_record.log_runtime -* active_record.initialize_database_middleware -* active_record.load_observers -* active_record.set_dispatch_hooks - -**Action View Initializers ** - -* action_view.cache_asset_timestamps - -**Action Mailer Initializers ** - -* action_mailer.logger -* action_mailer.set_configs -* action_mailer.url_for - -**Active Resource Initializers** - -* active_resource.set_configs - -**Rails::Engine Initializers** - -* set_load_path -* set_autoload_paths -* add_routing_paths - - -h4. +Rails::Engine.new+ - -The +new+ method doesn't exist, but in Ruby classes calling +new+ on the class instantiates a new instance of that class and calls the instance method +initialize+ on it. This method for +Rails::Application+ goes like this: - -<ruby> - def initialize - require_environment - Rails.application ||= self - @route_configuration_files = [] - end -</ruby> - -h4. +Rails::Application#require_environment+ - -This is not a crafty method like the previous ones, it just does as it says on the box: +Once this +initialize+ method is finished, the object is added to the object the +initializers+ method returns: <ruby> - def require_environment - require config.environment_path - rescue LoadError + def initializers + @initializers ||= self.class.initializers_for(self) end </ruby> -The +config+ object here is actually another +delegate+'d method (along with +routes+), this time to +self.class+: - -<ruby> - delegate :config, :routes, :to => :'self.class' -</ruby> - -So the method call is actually +self.class.config+. - - -h4. +Rails::Application.config+ - -Defined back inside the +class << self+ for +Rails::Application+, +config+ makes a new +Rails::Application::Configuration+ object and caches it in a variable called +@config+: +If +@initializers+ isn't set (which it won't be at this point), the +intializers_for+ method will be called for this class. <ruby> - def config - @config ||= Configuration.new(Plugin::Configuration.default) + def initializers_for(binding) + Collection.new(initializers_chain.map { |i| i.bind(binding) }) end </ruby> -h4. +Rails::Plugin::Configuration.default+ +The +Collection+ class in +railties/lib/rails/initializable.rb+ inherits from +Array+ and includes the +TSort+ module which is used to sort out the order of the initializers based on the order they are placed in. -The +Rails::Plugin::Configuration+ class may be a bit difficult to find at first, but if you look for _plugin.rb_ in Rails, you'll find it in _railties/lib/rails/plugin.rb_. In this file, we see the following: +The +initializers_chain+ method referenced in the +initializers_for+ method is defined like this: -<ruby> - module Rails - class Plugin < Railtie - ... +<rub> + def initializers_chain + initializers = Collection.new + ancestors.reverse_each do | klass | + next unless klass.respond_to?(:initializers) + initializers = initializers + klass.initializers end + initializers end </ruby> -So we note here that +Rails::Plugin+ descends from +Rails::Railtie+ and secondly we note that the class +Configuration+ is not actually included in the +Plugin+ class, but it **is** in the +Railtie+ class! - -h4. +Rails::Railtie::Configuration+ - -We've now tracked down the +Plugin::Configuration.default+ method to being +Railtie::Configuration.default+, which is defined like this in _railties/lib/rails/configuration.rb_: +This method collects the initializers from the ancestors of this class and adds them to a new +Collection+ object using the <tt>+</tt> method which is defined like this for the <tt>Collection</tt> class: <ruby> - class Railtie::Configuration - def self.default - @default ||= new - end - ... + def +(other) + Collection.new(to_a + other.to_a) end </ruby> -In this case we have effectively seen that it's doing Configuration.new(Configuration.new). I'll explain why. - -h4. +Rails::Application::Configuration.new+ +So this <tt>+</tt> method is overriden to return a new collection comprising of the existing collection as an array and then using the <tt>Array#+</tt> method combines these two collections, returning a "super" +Collection+ object. In this case, the only initializer that's going to be in this new +Collection+ object is the +i18n.callbacks+ initializer. -TODO: CLEAN THIS UP! This subclassing is only temporary and will probably not be separate in Rails 3. This is based solely off what the comment at the top of the Railtie::Configuration class says! - -The first thing to note here is that this class is subclassed from +Railtie::Configuration+ and therefore the method here is actually +Railtie::Configuration.new+. As mentioned previously, calling +new+ will make a new object of this class and then call +initialize+ on it, which is defined like this: +The next method to be called after this +initializer+ method is the +after_initialize+ method on the +config+ object, which is defined like this: <ruby> - def initialize(base = nil) - if base - @options = base.options.dup - @middleware = base.middleware.dup - else - @options = Hash.new { |h,k| h[k] = ActiveSupport::OrderedOptions.new } - @middleware = self.class.default_middleware_stack - end + def after_initialize(&block) + ActiveSupport.on_load(:after_initialize, :yield => true, &block) end </ruby> -This method is not called with a +base+ argument for +Plugin::Configuration.default+ but it is for the +Configuration.new+ wrapped around it. We'll go for the internal one first, since that's the order Rails loads them in. - -h4. +default_middleware_stack+ - -This method is defined like this: +The +on_load+ method here is provided by the +active_support/lazy_load_hooks+ file which was required earlier and is defined like this: <ruby> - def self.default_middleware_stack - ActionDispatch::MiddlewareStack.new.tap do |middleware| - middleware.use('ActionDispatch::Static', lambda { Rails.public_path }, :if => lambda { Rails.application.config.serve_static_assets }) - middleware.use('::Rack::Lock', :if => lambda { !ActionController::Base.allow_concurrency }) - middleware.use('::Rack::Runtime') - middleware.use('ActionDispatch::ShowExceptions', lambda { ActionController::Base.consider_all_requests_local }) - middleware.use('ActionDispatch::Notifications') - middleware.use('ActionDispatch::Callbacks', lambda { !Rails.application.config.cache_classes }) - middleware.use('ActionDispatch::Cookies') - middleware.use(lambda { ActionController::Base.session_store }, lambda { ActionController::Base.session_options }) - middleware.use('ActionDispatch::Flash', :if => lambda { ActionController::Base.session_store }) - middleware.use('ActionDispatch::ParamsParser') - middleware.use('::Rack::MethodOverride') - middleware.use('::ActionDispatch::Head') + def self.on_load(name, options = {}, &block) + if base = @loaded[name] + execute_hook(base, options, block) + else + @load_hooks[name] << [block, options] end end </ruby> -To really understand this method we need to dig a little deeper, down into where +ActionDispatch::MiddlewareStack.new+ is defined and what in particular it does for us. - -h4. +ActionDispatch::MiddlewareStack.new+ - -+ActionDispatch+ is our first foray outside of the +railties+ gem, as this is actually defined in the +actionpack+ part of Rails. The class definition is as important as the method: +The +@loaded+ variable here is a hash containing elements representing the different components of Rails that have been loaded at this stage. Currently, this hash is empty. So the +else+ is executed here, using the +@load_hooks+ variable defined in +active_support/lazy_load_hooks+: <ruby> - module ActionDispatch - class MiddlewareStack < Array - - ... - - def initialize(*args, &block) - super(*args) - block.call(self) if block_given? - end - end - end + @load_hooks = Hash.new {|h,k| h[k] = [] } </ruby> -When it's calling +super+ here it's actually calling +initialize+ on the Array class and from this we can determine that an +ActionDispatch::MiddlewareStack+ object is just an +Array+ object with special powers. One of those special powers is the ability to take a block, and +call+ it with +self+, meaning the block's parameter is the object itself! - -h4. +ActionDispatch::MiddlewareStack.use+ - -Previously we saw a chunk of code that I'll re-show you stripped down: +This defines a new hash which has keys that default to empty arrays. This saves Rails from having to do something like this instead: <ruby> - def self.default_middleware_stack - ActionDispatch::MiddlewareStack.new.tap do |middleware| - middleware.use('ActionDispatch::Static', lambda { Rails.public_path }, :if => lambda { Rails.application.config.serve_static_assets }) - ... - end - end + @load_hooks[name] = [] + @load_hooks[name] << [block, options] </ruby> -As explained in the previous section, we know that the +new+ on +ActionDispatch::MiddlewareStack+ takes a block and that block has one parameter which is the object itself. On this object we call the +use+ method to include middleware into our application. The use method simply does this: +The value added to this array here consists of the block and options passed to +after_initialize+. -<ruby> - def use(*args, &block) - middleware = Middleware.new(*args, &block) - push(middleware) - end -</ruby> +We'll see these +@load_hooks+ used later on in the initialization process. -We'll come back to this method later on. +This rest of +i18n_railtie.rb+ defines the protected class methods +include_fallback_modules+, +init_fallbacks+ and +validate_fallbacks+. -h4. +ActionController::Middleware.new+ +h4. Back to +activesupport/lib/active_support/railtie.rb+ -This +initialize+ method also is in a class who's ancestry is important so once again I'll show the ancestry and we'll go up that particular chain: +This file defines the +ActiveSupport::Railtie+ constant which like the +I18n::Railtie+ constant just defined, inherits from +Rails::Railtie+ meaning the +inherited+ method would be called again here, including +Rails::Configurable+ into this class. This class makes use of +Rails::Railtie+'s +config+ method again, setting up the configuration options for Active Support. -<ruby> - module ActionController - class Middleware < Metal - - ... - - def initialize(app) - super() - @_app = app - end - end - end -</ruby> +Then this Railtie sets up three more initializers: -Here our method calls +super+ but with a difference: it's passing in no arguments intentionally by putting the two brackets at the end. The method called here is therefore +ActionController::Metal.initialize+. +* +active_support.initialize_whiny_nils+ +* +active_support.deprecation_behavior+ +* +active_support.initialize_time_zone+ -h4. +ActionController::Metal.initialize+ +We will cover what each of these initializers do when they run. -This is another subclassed class, this time from +ActionController::AbstractController+ and I'm sure you can guess what that means: +Once the +active_support/railtie+ file has finished loading the next file required from +railties/lib/rails.rb+ is the +action_dispatch/railtie+. -<ruby> - class Metal < AbstractController::Base - - ... - - def initialize(*) - @_headers = {} - super - end - end -</ruby> +h4. +activesupport/lib/action_dispatch/railtie.rb+ -The single +*+ in the argument listing means we can accept any number of arguments, we just don't care what they are. +This file defines the +ActionDispatch::Railtie+ class, but not before requiring +action_dispatch+. -h4. +AbstractController::Base.initialize+ +h4. +activesupport/lib/action_dispatch.rb+ -This may be anti-climatic, but the initialize method here just returns an +AbstractController::Base+ object: +This file attempts to locate the +active_support+ and +active_model+ libraries by looking a couple of directories back from the current file and then adds the +active_support+ and +active_model+ +lib+ directories to the load path, but only if they aren't already, which they are. <ruby> - # Initialize controller with nil formats. - def initialize #:nodoc: - @_formats = nil - end -</ruby> - -h4. +ActionDispatch::MiddlewareStack.use+ - -Now we're back to this method, from our foray into the depths of how +Middleware.new+ works, we've showed that it is an instance of +AbstractController::Base+. Therefore it does - -TODO: ELABORATE ON THIS SECTION, including explaining what all the pieces of middleware do. Then explain how the default_middleware_stack does what it does, whatever that is. - -h4. Back to +Rails::Application::Configuration.new+ - -Now that the first call to this method is complete (+Plugin::Configuration.default+), we can move onto the second call. Here's a refresher of what this method does: + activesupport_path = File.expand_path('../../../activesupport/lib', __FILE__) + $:.unshift(activesupport_path) if File.directory?(activesupport_path) && !$:.include?(activesupport_path) -<ruby> - def initialize(base = nil) - if base - @options = base.options.dup - @middleware = base.middleware.dup - else - @options = Hash.new { |h,k| h[k] = ActiveSupport::OrderedOptions.new } - @middleware = self.class.default_middleware_stack - end - end + activemodel_path = File.expand_path('../../../activemodel/lib', __FILE__) + $:.unshift(activemodel_path) if File.directory?(activemodel_path) && !$:.include?(activemodel_path) </ruby> -You'll note now that this method is being called now is +Configuration.new(Plugin::Configuration.default)+ and with the argument, it's going to perform differently than before, this time duplicating the +options+ and +middleware+ of the object it was passed. - -TODO: Find out what purpose the +@options+ and +@middleware+ variables serve. +In effect, these lines only define the +activesupport_path+ and +activemodel_path+ variables and nothing more. -Finally, a +Rails::Application::Configuration+ object will be returned. On this class there are a couple of +attr_accessor+s and +attr_writer+s defined: +The next two requires in this file are already done, so they are not run: <ruby> - attr_accessor :after_initialize_blocks, :cache_classes, :colorize_logging, - :consider_all_requests_local, :dependency_loading, - :load_once_paths, :logger, :plugins, - :preload_frameworks, :reload_plugins, :serve_static_assets, - :time_zone, :whiny_nils - - attr_writer :cache_store, :controller_paths, - :database_configuration_file, :eager_load_paths, - :i18n, :load_paths, :log_level, :log_path, :paths, - :routes_configuration_file, :view_path -</ruby> - -Along with these are a lot of helper methods, and one of them is +environment_path+: - -<ruby> - def environment_path - "#{root}/config/environments/#{Rails.env}.rb" - end + require 'active_support' + require 'active_support/dependencies/autoload' </ruby> -h4. Back to +Rails::Application#require_environment+ - -Now that we have a +Rails::Application::Configuration+ object for the +config+ method, we call the +environment_path+ which, as we've seen above, just requires the current environment file which in this case is _config/environments/development.rb_. If this file cannot be found, the +LoadError+ +require+ throws will be +rescue+'d and Rails will continue on its merry way. - -h4. _config/environments/development.rb_ - -In a standard Rails application we have this in our _config/environments/development.rb_ file: +The following require is to +action_pack+ (+activesupport/lib/action_pack.rb+) which has a 22-line copyright notice at the top of it and ends in a simple require to +action_pack/version+. This file, like other +version.rb+ files before it, defines the +ActionPack::VERSION+ constant: <ruby> - YourApp::Application.configure do - # Settings specified here will take precedence over those in config/environment.rb - - # In the development environment your application's code is reloaded on - # every request. This slows down response time but is perfect for development - # since you don't have to restart the webserver when you make code changes. - config.cache_classes = false - - # Log error messages when you accidentally call methods on nil. - config.whiny_nils = true - - # Show full error reports and disable caching - config.action_controller.consider_all_requests_local = true - config.action_view.debug_rjs = true - config.action_controller.perform_caching = false + module ActionPack + module VERSION #:nodoc: + MAJOR = 3 + MINOR = 1 + TINY = 0 + PRE = "beta" - # Don't care if the mailer can't send - config.action_mailer.raise_delivery_errors = false + STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.') + end end </ruby> -It's a little bit sneaky here, but +configure+ is +alias+'d to +class_eval+ on subclasses of +Rails::Application+ which of course includes +YourApp::Application+. This means that the code inside the +configure do+ block will be evaled within the context of +YourApp::Application+. The +config+ method here is the one mentioned before: the +Rails::Application::Configuration+ object. The methods on it should look familiar too: they're the ones that had +attr_accessor+ and +attr_writer+ definitions. +Once +action_pack+ is finished, then +active_model+ is required. -The ones down the bottom, +config.action_controller+, +config.action_view+ and +config.action_mailer+ aren't defined by +attr_accessor+ or +attr_writer+, rather they're undefined methods and therefore will trigger the +method_missing+ on the +Rails::Application::Configuration+ option. +h4. +activemodel/lib/active_model.rb+ -h5. config.cache_classes= - -The first method call in this file, this tells Rails to not cache the classes for every request. This means for every single request Rails will reload the classes of your application. If you have a lot of classes, this will slow down the request cycle of your application. This is set to +false+ in the _development_ environment, and +true+ in the _test_ & _production_ environments. - -h5. config.whiny_nils= - -If this is set to +true+, like it is here in the _development_ environment, _activesupport/whiny_nil_ will be +require+'d. Have you ever seen this error: - -<ruby> - Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id -</ruby> - -Or perhaps this one? +This file makes a require to +active_model/version+ which defines the version for Active Model: <ruby> - You have a nil object when you didn't expect it! - You might have expected an instance of Array. - The error occurred while evaluating nil.flatten! -</ruby> - -If you have, then this is _activesupport/whiny_nil_ at work. - - -h5. The frameworks - -As mentioned before, the methods +action_controller+, +action_view+ and +action_mailer+ aren't defined on the +Rails::Application::Configuration+ object, rather they are caught by +method_missing+ which does this: + module ActiveModel + module VERSION #:nodoc: + MAJOR = 3 + MINOR = 1 + TINY = 0 + PRE = "beta" -<ruby> - def method_missing(name, *args, &blk) - if name.to_s =~ config_key_regexp - return $2 == '=' ? @options[$1] = args.first : @options[$1] + STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.') end - - super end </ruby> -Whilst this code is not obvious at first, a little bit of further explanation will help you understand. +config_key_regexp+ is another method (a private one, like +method_missing+) defined here: +Once the +version.rb+ file is loaded, the +ActiveModel+ module has its autoloaded constants defined as well as a sub-module called +ActiveModel::Serializers+ which has autoloads of its own. When the +ActiveModel+ module is closed the +active_support/i18n+ file is required. -<ruby> - def config_key_regexp - bits = config_keys.map { |n| Regexp.escape(n.to_s) }.join('|') - /^(#{bits})(?:=)?$/ - end -</ruby> +h4. +activesupport/lib/active_support/i18n.rb+ -As is +config_keys+: +This is where the +i18n+ gem is required and first configured: <ruby> - def config_keys - ([ :active_support, :action_view ] + - Railtie.plugin_names).map { |n| n.to_s }.uniq + begin + require 'i18n' + require 'active_support/lazy_load_hooks' + rescue LoadError => e + $stderr.puts "You don't have i18n installed in your application. Please add it to your Gemfile and run bundle install" + raise e end -</ruby> - -Aha! There we've got mention of +action_view+, but what is in +Railtie.plugin_names+? Most likely in this case the other frameworks. -h5. +Railtie.plugin_names+ - -I'm going to show you two methods since the third one, +self.plugin_name+, calls the second one, +self.plugins+ and they're right after each other: - -<ruby> - module Rails - class Railtie - def self.inherited(klass) - @plugins ||= [] - @plugins << klass unless klass == Plugin - end - - def self.plugins - @plugins - end - - def self.plugin_names - plugins.map { |p| p.plugin_name } - end - end - end + I18n.load_path << "#{File.dirname(__FILE__)}/locale/en.yml" </ruby> -In here we see that we get the +plugin_names+ from a variable called +@plugins+... which we haven't seen yet. Through the power of the wonderful +inherited+ the +@plugins+ variable is populated. +inherited+ is called when a class inherits, or subclasses, from this class. Therefore we can determine that the other classes are probably inheriting or subclassing from +Rails::Railtie+. - -h3. Serving a Request - -Now that your application is fully initialized, it's now ready to start serving requests. - -h4. _rails server_ - -For servers running through _rails server_ you may recall that this uses +Rails::Server+ which is a subclass of +Rack::Server+. Previously we covered the initialization process of Rack but not completely up to the point where the server was running. Now that's what we'll do. Back when the +Rack::Server+ class was first covered there was a mention of the +start+ method which we only touched on. It goes a little like this: - -<ruby> - def start - if options[:debug] - $DEBUG = true - require 'pp' - p options[:server] - pp wrapped_app - pp app - end - - if options[:warn] - $-w = true - end +In effect, the +I18n+ module first defined by +i18n_railtie+ is extended by the +i18n+ gem, rather than the other way around. This has no ill effect. They both work on the same way. - if includes = options[:include] - $LOAD_PATH.unshift *includes - end +This is another spot where +active_support/lazy_load_hooks+ is required, but it has already been required so it's not loaded again. - if library = options[:require] - require library - end +If +i18n+ cannot be loaded, the user is presented with an error which says that it cannot be loaded and recommends that it's added to the +Gemfile+. However, in a normal Rails application this gem would be loaded. - daemonize_app if options[:daemonize] - write_pid if options[:pid] - server.run wrapped_app, options - end -</ruby> +Once it has finished loading, the +I18n.load_path+ method is used to add the +activesupport/lib/active_support/locale/en.yml+ file to I18n's load path. When the translations are loaded in the initialization process, this is one of the files where they will be sourced from. -We were at the point of explaining what +wrapped_app+ was before we dived into the Rails initialization process.Now that we have a +wrapped_app+ we pass it as the first argument to +server.run+. +server+ in this instance is defined like this: +The loading of this file finishes the loading of +active_model+ and so we go back to +action_dispatch+. -<ruby> - def server - @_server ||= Rack::Handler.get(options[:server]) || Rack::Handler.default - end -</ruby> +h4. Back to +activesupport/lib/action_dispatch.rb+ -Our +options+ Hash is still the default, and there is no +server+ key set in +default_options+, so it will default to +Rack::Handler.default+. This code works like this: +The remainder of this file requires the +rack+ file from the Rack gem which defines the +Rack+ module. After +rack+, there's autoloads defined for the +Rack+, +ActionDispatch+, +ActionDispatch::Http+, +ActionDispatch::Session+. A new method called +autoload_under+ is used here, and this simply prefixes the files where the modules are autoloaded from with the path specified. For example here: <ruby> - def self.default(options = {}) - # Guess. - if ENV.include?("PHP_FCGI_CHILDREN") - # We already speak FastCGI - options.delete :File - options.delete :Port - - Rack::Handler::FastCGI - elsif ENV.include?("REQUEST_METHOD") - Rack::Handler::CGI - else - begin - Rack::Handler::Mongrel - rescue LoadError => e - Rack::Handler::WEBrick - end - end - end + autoload_under 'testing' do + autoload :Assertions + ... </ruby> +The +Assertions+ module is in the +action_dispatch/testing+ folder rather than simply +action_dispatch+. -We don't have +PHP_FCGI_CHILDREN+ in our +ENV+, so it's not going to be +FastCGI+. We also don't have +REQUEST_METHOD+ in there, so it's not going to be +CGI+. If we have Mongrel installed it'll default to that and then finally it'll use WEBrick. For this, we'll assume a bare-bones installation and assume WEBrick. So from this we can determine our default handler is +Rack::Handler::WEBrick+. +Finally, this file defines a top-level autoload, the +Mime+ constant. -(side-note: Mongrel doesn't install on 1.9. TODO: How do we format these anyway?) +h4. Back to +activesupport/lib/action_dispatch/railtie.rb+ -h5. +Rack::Handler::WEBrick+ +After +action_dispatch+ is required in this file, the +ActionDispatch::Railtie+ class is defined and is yet another class that inherits from +Rails::Railtie+. This class defines some initial configuration option defaults for +config.action_dispatch+ before setting up a single initializer called +action_dispatch.configure+. -This class is subclassed from +WEBrick::HTTPServlet::AbstractServlet+ which is a class that comes with the Ruby standard library. This is the magical class that serves the requests and deals with the comings (requests) and goings (responses) for your server. +With +action_dispatch/railtie+ now complete, we go back to +railties/lib/rails.rb+. +h4. Back to +railties/lib/rails.rb+ -+Rack::Server+ has handlers for the request and by default the handler for a _rails server_ server is +With the Active Support and Action Dispatch railties now both loaded, the rest of this file deals with setting up UTF-8 to be the default encoding for Rails and then finally setting up the +Rails+ module. This module defines useful methods such as +Rails.logger+, +Rails.application+, +Rails.env+, and +Rails.root+. -h3. Cruft! +h4. Back to +railties/lib/rails/all.rb+ -The final line of _config/environment.rb_: +Now that +rails.rb+ is required, the remaining railties are loaded next, beginning with +active_record/railtie+. -<ruby> - YourApp::Application.initialize! -</ruby> +h4. +activerecord/lib/active_record/railtie.rb+ -gets down to actually initializing the application! +Before this file gets into the swing of defining the +ActiveRecord::Railtie+ class, there are a couple of files that are required first. The first one of these is +active_record+. -TODO: Cover the other +config.*+ methods in perhaps a "Bonus" section near the end. If they aren't referenced in a config file they aren't that important, right? +h4. +activerecord/lib/active_record.rb+ +This file begins by detecting if the +lib+ directories of +active_support+ and +active_model+ are not in the load path and if they aren't then adds them. As we saw back in +action_dispatch.rb+, these directories are already there. -TODO: This belongs in the guide, I just don't know where yet. Maybe towards the end, since this is really the "final" thing to be done before being able to serve requests. +The first three requires have already been done by other files and so aren't loaded here, but the 4th require, the one to +arel+ will require the file provided by the Arel gem, which defines the +Arel+ module. <ruby> - def build_app(app) - middleware[options[:environment]].reverse_each do |middleware| - middleware = middleware.call(self) if middleware.respond_to?(:call) - next unless middleware - klass = middleware.shift - app = klass.new(app, *middleware) - end - app - end -</ruby> - -Because we don't have any middleware for our application, this returns the application itself( Guessing here!! TODO: Investigate if this is really the case.) - -Now that we have an app instance, the last line in +start+ calls +server.run wrapped_app, options+. We know what our app is, and that our options are just the default options, so what is +server+? +server+ is this: - -<ruby> - def server - @_server ||= Rack::Handler.get(options[:server]) || Rack::Handler.default - end + require 'active_support' + require 'active_support/i18n' + require 'active_model' + require 'arel' </ruby> -Since we have default options, the server is obviously going to be +Rack::Handler.default+. The +default+ method goes like this: +The 5th require in this file is one to +active_record/version+ which defines the +ActiveRecord::VERSION+ constant: <ruby> - def self.default(options = {}) - # Guess. - if ENV.include?("PHP_FCGI_CHILDREN") - # We already speak FastCGI - options.delete :File - options.delete :Port - - Rack::Handler::FastCGI - elsif ENV.include?("REQUEST_METHOD") - Rack::Handler::CGI - else - begin - Rack::Handler::Mongrel - rescue LoadError => e - Rack::Handler::WEBrick - end - end - end -</ruby> - -h3. +Rails::Paths+ - - -The +super+ method it references comes from +Rails::Engine::Configuration+ which defines these paths: + module ActiveRecord + module VERSION #:nodoc: + MAJOR = 3 + MINOR = 1 + TINY = 0 + PRE = "beta" -<ruby> - def paths - @paths ||= begin - paths = Rails::Paths::Root.new(@root) - paths.app "app", :eager_load => true, :glob => "*" - paths.app.controllers "app/controllers", :eager_load => true - paths.app.helpers "app/helpers", :eager_load => true - paths.app.models "app/models", :eager_load => true - paths.app.views "app/views" - paths.lib "lib", :load_path => true - paths.lib.tasks "lib/tasks", :glob => "**/*.rake" - paths.lib.templates "lib/templates" - paths.config "config" - paths.config.initializers "config/initializers", :glob => "**/*.rb" - paths.config.locales "config/locales", :glob => "*.{rb,yml}" - paths.config.routes "config/routes.rb" - paths + STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.') end end </ruby> -h3. Appendix A - -This file is _activesupport/lib/active_support/inflector/inflections.rb_ and defines the +ActiveSupport::Inflector::Inflections+ class which defines the +singularize+, +pluralize+, +humanize+, +tableize+, +titleize+ and +classify+ methods as well as the code to defining how to work out the irregular, singular, plural and human versions of words. These methods are called +irregular+, +singular+, +plural+ and +human+ respectively, as is the Rails way. - -This file is _activesupport/lib/active_support/inflector/transliterate.rb_ and defines two methods, +transliterate+ and +parameterize+. +Once these requires are finished, the base for the +ActiveRecord+ module is defined along with its autoloads. -This file first requires _activesupport/lib/active_support/core_ext/string/multibyte.rb_, which requires _activesupport/lib/active_support/multibyte.rb_, which subsequently requires _activesupport/core_ext/module/attribute_accessors.rb_. The _attribute_accessors.rb_ file is needed to gain access to the +mattr_accessor+ (module attribute accessor) method, which is called in _active_suport/multibyte.rb_. The file _active_support/multibyte.rb_ also autoloads three other classes: +Near the end of the file, we see this line: <ruby> -module ActiveSupport #:nodoc: - module Multibyte - autoload :EncodingError, 'active_support/multibyte/exceptions' - autoload :Chars, 'active_support/multibyte/chars' - autoload :Unicode, 'active_support/multibyte/unicode' - ... + ActiveSupport.on_load(:active_record) do + Arel::Table.engine = self end -end </ruby> -There are also these method definitions: - -<ruby> - # The proxy class returned when calling mb_chars. You can use this accessor to configure your own proxy - # class so you can support other encodings. See the ActiveSupport::Multibyte::Chars implementation for - # an example how to do this. - # - # Example: - # ActiveSupport::Multibyte.proxy_class = CharsForUTF32 - def self.proxy_class=(klass) - @proxy_class = klass - end - - # Returns the currect proxy class - def self.proxy_class - @proxy_class ||= ActiveSupport::Multibyte::Chars - end -</ruby> +This will set the engine for +Arel::Table+ to be +ActiveRecord::Base+. -These methods are used in _activesupport/lib/active_support/core_ext/string/multibyte.rb_. - -The file _activesupport/lib/active_support/core_ext/string/chars.rb_ defines the default proxy class that will be returned by +mb_chars+. - -Because Ruby 1.9's +String+ class has support for multibyte encodings, some methods are defined only for Ruby 1.8: - -* +self.wants?+ -* +++ -* +=~+ -* +=~+ -* +center+ -* +include?+ -* +index+ -* +insert+ -* +ljust+ -* +lstrip+, +lstrip!+ -* +ord+ -* +rindex+ -* +rjust+ -* +rstrip+, +rstrip!+ -* +size+ -* +strip+, +strip!+ - -However, Ruby 1.9 lacks support for some needed operations, so the following methods are defined for both Ruby 1.8 and Ruby 1.9: - -* +<=>+ -* +[]=+ -* +capitalize+, +capitalize!+ -* +compose+ -* +decompose+ -* +downcase+, +downcase!+ -* +g_length+ -* +limit+ -* +normalize+ -* +reverse+, +reverse+! -* +slice+, +slice!+ -* +split+ -* +tidy_bytes+, +tidy_bytes!+ -* +titleize+ -* +upcase+, +upcase!+ +The file then finishes with this line: <ruby> - class String - if RUBY_VERSION >= "1.9" - def mb_chars - if ActiveSupport::Multibyte.proxy_class.consumes?(self) - ActiveSupport::Multibyte.proxy_class.new(self) - else - self - end - end - - def is_utf8? #:nodoc - case encoding - when Encoding::UTF_8 - valid_encoding? - when Encoding::ASCII_8BIT, Encoding::US_ASCII - dup.force_encoding(Encoding::UTF_8).valid_encoding? - else - false - end - end - else - def mb_chars - if ActiveSupport::Multibyte.proxy_class.wants?(self) - ActiveSupport::Multibyte.proxy_class.new(self) - else - self - end - end - - # Returns true if the string has UTF-8 semantics (a String used for purely byte resources is unlikely to have - # them), returns false otherwise. - def is_utf8? - ActiveSupport::Multibyte::Chars.consumes?(self) - end - end + I18n.load_path << File.dirname(__FILE__) + '/active_record/locale/en.yml' </ruby> -As you can see, +mb_chars+ is where the +proxy_class+ property comes in handy. This method will create a new instance of the configured proxy class using the instance of +String+ as a constructor argument. By default, the new +String+-like object will be an instance of the proxy class +ActiveSupport::Multibyte::Chars+. You can use +ActiveSupport::Multibyte.proxy_class=+ to set a different proxy class if you wish. - -Here, +mb_chars+ invokes +is_utf8?+ to checks if the string can be treated as UTF-8. On 1.9, the string's +encoding+ property is checked. On 1.8, +wants?+ checks to see if +$KCODE+ is "UTF-8" and, and +consumes?+ checks whether the string can be unpacked as UTF-8 without raising an error. - -The keen eye will have seen +ActiveSupport::Multibyte::Chars+ was specified as an +autoload+ earlier: _activesupport/lib/active_support/multibyte/chars.rb_ will be loaded without an explicit +require+ when we call +is_utf8+ on 1.8, or +mb_chars+ on any Ruby version. This file includes _activesupport/lib/active_support/string/access.rb_ which defines methods such as +at+, +from+, +to+, +first+ and +last+. These methods will return parts of the string depending on what is passed to them. +This will add the translations from +activerecord/lib/active_record/locale/en.yml+ to the load path for +I18n+, with this file being parsed when all the translations are loaded. -The second file included is _activesupport/lib/active_support/string/behavior.rb_ which only defines +acts_like_string?+ on +String+, a method which always returns +true+. This method is used by +Object#acts_like?+, which accepts a single argument representing the downcased and symbolised version of a class, and returns true if the object's behavior is like that class. In this case the code would be +acts_like?(:string)+. +h4. Back to +activerecord/lib/active_record/railtie.rb+ -The +Chars+ class also defines other important methods such as the "spaceship" method +<=>+, which is needed by the +Comparable+ module, in order to allow UTF-8-aware sorting. - -h3. Common Includes - -TODO: I feel this section would be better at the end of the guide as it breaks the flow. - -This section is for all the common includes in the Railties. - -h4. +require 'active_support/inflector'+ - -This file is _activesupport/lib/active_support/inflector.rb_ and makes a couple of requires out different files tasked with putting inflections in place: +The next two <tt>require</tt>s in this file aren't run because their files are already required, with +rails+ being required by +rails/all+ and +active_model/railtie+ being required from +action_dispatch+. <ruby> - require 'active_support/inflector/inflections' - require 'active_support/inflector/transliterate' - require 'active_support/inflector/methods' - - require 'active_support/inflections' - require 'active_support/core_ext/string/inflections' + require "rails" + require "active_model/railtie" </ruby> -The files included here define methods for modifying strings, such as +transliterate+ which will convert a Unicode string to its ASCII version, +parameterize+ for making strings into url-safe versions, +camelize+ for camel-casing a string such as +string_other+ into +StringOther+ and +ordinalize+ converting a string such as +101+ into +101st+. More information about these methods can be found in the Active Support Core Extensions Guide. TODO: Link to AS Guide. - -h4. +require 'active_support/core_ext/module/delegation'+ - -_activesupport/lib/active_support/core_ext/module/delegation.rb_ defines the +delegate+ method which can be used to delegate methods to other methods in your code. Take the following code example: +The next +require+ in this file is to +action_controller/railtie+. -<ruby> - class Client < ActiveRecord::Base - has_one :address - - delegate :address_line_1, :to => :address - end -</ruby> +h4. +actionpack/lib/action_controller/railtie.rb+ -This defines an +address_line_1+ method which is defined as: +This file begins with a couple more requires to files that have already been loaded: <ruby> - def address_line_1(*args, &block) - address.__send__(:address_line_1, *args, &block) - rescue NoMethodError - if address.nil? - raise "address_line_1 is delegated to address.address_line_1, but address is nil: #{client.inspect}" - end - end + require "rails" + require "action_controller" + require "action_dispatch/railtie" </ruby> -h4. +require 'active_support/core_ext/class/attribute_accessors'+ - -The file, _activesupport/lib/active_support/core_ext/class/attribute_accessors.rb_, defines the class accessor methods +cattr_writer+, +cattr_reader+ and +cattr_accessor+. +cattr_accessor+ defines a +cattr_reader+ and +cattr_writer+ for the symbol passed in. These methods work by defining class variables when you call their dynamic methods. - -Throughout the Railties there a couple of common includes. They are listed here for your convenience. - -h4. +require 'active_support/core_ext/module/attr_internal+ - -This file defines three methods +attr_internal_reader+, +attr_internal_writer+ and +attr_internal_accessor+. These work very similar to the +attr_reader+, +attr_writer+ and +attr_accessor+ methods, except the variables they define begin with +@_+. This was done to ensure that they do not clash with variables used people using Rails, as people are less-likely to define say, +@_request+ than they are to define +@request+. An example of where this method is used is for +params+ in the +ActionController::Metal+ class. - -h4. +require 'active_support/ruby/shim'+ - -The _activesupport/lib/active_support/ruby/shim.rb_ file requires methods that have been implemented in Ruby versions greater than 1.9. This is done so you can use Rails 3 on versions earlier than 1.9, such as 1.8.7. These methods are: - -* +Date#next_month+ -* +Date#next_year+ -* +DateTime#to_date+ -* +DateTime#to_datetime+ -* +DateTime#xmlschema+ -* +Enumerable#group_by+ -* +Enumerable#each_with_object+ -* +Enumerable#none?+ -* +Process#daemon+ -* +String#ord+ -* +Time#to_date+ -* +Time.to_time+ -* +Time.to_datetime+ +However the require after these is to a file that hasn't yet been loaded, +action_view/railtie+, which begins by requiring +action_view+. -For more information see the Active Support Core Extensions guide TODO: link to relevant sections for each method. +h4. +actionpack/lib/action_view.rb+ -And "the REXML security fix detailed here":[http://weblog.rubyonrails.org/2008/8/23/dos-vulnerabilities-in-rexml] ++action_view.rb+ diff --git a/railties/guides/source/layout.html.erb b/railties/guides/source/layout.html.erb index cc7d54c256..f2681c6461 100644 --- a/railties/guides/source/layout.html.erb +++ b/railties/guides/source/layout.html.erb @@ -8,13 +8,12 @@ <title><%= yield(:page_title) || 'Ruby on Rails guides' %></title> <link rel="stylesheet" type="text/css" href="stylesheets/style.css" /> -<link rel="stylesheet" type="text/css" href="stylesheets/syntax.css" /> <link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print" /> -<script type="text/javascript" src="javascripts/guides.js"></script> -<script type="text/javascript" src="javascripts/code_highlighter.js"></script> -<script type="text/javascript" src="javascripts/highlighters.js"></script> +<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shCore.css" /> +<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shThemeRailsGuides.css" /> +<link rel="stylesheet" type="text/css" href="stylesheets/fixes.css" /> </head> <body class="guide"> <% if @edge %> @@ -76,11 +75,12 @@ <dt>Extending Rails</dt> <dd><a href="plugins.html">The Basics of Creating Rails Plugins</a></dd> <dd><a href="rails_on_rack.html">Rails on Rack</a></dd> - <dd><a href="generators.html">Adding a Generator to Your Plugin</a></dd> + <dd><a href="generators.html">Creating and Customizing Rails Generators</a></dd> - <dt>Contributing to Rails</dt> - <dd><a href="contributing_to_rails.html">Contributing to Rails</a></dd> + <dt>Contributing to Ruby on Rails</dt> + <dd><a href="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</a></dd> <dd><a href="api_documentation_guidelines.html">API Documentation Guidelines</a></dd> + <dd><a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a></dd> <dt>Release Notes</dt> <dd><a href="3_0_release_notes.html">Ruby on Rails 3.0 Release Notes</a></dd> @@ -108,6 +108,28 @@ <div class="wrapper"> <div id="mainCol"> <%= yield.html_safe %> + + <h3>Feedback</h3> + <p> + You're encouraged to help in keeping the quality of this guide. + </p> + <p> + If you see any typos or factual errors you are confident to + patch, please clone <%= link_to 'docrails', 'https://github.com/lifo/docrails' %> + and push the change yourself. That branch of Rails has public write access. + Commits are still reviewed, but that happens after you've submitted your + contribution. <%= link_to 'docrails', 'https://github.com/lifo/docrails' %> is + cross-merged with master periodically. + </p> + <p> + You may also find incomplete content, or stuff that is not up to date. + Please do add any missing documentation for master. Check the + <%= link_to 'Ruby on Rails Guides Guidelines', 'ruby_on_rails_guides_guidelines.html' %> + for style and conventions. + </p> + <p>And last but not least, any kind of discussion regarding Ruby on Rails + documentation is very welcome in the <%= link_to 'rubyonrails-docs mailing list', 'http://groups.google.com/group/rubyonrails-docs' %>. + </p> </div> </div> </div> @@ -119,5 +141,15 @@ <p>"Rails", "Ruby on Rails", and the Rails logo are trademarks of David Heinemeier Hansson. All rights reserved.</p> </div> </div> + + <script type="text/javascript" src="javascripts/guides.js"></script> + <script type="text/javascript" src="javascripts/syntaxhighlighter/shCore.js"></script> + <script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushRuby.js"></script> + <script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushXml.js"></script> + <script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushSql.js"></script> + <script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushPlain.js"></script> + <script type="text/javascript"> + SyntaxHighlighter.all() + </script> </body> </html> diff --git a/railties/guides/source/layouts_and_rendering.textile b/railties/guides/source/layouts_and_rendering.textile index b9a201e5f0..1548da0eb5 100644 --- a/railties/guides/source/layouts_and_rendering.textile +++ b/railties/guides/source/layouts_and_rendering.textile @@ -27,7 +27,7 @@ I'll cover each of these methods in turn. But first, a few words about the very h4. Rendering by Default: Convention Over Configuration in Action -You've heard that Rails promotes "convention over configuration." Default rendering is an excellent example of this. By default, controllers in Rails automatically render views with names that correspond to valid routes. For example, if you have this code in your +BooksController+ class: +You've heard that Rails promotes "convention over configuration". Default rendering is an excellent example of this. By default, controllers in Rails automatically render views with names that correspond to valid routes. For example, if you have this code in your +BooksController+ class: <ruby> class BooksController < ApplicationController @@ -46,7 +46,7 @@ And you have a view file +app/views/books/index.html.erb+: <h1>Books are coming soon!</h1> </ruby> -Rails will automatically render +app/views/books/index.html.erb+ when you navigate to +/books+ and you will see on your screen that "Books are coming soon!" +Rails will automatically render +app/views/books/index.html.erb+ when you navigate to +/books+ and you will see "Books are coming soon!" on your screen. However a coming soon screen is only minimally useful, so you will soon create your +Book+ model and add the index action to +BooksController+: @@ -58,9 +58,9 @@ class BooksController < ApplicationController end </ruby> -Note that again, we have convention over configuration, in that there is no explicit render at the end of this index action. The rule is that if you do not explicitly render something by the end of the controller action, rails will look for the +action_name.html.erb+ template in the controllers view path and then render that, so in this case, Rails will render the +app/views/books/index.html.erb+ file. +Note that we don't have explicit render at the end of the index action in accordance with "convention over configuration" principle. The rule is that if you do not explicitly render something at the end of a controller action, Rails will automatically look for the +action_name.html.erb+ template in the controller's view path and render it. So in this case, Rails will render the +app/views/books/index.html.erb+ file. -So in our view, we want to display the properties of all the books, we could do this with an ERB template like this: +If we want to display the properties of all the books in our view, we can do so with an ERB template like this: <ruby> <h1>Listing Books</h1> @@ -90,7 +90,7 @@ So in our view, we want to display the properties of all the books, we could do <%= link_to 'New book', new_book_path %> </ruby> -NOTE: The actual rendering is done by subclasses of +ActionView::TemplateHandlers+. This guide does not dig into that process, but it's important to know that the file extension on your view controls the choice of template handler. In Rails 2, the standard extensions are +.erb+ for ERB (HTML with embedded Ruby), +.rjs+ for RJS (javascript with embedded ruby) and +.builder+ for Builder (XML generator). +NOTE: The actual rendering is done by subclasses of +ActionView::TemplateHandlers+. This guide does not dig into that process, but it's important to know that the file extension on your view controls the choice of template handler. In Rails 2, the standard extensions are +.erb+ for ERB (HTML with embedded Ruby), +.rjs+ for RJS (JavaScript with embedded ruby) and +.builder+ for Builder (XML generator). h4. Using +render+ @@ -106,10 +106,10 @@ Perhaps the simplest thing you can do with +render+ is to render nothing at all: render :nothing => true </ruby> -If you look at the response for this using Curl you will see the following: +If you look at the response for this using cURL, you will see the following: <shell> - $ curl -i 127.0.0.1:3000/books +$ curl -i 127.0.0.1:3000/books HTTP/1.1 200 OK Connection: close Date: Sun, 24 Jan 2010 09:25:18 GMT @@ -123,7 +123,7 @@ Cache-Control: no-cache $ </shell> -We see there is an empty response (no data after the +Cache-Control+ line), but that Rails has set the response to 200 OK, so the request was successful. You can set the +:status+ options on render to change this response. Rendering nothing can be useful for AJAX requests where all you want to send back to the browser is an acknowledgement that the request was completed. +We see there is an empty response (no data after the +Cache-Control+ line), but the request was successful because Rails has set the response to 200 OK. You can set the +:status+ option on render to change this response. Rendering nothing can be useful for AJAX requests where all you want to send back to the browser is an acknowledgement that the request was completed. TIP: You should probably be using the +head+ method, discussed later in this guide, instead of +render :nothing+. This provides additional flexibility and makes it explicit that you're only generating HTTP headers. @@ -134,27 +134,25 @@ If you want to render the view that corresponds to a different action within the <ruby> def update @book = Book.find(params[:id]) - if @book.update_attributes(params[:book]) - redirect_to(@book) - else - render "edit" - end + if @book.update_attributes(params[:book]) + redirect_to(@book) + else + render "edit" end end </ruby> -If the call to +update_attributes+ fails, calling the +update+ action in this controller will render the +edit.html.erb+ template belonging to the same controller. +If the call to +update_attributes+ fails, calling the +update+ action in this controller will render the +edit.html.erb+ template belonging to the same controller. If you prefer, you can use a symbol instead of a string to specify the action to render: <ruby> def update @book = Book.find(params[:id]) - if @book.update_attributes(params[:book]) - redirect_to(@book) - else - render :edit - end + if @book.update_attributes(params[:book]) + redirect_to(@book) + else + render :edit end end </ruby> @@ -164,11 +162,10 @@ To be explicit, you can use +render+ with the +:action+ option (though this is n <ruby> def update @book = Book.find(params[:id]) - if @book.update_attributes(params[:book]) - redirect_to(@book) - else - render :action => "edit" - end + if @book.update_attributes(params[:book]) + redirect_to(@book) + else + render :action => "edit" end end </ruby> @@ -200,7 +197,7 @@ render "/u/apps/warehouse_app/current/app/views/products/show" Rails determines that this is a file render because of the leading slash character. To be explicit, you can use the +:file+ option (which was required on Rails 2.2 and earlier): <ruby> -render :file => +render :file => "/u/apps/warehouse_app/current/app/views/products/show" </ruby> @@ -208,13 +205,13 @@ The +:file+ option takes an absolute file-system path. Of course, you need to ha NOTE: By default, the file is rendered without using the current layout. If you want Rails to put the file into the current layout, you need to add the +:layout => true+ option. -TIP: If you're running on Microsoft Windows, you should use the +:file+ option to render a file, because Windows filenames do not have the same format as Unix filenames. +TIP: If you're running Rails on Microsoft Windows, you should use the +:file+ option to render a file, because Windows filenames do not have the same format as Unix filenames. h5. Wrapping it up -The above three methods of render (rendering another template within the controller, rendering a template within another controller and rendering an arbitrary file on the file system) are actually all variants of the same action. +The above three ways of rendering (rendering another template within the controller, rendering a template within another controller and rendering an arbitrary file on the file system) are actually variants of the same action. -In fact, in the BooksController method, inside of the edit action where we want to render the edit template if the book does not update successfully, all of the following render calls would all render the +edit.html.erb+ template in the +views/books+ directory: +In fact, in the BooksController class, inside of the update action where we want to render the edit template if the book does not update successfully, all of the following render calls would all render the +edit.html.erb+ template in the +views/books+ directory: <ruby> render :edit @@ -240,22 +237,22 @@ h5. Using +render+ with +:inline+ The +render+ method can do without a view completely, if you're willing to use the +:inline+ option to supply ERB as part of the method call. This is perfectly valid: <ruby> -render :inline => - "<% products.each do |p| %><p><%= p.name %><p><% end %>" +render :inline => + "<% products.each do |p| %><p><%= p.name %></p><% end %>" </ruby> WARNING: There is seldom any good reason to use this option. Mixing ERB into your controllers defeats the MVC orientation of Rails and will make it harder for other developers to follow the logic of your project. Use a separate erb view instead. -By default, inline rendering uses ERb. You can force it to use Builder instead with the +:type+ option: +By default, inline rendering uses ERB. You can force it to use Builder instead with the +:type+ option: <ruby> -render :inline => +render :inline => "xml.p {'Horrid coding practice!'}", :type => :builder </ruby> h5. Using +render+ with +:update+ -You can also render javascript-based page updates inline using the +:update+ option to +render+: +You can also render JavaScript-based page updates inline using the +:update+ option to +render+: <ruby> render :update do |page| @@ -263,7 +260,7 @@ render :update do |page| end </ruby> -WARNING: Placing javascript updates in your controller may seem to streamline small updates, but it defeats the MVC orientation of Rails and will make it harder for other developers to follow the logic of your project. We recommend using a separate rjs template instead, no matter how small the update. +WARNING: Placing JavaScript updates in your controller may seem to streamline small updates, but it defeats the MVC orientation of Rails and will make it harder for other developers to follow the logic of your project. We recommend using a separate RJS template instead, no matter how small the update. h5. Rendering Text @@ -275,11 +272,11 @@ render :text => "OK" TIP: Rendering pure text is most useful when you're responding to AJAX or web service requests that are expecting something other than proper HTML. -NOTE: By default, if you use the +:text+ option the text is rendered without using the current layout. If you want Rails to put the text into the current layout, you need to add the +:layout => true+ option. +NOTE: By default, if you use the +:text+ option, the text is rendered without using the current layout. If you want Rails to put the text into the current layout, you need to add the +:layout => true+ option. h5. Rendering JSON -JSON is a javascript data format used by many AJAX libraries. Rails has built-in support for converting objects to JSON and rendering that JSON back to the browser: +JSON is a JavaScript data format used by many AJAX libraries. Rails has built-in support for converting objects to JSON and rendering that JSON back to the browser: <ruby> render :json => @product @@ -342,14 +339,14 @@ render :layout => false h6. The +:status+ Option -Rails will automatically generate a response with the correct HTML status code (in most cases, this is +200 OK+). You can use the +:status+ option to change this: +Rails will automatically generate a response with the correct HTTP status code (in most cases, this is +200 OK+). You can use the +:status+ option to change this: <ruby> render :status => 500 render :status => :forbidden </ruby> -Rails understands either numeric status codes or symbols for status codes. You can find its list of status codes in +actionpack/lib/action_controller/status_codes.rb+. You can also see there how Rails maps symbols to status codes. +Rails understands both numeric status codes and symbols for status codes. h6. The +:location+ Option @@ -498,7 +495,7 @@ def show end </ruby> -If +@book.special?+ evaluates to +true+, Rails will start the rendering process to dump the +@book+ variable into the +special_show+ view. But this will _not_ stop the rest of the code in the +show+ action from running, and when Rails hits the end of the action, it will start to render the +show+ view - and throw an error. The solution is simple: make sure that you only have one call to +render+ or +redirect+ in a single code path. One thing that can help is +and return+. Here's a patched version of the method: +If +@book.special?+ evaluates to +true+, Rails will start the rendering process to dump the +@book+ variable into the +special_show+ view. But this will _not_ stop the rest of the code in the +show+ action from running, and when Rails hits the end of the action, it will start to render the +regular_show+ view - and throw an error. The solution is simple: make sure that you have only one call to +render+ or +redirect+ in a single code path. One thing that can help is +and return+. Here's a patched version of the method: <ruby> def show @@ -568,7 +565,7 @@ def show end </ruby> -With the code in this form, there will be likely be a problem if the +@book+ variable is +nil+. Remember, a +render :action+ doesn't run any code in the target action, so nothing will set up the +@books+ variable that the +index+ view is presumably depending on. One way to fix this is to redirect instead of rendering: +With the code in this form, there will likely be a problem if the +@book+ variable is +nil+. Remember, a +render :action+ doesn't run any code in the target action, so nothing will set up the +@books+ variable that the +index+ view is presumably depending on. One way to fix this is to redirect instead of rendering: <ruby> def index @@ -585,7 +582,7 @@ end With this code, the browser will make a fresh request for the index page, the code in the +index+ method will run, and all will be well. -The only downside to this code, is that it requires a round trip to the browser, the browser requested the show action with +/books/1+ and the controller finds that there are no books, so the controller sends out a 301 redirect response to the browser telling it to go to +/books/+, the browser complies and sends a new request back to the controller asking now for the +index+ action, the controller then gets all the books in the database and renders the index template, sending it back down to the browser which then shows it on your screen. +The only downside to this code, is that it requires a round trip to the browser, the browser requested the show action with +/books/1+ and the controller finds that there are no books, so the controller sends out a 302 redirect response to the browser telling it to go to +/books/+, the browser complies and sends a new request back to the controller asking now for the +index+ action, the controller then gets all the books in the database and renders the index template, sending it back down to the browser which then shows it on your screen. While in a small app, this added latency might not be a problem, it is something to think about when speed of response is of the essence. One way to handle this double request (though a contrived example) could be: @@ -603,11 +600,11 @@ def show end </ruby> -Which would detect that there are no books populate the +@books+ instance variable with all the books in the database and then directly render the +index.html.erb+ template returning it to the browser with a flash alert message telling the user what happened. +Which would detect that there are no books, populate the +@books+ instance variable with all the books in the database and then directly render the +index.html.erb+ template returning it to the browser with a flash alert message telling the user what happened. h4. Using +head+ To Build Header-Only Responses -The +head+ method exists to let you send back responses to the browser that have only headers. It provides a more obvious alternative to calling +render :nothing+. The +head+ method takes one response, which is interpreted as a hash of header names and values. For example, you can return only an error header: +The +head+ method can be used to send responses with only headers to the browser. It provides a more obvious alternative to calling +render :nothing+. The +head+ method takes one parameter, which is interpreted as a hash of header names and values. For example, you can return only an error header: <ruby> head :bad_request @@ -654,11 +651,9 @@ When Rails renders a view as a response, it does so by combining the view with t * +yield+ and +content_for+ * Partials -I'll discuss each of these in turn. - h4. Asset Tags -Asset tags provide methods for generating HTML that links views to assets like images, videos, audio, javascript, stylesheets, and feeds. There are six types of include tag: +Asset tags provide methods for generating HTML that links views to feeds, JavaScript, stylesheets, images, videos and audios. These are the six asset tags available in Rails: * +auto_discovery_link_tag+ * +javascript_include_tag+ @@ -676,17 +671,17 @@ h5. Linking to Feeds with +auto_discovery_link_tag+ The +auto_discovery_link_tag+ helper builds HTML that most browsers and newsreaders can use to detect the presences of RSS or ATOM feeds. It takes the type of the link (+:rss+ or +:atom+), a hash of options that are passed through to url_for, and a hash of options for the tag: <erb> -<%= auto_discovery_link_tag(:rss, {:action => "feed"}, +<%= auto_discovery_link_tag(:rss, {:action => "feed"}, {:title => "RSS Feed"}) %> </erb> There are three tag options available for +auto_discovery_link_tag+: * +:rel+ specifies the +rel+ value in the link (defaults to "alternate") -* +:type+ specifies an explicit MIME type. Rails will generate an appropriate MIME type automatically +* +:type+ specifies an explicit MIME type. Rails will generate an appropriate MIME type automatically. * +:title+ specifies the title of the link -h5. Linking to Javascript Files with +javascript_include_tag+ +h5. Linking to JavaScript Files with +javascript_include_tag+ The +javascript_include_tag+ helper returns an HTML +script+ tag for each source provided. Rails looks in +public/javascripts+ for these files by default, but you can specify a full path relative to the document root, or a URL, if you prefer. For example, to include +public/javascripts/main.js+: @@ -718,7 +713,7 @@ The +defaults+ option loads the Prototype and Scriptaculous libraries: <%= javascript_include_tag :defaults %> </erb> -The +all+ option loads every javascript file in +public/javascripts+, starting with the Prototype and Scriptaculous libraries: +The +all+ option loads every JavaScript file in +public/javascripts+, starting with the Prototype and Scriptaculous libraries: <erb> <%= javascript_include_tag :all %> @@ -730,7 +725,7 @@ You can supply the +:recursive+ option to load files in subfolders of +public/ja <%= javascript_include_tag :all, :recursive => true %> </erb> -If you're loading multiple javascript files, you can create a better user experience by combining multiple files into a single download. To make this happen in production, specify +:cache => true+ in your +javascript_include_tag+: +If you're loading multiple JavaScript files, you can create a better user experience by combining multiple files into a single download. To make this happen in production, specify +:cache => true+ in your +javascript_include_tag+: <erb> <%= javascript_include_tag "main", "columns", :cache => true %> @@ -739,7 +734,7 @@ If you're loading multiple javascript files, you can create a better user experi By default, the combined file will be delivered as +javascripts/all.js+. You can specify a location for the cached asset file instead: <erb> -<%= javascript_include_tag "main", "columns", +<%= javascript_include_tag "main", "columns", :cache => 'cache/main/display' %> </erb> @@ -798,7 +793,7 @@ If you're loading multiple CSS files, you can create a better user experience by By default, the combined file will be delivered as +stylesheets/all.css+. You can specify a location for the cached asset file instead: <erb> -<%= stylesheet_link_tag "main", "columns", +<%= stylesheet_link_tag "main", "columns", :cache => 'cache/main/display' %> </erb> @@ -806,7 +801,9 @@ You can even use dynamic paths such as +cache/#{current_site}/main/display+. h5. Linking to Images with +image_tag+ -The +image_tag+ helper builds an HTML +<img />+ tag to the specified file. By default, files are loaded from +public/images+, note, you must specify the extension, previous versions of Rails would allow you to just call the image name and would append +.png+ if no extension was given, Rails 3.0 does not. +The +image_tag+ helper builds an HTML +<img />+ tag to the specified file. By default, files are loaded from +public/images+. + +WARNING: Note that you must specify the extension of the image. Previous versions of Rails would allow you to just use the image name and would append +.png+ if no extension was given but Rails 3.0 does not. <erb> <%= image_tag "header.png" %> @@ -830,7 +827,7 @@ You can also supply an alternate image to show on mouseover: <%= image_tag "home.gif", :onmouseover => "menu/home_highlight.gif" %> </erb> -Or alternate text if the user has rendering images turned off in their browser, if you do not specify an explicit alt tag, it defaults to the file name of the file, capitalized and with no extension, for example, these two image tags would return the same code: +You can supply alternate text for the image which will be used if the user has images turned off in their browser. If you do not specify an alt text explicitly, it defaults to the file name of the file, capitalized and with no extension. For example, these two image tags would return the same code: <erb> <%= image_tag "home.gif" %> @@ -843,7 +840,7 @@ You can also specify a special size tag, in the format "{width}x{height}": <%= image_tag "home.gif", :size => "50x20" %> </erb> -In addition to the above special tags, you can supply a final hash of standard HTML options, such as +:class+ or +:id+ or +:name+: +In addition to the above special tags, you can supply a final hash of standard HTML options, such as +:class+, +:id+ or +:name+: <erb> <%= image_tag "home.gif", :alt => "Go Home", @@ -940,7 +937,7 @@ The main body of the view will always render into the unnamed +yield+. To render h4. Using +content_for+ -The +content_for+ method allows you to insert content into a +yield+ block in your layout. You only use +content_for+ to insert content in named yields. For example, this view would work with the layout that you just saw: +The +content_for+ method allows you to insert content into a named +yield+ block in your layout. For example, this view would work with the layout that you just saw: <erb> <% content_for :head do %> @@ -963,15 +960,15 @@ The result of rendering this page into the supplied layout would be this HTML: </html> </erb> -The +content_for+ method is very helpful when your layout contains distinct regions such as sidebars and footers that should get their own blocks of content inserted. It's also useful for inserting tags that load page-specific javascript or css files into the header of an otherwise generic layout. +The +content_for+ method is very helpful when your layout contains distinct regions such as sidebars and footers that should get their own blocks of content inserted. It's also useful for inserting tags that load page-specific JavaScript or css files into the header of an otherwise generic layout. h4. Using Partials -Partial templates - usually just called "partials" - are another device for breaking apart the rendering process into more manageable chunks. With a partial, you can move the code for rendering a particular piece of a response to its own file. +Partial templates - usually just called "partials" - are another device for breaking the rendering process into more manageable chunks. With a partial, you can move the code for rendering a particular piece of a response to its own file. h5. Naming Partials -To render a partial as part of a view, you use the +render+ method within the view, and include the +:partial+ option: +To render a partial as part of a view, you use the +render+ method within the view: <ruby> <%= render "menu" %> @@ -1009,11 +1006,13 @@ h5. Partial Layouts A partial can use its own layout file, just as a view can use a layout. For example, you might call a partial like this: <erb> -<%= render "link_area", :layout => "graybar" %> +<%= render :partial => "link_area", :layout => "graybar" %> </erb> This would look for a partial named +_link_area.html.erb+ and render it using the layout +_graybar.html.erb+. Note that layouts for partials follow the same leading-underscore naming as regular partials, and are placed in the same folder with the partial that they belong to (not in the master +layouts+ folder). +Also note that explicitly specifying +:partial+ is required when passing additional options such as +:layout+. + h5. Passing Local Variables You can also pass local variables into partials, making them even more powerful and flexible. For example, you can use this technique to reduce duplication between new and edit pages, while still keeping a bit of distinct content: @@ -1085,17 +1084,15 @@ Partials are very useful in rendering collections. When you pass a collection to <p>Product Name: <%= product.name %></p> </erb> -When a partial is called with a pluralized collection, then the individual instances of the partial have access to the member of the collection being rendered via a variable named after the partial. In this case, the partial is +_product+, and within the +_product+ partial, you can refer to +product+ to get the instance that is being rendered. +When a partial is called with a pluralized collection, then the individual instances of the partial have access to the member of the collection being rendered via a variable named after the partial. In this case, the partial is +_product+, and within the +_product+ partial, you can refer to +product+ to get the instance that is being rendered. -In Rails 3.0 there is also a shorthand for this, assuming +@posts+ is a collection of +post+ instances, you can simply do in the +index.html.erb+: +In Rails 3.0, there is also a shorthand for this. Assuming +@products+ is a collection of +product+ instances, you can simply write this in the +index.html.erb+ to produce the same result: <erb> <h1>Products</h1> <%= render @products %> </erb> -To produce the same result. - Rails determines the name of the partial to use by looking at the model name in the collection. In fact, you can even create a heterogeneous collection and render it this way, and Rails will choose the proper partial for each member of the collection: * +index.html.erb+ @@ -1132,7 +1129,7 @@ With this change, you can access an instance of the +@products+ collection as th You can also pass in arbitrary local variables to any partial you are rendering with the +:locals => {}+ option: <erb> -<%= render :partial => 'products', :collection => @products, +<%= render :partial => 'products', :collection => @products, :as => :item, :locals => {:title => "Products Page"} %> </erb> @@ -1186,17 +1183,15 @@ On pages generated by +NewsController+, you want to hide the top menu and add a <div id="right_menu">Right menu items here</div> <%= yield(:news_content) or yield %> <% end %> -<%= render :file => 'layouts/application' %> +<%= render :template => 'layouts/application' %> </erb> That's it. The News views will use the new layout, hiding the top menu and adding a new right menu inside the "content" div. -There are several ways of getting similar results with different sub-templating schemes using this technique. Note that there is no limit in nesting levels. One can use the +ActionView::render+ method via +render :file => 'layouts/news'+ to base a new layout on the News layout. If you are sure you will not subtemplate the +News+ layout, you can replace the +yield(:news_content) or yield+ with simply +yield+. +There are several ways of getting similar results with different sub-templating schemes using this technique. Note that there is no limit in nesting levels. One can use the +ActionView::render+ method via +render :template => 'layouts/news'+ to base a new layout on the News layout. If you are sure you will not subtemplate the +News+ layout, you can replace the +yield(:news_content) or yield+ with simply +yield+. h3. Changelog -"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/15 - * April 4, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com * January 25, 2010: Rails 3.0 Update by "Mikel Lindsaar":credits.html#raasdnil * December 27, 2008: Merge patch from Rodrigo Rosenfeld Rosas covering subtemplates diff --git a/railties/guides/source/migrations.textile b/railties/guides/source/migrations.textile index 16f616a5bc..57e6bcd123 100644 --- a/railties/guides/source/migrations.textile +++ b/railties/guides/source/migrations.textile @@ -109,7 +109,7 @@ h4. Creating a Model The model and scaffold generators will create migrations appropriate for adding a new model. This migration will already contain instructions for creating the relevant table. If you tell Rails what columns you want then statements for adding those will also be created. For example, running <shell> -rails generate model Product name:string description:text +$ rails generate model Product name:string description:text </shell> will create a migration that looks like this @@ -139,7 +139,7 @@ h4. Creating a Standalone Migration If you are creating migrations for other purposes (for example to add a column to an existing table) then you can use the migration generator: <shell> -rails generate migration AddPartNumberToProducts +$ rails generate migration AddPartNumberToProducts </shell> This will create an empty but appropriately named migration: @@ -157,7 +157,7 @@ end If the migration name is of the form "AddXXXToYYY" or "RemoveXXXFromYYY" and is followed by a list of column names and types then a migration containing the appropriate +add_column+ and +remove_column+ statements will be created. <shell> -rails generate migration AddPartNumberToProducts part_number:string +$ rails generate migration AddPartNumberToProducts part_number:string </shell> will generate @@ -177,7 +177,7 @@ end Similarly, <shell> -rails generate migration RemovePartNumberFromProducts part_number:string +$ rails generate migration RemovePartNumberFromProducts part_number:string </shell> generates @@ -197,7 +197,7 @@ end You are not limited to one magically generated column, for example <shell> -rails generate migration AddDetailsToProducts part_number:string price:decimal +$ rails generate migration AddDetailsToProducts part_number:string price:decimal </shell> generates @@ -250,7 +250,7 @@ create_table :products do |t| end </ruby> -By default +create_table+ will create a primary key called +id+. You can change the name of the primary key with the +:primary_key+ option (don't forget to update the corresponding model) or if you don't want a primary key at all (for example for a HABTM join table) you can pass +:id => false+. If you need to pass database specific options you can place a SQL fragment in the +:options+ option. For example +By default +create_table+ will create a primary key called +id+. You can change the name of the primary key with the +:primary_key+ option (don't forget to update the corresponding model) or if you don't want a primary key at all (for example for a HABTM join table) you can pass +:id => false+. If you need to pass database specific options you can place an SQL fragment in the +:options+ option. For example <ruby> create_table :products, :options => "ENGINE=BLACKHOLE" do |t| @@ -383,7 +383,7 @@ If you specify a target version, Active Record will run the required migrations version is the numerical prefix on the migration's filename. For example to migrate to version 20080906120000 run <shell> -rake db:migrate VERSION=20080906120000 +$ rake db:migrate VERSION=20080906120000 </shell> If this is greater than the current version (i.e. it is migrating upwards) this will run the +up+ method on all migrations up to and including 20080906120000, if migrating downwards this will run the +down+ method on all the migrations down to, but not including, 20080906120000. @@ -393,13 +393,13 @@ h4. Rolling Back A common task is to rollback the last migration, for example if you made a mistake in it and wish to correct it. Rather than tracking down the version number associated with the previous migration you can run <shell> -rake db:rollback +$ rake db:rollback </shell> This will run the +down+ method from the latest migration. If you need to undo several migrations you can provide a +STEP+ parameter: <shell> -rake db:rollback STEP=3 +$ rake db:rollback STEP=3 </shell> will run the +down+ method from the last 3 migrations. @@ -407,7 +407,7 @@ will run the +down+ method from the last 3 migrations. The +db:migrate:redo+ task is a shortcut for doing a rollback and then migrating back up again. As with the +db:rollback+ task you can use the +STEP+ parameter if you need to go more than one version back, for example <shell> -rake db:migrate:redo STEP=3 +$ rake db:migrate:redo STEP=3 </shell> Neither of these Rake tasks do anything you could not do with +db:migrate+, they are simply more convenient since you do not need to explicitly specify the version to migrate to. @@ -421,7 +421,7 @@ h4. Being Specific If you need to run a specific migration up or down the +db:migrate:up+ and +db:migrate:down+ tasks will do that. Just specify the appropriate version and the corresponding migration will have its +up+ or +down+ method invoked, for example <shell> -rake db:migrate:up VERSION=20080906120000 +$ rake db:migrate:up VERSION=20080906120000 </shell> will run the +up+ method from the 20080906120000 migration. These tasks check whether the migration has already run, so for example +db:migrate:up VERSION=20080906120000+ will do nothing if Active Record believes that 20080906120000 has already been run. @@ -546,7 +546,7 @@ Schema files are also useful if you want a quick look at what attributes an Acti h4. Types of Schema Dumps -There are two ways to dump the schema. This is set in +config/environment.rb+ by the +config.active_record.schema_format+ setting, which may be either +:sql+ or +:ruby+. +There are two ways to dump the schema. This is set in +config/application.rb+ by the +config.active_record.schema_format+ setting, which may be either +:sql+ or +:ruby+. If +:ruby+ is selected then the schema is stored in +db/schema.rb+. If you look at this file you'll find that it looks an awful lot like one very big migration: @@ -584,13 +584,11 @@ h3. Active Record and Referential Integrity The Active Record way claims that intelligence belongs in your models, not in the database. As such, features such as triggers or foreign key constraints, which push some of that intelligence back into the database, are not heavily used. -Validations such as +validates_uniqueness_of+ are one way in which models can enforce data integrity. The +:dependent+ option on associations allows models to automatically destroy child objects when the parent is destroyed. Like anything which operates at the application level these cannot guarantee referential integrity and so some people augment them with foreign key constraints. +Validations such as +validates :foreign_key, :uniqueness => true+ are one way in which models can enforce data integrity. The +:dependent+ option on associations allows models to automatically destroy child objects when the parent is destroyed. Like anything which operates at the application level these cannot guarantee referential integrity and so some people augment them with foreign key constraints. -Although Active Record does not provide any tools for working directly with such features, the +execute+ method can be used to execute arbitrary SQL. There are also a number of plugins such as "foreign_key_migrations":http://github.com/harukizaemon/redhillonrails/tree/master/foreign_key_migrations/ which add foreign key support to Active Record (including support for dumping foreign keys in +db/schema.rb+). +Although Active Record does not provide any tools for working directly with such features, the +execute+ method can be used to execute arbitrary SQL. There are also a number of plugins such as "foreign_key_migrations":https://github.com/harukizaemon/redhillonrails/tree/master/foreign_key_migrations/ which add foreign key support to Active Record (including support for dumping foreign keys in +db/schema.rb+). h3. Changelog -"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/6 - * July 15, 2010: minor typos corrected by "Jaime Iniesta":http://jaimeiniesta.com * September 14, 2008: initial version by "Frederick Cheung":credits.html#fcheung diff --git a/railties/guides/source/nested_model_forms.textile b/railties/guides/source/nested_model_forms.textile index 39b0c32f24..55694c0eb4 100644 --- a/railties/guides/source/nested_model_forms.textile +++ b/railties/guides/source/nested_model_forms.textile @@ -1,6 +1,6 @@ h2. Rails nested model forms -Creating a form for a model _and_ its associations can become quite tedious. Therefor Rails provides helpers to assist in dealing with the complexities of generating these forms _and_ the required CRUD operations to create, update, and destroy associations. +Creating a form for a model _and_ its associations can become quite tedious. Therefore Rails provides helpers to assist in dealing with the complexities of generating these forms _and_ the required CRUD operations to create, update, and destroy associations. In this guide you will: @@ -63,7 +63,7 @@ class Person def address Address.new end - + def address_attributes=(attributes) # ... end @@ -77,7 +77,7 @@ class Person def projects [Project.new, Project.new] end - + def projects_attributes=(attributes) # ... end @@ -101,7 +101,7 @@ class PeopleController < ActionController:Base @person.built_address 2.times { @person.projects.build } end - + def create @person = Person.new(params[:person]) if @person.save @@ -142,7 +142,7 @@ Now add a nested form for the +address+ association: <erb> <%= form_for @person do |f| %> <%= f.text_field :name %> - + <%= f.fields_for :address do |af| %> <%= f.text_field :street %> <% end %> @@ -154,7 +154,7 @@ This generates: <html> <form action="/people" class="new_person" id="new_person" method="post"> <input id="person_name" name="person[name]" size="30" type="text" /> - + <input id="person_address_attributes_street" name="person[address_attributes][street]" size="30" type="text" /> </form> </html> @@ -183,7 +183,7 @@ The form code for an association collection is pretty similar to that of a singl <erb> <%= form_for @person do |f| %> <%= f.text_field :name %> - + <%= f.fields_for :projects do |pf| %> <%= f.text_field :name %> <% end %> @@ -195,7 +195,7 @@ Which generates: <html> <form action="/people" class="new_person" id="new_person" method="post"> <input id="person_name" name="person[name]" size="30" type="text" /> - + <input id="person_projects_attributes_0_name" name="person[projects_attributes][0][name]" size="30" type="text" /> <input id="person_projects_attributes_1_name" name="person[projects_attributes][1][name]" size="30" type="text" /> </form> @@ -219,4 +219,4 @@ You can basically see the +projects_attributes+ hash as an array of attribute ha NOTE: The reason that +fields_for+ constructed a form which would result in a hash instead of an array is that it won't work for any forms nested deeper than one level deep. -TIP: You _can_ however pass an array to the writer method generated by +accepts_nested_attributes_for+ if you're using plain Ruby or some other API access. See (TODO) for more info and example.
\ No newline at end of file +TIP: You _can_ however pass an array to the writer method generated by +accepts_nested_attributes_for+ if you're using plain Ruby or some other API access. See (TODO) for more info and example. diff --git a/railties/guides/source/performance_testing.textile b/railties/guides/source/performance_testing.textile index 65f8d07e7a..5679bae531 100644 --- a/railties/guides/source/performance_testing.textile +++ b/railties/guides/source/performance_testing.textile @@ -20,7 +20,7 @@ In a freshly generated Rails application, +test/performance/browsing_test.rb+ co <ruby> require 'test_helper' -require 'performance_test_help' +require 'rails/performance_test_help' # Profiling results for each test method are written to tmp/performance. class BrowsingTest < ActionController::PerformanceTest @@ -34,17 +34,17 @@ This example is a simple performance test case for profiling a GET request to th h4. Generating Performance Tests -Rails provides a generator called +performance_test+ for creating new performance tests: +Rails provides a generator called +test_unit:performance+ for creating new performance tests: <shell> -rails generate performance_test homepage +$ rails generate test_unit:performance homepage </shell> This generates +homepage_test.rb+ in the +test/performance+ directory: <ruby> require 'test_helper' -require 'performance_test_help' +require 'rails/performance_test_help' class HomepageTest < ActionController::PerformanceTest # Replace this with your real tests. @@ -60,8 +60,8 @@ Let's assume your application has the following controller and model: <ruby> # routes.rb -map.root :controller => 'home' -map.resources :posts +root :to => 'home#index' +resources :posts # home_controller.rb class HomeController < ApplicationController @@ -103,7 +103,7 @@ Here's the performance test for +HomeController#dashboard+ and +PostsController# <ruby> require 'test_helper' -require 'performance_test_help' +require 'rails/performance_test_help' class PostPerformanceTest < ActionController::PerformanceTest def setup @@ -131,7 +131,7 @@ Performance test for +Post+ model: <ruby> require 'test_helper' -require 'performance_test_help' +require 'rails/performance_test_help' class PostModelTest < ActionController::PerformanceTest def test_creation @@ -316,16 +316,16 @@ Compile Ruby and apply this "GC Patch":http://rubyforge.org/tracker/download.php h5. Download and Extract <shell> -[lifo@null ~]$ mkdir rubygc -[lifo@null ~]$ wget <download the latest stable ruby from ftp://ftp.ruby-lang.org/pub/ruby> -[lifo@null ~]$ tar -xzvf <ruby-version.tar.gz> -[lifo@null ~]$ cd <ruby-version> +$ mkdir rubygc +$ wget <download the latest stable ruby from ftp://ftp.ruby-lang.org/pub/ruby> +$ tar -xzvf <ruby-version.tar.gz> +$ cd <ruby-version> </shell> h5. Apply the Patch <shell> -[lifo@null ruby-version]$ curl http://rubyforge.org/tracker/download.php/1814/7062/17676/3291/ruby186gc.patch | patch -p0 +$ curl http://rubyforge.org/tracker/download.php/1814/7062/17676/3291/ruby186gc.patch | patch -p0 </shell> h5. Configure and Install @@ -333,8 +333,8 @@ h5. Configure and Install The following will install ruby in your home directory's +/rubygc+ directory. Make sure to replace +<homedir>+ with a full patch to your actual home directory. <shell> -[lifo@null ruby-version]$ ./configure --prefix=/<homedir>/rubygc -[lifo@null ruby-version]$ make && make install +$ ./configure --prefix=/<homedir>/rubygc +$ make && make install </shell> h5. Prepare Aliases @@ -364,8 +364,8 @@ Additionally, install the following gems: If installing +mysql+ fails, you can try to install it manually: <shell> -[lifo@null mysql]$ gcruby extconf.rb --with-mysql-config -[lifo@null mysql]$ make && make install +$ gcruby extconf.rb --with-mysql-config +$ make && make install </shell> And you're ready to go. Don't forget to use +gcruby+ and +gcrake+ aliases when running the performance tests. @@ -398,7 +398,7 @@ $ rails benchmarker 'Item.first' 'Item.last' h4. +profiler+ -+profiler+ is a wrapper around http://ruby-prof.rubyforge.org/[ruby-prof] gem. ++profiler+ is a wrapper around the "ruby-prof":http://ruby-prof.rubyforge.org gem. Usage: @@ -436,7 +436,7 @@ h4. Model Project.benchmark("Creating project") do project = Project.create("name" => "stuff") project.create_manager("name" => "David") - project.milestones << Milestone.find(:all) + project.milestones << Milestone.all end </ruby> @@ -469,7 +469,7 @@ And in "views":http://api.rubyonrails.org/classes/ActionController/Benchmarking/ <erb> <% benchmark("Showing projects partial") do %> - <%= render :partial => @projects %> + <%= render @projects %> <% end %> </erb> @@ -500,8 +500,8 @@ h4. Rails Plugins and Gems * "Rails Analyzer":http://rails-analyzer.rubyforge.org * "Palmist":http://www.flyingmachinestudios.com/projects/ -* "Rails Footnotes":http://github.com/josevalim/rails-footnotes/tree/master -* "Query Reviewer":http://github.com/dsboulder/query_reviewer/tree/master +* "Rails Footnotes":https://github.com/josevalim/rails-footnotes/tree/master +* "Query Reviewer":https://github.com/dsboulder/query_reviewer/tree/master h4. Generic Tools @@ -524,7 +524,5 @@ Rails has been lucky to have two startups dedicated to Rails specific performanc h3. Changelog -"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/4 - * January 9, 2009: Complete rewrite by "Pratik":credits.html#lifo * September 6, 2008: Initial version by Matthew Bergman diff --git a/railties/guides/source/plugins.textile b/railties/guides/source/plugins.textile index 82f2276153..2d9821e627 100644 --- a/railties/guides/source/plugins.textile +++ b/railties/guides/source/plugins.textile @@ -10,281 +10,71 @@ After reading this guide you should be familiar with: * Creating a plugin from scratch * Writing and running tests for the plugin -* Storing models, views, controllers, helpers and even other plugins in your plugins -* Writing generators -* Writing custom Rake tasks in your plugin -* Generating RDoc documentation for your plugin -* Avoiding common pitfalls with 'init.rb' This guide describes how to build a test-driven plugin that will: * Extend core ruby classes like Hash and String * Add methods to ActiveRecord::Base in the tradition of the 'acts_as' plugins -* Add a view helper that can be used in erb templates -* Add a new generator that will generate a migration -* Add a custom generator command -* A custom route method that can be used in routes.rb +* Give you information about where to put generators in your plugin. -For the purpose of this guide pretend for a moment that you are an avid bird watcher. Your favorite bird is the Yaffle, and you want to create a plugin that allows other developers to share in the Yaffle goodness. First, you need to get setup for development. +For the purpose of this guide pretend for a moment that you are an avid bird watcher. +Your favorite bird is the Yaffle, and you want to create a plugin that allows other developers to share in the Yaffle +goodness. endprologue. h3. Setup -h4. Create the Basic Application +h4. Generating the Plugin Skeleton -The examples in this guide require that you have a working rails application. To create a simple rails app execute: +Rails currently ships with a generator to generate a plugin within a Rails application. Help text is available that will explain +how this generator works. <shell> -gem install rails -rails yaffle_guide -cd yaffle_guide -rails generate scaffold bird name:string -rake db:migrate -rails server +$ rails generate plugin --help </shell> -Then navigate to http://localhost:3000/birds. Make sure you have a functioning rails app before continuing. +This generator places the plugin into the vendor/plugins directory. -NOTE: The aforementioned instructions will work for sqlite3. For more detailed instructions on how to create a rails app for other databases see the API docs. +Vendored plugins are useful for quickly prototyping your plugin but current thinking in the Rails community is shifting towards +packaging plugins as gems, especially with the inclusion of Bundler as the Rails dependency manager. +Packaging a plugin as a gem may be overkill for any plugins that will not be shared across projects but doing so from the start makes it easier to share the plugin going forward without adding too much additional overhead during development. - -h4. Generate the Plugin Skeleton - -Rails ships with a plugin generator which creates a basic plugin skeleton. Pass the plugin name, either 'CamelCased' or 'under_scored', as an argument. Pass +--with-generator+ to add an example generator also. - -This creates a plugin in +vendor/plugins+ including an +init.rb+ and +README+ as well as standard +lib+, +task+, and +test+ directories. - -Examples: -<shell> -rails generate plugin yaffle -rails generate plugin yaffle --with-generator -</shell> - -To get more detailed help on the plugin generator, type +rails generate plugin+. - -Later on this guide will describe how to work with generators, so go ahead and generate your plugin with the +--with-generator+ option now: - -<shell> -rails generate plugin yaffle --with-generator -</shell> - -You should see the following output: - -<shell> -create vendor/plugins/yaffle/lib -create vendor/plugins/yaffle/tasks -create vendor/plugins/yaffle/test -create vendor/plugins/yaffle/README -create vendor/plugins/yaffle/MIT-LICENSE -create vendor/plugins/yaffle/Rakefile -create vendor/plugins/yaffle/init.rb -create vendor/plugins/yaffle/install.rb -create vendor/plugins/yaffle/uninstall.rb -create vendor/plugins/yaffle/lib/yaffle.rb -create vendor/plugins/yaffle/tasks/yaffle_tasks.rake -create vendor/plugins/yaffle/test/core_ext_test.rb -create vendor/plugins/yaffle/generators -create vendor/plugins/yaffle/generators/yaffle -create vendor/plugins/yaffle/generators/yaffle/templates -create vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb -create vendor/plugins/yaffle/generators/yaffle/USAGE -</shell> - -h4. Organize Your Files - -To make it easy to organize your files and to make the plugin more compatible with GemPlugins, start out by altering your file system to look like this: +Rails 3.1 will ship with a plugin generator that will default to setting up a plugin +as a gem. This tutorial will begin to bridge that gap by demonstrating how to create a gem based plugin using the +"Enginex gem":http://www.github.com/josevalim/enginex. <shell> -|-- lib -| |-- yaffle -| `-- yaffle.rb -`-- rails - | - `-- init.rb +$ gem install enginex +$ enginex --help +$ enginex yaffle </shell> -<ruby> -# vendor/plugins/yaffle/init.rb - -require 'yaffle' -</ruby> - -Now you can add any +require+ statements to +lib/yaffle.rb+ and keep +init.rb+ clean. - -h3. Tests - -In this guide you will learn how to test your plugin against multiple different database adapters using Active Record. To setup your plugin to allow for easy testing you'll need to add 3 files: - - * A +database.yml+ file with all of your connection strings - * A +schema.rb+ file with your table definitions - * A test helper method that sets up the database - -h4. Test Setup +This command will create a new directory named "yaffle" within the current directory. -<yaml> -# vendor/plugins/yaffle/test/database.yml +h3. Testing your newly generated plugin -sqlite: - :adapter: sqlite - :dbfile: vendor/plugins/yaffle/test/yaffle_plugin.sqlite.db - -sqlite3: - :adapter: sqlite3 - :dbfile: vendor/plugins/yaffle/test/yaffle_plugin.sqlite3.db - -postgresql: - :adapter: postgresql - :username: postgres - :password: postgres - :database: yaffle_plugin_test - :min_messages: ERROR - -mysql: - :adapter: mysql - :host: localhost - :username: root - :password: password - :database: yaffle_plugin_test -</yaml> - -For this guide you'll need 2 tables/models, Hickwalls and Wickwalls, so add the following: - -<ruby> -# vendor/plugins/yaffle/test/schema.rb - -ActiveRecord::Schema.define(:version => 0) do - create_table :hickwalls, :force => true do |t| - t.string :name - t.string :last_squawk - t.datetime :last_squawked_at - end - create_table :wickwalls, :force => true do |t| - t.string :name - t.string :last_tweet - t.datetime :last_tweeted_at - end - create_table :woodpeckers, :force => true do |t| - t.string :name - end -end -</ruby> - -<ruby> -# vendor/plugins/yaffle/test/test_helper.rb - -ENV['RAILS_ENV'] = 'test' -ENV['RAILS_ROOT'] ||= File.dirname(__FILE__) + '/../../../..' - -require 'test/unit' -require File.expand_path(File.join(ENV['RAILS_ROOT'], 'config/environment.rb')) - -def load_schema - config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml')) - ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log") - - db_adapter = ENV['DB'] - - # no db passed, try one of these fine config-free DBs before bombing. - db_adapter ||= - begin - require 'rubygems' - require 'sqlite' - 'sqlite' - rescue MissingSourceFile - begin - require 'sqlite3' - 'sqlite3' - rescue MissingSourceFile - end - end - - if db_adapter.nil? - raise "No DB Adapter selected. Pass the DB= option to pick one, or install Sqlite or Sqlite3." - end - - ActiveRecord::Base.establish_connection(config[db_adapter]) - load(File.dirname(__FILE__) + "/schema.rb") - require File.dirname(__FILE__) + '/../rails/init' -end -</ruby> - -Now whenever you write a test that requires the database, you can call 'load_schema'. - -h4. Run the Plugin Tests - -Once you have these files in place, you can write your first test to ensure that your plugin-testing setup is correct. By default rails generates a file in +vendor/plugins/yaffle/test/yaffle_test.rb+ with a sample test. Replace the contents of that file with: - -<ruby> -# vendor/plugins/yaffle/test/yaffle_test.rb - -require File.dirname(__FILE__) + '/test_helper' - -class YaffleTest < Test::Unit::TestCase - load_schema - - class Hickwall < ActiveRecord::Base - end - - class Wickwall < ActiveRecord::Base - end - - def test_schema_has_loaded_correctly - assert_equal [], Hickwall.all - assert_equal [], Wickwall.all - end - -end -</ruby> - -To run this, go to the plugin directory and run +rake+: - -<shell> -cd vendor/plugins/yaffle -rake -</shell> +You can navigate to the directory that contains the plugin, run the +bundle install+ command + and run the one generated test using the +rake+ command. -You should see output like: +You should see: <shell> -/opt/local/bin/ruby -Ilib:lib "/opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader.rb" "test/yaffle_test.rb" - create_table(:hickwalls, {:force=>true}) - -> 0.0220s --- create_table(:wickwalls, {:force=>true}) - -> 0.0077s --- initialize_schema_migrations_table() - -> 0.0007s --- assume_migrated_upto_version(0) - -> 0.0007s -Loaded suite /opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader -Started -. -Finished in 0.002236 seconds. - -1 test, 1 assertion, 0 failures, 0 errors + 2 tests, 2 assertions, 0 failures, 0 errors, 0 skips </shell> -By default the setup above runs your tests with sqlite or sqlite3. To run tests with one of the other connection strings specified in +database.yml+, pass the DB environment variable to rake: - -<shell> -rake DB=sqlite -rake DB=sqlite3 -rake DB=mysql -rake DB=postgresql -</shell> - -Now you are ready to test-drive your plugin! +This will tell you that everything got generated properly and you are ready to start adding functionality. h3. Extending Core Classes -This section will explain how to add a method to String that will be available anywhere in your rails app. +This section will explain how to add a method to String that will be available anywhere in your rails application. In this example you will add a method to String named +to_squawk+. To begin, create a new test file with a few assertions: <ruby> -# vendor/plugins/yaffle/test/core_ext_test.rb +# yaffle/test/core_ext_test.rb -require File.dirname(__FILE__) + '/test_helper' +require 'test_helper' class CoreExtTest < Test::Unit::TestCase def test_to_squawk_prepends_the_word_squawk @@ -293,20 +83,13 @@ class CoreExtTest < Test::Unit::TestCase end </ruby> -Navigate to your plugin directory and run +rake test+: +Run +rake+ to run the test. This test should fail because we haven't implemented the +to_squak+ method: <shell> -cd vendor/plugins/yaffle -rake test -</shell> - -The test above should fail with the message: - -<shell> - 1) Error: -test_to_squawk_prepends_the_word_squawk(CoreExtTest): -NoMethodError: undefined method `to_squawk' for "Hello World":String - ./test/core_ext_test.rb:5:in `test_to_squawk_prepends_the_word_squawk' + 1) Error: + test_to_squawk_prepends_the_word_squawk(CoreExtTest): + NoMethodError: undefined method `to_squawk' for "Hello World":String + test/core_ext_test.rb:5:in `test_to_squawk_prepends_the_word_squawk' </shell> Great - now you are ready to start development. @@ -314,16 +97,19 @@ Great - now you are ready to start development. Then in +lib/yaffle.rb+ require +lib/core_ext+: <ruby> -# vendor/plugins/yaffle/lib/yaffle.rb +# yaffle/lib/yaffle.rb require "yaffle/core_ext" + +module Yaffle +end </ruby> Finally, create the +core_ext.rb+ file and add the +to_squawk+ method: <ruby> -# vendor/plugins/yaffle/lib/yaffle/core_ext.rb - +# yaffle/lib/yaffle/core_ext.rb + String.class_eval do def to_squawk "squawk! #{self}".strip @@ -331,7 +117,13 @@ String.class_eval do end </ruby> -To test that your method does what it says it does, run the unit tests with +rake+ from your plugin directory. To see this in action, fire up a console and start squawking: +To test that your method does what it says it does, run the unit tests with +rake+ from your plugin directory. + +<shell> + 3 tests, 3 assertions, 0 failures, 0 errors, 0 skips +</shell> + +To see this in action, change to the test/dummy directory, fire up a console and start squawking: <shell> $ rails console @@ -339,115 +131,56 @@ $ rails console => "squawk! Hello World" </shell> -h4. Working with +init.rb+ - -When Rails loads plugins it looks for a file named +init.rb+. However, when the plugin is initialized, +init.rb+ is invoked via +eval+ (not +require+) so it has slightly different behavior. - -NOTE: The plugins loader also looks for +rails/init.rb+, but that one is deprecated in favor of the top-level +init.rb+ aforementioned. - -Under certain circumstances if you reopen classes or modules in +init.rb+ you may inadvertently create a new class, rather than reopening an existing class. A better alternative is to reopen the class in a different file, and require that file from +init.rb+, as shown above. - -If you must reopen a class in +init.rb+ you can use +module_eval+ or +class_eval+ to avoid any issues: - -<ruby> -# vendor/plugins/yaffle/init.rb - -Hash.class_eval do - def is_a_special_hash? - true - end -end -</ruby> - -Another way is to explicitly define the top-level module space for all modules and classes, like +::Hash+: - -<ruby> -# vendor/plugins/yaffle/init.rb - -class ::Hash - def is_a_special_hash? - true - end -end -</ruby> - h3. Add an "acts_as" Method to Active Record -A common pattern in plugins is to add a method called 'acts_as_something' to models. In this case, you want to write a method called 'acts_as_yaffle' that adds a 'squawk' method to your models. +A common pattern in plugins is to add a method called 'acts_as_something' to models. In this case, you +want to write a method called 'acts_as_yaffle' that adds a 'squawk' method to your Active Record models. To begin, set up your files so that you have: -* *vendor/plugins/yaffle/test/acts_as_yaffle_test.rb* - <ruby> -require File.dirname(__FILE__) + '/test_helper' +# yaffle/test/acts_as_yaffle_test.rb + +require 'test_helper' class ActsAsYaffleTest < Test::Unit::TestCase end </ruby> -* *vendor/plugins/yaffle/lib/yaffle.rb* - <ruby> -require 'yaffle/acts_as_yaffle' -</ruby> +# yaffle/lib/yaffle.rb -* *vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb* +require "yaffle/core_ext" +require 'yaffle/acts_as_yaffle' -<ruby> module Yaffle - # your code will go here end </ruby> -Note that after requiring 'acts_as_yaffle' you also have to include it into ActiveRecord::Base so that your plugin methods will be available to the rails models. - -One of the most common plugin patterns for 'acts_as_yaffle' plugins is to structure your file like so: - -* *vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb* - <ruby> -module Yaffle - def self.included(base) - base.send :extend, ClassMethods - end - - module ClassMethods - # any method placed here will apply to classes, like Hickwall - def acts_as_something - send :include, InstanceMethods - end - end +# yaffle/lib/yaffle/acts_as_yaffle.rb - module InstanceMethods - # any method placed here will apply to instaces, like @hickwall +module Yaffle + module ActsAsYaffle + # your code will go here end end </ruby> -With structure you can easily separate the methods that will be used for the class (like +Hickwall.some_method+) and the instance (like +@hickwell.some_method+). - h4. Add a Class Method -This plugin will expect that you've added a method to your model named 'last_squawk'. However, the plugin users might have already defined a method on their model named 'last_squawk' that they use for something else. This plugin will allow the name to be changed by adding a class method called 'yaffle_text_field'. +This plugin will expect that you've added a method to your model named 'last_squawk'. However, the +plugin users might have already defined a method on their model named 'last_squawk' that they use +for something else. This plugin will allow the name to be changed by adding a class method called 'yaffle_text_field'. To start out, write a failing test that shows the behavior you'd like: -* *vendor/plugins/yaffle/test/acts_as_yaffle_test.rb* - <ruby> -require File.dirname(__FILE__) + '/test_helper' - -class Hickwall < ActiveRecord::Base - acts_as_yaffle -end +# yaffle/test/acts_as_yaffle_test.rb -class Wickwall < ActiveRecord::Base - acts_as_yaffle :yaffle_text_field => :last_tweet -end +require 'test_helper' class ActsAsYaffleTest < Test::Unit::TestCase - load_schema def test_a_hickwalls_yaffle_text_field_should_be_last_squawk assert_equal "last_squawk", Hickwall.yaffle_text_field @@ -456,1060 +189,281 @@ class ActsAsYaffleTest < Test::Unit::TestCase def test_a_wickwalls_yaffle_text_field_should_be_last_tweet assert_equal "last_tweet", Wickwall.yaffle_text_field end + end </ruby> -To make these tests pass, you could modify your +acts_as_yaffle+ file like so: +When you run +rake+, you should see the following: -* *vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb* +<shell> + 1) Error: + test_a_hickwalls_yaffle_text_field_should_be_last_squawk(ActsAsYaffleTest): + NameError: uninitialized constant ActsAsYaffleTest::Hickwall + test/acts_as_yaffle_test.rb:6:in `test_a_hickwalls_yaffle_text_field_should_be_last_squawk' -<ruby> -module Yaffle - def self.included(base) - base.send :extend, ClassMethods - end + 2) Error: + test_a_wickwalls_yaffle_text_field_should_be_last_tweet(ActsAsYaffleTest): + NameError: uninitialized constant ActsAsYaffleTest::Wickwall + test/acts_as_yaffle_test.rb:10:in `test_a_wickwalls_yaffle_text_field_should_be_last_tweet' - module ClassMethods - def acts_as_yaffle(options = {}) - cattr_accessor :yaffle_text_field - self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s - end - end -end + 5 tests, 3 assertions, 0 failures, 2 errors, 0 skips +</shell> -ActiveRecord::Base.send :include, Yaffle -</ruby> +This tells us that we don't have the necessary models (Hickwall and Wickwall) that we are trying to test. +We can easily generate these models in our "dummy" Rails application by running the following commands from the +test/dummy directory: -h4. Add an Instance Method +<shell> +$ cd test/dummy +$ rails generate model Hickwall last_squak:string +$ rails generate model Wickwall last_squak:string last_tweet:string +</shell> -This plugin will add a method named 'squawk' to any Active Record objects that call 'acts_as_yaffle'. The 'squawk' method will simply set the value of one of the fields in the database. +Now you can create the necessary database tables in your testing database by navigating to your dummy app +and migrating the database. First -To start out, write a failing test that shows the behavior you'd like: +<shell> +$ cd test/dummy +$ rake db:migrate +$ rake db:test:prepare +</shell> -* *vendor/plugins/yaffle/test/acts_as_yaffle_test.rb* +While you are here, change the Hickwall and Wickwall models so that they know that they are supposed to act +like yaffles. <ruby> -require File.dirname(__FILE__) + '/test_helper' +# test/dummy/app/models/hickwall.rb class Hickwall < ActiveRecord::Base acts_as_yaffle end +# test/dummy/app/models/wickwall.rb + class Wickwall < ActiveRecord::Base acts_as_yaffle :yaffle_text_field => :last_tweet end -class ActsAsYaffleTest < Test::Unit::TestCase - load_schema - - def test_a_hickwalls_yaffle_text_field_should_be_last_squawk - assert_equal "last_squawk", Hickwall.yaffle_text_field - end - - def test_a_wickwalls_yaffle_text_field_should_be_last_tweet - assert_equal "last_tweet", Wickwall.yaffle_text_field - end - - def test_hickwalls_squawk_should_populate_last_squawk - hickwall = Hickwall.new - hickwall.squawk("Hello World") - assert_equal "squawk! Hello World", hickwall.last_squawk - end - - def test_wickwalls_squawk_should_populate_last_tweeted_at - wickwall = Wickwall.new - wickwall.squawk("Hello World") - assert_equal "squawk! Hello World", wickwall.last_tweet - end -end </ruby> -Run this test to make sure the last two tests fail, then update 'acts_as_yaffle.rb' to look like this: - -* *vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb* +We will also add code to define the acts_as_yaffle method. <ruby> +# yaffle/lib/yaffle/acts_as_yaffle.rb module Yaffle - def self.included(base) - base.send :extend, ClassMethods - end + module ActsAsYaffle + extend ActiveSupport::Concern - module ClassMethods - def acts_as_yaffle(options = {}) - cattr_accessor :yaffle_text_field - self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s - send :include, InstanceMethods + included do end - end - module InstanceMethods - def squawk(string) - write_attribute(self.class.yaffle_text_field, string.to_squawk) + module ClassMethods + def acts_as_yaffle(options = {}) + # your code will go here + end end end end -ActiveRecord::Base.send :include, Yaffle +ActiveRecord::Base.send :include, Yaffle::ActsAsYaffle </ruby> -NOTE: The use of +write_attribute+ to write to the field in model is just one example of how a plugin can interact with the model, and will not always be the right method to use. For example, you could also use +send("#{self.class.yaffle_text_field}=", string.to_squawk)+. - -h3. Models - -This section describes how to add a model named 'Woodpecker' to your plugin that will behave the same as a model in your main app. When storing models, controllers, views and helpers in your plugin, it's customary to keep them in directories that match the rails directories. For this example, create a file structure like this: +You can then return to the root directory (+cd ../..+) of your plugin and rerun the tests using +rake+. <shell> -vendor/plugins/yaffle/ -|-- lib -| |-- app -| | |-- controllers -| | |-- helpers -| | |-- models -| | | `-- woodpecker.rb -| | `-- views -| |-- yaffle -| | |-- acts_as_yaffle.rb -| | |-- commands.rb -| | `-- core_ext.rb -| `-- yaffle.rb -</shell> - -As always, start with a test: - -* *vendor/plugins/yaffle/test/woodpecker_test.rb:* - -<ruby> -require File.dirname(__FILE__) + '/test_helper' - -class WoodpeckerTest < Test::Unit::TestCase - load_schema - - def test_woodpecker - assert_kind_of Woodpecker, Woodpecker.new - end -end -</ruby> - -This is just a simple test to make sure the class is being loaded correctly. After watching it fail with +rake+, you can make it pass like so: - -* *vendor/plugins/yaffle/lib/yaffle.rb:* - -<ruby> -%w{ models }.each do |dir| - path = File.join(File.dirname(__FILE__), 'app', dir) - $LOAD_PATH << path - ActiveSupport::Dependencies.load_paths << path - ActiveSupport::Dependencies.load_once_paths.delete(path) -end -</ruby> - -Adding directories to the load path makes them appear just like files in the main app directory - except that they are only loaded once, so you have to restart the web server to see the changes in the browser. Removing directories from the 'load_once_paths' allow those changes to picked up as soon as you save the file - without having to restart the web server. This is particularly useful as you develop the plugin. - -* *vendor/plugins/yaffle/lib/app/models/woodpecker.rb:* - -<ruby> -class Woodpecker < ActiveRecord::Base -end -</ruby> - -Finally, add the following to your plugin's 'schema.rb': - -* *vendor/plugins/yaffle/test/schema.rb:* - -<ruby> -create_table :woodpeckers, :force => true do |t| - t.string :name -end -</ruby> - -Now your test should be passing, and you should be able to use the Woodpecker model from within your rails app, and any changes made to it are reflected immediately when running in development mode. - -h3. Controllers - -This section describes how to add a controller named 'woodpeckers' to your plugin that will behave the same as a controller in your main app. This is very similar to adding a model. - -You can test your plugin's controller as you would test any other controller: - -* *vendor/plugins/yaffle/test/woodpeckers_controller_test.rb:* - -<ruby> -require File.dirname(__FILE__) + '/test_helper' -require 'woodpeckers_controller' -require 'action_controller/test_process' - -class WoodpeckersController; def rescue_action(e) raise e end; end - -class WoodpeckersControllerTest < Test::Unit::TestCase - def setup - @controller = WoodpeckersController.new - @request = ActionController::TestRequest.new - @response = ActionController::TestResponse.new - - ActionController::Routing::Routes.draw do |map| - map.resources :woodpeckers - end - end - - def test_index - get :index - assert_response :success - end -end -</ruby> - -This is just a simple test to make sure the controller is being loaded correctly. After watching it fail with +rake+, you can make it pass like so: - -* *vendor/plugins/yaffle/lib/yaffle.rb:* - -<ruby> -%w{ models controllers }.each do |dir| - path = File.join(File.dirname(__FILE__), 'app', dir) - $LOAD_PATH << path - ActiveSupport::Dependencies.load_paths << path - ActiveSupport::Dependencies.load_once_paths.delete(path) -end -</ruby> - -* *vendor/plugins/yaffle/lib/app/controllers/woodpeckers_controller.rb:* - -<ruby> -class WoodpeckersController < ActionController::Base - - def index - render :text => "Squawk!" - end - -end -</ruby> + 1) Error: + test_a_hickwalls_yaffle_text_field_should_be_last_squawk(ActsAsYaffleTest): + NoMethodError: undefined method `yaffle_text_field' for #<Class:0x000001016661b8> + /Users/xxx/.rvm/gems/ruby-1.9.2-p136@xxx/gems/activerecord-3.0.3/lib/active_record/base.rb:1008:in `method_missing' + test/acts_as_yaffle_test.rb:5:in `test_a_hickwalls_yaffle_text_field_should_be_last_squawk' -Now your test should be passing, and you should be able to use the Woodpeckers controller in your app. If you add a route for the woodpeckers controller you can start up your server and go to http://localhost:3000/woodpeckers to see your controller in action. + 2) Error: + test_a_wickwalls_yaffle_text_field_should_be_last_tweet(ActsAsYaffleTest): + NoMethodError: undefined method `yaffle_text_field' for #<Class:0x00000101653748> + Users/xxx/.rvm/gems/ruby-1.9.2-p136@xxx/gems/activerecord-3.0.3/lib/active_record/base.rb:1008:in `method_missing' + test/acts_as_yaffle_test.rb:9:in `test_a_wickwalls_yaffle_text_field_should_be_last_tweet' -h3. Helpers + 5 tests, 3 assertions, 0 failures, 2 errors, 0 skips -This section describes how to add a helper named 'WoodpeckersHelper' to your plugin that will behave the same as a helper in your main app. This is very similar to adding a model and a controller. - -You can test your plugin's helper as you would test any other helper: - -* *vendor/plugins/yaffle/test/woodpeckers_helper_test.rb* - -<ruby> -require File.dirname(__FILE__) + '/test_helper' -include WoodpeckersHelper - -class WoodpeckersHelperTest < Test::Unit::TestCase - def test_tweet - assert_equal "Tweet! Hello", tweet("Hello") - end -end -</ruby> - -This is just a simple test to make sure the helper is being loaded correctly. After watching it fail with +rake+, you can make it pass like so: - -* *vendor/plugins/yaffle/lib/yaffle.rb:* - -<ruby> -%w{ models controllers helpers }.each do |dir| - path = File.join(File.dirname(__FILE__), 'app', dir) - $LOAD_PATH << path - ActiveSupport::Dependencies.load_paths << path - ActiveSupport::Dependencies.load_once_paths.delete(path) -end -</ruby> - -* *vendor/plugins/yaffle/lib/app/helpers/woodpeckers_helper.rb:* - -<ruby> -module WoodpeckersHelper - - def tweet(text) - "Tweet! #{text}" - end - -end -</ruby> - -Now your test should be passing, and you should be able to use the Woodpeckers helper in your app. - -h3. Routes - -In a standard 'routes.rb' file you use routes like 'map.connect' or 'map.resources'. You can add your own custom routes from a plugin. This section will describe how to add a custom method called that can be called with 'map.yaffles'. - -Testing routes from plugins is slightly different from testing routes in a standard rails app. To begin, add a test like this: +</shell> -* *vendor/plugins/yaffle/test/routing_test.rb* +Getting closer...now we will implement the code of the acts_as_yaffle method to make the tests pass. <ruby> -require "#{File.dirname(__FILE__)}/test_helper" - -class RoutingTest < Test::Unit::TestCase - - def setup - ActionController::Routing::Routes.draw do |map| - map.yaffles - end - end - - def test_yaffles_route - assert_recognition :get, "/yaffles", :controller => "yaffles_controller", :action => "index" - end +# yaffle/lib/yaffle/acts_as_yaffle.rb - private +module Yaffle + module ActsAsYaffle + extend ActiveSupport::Concern - def assert_recognition(method, path, options) - result = ActionController::Routing::Routes.recognize_path(path, :method => method) - assert_equal options, result + included do end -end -</ruby> - -Once you see the tests fail by running 'rake', you can make them pass with: - -* *vendor/plugins/yaffle/lib/yaffle.rb* - -<ruby> -require "yaffle/routing" -</ruby> - -* *vendor/plugins/yaffle/lib/yaffle/routing.rb* -<ruby> -module Yaffle #:nodoc: - module Routing #:nodoc: - module MapperExtensions - def yaffles - @set.add_route("/yaffles", {:controller => "yaffles_controller", :action => "index"}) + module ClassMethods + def acts_as_yaffle(options = {}) + cattr_accessor :yaffle_text_field + self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s end end end end -ActionController::Routing::RouteSet::Mapper.send :include, Yaffle::Routing::MapperExtensions -</ruby> - -* *config/routes.rb* - -<ruby> -ActionController::Routing::Routes.draw do |map| - map.yaffles -end +ActiveRecord::Base.send :include, Yaffle::ActsAsYaffle </ruby> -You can also see if your routes work by running +rake routes+ from your app directory. - -h3. Generators - -Many plugins ship with generators. When you created the plugin above, you specified the +--with-generator+ option, so you already have the generator stubs in 'vendor/plugins/yaffle/generators/yaffle'. - -Building generators is a complex topic unto itself and this section will cover one small aspect of generators: generating a simple text file. - -h4. Testing Generators - -Many rails plugin authors do not test their generators, however testing generators is quite simple. A typical generator test does the following: - - * Creates a new fake rails root directory that will serve as destination - * Runs the generator - * Asserts that the correct files were generated - * Removes the fake rails root - -This section will describe how to create a simple generator that adds a file. For the generator in this section, the test could look something like this: - -* *vendor/plugins/yaffle/test/definition_generator_test.rb* - -<ruby> -require File.dirname(__FILE__) + '/test_helper' -require 'rails_generator' -require 'rails_generator/scripts/generate' - -class DefinitionGeneratorTest < Test::Unit::TestCase - - def setup - FileUtils.mkdir_p(fake_rails_root) - @original_files = file_list - end - - def teardown - FileUtils.rm_r(fake_rails_root) - end - - def test_generates_correct_file_name - Rails::Generator::Scripts::Generate.new.run(["yaffle_definition"], :destination => fake_rails_root) - new_file = (file_list - @original_files).first - assert_equal "definition.txt", File.basename(new_file) - end - - private - - def fake_rails_root - File.join(File.dirname(__FILE__), 'rails_root') - end - - def file_list - Dir.glob(File.join(fake_rails_root, "*")) - end - -end -</ruby> - -You can run 'rake' from the plugin directory to see this fail. Unless you are doing more advanced generator commands it typically suffices to just test the Generate script, and trust that rails will handle the Destroy and Update commands for you. - -To make it pass, create the generator: - -* *vendor/plugins/yaffle/generators/yaffle_definition/yaffle_definition_generator.rb* - -<ruby> -class YaffleDefinitionGenerator < Rails::Generator::Base - def manifest - record do |m| - m.file "definition.txt", "definition.txt" - end - end -end -</ruby> - -h4. The +USAGE+ File - -If you plan to distribute your plugin, developers will expect at least a minimum of documentation. You can add simple documentation to the generator by updating the USAGE file. - -Rails ships with several built-in generators. You can see all of the generators available to you by typing the following at the command line: - -<shell> -rails generate -</shell> - -You should see something like this: - -<shell> -Installed Generators - Plugins (vendor/plugins): yaffle_definition - Builtin: controller, integration_test, mailer, migration, model, observer, plugin, resource, scaffold, session_migration -</shell> - -When you run +rails generate yaffle_definition -h+ you should see the contents of your 'vendor/plugins/yaffle/generators/yaffle_definition/USAGE'. - -For this plugin, update the USAGE file could look like this: +When you run +rake+ you should see the tests all pass: <shell> -Description: - Adds a file with the definition of a Yaffle to the app's main directory + 5 tests, 5 assertions, 0 failures, 0 errors, 0 skips </shell> -h3. Add a Custom Generator Command - -You may have noticed above that you can used one of the built-in rails migration commands +migration_template+. If your plugin needs to add and remove lines of text from existing files you will need to write your own generator methods. - -This section describes how you you can create your own commands to add and remove a line of text from 'routes.rb'. This example creates a very simple method that adds or removes a text file. - -To start, add the following test method: - -* *vendor/plugins/yaffle/test/generator_test.rb* - -<ruby> -def test_generates_definition - Rails::Generator::Scripts::Generate.new.run(["yaffle", "bird"], :destination => fake_rails_root) - definition = File.read(File.join(fake_rails_root, "definition.txt")) - assert_match /Yaffle\:/, definition -end -</ruby> - -Run +rake+ to watch the test fail, then make the test pass add the following: - -* *vendor/plugins/yaffle/generators/yaffle/templates/definition.txt* - -<shell> -Yaffle: A bird -</shell> - -* *vendor/plugins/yaffle/lib/yaffle.rb* - -<ruby> -require "yaffle/commands" -</ruby> - -* *vendor/plugins/yaffle/lib/commands.rb* - -<ruby> -require 'rails_generator' -require 'rails_generator/commands' - -module Yaffle #:nodoc: - module Generator #:nodoc: - module Commands #:nodoc: - module Create - def yaffle_definition - file("definition.txt", "definition.txt") - end - end - - module Destroy - def yaffle_definition - file("definition.txt", "definition.txt") - end - end - - module List - def yaffle_definition - file("definition.txt", "definition.txt") - end - end - - module Update - def yaffle_definition - file("definition.txt", "definition.txt") - end - end - end - end -end - -Rails::Generator::Commands::Create.send :include, Yaffle::Generator::Commands::Create -Rails::Generator::Commands::Destroy.send :include, Yaffle::Generator::Commands::Destroy -Rails::Generator::Commands::List.send :include, Yaffle::Generator::Commands::List -Rails::Generator::Commands::Update.send :include, Yaffle::Generator::Commands::Update -</ruby> - -Finally, call your new method in the manifest: - -* *vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb* - -<ruby> -class YaffleGenerator < Rails::Generator::NamedBase - def manifest - m.yaffle_definition - end -end -</ruby> - -h3. Generator Commands - -You may have noticed above that you can used one of the built-in rails migration commands +migration_template+. If your plugin needs to add and remove lines of text from existing files you will need to write your own generator methods. - -This section describes how you you can create your own commands to add and remove a line of text from 'config/routes.rb'. +h4. Add an Instance Method -To start, add the following test method: +This plugin will add a method named 'squawk' to any Active Record objects that call 'acts_as_yaffle'. The 'squawk' +method will simply set the value of one of the fields in the database. -* *vendor/plugins/yaffle/test/route_generator_test.rb* +To start out, write a failing test that shows the behavior you'd like: <ruby> -require File.dirname(__FILE__) + '/test_helper' -require 'rails_generator' -require 'rails_generator/scripts/generate' -require 'rails_generator/scripts/destroy' +# yaffle/test/acts_as_yaffle_test.rb +require 'test_helper' -class RouteGeneratorTest < Test::Unit::TestCase +class ActsAsYaffleTest < Test::Unit::TestCase - def setup - FileUtils.mkdir_p(File.join(fake_rails_root, "config")) + def test_a_hickwalls_yaffle_text_field_should_be_last_squawk + assert_equal "last_squawk", Hickwall.yaffle_text_field end - def teardown - FileUtils.rm_r(fake_rails_root) + def test_a_wickwalls_yaffle_text_field_should_be_last_tweet + assert_equal "last_tweet", Wickwall.yaffle_text_field end - def test_generates_route - content = <<-END - ActionController::Routing::Routes.draw do |map| - map.connect ':controller/:action/:id' - map.connect ':controller/:action/:id.:format' - end - END - File.open(routes_path, 'wb') {|f| f.write(content) } - - Rails::Generator::Scripts::Generate.new.run(["yaffle_route"], :destination => fake_rails_root) - assert_match /map\.yaffles/, File.read(routes_path) + def test_hickwalls_squawk_should_populate_last_squawk + hickwall = Hickwall.new + hickwall.squawk("Hello World") + assert_equal "squawk! Hello World", hickwall.last_squawk end - def test_destroys_route - content = <<-END - ActionController::Routing::Routes.draw do |map| - map.yaffles - map.connect ':controller/:action/:id' - map.connect ':controller/:action/:id.:format' - end - END - File.open(routes_path, 'wb') {|f| f.write(content) } - - Rails::Generator::Scripts::Destroy.new.run(["yaffle_route"], :destination => fake_rails_root) - assert_no_match /map\.yaffles/, File.read(routes_path) + def test_wickwalls_squawk_should_populate_last_tweeted_at + wickwall = Wickwall.new + wickwall.squawk("Hello World") + assert_equal "squawk! Hello World", wickwall.last_tweet end - - private - - def fake_rails_root - File.join(File.dirname(__FILE__), "rails_root") - end - - def routes_path - File.join(fake_rails_root, "config", "routes.rb") - end - end </ruby> -Run +rake+ to watch the test fail, then make the test pass add the following: - -* *vendor/plugins/yaffle/lib/yaffle.rb* +Run the test to make sure the last two tests fail the an error that contains "NoMethodError: undefined method `squawk'", +then update 'acts_as_yaffle.rb' to look like this: <ruby> -require "yaffle/commands" -</ruby> +# yaffle/lib/yaffle/acts_as_yaffle.rb -* *vendor/plugins/yaffle/lib/yaffle/commands.rb* - -<ruby> -require 'rails_generator' -require 'rails_generator/commands' - -module Yaffle #:nodoc: - module Generator #:nodoc: - module Commands #:nodoc: - module Create - def yaffle_route - logger.route "map.yaffle" - look_for = 'ActionController::Routing::Routes.draw do |map|' - unless options[:pretend] - gsub_file('config/routes.rb', /(#{Regexp.escape(look_for)})/mi){|match| "#{match}\n map.yaffles\n"} - end - end - end - - module Destroy - def yaffle_route - logger.route "map.yaffle" - gsub_file 'config/routes.rb', /\n.+?map\.yaffles/mi, '' - end - end - - module List - def yaffle_route - end - end +module Yaffle + module ActsAsYaffle + extend ActiveSupport::Concern - module Update - def yaffle_route - end - end + included do end - end -end -Rails::Generator::Commands::Create.send :include, Yaffle::Generator::Commands::Create -Rails::Generator::Commands::Destroy.send :include, Yaffle::Generator::Commands::Destroy -Rails::Generator::Commands::List.send :include, Yaffle::Generator::Commands::List -Rails::Generator::Commands::Update.send :include, Yaffle::Generator::Commands::Update -</ruby> - -* *vendor/plugins/yaffle/generators/yaffle_route/yaffle_route_generator.rb* - -<ruby> -class YaffleRouteGenerator < Rails::Generator::Base - def manifest - record do |m| - m.yaffle_route - end - end -end -</ruby> - -To see this work, type: - -<shell> -rails generate yaffle_route -rails destroy yaffle_route -</shell> - -NOTE: If you haven't set up the custom route from above, 'rails destroy' will fail and you'll have to remove it manually. - -h3. Migrations - -If your plugin requires changes to the app's database you will likely want to somehow add migrations. Rails does not include any built-in support for calling migrations from plugins, but you can still make it easy for developers to call migrations from plugins. - -If you have a very simple needs, like creating a table that will always have the same name and columns, then you can use a more simple solution, like creating a custom rake task or method. If your migration needs user input to supply table names or other options, you probably want to opt for generating a migration. - -Let's say you have the following migration in your plugin: - -* *vendor/plugins/yaffle/lib/db/migrate/20081116181115_create_birdhouses.rb:* - -<ruby> -class CreateBirdhouses < ActiveRecord::Migration - def self.up - create_table :birdhouses, :force => true do |t| - t.string :name - t.timestamps + module ClassMethods + def acts_as_yaffle(options = {}) + cattr_accessor :yaffle_text_field + self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s + end end - end - - def self.down - drop_table :birdhouses - end -end -</ruby> - -Here are a few possibilities for how to allow developers to use your plugin migrations: - -h4. Create a Custom Rake Task - -* *vendor/plugins/yaffle/tasks/yaffle_tasks.rake:* -<ruby> -namespace :db do - namespace :migrate do - description = "Migrate the database through scripts in vendor/plugins/yaffle/lib/db/migrate" - description << "and update db/schema.rb by invoking db:schema:dump." - description << "Target specific version with VERSION=x. Turn off output with VERBOSE=false." - - desc description - task :yaffle => :environment do - ActiveRecord::Migration.verbose = ENV["VERBOSE"] ? ENV["VERBOSE"] == "true" : true - ActiveRecord::Migrator.migrate("vendor/plugins/yaffle/lib/db/migrate/", ENV["VERSION"] ? ENV["VERSION"].to_i : nil) - Rake::Task["db:schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby + def squawk(string) + write_attribute(self.class.yaffle_text_field, string.to_squawk) end - end -end -</ruby> - -h4. Call Migrations Directly - -* *vendor/plugins/yaffle/lib/yaffle.rb:* - -<ruby> -Dir.glob(File.join(File.dirname(__FILE__), "db", "migrate", "*")).each do |file| - require file -end -</ruby> - -* *db/migrate/20081116181115_create_birdhouses.rb:* - -<ruby> -class CreateBirdhouses < ActiveRecord::Migration - def self.up - Yaffle::CreateBirdhouses.up - end - - def self.down - Yaffle::CreateBirdhouses.down - end -end -</ruby> - -NOTE: several plugin frameworks such as Desert and Engines provide more advanced plugin functionality. - -h4. Generate Migrations - -Generating migrations has several advantages over other methods. Namely, you can allow other developers to more easily customize the migration. The flow looks like this: - - * call your rails generate script and pass in whatever options they need - * examine the generated migration, adding/removing columns or other options as necessary - -This example will demonstrate how to use one of the built-in generator methods named 'migration_template' to create a migration file. Extending the rails migration generator requires a somewhat intimate knowledge of the migration generator internals, so it's best to write a test first: - -* *vendor/plugins/yaffle/test/yaffle_migration_generator_test.rb* - -<ruby> -require File.dirname(__FILE__) + '/test_helper' -require 'rails_generator' -require 'rails_generator/scripts/generate' -class MigrationGeneratorTest < Test::Unit::TestCase - - def setup - FileUtils.mkdir_p(fake_rails_root) - @original_files = file_list - end - - def teardown - ActiveRecord::Base.pluralize_table_names = true - FileUtils.rm_r(fake_rails_root) - end - - def test_generates_correct_file_name - Rails::Generator::Scripts::Generate.new.run(["yaffle_migration", "some_name_nobody_is_likely_to_ever_use_in_a_real_migration"], - :destination => fake_rails_root) - new_file = (file_list - @original_files).first - assert_match /add_yaffle_fields_to_some_name_nobody_is_likely_to_ever_use_in_a_real_migrations/, new_file - assert_match /add_column :some_name_nobody_is_likely_to_ever_use_in_a_real_migrations do |t|/, File.read(new_file) end - - def test_pluralizes_properly - ActiveRecord::Base.pluralize_table_names = false - Rails::Generator::Scripts::Generate.new.run(["yaffle_migration", "some_name_nobody_is_likely_to_ever_use_in_a_real_migration"], - :destination => fake_rails_root) - new_file = (file_list - @original_files).first - assert_match /add_yaffle_fields_to_some_name_nobody_is_likely_to_ever_use_in_a_real_migration/, new_file - assert_match /add_column :some_name_nobody_is_likely_to_ever_use_in_a_real_migration do |t|/, File.read(new_file) - end - - private - def fake_rails_root - File.join(File.dirname(__FILE__), 'rails_root') - end - - def file_list - Dir.glob(File.join(fake_rails_root, "db", "migrate", "*")) - end - end -</ruby> -NOTE: the migration generator checks to see if a migation already exists, and it's hard-coded to check the 'db/migrate' directory. As a result, if your test tries to generate a migration that already exists in the app, it will fail. The easy workaround is to make sure that the name you generate in your test is very unlikely to actually appear in the app. - -After running the test with 'rake' you can make it pass with: - -* *vendor/plugins/yaffle/generators/yaffle_migration/yaffle_migration_generator.rb* - -<ruby> -class YaffleMigrationGenerator < Rails::Generator::NamedBase - def manifest - record do |m| - m.migration_template 'migration:migration.rb', "db/migrate", {:assigns => yaffle_local_assigns, - :migration_file_name => "add_yaffle_fields_to_#{custom_file_name}" - } - end - end - - private - def custom_file_name - custom_name = class_name.underscore.downcase - custom_name = custom_name.pluralize if ActiveRecord::Base.pluralize_table_names - custom_name - end - - def yaffle_local_assigns - {}.tap do |assigns| - assigns[:migration_action] = "add" - assigns[:class_name] = "add_yaffle_fields_to_#{custom_file_name}" - assigns[:table_name] = custom_file_name - assigns[:attributes] = [Rails::Generator::GeneratedAttribute.new("last_squawk", "string")] - end - end -end +ActiveRecord::Base.send :include, Yaffle::ActsAsYaffle </ruby> -The generator creates a new file in 'db/migrate' with a timestamp and an 'add_column' statement. It reuses the built-in rails +migration_template+ method, and reuses the built-in rails migration template. - -It's courteous to check to see if table names are being pluralized whenever you create a generator that needs to be aware of table names. This way people using your generator won't have to manually change the generated files if they've turned pluralization off. - -To run the generator, type the following at the command line: - +Run +rake+ one final time and you should see: <shell> -rails generate yaffle_migration bird + 7 tests, 7 assertions, 0 failures, 0 errors, 0 skips </shell> -and you will see a new file: - -* *db/migrate/20080529225649_add_yaffle_fields_to_birds.rb* - -<ruby> -class AddYaffleFieldsToBirds < ActiveRecord::Migration - def self.up - add_column :birds, :last_squawk, :string - end - - def self.down - remove_column :birds, :last_squawk - end -end -</ruby> +NOTE: The use of +write_attribute+ to write to the field in model is just one example of how a plugin can +interact with the model, and will not always be the right method to use. For example, you could also +use +send("#{self.class.yaffle_text_field}=", string.to_squawk)+. -h3. Rake tasks +h3. Generators -When you created the plugin with the built-in rails generator, it generated a rake file for you in 'vendor/plugins/yaffle/tasks/yaffle_tasks.rake'. Any rake task you add here will be available to the app. +Generators can be included in your gem simply by creating them in a lib/generators directory of your plugin. More information about +the creation of generators can be found in the "Generators Guide":generators.html -Many plugin authors put all of their rake tasks into a common namespace that is the same as the plugin, like so: +h3. Publishing your Gem -* *vendor/plugins/yaffle/tasks/yaffle_tasks.rake* +Gem plugins in progress can be easily be shared from any Git repository. To share the Yaffle gem with others, simply +commit the code to a Git repository (like Github) and add a line to the Gemfile of the any application: <ruby> -namespace :yaffle do - desc "Prints out the word 'Yaffle'" - task :squawk => :environment do - puts "squawk!" - end -end +gem 'yaffle', :git => 'git://github.com/yaffle_watcher/yaffle.git' </ruby> -When you run +rake -T+ from your plugin you will see: - -<shell> -yaffle:squawk # Prints out the word 'Yaffle' -</shell> +After running +bundle install+, your gem functionality will be available to the application. -You can add as many files as you want in the tasks directory, and if they end in .rake Rails will pick them up. +When the gem is ready to be shared as a formal release, it can be published to "RubyGems":http://www.rubygems.org. +For more information about publishing gems to RubyGems, see: "http://blog.thepete.net/2010/11/creating-and-publishing-your-first-ruby.html":http://blog.thepete.net/2010/11/creating-and-publishing-your-first-ruby.html -Note that tasks from +vendor/plugins/yaffle/Rakefile+ are not available to the main app. +h3. Non-Gem Plugins -h3. Plugins as Gems +Non-gem plugins are useful for functionality that won't be shared with another project. Keeping your custom functionality in the +vendor/plugins directory un-clutters the rest of the application. -Turning your rails plugin into a gem is a simple and straightforward task. This section will cover how to turn your plugin into a gem. It will not cover how to distribute that gem. - -The initialization file has to be called +rails/init.rb+, the root +init.rb+ file, if any, is ignored by Rails. Also, the name of the plugin now is relevant since +config.gem+ tries to load it. Either name the main file after your gem, or document that users should use the +:lib+ option. - -It's common practice to put any developer-centric rake tasks (such as tests, rdoc and gem package tasks) in +Rakefile+. A rake task that packages the gem might look like this: - -* *vendor/plugins/yaffle/Rakefile:* +Move the directory that you created for the gem based plugin into the vendor/plugins directory of a generated Rails application, create a vendor/plugins/yaffle/init.rb file that contains "require 'yaffle'" and everything will still work. <ruby> -PKG_FILES = FileList[ - '[a-zA-Z]*', - 'generators/**/*', - 'lib/**/*', - 'rails/**/*', - 'tasks/**/*', - 'test/**/*' -] - -spec = Gem::Specification.new do |s| - s.name = "yaffle" - s.version = "0.0.1" - s.author = "Gleeful Yaffler" - s.email = "yaffle@example.com" - s.homepage = "http://yafflers.example.com/" - s.platform = Gem::Platform::RUBY - s.summary = "Sharing Yaffle Goodness" - s.files = PKG_FILES.to_a - s.require_path = "lib" - s.has_rdoc = false - s.extra_rdoc_files = ["README"] -end +# yaffle/init.rb -desc 'Turn this plugin into a gem.' -Rake::GemPackageTask.new(spec) do |pkg| - pkg.gem_spec = spec -end +require 'yaffle' </ruby> -To build and install the gem locally, run the following commands: - +You can test this by changing to the Rails application that you added the plugin to and starting a rails console. Once in the +console we can check to see if the String has an instance method of to_squawk. <shell> -cd vendor/plugins/yaffle -rake gem -sudo gem install pkg/yaffle-0.0.1.gem +$ cd my_app +$ rails console +$ String.instance_methods.sort </shell> -To test this, create a new rails app, add +config.gem "yaffle"+ to +config/environment.rb+ and all of your plugin's functionality will be available to you. +You can also remove the .gemspec, Gemfile and Gemfile.lock files as they will no longer be needed. h3. RDoc Documentation Once your plugin is stable and you are ready to deploy do everyone else a favor and document it! Luckily, writing documentation for your plugin is easy. -The first step is to update the README file with detailed information about how to use your plugin. A few key things to include are: +The first step is to update the README file with detailed information about how to use your plugin. A few key things to include are: * Your name * How to install * How to add the functionality to the app (several examples of common use cases) * Warning, gotchas or tips that might help save users time -Once your README is solid, go through and add rdoc comments to all of the methods that developers will use. It's also customary to add '#:nodoc:' comments to those parts of the code that are not part of the public api. +Once your README is solid, go through and add rdoc comments to all of the methods that developers will use. It's also customary to add '#:nodoc:' comments to those parts of the code that are not part of the public api. Once your comments are good to go, navigate to your plugin directory and run: <shell> -rake rdoc +$ rake rdoc </shell> -h3. Appendix - -If you prefer to use RSpec instead of Test::Unit, you may be interested in the "RSpec Plugin Generator":http://github.com/patmaddox/rspec-plugin-generator. - h4. References -* http://nubyonrails.com/articles/the-complete-guide-to-rails-plugins-part-i -* http://nubyonrails.com/articles/the-complete-guide-to-rails-plugins-part-ii -* http://github.com/technoweenie/attachment_fu/tree/master -* http://daddy.platte.name/2007/05/rails-plugins-keep-initrb-thin.html -* http://www.mbleigh.com/2008/6/11/gemplugins-a-brief-introduction-to-the-future-of-rails-plugins -* http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2. - -h4. Contents of +lib/yaffle.rb+ - -* *vendor/plugins/yaffle/lib/yaffle.rb:* - -<ruby> -require "yaffle/core_ext" -require "yaffle/acts_as_yaffle" -require "yaffle/commands" -require "yaffle/routing" - -%w{ models controllers helpers }.each do |dir| - path = File.join(File.dirname(__FILE__), 'app', dir) - $LOAD_PATH << path - ActiveSupport::Dependencies.load_paths << path - ActiveSupport::Dependencies.load_once_paths.delete(path) -end - -# optionally: -# Dir.glob(File.join(File.dirname(__FILE__), "db", "migrate", "*")).each do |file| -# require file -# end -</ruby> - -h4. Final Plugin Directory Structure - -The final plugin should have a directory structure that looks something like this: - -<shell> -|-- MIT-LICENSE -|-- README -|-- Rakefile -|-- generators -| |-- yaffle_definition -| | |-- USAGE -| | |-- templates -| | | `-- definition.txt -| | `-- yaffle_definition_generator.rb -| |-- yaffle_migration -| | |-- USAGE -| | |-- templates -| | `-- yaffle_migration_generator.rb -| `-- yaffle_route -| |-- USAGE -| |-- templates -| `-- yaffle_route_generator.rb -|-- install.rb -|-- lib -| |-- app -| | |-- controllers -| | | `-- woodpeckers_controller.rb -| | |-- helpers -| | | `-- woodpeckers_helper.rb -| | `-- models -| | `-- woodpecker.rb -| |-- db -| | `-- migrate -| | `-- 20081116181115_create_birdhouses.rb -| |-- yaffle -| | |-- acts_as_yaffle.rb -| | |-- commands.rb -| | |-- core_ext.rb -| | `-- routing.rb -| `-- yaffle.rb -|-- pkg -| `-- yaffle-0.0.1.gem -|-- rails -| `-- init.rb -|-- tasks -| `-- yaffle_tasks.rake -|-- test -| |-- acts_as_yaffle_test.rb -| |-- core_ext_test.rb -| |-- database.yml -| |-- debug.log -| |-- definition_generator_test.rb -| |-- migration_generator_test.rb -| |-- route_generator_test.rb -| |-- routes_test.rb -| |-- schema.rb -| |-- test_helper.rb -| |-- woodpecker_test.rb -| |-- woodpeckers_controller_test.rb -| |-- wookpeckers_helper_test.rb -| |-- yaffle_plugin.sqlite3.db -| `-- yaffle_test.rb -`-- uninstall.rb -</shell> +* "Developing a RubyGem using Bundler":https://github.com/radar/guides/blob/master/gem-development.md +* "Using Gemspecs As Intended":http://yehudakatz.com/2010/04/02/using-gemspecs-as-intended/ +* "Gemspec Reference":http://docs.rubygems.org/read/chapter/20 +* "GemPlugins":http://www.mbleigh.com/2008/06/11/gemplugins-a-brief-introduction-to-the-future-of-rails-plugins +* "Keeping init.rb thin":http://daddy.platte.name/2007/05/rails-plugins-keep-initrb-thin.html h3. Changelog -"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213/tickets/32-update-plugins-guide - +* March 10, 2011: Minor formatting tweaks. +* February 13, 2011: Get guide in synch with Rails 3.0.3. Remove information not compatible with Rails 3. Send reader elsewhere +for information that is covered elsewhere. * April 4, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com * November 17, 2008: Major revision by Jeff Dean diff --git a/railties/guides/source/rails_application_templates.textile b/railties/guides/source/rails_application_templates.textile index 1bf9cfec33..8e51f9e23b 100644 --- a/railties/guides/source/rails_application_templates.textile +++ b/railties/guides/source/rails_application_templates.textile @@ -20,7 +20,7 @@ $ rails new blog -m ~/template.rb It's also possible to apply a template using a URL : <shell> -$ rails new blog -m http://gist.github.com/31208.txt +$ rails new blog -m https://gist.github.com/755496.txt </shell> Alternatively, you can use the rake task +rails:template+ to apply a template to an existing Rails application : @@ -37,7 +37,7 @@ Rails templates API is very self explanatory and easy to understand. Here's an e # template.rb run "rm public/index.html" generate(:scaffold, "person name:string") -route "map.root :controller => 'people'" +route "root :to => 'people#index'" rake("db:migrate") git :init @@ -49,7 +49,7 @@ The following sections outlines the primary methods provided by the API : h4. gem(name, options = {}) -Adds a +config.gem+ entry for the supplied gem to the generated application’s +config/environment.rb+. +Adds a +gem+ entry for the supplied gem to the generated application’s +Gemfile+. For example, if your application depends on the gems +bj+ and +nokogiri+ : @@ -66,6 +66,16 @@ rake "gems:install" And let Rails take care of installing the required gems if they’re not already installed. +h4. add_source(source, options = {}) + +Adds the given source to the generated application's +Gemfile+. + +For example, if you need to source a gem from "http://code.whytheluckystiff.net": + +<ruby> +add_source "http://code.whytheluckystiff.net" +</ruby> + h4. plugin(name, options = {}) Installs a plugin to the generated application. @@ -79,7 +89,7 @@ plugin 'authentication', :git => 'git://github.com/foor/bar.git' You can even install plugins as git submodules : <ruby> -plugin 'authentication', :git => 'git://github.com/foor/bar.git', +plugin 'authentication', :git => 'git://github.com/foor/bar.git', :submodule => true </ruby> @@ -103,7 +113,7 @@ class Object def not_nil? !nil? end - + def not_blank? !blank? end @@ -183,12 +193,12 @@ h4. route(routing_code) This adds a routing entry to the +config/routes.rb+ file. In above steps, we generated a person scaffold and also removed +public/index.html+. Now to make +PeopleController#index+ as the default page for the application : <ruby> -route "map.root :controller => :person" +route "root :to => 'person#index'" </ruby> h4. inside(dir) -I have my edge rails lying at +~/commit-rails/rails+. So every time i have to manually symlink edge from my new app. But now : +Enables you to run a command from the given directory. For example, if you have a copy of edge rails that you wish to symlink from your new apps, you can do this: <ruby> inside('vendor') do @@ -196,8 +206,6 @@ inside('vendor') do end </ruby> -So +inside()+ runs the command from the given directory. - h4. ask(question) +ask()+ gives you a chance to get some feedback from the user and use it in your templates. Lets say you want your user to name the new shiny library you’re adding : @@ -233,6 +241,4 @@ git :commit => "-a -m 'Initial commit'" h3. Changelog -"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/78 - * April 29, 2009: Initial version by "Pratik":credits.html#lifo diff --git a/railties/guides/source/rails_on_rack.textile b/railties/guides/source/rails_on_rack.textile index eaebb05f17..b1db2942dd 100644 --- a/railties/guides/source/rails_on_rack.textile +++ b/railties/guides/source/rails_on_rack.textile @@ -17,12 +17,7 @@ bq. Rack provides a minimal, modular and adaptable interface for developing web - "Rack API Documentation":http://rack.rubyforge.org/doc/ -Explaining Rack is not really in the scope of this guide. In case you are not familiar with Rack's basics, you should check out the following links: - -* "Official Rack Website":http://rack.github.com -* "Introducing Rack":http://chneukirchen.org/blog/archive/2007/02/introducing-rack.html -* "Ruby on Rack #1 - Hello Rack!":http://m.onkey.org/2008/11/17/ruby-on-rack-1 -* "Ruby on Rack #2 - The Builder":http://m.onkey.org/2008/11/18/ruby-on-rack-2-rack-builder +Explaining Rack is not really in the scope of this guide. In case you are not familiar with Rack's basics, you should check out the "Resources":#resources section below. h3. Rails on Rack @@ -68,13 +63,13 @@ run ActionController::Dispatcher.new And start the server: <shell> -[lifo@null application]$ rackup config.ru +$ rackup config.ru </shell> To find out more about different +rackup+ options: <shell> -[lifo@null application]$ rackup --help +$ rackup --help </shell> h3. Action Controller Middleware Stack @@ -165,7 +160,7 @@ Much of Action Controller's functionality is implemented as Middlewares. The fol |_.Middleware|_.Purpose| |+Rack::Lock+|Sets +env["rack.multithread"]+ flag to +true+ and wraps the application within a Mutex.| |+ActionController::Failsafe+|Returns HTTP Status +500+ to the client if an exception gets raised while dispatching.| -|+ActiveRecord::QueryCache+|Enable the Active Record query cache.| +|+ActiveRecord::QueryCache+|Enables the Active Record query cache.| |+ActionController::Session::CookieStore+|Uses the cookie based session store.| |+ActionController::Session::MemCacheStore+|Uses the memcached based session store.| |+ActiveRecord::SessionStore+|Uses the database based session store.| @@ -228,8 +223,8 @@ h4. Learning Rack * "Official Rack Website":http://rack.github.com * "Introducing Rack":http://chneukirchen.org/blog/archive/2007/02/introducing-rack.html -* "Ruby on Rack #1 - Hello Rack!":http://m.onkey.org/2008/11/17/ruby-on-rack-1 -* "Ruby on Rack #2 - The Builder":http://m.onkey.org/2008/11/18/ruby-on-rack-2-rack-builder +* "Ruby on Rack #1 - Hello Rack!":http://m.onkey.org/ruby-on-rack-1-hello-rack +* "Ruby on Rack #2 - The Builder":http://m.onkey.org/ruby-on-rack-2-the-builder h4. Understanding Middlewares @@ -237,7 +232,5 @@ h4. Understanding Middlewares h3. Changelog -"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/58 - * February 7, 2009: Second version by "Pratik":credits.html#lifo * January 11, 2009: First version by "Pratik":credits.html#lifo diff --git a/railties/guides/source/routing.textile b/railties/guides/source/routing.textile index 625941ba31..c447fd911a 100644 --- a/railties/guides/source/routing.textile +++ b/railties/guides/source/routing.textile @@ -3,7 +3,7 @@ h2. Rails Routing from the Outside In This guide covers the user-facing features of Rails routing. By referring to this guide, you will be able to: * Understand the code in +routes.rb+ -* Construct your own routes, using either the preferred resourceful style or with the <tt>match</tt> method +* Construct your own routes, using either the preferred resourceful style or the <tt>match</tt> method * Identify what parameters to expect an action to receive * Automatically create paths and URLs using route helpers * Use advanced techniques such as constraints and Rack endpoints @@ -39,10 +39,10 @@ You can also generate paths and URLs. If your application contains this code: </ruby> <erb> -<%= link_to "Patient Record", patients_path(@patient.id) %> +<%= link_to "Patient Record", patient_path(@patient) %> </erb> -The router will generate the path +/patients/17+. This reduces the brittleness of your view and makes your code easier to understand. +The router will generate the path +/patients/17+. This reduces the brittleness of your view and makes your code easier to understand. Note that the id does not need to be specified in the route helper. h3. Resource Routing: the Rails Default @@ -50,7 +50,7 @@ Resource routing allows you to quickly declare all of the common routes for a gi h4. Resources on the Web -Browsers request pages from Rails by making a request for a URL using a specific HTTP method, such as +GET+, +POST+, +PUT+ and +DELETE+. Each method is a request to perform an operation on the resource. A resource route maps a number of related request to the actions in a single controller. +Browsers request pages from Rails by making a request for a URL using a specific HTTP method, such as +GET+, +POST+, +PUT+ and +DELETE+. Each method is a request to perform an operation on the resource. A resource route maps a number of related requests to actions in a single controller. When your Rails application receives an incoming request for @@ -76,14 +76,17 @@ resources :photos creates seven different routes in your application, all mapping to the +Photos+ controller: -|_. Verb |_.Path |_.action |_.used for| -|GET |/photos |index |display a list of all photos| -|GET |/photos/new |new |return an HTML form for creating a new photo| -|POST |/photos |create |create a new photo| -|GET |/photos/:id |show |display a specific photo| -|GET |/photos/:id/edit |edit |return an HTML form for editing a photo| -|PUT |/photos/:id |update |update a specific photo| -|DELETE |/photos/:id |destroy |delete a specific photo| +|_. HTTP Verb |_.Path |_.action |_.used for | +|GET |/photos |index |display a list of all photos | +|GET |/photos/new |new |return an HTML form for creating a new photo | +|POST |/photos |create |create a new photo | +|GET |/photos/:id |show |display a specific photo | +|GET |/photos/:id/edit |edit |return an HTML form for editing a photo | +|PUT |/photos/:id |update |update a specific photo | +|DELETE |/photos/:id |destroy |delete a specific photo | + + +NOTE: Rails routes are matched in the order they are specified, so if you have a +resources :photos+ above a +get 'photos/poll'+ the +show+ action's route for the +resources+ line will be matched before the +get+ line. To fix this, move the +get+ line *above* the +resources+ line so that it is matched first. h4. Paths and URLs @@ -91,7 +94,7 @@ Creating a resourceful route will also expose a number of helpers to the control * +photos_path+ returns +/photos+ * +new_photo_path+ returns +/photos/new+ -* +edit_photo_path+ returns +/photos/edit+ +* +edit_photo_path(id)+ returns +/photos/:id/edit+ (for instance, +edit_photo_path(10)+ returns +/photos/10/edit+) * +photo_path(id)+ returns +/photos/:id+ (for instance, +photo_path(10)+ returns +/photos/10+) Each of these helpers has a corresponding +_url+ helper (such as +photos_url+) which returns the same path prefixed with the current host, port and path prefix. @@ -116,7 +119,7 @@ resources :videos h4. Singular Resources -Sometimes, you have a resource that clients always look up without referencing an ID. A common example, +/profile+ always shows the profile of the currently logged in user. In this case, you can use a singular resource to map +/profile+ (rather than +/profile/:id+) to the +show+ action. +Sometimes, you have a resource that clients always look up without referencing an ID. For example, you would like +/profile+ to always show the profile of the currently logged in user. In this case, you can use a singular resource to map +/profile+ (rather than +/profile/:id+) to the +show+ action. <ruby> match "profile" => "users#show" @@ -130,13 +133,13 @@ resource :geocoder creates six different routes in your application, all mapping to the +Geocoders+ controller: -|_. Verb |_.Path |_.action |_.used for| -|GET |/geocoder/new |new |return an HTML form for creating the geocoder| -|POST |/geocoder |create |create the new geocoder| -|GET |/geocoder |show |display the one and only geocoder resource| -|GET |/geocoder/edit |edit |return an HTML form for editing the geocoder| -|PUT |/geocoder |update |update the one and only geocoder resource| -|DELETE |/geocoder |destroy |delete the geocoder resource| +|_.HTTP Verb |_.Path |_.action |_.used for | +|GET |/geocoder/new |new |return an HTML form for creating the geocoder | +|POST |/geocoder |create |create the new geocoder | +|GET |/geocoder |show |display the one and only geocoder resource | +|GET |/geocoder/edit |edit |return an HTML form for editing the geocoder | +|PUT |/geocoder |update |update the one and only geocoder resource | +|DELETE |/geocoder |destroy |delete the geocoder resource | NOTE: Because you might want to use the same controller for a singular route (+/account+) and a plural route (+/accounts/45+), singular resources map to plural controllers. @@ -153,23 +156,23 @@ h4. Controller Namespaces and Routing You may wish to organize groups of controllers under a namespace. Most commonly, you might group a number of administrative controllers under an +Admin::+ namespace. You would place these controllers under the +app/controllers/admin+ directory, and you can group them together in your router: <ruby> -namespace "admin" do +namespace :admin do resources :posts, :comments end </ruby> This will create a number of routes for each of the +posts+ and +comments+ controller. For +Admin::PostsController+, Rails will create: -|_. Verb |_.Path |_.action |_. helper | -|GET |/admin/photos |index | admin_photos_path | -|GET |/admin/photos/new |new | new_admin_photos_path | -|POST |/admin/photos |create | admin_photos_path | -|GET |/admin/photos/1 |show | admin_photo_path(id) | -|GET |/admin/photos/1/edit |edit | edit_admin_photo_path(id) | -|PUT |/admin/photos/1 |update | admin_photo_path(id) | -|DELETE |/admin/photos/1 |destroy | admin_photo_path(id) | +|_.HTTP Verb |_.Path |_.action |_.named helper | +|GET |/admin/posts |index | admin_posts_path | +|GET |/admin/posts/new |new | new_admin_posts_path | +|POST |/admin/posts |create | admin_posts_path | +|GET |/admin/posts/1 |show | admin_post_path(id) | +|GET |/admin/posts/1/edit |edit | edit_admin_post_path(id) | +|PUT |/admin/posts/1 |update | admin_post_path(id) | +|DELETE |/admin/posts/1 |destroy | admin_post_path(id) | -If you want to route +/photos+ (without the prefix +/admin+) to +Admin::PostsController+, you could use +If you want to route +/posts+ (without the prefix +/admin+) to +Admin::PostsController+, you could use <ruby> scope :module => "admin" do @@ -183,7 +186,7 @@ or, for a single case resources :posts, :module => "admin" </ruby> -If you want to route +/admin/photos+ to +PostsController+ (without the +Admin::+ module prefix), you could use +If you want to route +/admin/posts+ to +PostsController+ (without the +Admin::+ module prefix), you could use <ruby> scope "/admin" do @@ -194,19 +197,19 @@ end or, for a single case <ruby> -resources :posts, :path => "/admin" +resources :posts, :path => "/admin/posts" </ruby> In each of these cases, the named routes remain the same as if you did not use +scope+. In the last case, the following paths map to +PostsController+: -|_. Verb |_.Path |_.action |_. helper | -|GET |/admin/photos |index | photos_path | -|GET |/admin/photos/new |new | photos_path | -|POST |/admin/photos |create | photos_path | -|GET |/admin/photos/1 |show | photo_path(id) | -|GET |/admin/photos/1/edit |edit | edit_photo_path(id) | -|PUT |/admin/photos/1 |update | photo_path(id) | -|DELETE |/admin/photos/1 |destroy | photo_path(id) | +|_.HTTP Verb |_.Path |_.action |_.named helper | +|GET |/admin/posts |index | posts_path | +|GET |/admin/posts/new |new | posts_path | +|POST |/admin/posts |create | posts_path | +|GET |/admin/posts/1 |show | post_path(id) | +|GET |/admin/posts/1/edit |edit | edit_post_path(id) | +|PUT |/admin/posts/1 |update | post_path(id) | +|DELETE |/admin/posts/1 |destroy | post_path(id) | h4. Nested Resources @@ -232,14 +235,14 @@ end In addition to the routes for magazines, this declaration will also route ads to an +AdsController+. The ad URLs require a magazine: -|_.Verb |_.Path |_.action |_.used for| -|GET |/magazines/1/ads |index |display a list of all ads for a specific magazine| -|GET |/magazines/1/ads/new |new |return an HTML form for creating a new ad belonging to a specific magazine| -|POST |/magazines/1/ads |create |create a new ad belonging to a specific magazine| -|GET |/magazines/1/ads/1 |show |display a specific ad belonging to a specific magazine| -|GET |/magazines/1/ads/1/edit |edit |return an HTML form for editing an ad belonging to a specific magazine| -|PUT |/magazines/1/ads/1 |update |update a specific ad belonging to a specific magazine| -|DELETE |/magazines/1/ads/1 |destroy |delete a specific ad belonging to a specific magazine| +|_.HTTP Verb |_.Path |_.action |_.used for | +|GET |/magazines/1/ads |index |display a list of all ads for a specific magazine | +|GET |/magazines/1/ads/new |new |return an HTML form for creating a new ad belonging to a specific magazine | +|POST |/magazines/1/ads |create |create a new ad belonging to a specific magazine | +|GET |/magazines/1/ads/1 |show |display a specific ad belonging to a specific magazine | +|GET |/magazines/1/ads/1/edit |edit |return an HTML form for editing an ad belonging to a specific magazine | +|PUT |/magazines/1/ads/1 |update |update a specific ad belonging to a specific magazine | +|DELETE |/magazines/1/ads/1 |destroy |delete a specific ad belonging to a specific magazine | This will also create routing helpers such as +magazine_ads_url+ and +edit_magazine_ad_path+. These helpers take an instance of Magazine as the first parameter (+magazine_ads_url(@magazine)+). @@ -313,7 +316,7 @@ To add a member route, just add a +member+ block into the resource block: <ruby> resources :photos do member do - get :preview + get 'preview' end end </ruby> @@ -324,7 +327,7 @@ Within the block of member routes, each route name specifies the HTTP verb that <ruby> resources :photos do - get :preview, :on => :member + get 'preview', :on => :member end </ruby> @@ -335,7 +338,7 @@ To add a route to the collection: <ruby> resources :photos do collection do - get :search + get 'search' end end </ruby> @@ -346,7 +349,7 @@ Just as with member routes, you can pass +:on+ to a route: <ruby> resources :photos do - get :search, :on => :collection + get 'search', :on => :collection end </ruby> @@ -370,7 +373,7 @@ When you set up a regular route, you supply a series of symbols that Rails maps match ':controller(/:action(/:id))' </ruby> -If an incoming request of +/photos/show/1+ is processed by this route (because it hasn't matched any previous route in the file), then the result will be to invoke the +show+ action of the +PhotosController+, and to make the final parameter +"1"+ available as +params[:id]+. This route will also route the incoming request of +/photos+ to +PhotosController+, since +:action+ and +:id+ are optional parameters, denoted by parentheses. +If an incoming request of +/photos/show/1+ is processed by this route (because it hasn't matched any previous route in the file), then the result will be to invoke the +show+ action of the +PhotosController+, and to make the final parameter +"1"+ available as +params[:id]+. This route will also route the incoming request of +/photos+ to +PhotosController#index+, since +:action+ and +:id+ are optional parameters, denoted by parentheses. h4. Dynamic Segments @@ -388,6 +391,8 @@ NOTE: You can't use +namespace+ or +:module+ with a +:controller+ path segment. match ':controller(/:action(/:id))', :controller => /admin\/[^\/]+/ </ruby> +TIP: By default dynamic segments don't accept dots - this is because the dot is used as a separator for formatted routes. If you need to use a dot within a dynamic segment add a constraint which overrides this - for example +:id => /[^\/]<plus>/+ allows anything except a slash. + h4. Static Segments You can specify static segments when creating a route: @@ -434,7 +439,27 @@ You can specify a name for any route using the +:as+ option. match 'exit' => 'sessions#destroy', :as => :logout </ruby> -This will create +logout_path+ and +logout_url+ as named helpers in your application. Calling +logout_path+ will return +/logout+ +This will create +logout_path+ and +logout_url+ as named helpers in your application. Calling +logout_path+ will return +/exit+ + +h4. HTTP Verb Constraints + +You can use the +:via+ option to constrain the request to one or more HTTP methods: + +<ruby> +match 'photos/show' => 'photos#show', :via => :get +</ruby> + +There is a shorthand version of this as well: + +<ruby> +get 'photos/show' +</ruby> + +You can also permit more than one verb to a single route: + +<ruby> +match 'photos/show' => 'photos#show', :via => [:get, :post] +</ruby> h4. Segment Constraints @@ -450,7 +475,7 @@ This route would match paths such as +/photos/A12345+. You can more succinctly e match 'photos/:id' => 'photos#show', :id => /[A-Z]\d{5}/ </ruby> -+:constraints+ takes regular expression. However note that regexp anchors can't be used within constraints. For example following route will not work: ++:constraints+ takes regular expressions with the restriction that regexp anchors can't be used. For example, the following route will not work: <ruby> match '/:id' => 'posts#show', :constraints => {:id => /^\d/} @@ -475,10 +500,10 @@ You specify a request-based constraint the same way that you specify a segment c match "photos", :constraints => {:subdomain => "admin"} </ruby> -You can also specify constrains in a block form: +You can also specify constraints in a block form: <ruby> -namespace "admin" do +namespace :admin do constraints :subdomain => "admin" do resources :photos end @@ -501,7 +526,7 @@ class BlacklistConstraint end TwitterClone::Application.routes.draw do - match "*path" => "blacklist#index", + match "*path" => "blacklist#index", :constraints => BlacklistConstraint.new end </ruby> @@ -516,6 +541,22 @@ match 'photos/*other' => 'photos#unknown' This route would match +photos/12+ or +/photos/long/path/to/12+, setting +params[:other]+ to +"12"+ or +"long/path/to/12"+. +Wildcard segments can occur anywhere in a route. For example, + +<ruby> +match 'books/*section/:title' => 'books#show' +</ruby> + +would match +books/some/section/last-words-a-memoir+ with +params[:section]+ equals +"some/section"+, and +params[:title]+ equals +"last-words-a-memoir"+. + +Technically a route can have even more than one wildcard segment. The matcher assigns segments to parameters in an intuitive way. For example, + +<ruby> +match '*a/foo/*b' => 'test#index' +</ruby> + +would match +zoo/woo/foo/bar/baz+ with +params[:a]+ equals +"zoo/woo"+, and +params[:b]+ equals +"bar/baz"+. + h4. Redirection You can redirect any path to another path using the +redirect+ helper in your router: @@ -559,7 +600,7 @@ You can specify what Rails should route +"/"+ to with the +root+ method: root :to => 'pages#main' </ruby> -You should put the +root+ route at the end of the file. +You should put the +root+ route at the end of the file. You also need to delete the +public/index.html+ file for the root route to take effect. h3. Customizing Resourceful Routes @@ -573,16 +614,16 @@ The +:controller+ option lets you explicitly specify a controller to use for the resources :photos, :controller => "images" </ruby> -will recognize incoming paths beginning with +/photo+ but route to the +Images+ controller: +will recognize incoming paths beginning with +/photos+ but route to the +Images+ controller: -|_. Verb |_.Path |_.action | -|GET |/photos |index | -|GET |/photos/new |new | -|POST |/photos |create | -|GET |/photos/1 |show | -|GET |/photos/1/edit |edit | -|PUT |/photos/1 |update | -|DELETE |/photos/1 |destroy | +|_.HTTP Verb |_.Path |_.action |_.named helper | +|GET |/photos |index | photos_path | +|GET |/photos/new |new | new_photo_path | +|POST |/photos |create | photos_path | +|GET |/photos/1 |show | photo_path(id) | +|GET |/photos/1/edit |edit | edit_photo_path(id) | +|PUT |/photos/1 |update | photo_path(id) | +|DELETE |/photos/1 |destroy | photo_path(id) | NOTE: Use +photos_path+, +new_photos_path+, etc. to generate paths for this resource. @@ -594,7 +635,7 @@ You can use the +:constraints+ option to specify a required format on the implic resources :photos, :constraints => {:id => /[A-Z][A-Z][0-9]+/} </ruby> -This declaration constrains the +:id+ parameter to match the supplied regular expression. So, in this case, the router would no longer match +/photos/1+ to this route. Instead, +/photos/RR27+ would match. +This declaration constraints the +:id+ parameter to match the supplied regular expression. So, in this case, the router would no longer match +/photos/1+ to this route. Instead, +/photos/RR27+ would match. You can specify a single constraint to apply to a number of routes by using the block form: @@ -605,7 +646,9 @@ constraints(:id => /[A-Z][A-Z][0-9]+/) do end </ruby> -NOTE: Of course, you can use the more advanced constraints available in non-resourceful routes in this context +NOTE: Of course, you can use the more advanced constraints available in non-resourceful routes in this context. + +TIP: By default the +:id+ parameter doesn't accept dots - this is because the dot is used as a separator for formatted routes. If you need to use a dot within an +:id+ add a constraint which overrides this - for example +:id => /[^\/]+/+ allows anything except a slash. h4. Overriding the Named Helpers @@ -615,16 +658,16 @@ The +:as+ option lets you override the normal naming for the named route helpers resources :photos, :as => "images" </ruby> -will recognize incoming paths beginning with +/photos+ and route the requests to +PhotosController+: +will recognize incoming paths beginning with +/photos+ and route the requests to +PhotosController+, but use the value of the :as option to name the helpers. -|_.HTTP verb|_.Path |_.action |_.named helper | -|GET |/photos |index | images_path | -|GET |/photos/new |new | new_image_path | -|POST |/photos |create | images_path | -|GET |/photos/1 |show | image_path | -|GET |/photos/1/edit |edit | edit_image_path | -|PUT |/photos/1 |update | image_path | -|DELETE |/photos/1 |destroy | image_path | +|_.HTTP verb|_.Path |_.action |_.named helper | +|GET |/photos |index | images_path | +|GET |/photos/new |new | new_image_path | +|POST |/photos |create | images_path | +|GET |/photos/1 |show | image_path(id) | +|GET |/photos/1/edit |edit | edit_image_path(id) | +|PUT |/photos/1 |update | image_path(id) | +|DELETE |/photos/1 |destroy | image_path(id) | h4. Overriding the +new+ and +edit+ Segments @@ -643,7 +686,7 @@ This would cause the routing to recognize paths such as NOTE: The actual action names aren't changed by this option. The two paths shown would still route to the +new+ and +edit+ actions. -TIP: If you find yourself wanting to change this option uniformly for all of your routes, you can use a scope: +TIP: If you find yourself wanting to change this option uniformly for all of your routes, you can use a scope. <ruby> scope :path_names => { :new => "make" } do @@ -665,7 +708,7 @@ resources :photos This will provide route helpers such as +admin_photos_path+, +new_admin_photo_path+ etc. -To prefix a group of routes, use +:as+ with +scope+: +To prefix a group of route helpers, use +:as+ with +scope+: <ruby> scope "admin", :as => "admin" do @@ -675,11 +718,23 @@ end resources :photos, :accounts </ruby> +This will generate routes such as +admin_photos_path+ and +admin_accounts_path+ which map to +/admin/photos+ and +/admin/accounts+ respectively. + NOTE: The +namespace+ scope will automatically add +:as+ as well as +:module+ and +:path+ prefixes. +You can prefix routes with a named parameter also: + +<ruby> +scope ":username" do + resources :posts +end +</ruby> + +This will provide you with URLs such as +/bob/posts/1+ and will allow you to reference the +username+ part of the path as +params[:username]+ in controllers, helpers and views. + h4. Restricting the Routes Created -By default, Rails creates routes for all seven of the default actions (index, show, new, create, edit, update, and destroy) for every RESTful route in your application. You can use the +:only+ and +:except+ options to fine-tune this behavior. The +:only+ option tells Rails to create only the specified routes: +By default, Rails creates routes for the seven default actions (index, show, new, create, edit, update, and destroy) for every RESTful route in your application. You can use the +:only+ and +:except+ options to fine-tune this behavior. The +:only+ option tells Rails to create only the specified routes: <ruby> resources :photos, :only => [:index, :show] @@ -707,16 +762,16 @@ scope(:path_names => { :new => "neu", :edit => "bearbeiten" }) do end </ruby> -Rails now creates routes to the +CategoriesControlleR+. +Rails now creates routes to the +CategoriesController+. -|_.HTTP verb|_.Path |_.action | -|GET |/kategorien |index | -|GET |/kategorien/neu |new | -|POST |/kategorien |create | -|GET |/kategorien/1 |show | -|GET |/kategorien/:id/bearbeiten |edit | -|PUT |/kategorien/1 |update | -|DELETE |/kategorien/1 |destroy | +|_.HTTP verb|_.Path |_.action |_.named helper | +|GET |/kategorien |index | categories_path | +|GET |/kategorien/neu |new | new_category_path | +|POST |/kategorien |create | categories_path | +|GET |/kategorien/1 |show | category_path(id) | +|GET |/kategorien/1/bearbeiten |edit | edit_category_path(id) | +|PUT |/kategorien/1 |update | category_path(id) | +|DELETE |/kategorien/1 |destroy | category_path(id) | h4. Overriding the Singular Form @@ -765,14 +820,14 @@ formatted_users GET /users.:format {:controller=>"users", :action=>"index"} You may restrict the listing to the routes that map to a particular controller setting the +CONTROLLER+ environment variable: <shell> -$ CONTROLLER=users rake routes +$ CONTROLLER=users rake routes </shell> TIP: You'll find that the output from +rake routes+ is much more readable if you widen your terminal window until the output lines don't wrap. h4. Testing Routes -Routes should be included in your testing strategy (just like the rest of your application). Rails offers three "built-in assertions":http://api.rubyonrails.org/classes/ActionController/Assertions/RoutingAssertions.html designed to make testing routes simpler: +Routes should be included in your testing strategy (just like the rest of your application). Rails offers three "built-in assertions":http://api.rubyonrails.org/classes/ActionDispatch/Assertions/RoutingAssertions.html designed to make testing routes simpler: * +assert_generates+ * +assert_recognizes+ @@ -780,7 +835,7 @@ Routes should be included in your testing strategy (just like the rest of your a h5. The +assert_generates+ Assertion -Use +assert_generates+ to assert that a particular set of options generate a particular path. You can use this with default routes or custom routes ++assert_generates+ asserts that a particular set of options generate a particular path and can be used with default routes or custom routes. <ruby> assert_generates "/photos/1", { :controller => "photos", :action => "show", :id => "1" } @@ -789,7 +844,7 @@ assert_generates "/about", :controller => "pages", :action => "about" h5. The +assert_recognizes+ Assertion -The +assert_recognizes+ assertion is the inverse of +assert_generates+. It asserts that Rails recognizes the given path and routes it to a particular spot in your application. ++assert_recognizes+ is the inverse of +assert_generates+. It asserts that a given path is recognized and routes it to a particular spot in your application. <ruby> assert_recognizes({ :controller => "photos", :action => "show", :id => "1" }, "/photos/1") @@ -801,12 +856,6 @@ You can supply a +:method+ argument to specify the HTTP verb: assert_recognizes({ :controller => "photos", :action => "create" }, { :path => "photos", :method => :post }) </ruby> -You can also use the resourceful helpers to test recognition of a RESTful route: - -<ruby> -assert_recognizes new_photo_url, { :path => "photos", :method => :post } -</ruby> - h5. The +assert_routing+ Assertion The +assert_routing+ assertion checks the route both ways: it tests that the path generates the options, and that the options generate the path. Thus, it combines the functions of +assert_generates+ and +assert_recognizes+. @@ -817,8 +866,6 @@ assert_routing({ :path => "photos", :method => :post }, { :controller => "photos h3. Changelog -"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/3 - * April 10, 2010: Updated guide to remove outdated and superfluous information, and to provide information about new features, by "Yehuda Katz":http://www.yehudakatz.com * April 2, 2010: Updated guide to match new Routing DSL in Rails 3, by "Rizwan Reza":http://www.rizwanreza.com/ * Febuary 1, 2010: Modifies the routing documentation to match new routing DSL in Rails 3, by Prem Sichanugrist diff --git a/railties/guides/source/ruby_on_rails_guides_guidelines.textile b/railties/guides/source/ruby_on_rails_guides_guidelines.textile new file mode 100644 index 0000000000..6576758856 --- /dev/null +++ b/railties/guides/source/ruby_on_rails_guides_guidelines.textile @@ -0,0 +1,83 @@ +h2. Ruby on Rails Guides Guidelines + +This guide documents guidelines for writing guides. This guide follows itself in a gracile loop. + +endprologue. + +h3. Textile + +Guides are written in "Textile":http://www.textism.com/tools/textile/. There's comprehensive documentation "here":http://redcloth.org/hobix.com/textile/ and a cheatsheet for markup "here":http://redcloth.org/hobix.com/textile/quick.html. + +h3. Prologue + +Each guide should start with motivational text at the top. That's the little introduction in the blue area. The prologue should tell the readers what's the guide about, and what will they learn. See for example the "Routing Guide":routing.html. + +h3. Titles + +The title of every guide uses +h2+, guide sections use +h3+, subsections +h4+, etc. + +Capitalize all words except for internal articles, prepositions, conjunctions, and forms of the verb to be: + +<plain> +h5. Middleware Stack is an Array +h5. When are Objects Saved? +</plain> + +Use same typography as in regular text: + +<plain> +h6. The +:content_type+ Option +</plain> + +h3. API Documentation Guidelines + +The guides and the API should be coherent where appropriate. Please have a look at these particular sections of the "API Documentation Guidelines":api_documentation_guidelines.html: + +* "Wording":api_documentation_guidelines.html#wording +* "Example Code":api_documentation_guidelines.html#example-code +* "Filenames":api_documentation_guidelines.html#filenames +* "Fonts":api_documentation_guidelines.html#fonts + +Those guidelines apply also to guides. + +h3. HTML Generation + +To generate all the guides just cd into the +railties+ directory and execute + +<plain> +bundle exec rake generate_guides +</plain> + +You'll need the gems erubis, i18n, and RedCloth. + +To process +my_guide.textile+ and nothing else use the +ONLY+ environment variable: + +<plain> +bundle exec rake generate_guides ONLY=my_guide +</plain> + +Although by default guides that have not been modified are not processed, so +ONLY+ is rarely needed in practice. + +To force process of all the guides, pass +ALL=1+. + +It is also recommended that you work with +WARNINGS=1+, this detects duplicate IDs and warns about broken internal links. + +If you want to generate guides in languages other than English, you can keep them in a separate directory under +source+ (eg. <tt>source/es</tt>) and use the +LANGUAGE+ environment variable. + +<plain> +rake generate_guides LANGUAGE=es +</plain> + +h3. HTML Validation + +Please do validate the generated HTML with + +<plain> +rake validate_guides +</plain> + +Particularly, titles get an ID generated from their content and this often leads to duplicates. Please set +WARNINGS=1+ when generating guides to detect them. The warning messages suggest a way to fix them. + +h3. Changelog + +* October 5, 2010: ported from the docrails wiki and revised by "Xavier Noria":credits.html#fxn diff --git a/railties/guides/source/security.textile b/railties/guides/source/security.textile index 8ce0001080..182f3631ef 100644 --- a/railties/guides/source/security.textile +++ b/railties/guides/source/security.textile @@ -166,7 +166,7 @@ end The section about session fixation introduced the problem of maintained sessions. An attacker maintaining a session every five minutes can keep the session alive forever, although you are expiring sessions. A simple solution for this would be to add a created_at column to the sessions table. Now you can delete sessions that were created a long time ago. Use this line in the sweep method above: <ruby> -delete_all "updated_at < '#{time.to_s(:db)}' OR +delete_all "updated_at < '#{time.ago.to_s(:db)}' OR created_at < '#{2.days.ago.to_s(:db)}'" </ruby> @@ -240,7 +240,7 @@ There are many other possibilities, including Ajax to attack the victim in the b protect_from_forgery :secret => "123456789012345678901234567890..." </ruby> -This will automatically include a security token, calculated from the current session and the server-side secret, in all forms and Ajax requests generated by Rails. You won't need the secret, if you use CookieStorage as session storage. It will raise an ActionController::InvalidAuthenticityToken error, if the security token doesn't match what was expected. +This will automatically include a security token, calculated from the current session and the server-side secret, in all forms and Ajax requests generated by Rails. You won't need the secret, if you use CookieStorage as session storage. If the security token doesn't match what was expected, the session will be reset. *Note:* In Rails versions prior to 3.0.4, this raised an <tt>ActionController::InvalidAuthenticityToken</tt> error. Note that _(highlight)cross-site scripting (XSS) vulnerabilities bypass all CSRF protections_. XSS gives the attacker access to all elements on a page, so he can read the CSRF security token from a form or directly submit the form. Read <a href="#cross-site-scripting-xss">more about XSS</a> later. @@ -282,7 +282,7 @@ h4. File Uploads Many web applications allow users to upload files. _(highlight)File names, which the user may choose (partly), should always be filtered_ as an attacker could use a malicious file name to overwrite any file on the server. If you store file uploads at /var/www/uploads, and the user enters a file name like “../../../etc/passwd”, it may overwrite an important file. Of course, the Ruby interpreter would need the appropriate permissions to do so – one more reason to run web servers, database servers and other programs as a less privileged Unix user. -When filtering user input file names, _(highlight)don't try to remove malicious parts_. Think of a situation where the web application removes all “../” in a file name and an attacker uses a string such as “....//” - the result will be “../”. It is best to use a whitelist approach, which _(highlight)checks for the validity of a file name with a set of accepted characters_. This is opposed to a blacklist approach which attempts to remove not allowed characters. In case it isn't a valid file name, reject it (or replace not accepted characters), but don't remove them. Here is the file name sanitizer from the "attachment_fu plugin":http://github.com/technoweenie/attachment_fu/tree/master: +When filtering user input file names, _(highlight)don't try to remove malicious parts_. Think of a situation where the web application removes all “../” in a file name and an attacker uses a string such as “....//” - the result will be “../”. It is best to use a whitelist approach, which _(highlight)checks for the validity of a file name with a set of accepted characters_. This is opposed to a blacklist approach which attempts to remove not allowed characters. In case it isn't a valid file name, reject it (or replace not accepted characters), but don't remove them. Here is the file name sanitizer from the "attachment_fu plugin":https://github.com/technoweenie/attachment_fu/tree/master: <ruby> def sanitize_filename(filename) @@ -371,7 +371,7 @@ The mass-assignment feature may become a problem, as it allows an attacker to se <ruby> def signup - params[:user] #=> {:name => “ow3ned”, :admin => true} + params[:user] # => {:name => “ow3ned”, :admin => true} @user = User.new(params[:user]) end </ruby> @@ -385,7 +385,7 @@ Mass-assignment saves you much work, because you don't have to set each value in This will set the following parameters in the controller: <ruby> -params[:user] #=> {:name => “ow3ned”, :admin => true} +params[:user] # => {:name => “ow3ned”, :admin => true} </ruby> So if you create a new user using mass-assignment, it may be too easy to become an administrator. @@ -401,7 +401,7 @@ Note that this vulnerability is not restricted to database columns. Any setter class Child < ActiveRecord::Base belongs_to :person - end + end </ruby> As a result, the vulnerability is extended beyond simply exposing column assignment, allowing attackers the ability to create entirely new records in referenced tables (children in this case). @@ -423,11 +423,11 @@ attr_accessible :name If you want to set a protected attribute, you will to have to assign it individually: <ruby> -params[:user] #=> {:name => "ow3ned", :admin => true} +params[:user] # => {:name => "ow3ned", :admin => true} @user = User.new(params[:user]) -@user.admin #=> false # not mass-assigned +@user.admin # => false # not mass-assigned @user.admin = true -@user.admin #=> true +@user.admin # => true </ruby> A more paranoid technique to protect your whole project would be to enforce that all models whitelist their accessible attributes. This can be easily achieved with a very simple initializer: @@ -524,10 +524,10 @@ h4. Logging -- _Tell Rails not to put passwords in the log files._ -By default, Rails logs all requests being made to the web application. But log files can be a huge security issue, as they may contain login credentials, credit card numbers et cetera. When designing a web application security concept, you should also think about what will happen if an attacker got (full) access to the web server. Encrypting secrets and passwords in the database will be quite useless, if the log files list them in clear text. You can _(highlight)filter certain request parameters from your log files_ by the filter_parameter_logging method in a controller. These parameters will be marked [FILTERED] in the log. +By default, Rails logs all requests being made to the web application. But log files can be a huge security issue, as they may contain login credentials, credit card numbers et cetera. When designing a web application security concept, you should also think about what will happen if an attacker got (full) access to the web server. Encrypting secrets and passwords in the database will be quite useless, if the log files list them in clear text. You can _(highlight)filter certain request parameters from your log files_ by appending them to <tt>config.filter_parameters</tt> in the application configuration. These parameters will be marked [FILTERED] in the log. <ruby> -filter_parameter_logging :password +config.filter_parameters << :password </ruby> h4. Good Passwords @@ -550,7 +550,7 @@ Ruby uses a slightly different approach than many other languages to match the e <ruby> class File < ActiveRecord::Base - validates_format_of :name, :with => /^[\w\.\-\+]+$/ + validates :name, :format => /^[\w\.\-\+]+$/ end </ruby> @@ -616,7 +616,7 @@ h5(#sql-injection-introduction). Introduction SQL injection attacks aim at influencing database queries by manipulating web application parameters. A popular goal of SQL injection attacks is to bypass authorization. Another goal is to carry out data manipulation or reading arbitrary data. Here is an example of how not to use user input data in a query: <ruby> -Project.find(:all, :conditions => "name = '#{params[:name]}'") +Project.all(:conditions => "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: @@ -632,7 +632,7 @@ h5. Bypassing Authorization Usually a web application includes access control. The user enters his login credentials, the web application tries to find the matching record in the users table. The application grants access when it finds a record. However, an attacker may possibly bypass this check with SQL injection. The following shows a typical database query in Rails to find the first record in the users table which matches the login credentials parameters supplied by the user. <ruby> -User.find(:first, "login = '#{params[:name]}' AND password = '#{params[:password]}'") +User.first("login = '#{params[:name]}' AND password = '#{params[:password]}'") </ruby> If an attacker enters ' OR '1'='1 as the name, and ' OR '2'>'1 as the password, the resulting SQL query will be: @@ -648,7 +648,7 @@ h5. Unauthorized Reading The UNION statement connects two SQL queries and returns the data in one set. An attacker can use it to read arbitrary data from the database. Let's take the example from above: <ruby> -Project.find(:all, :conditions => "name = '#{params[:name]}'") +Project.all(:conditions => "name = '#{params[:name]}'") </ruby> And now let's inject another query using the UNION statement: @@ -675,13 +675,13 @@ Ruby on Rails has a built-in filter for special SQL characters, which will escap Instead of passing a string to the conditions option, you can pass an array to sanitize tainted strings like this: <ruby> -Model.find(:first, :conditions => ["login = ? AND password = ?", entered_user_name, entered_password]) +Model.first(:conditions => ["login = ? AND password = ?", entered_user_name, entered_password]) </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.find(:first, :conditions => {:login => entered_user_name, :password => entered_password}) +Model.first(:conditions => {:login => entered_user_name, :password => entered_password}) </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_. @@ -979,6 +979,4 @@ The security landscape shifts and it is important to keep up to date, because mi h3. Changelog -"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/7 - * November 1, 2008: First approved version by Heiko Webers diff --git a/railties/guides/source/testing.textile b/railties/guides/source/testing.textile index 69695c93c8..4ebdb3edf6 100644 --- a/railties/guides/source/testing.textile +++ b/railties/guides/source/testing.textile @@ -182,21 +182,27 @@ class PostTest < ActiveSupport::TestCase The +PostTest+ class defines a _test case_ because it inherits from +ActiveSupport::TestCase+. +PostTest+ thus has all the methods available from +ActiveSupport::TestCase+. You'll see those methods a little later in this guide. -<ruby> -def test_truth -</ruby> - Any method defined within a +Test::Unit+ test case that begins with +test+ (case sensitive) is simply called a test. So, +test_password+, +test_valid_password+ and +testValidPassword+ all are legal test names and are run automatically when the test case is run. -Rails adds a +test+ method that takes a test name and a block. It generates a normal +Test::Unit+ test with method names prefixed with +test_+. +Rails adds a +test+ method that takes a test name and a block. It generates a normal +Test::Unit+ test with method names prefixed with +test_+. So, <ruby> test "the truth" do - # ... + assert true end </ruby> -This makes test names more readable by replacing underscores with regular language. +acts as if you had written + +<ruby> +def test_the_truth + assert true +end +</ruby> + +only the +test+ macro allows a more readable test name. You can still use regular method definitions though. + +NOTE: The method name is generated by replacing spaces with underscores. The result does not need to be a valid Ruby identifier though, the name may contain punctuation characters etc. That's because in Ruby technically any string may be a method name. Odd ones need +define_method+ and +send+ calls, but formally there's no restriction. <ruby> assert true @@ -223,13 +229,13 @@ $ rake db:test:load Above +rake db:migrate+ runs any pending migrations on the _development_ environment and updates +db/schema.rb+. +rake db:test:load+ recreates the test database from the current +db/schema.rb+. On subsequent attempts, it is a good idea to first run +db:test:prepare+, as it first checks for pending migrations and warns you appropriately. -NOTE: +db:test:prepare+ will fail with an error if +db/schema.rb+ doesn't exists. +NOTE: +db:test:prepare+ will fail with an error if +db/schema.rb+ doesn't exist. h5. Rake Tasks for Preparing your Application for Testing |_.Tasks |_.Description| |+rake db:test:clone+ |Recreate the test database from the current environment's database schema| -|+rake db:test:clone_structure+ |Recreate the test databases from the development structure| +|+rake db:test:clone_structure+ |Recreate the test database from the development structure| |+rake db:test:load+ |Recreate the test database from the current +schema.rb+| |+rake db:test:prepare+ |Check for pending migrations and load the test schema| |+rake db:test:purge+ |Empty the test database.| @@ -241,8 +247,7 @@ h4. Running Tests Running a test is as simple as invoking the file containing the test cases through Ruby: <shell> -$ cd test -$ ruby unit/post_test.rb +$ ruby -Itest test/unit/post_test.rb Loaded suite unit/post_test Started @@ -252,12 +257,12 @@ Finished in 0.023513 seconds. 1 tests, 1 assertions, 0 failures, 0 errors </shell> -This will run all the test methods from the test case. +This will run all the test methods from the test case. Note that +test_helper.rb+ is in the +test+ directory, hence this directory needs to be added to the load path using the +-I+ switch. You can also run a particular test method from the test case by using the +-n+ switch with the +test method name+. <shell> -$ ruby unit/post_test.rb -n test_truth +$ ruby -Itest test/unit/post_test.rb -n test_the_truth Loaded suite unit/post_test Started @@ -316,7 +321,7 @@ Now to get this test to pass we can add a model level validation for the _title_ <ruby> class Post < ActiveRecord::Base - validates_presence_of :title + validates :title, :presence => true end </ruby> @@ -381,7 +386,7 @@ There are a bunch of different types of assertions you can use. Here's the compl |+assert( boolean, [msg] )+ |Ensures that the object/expression is true.| |+assert_equal( obj1, obj2, [msg] )+ |Ensures that +obj1 == obj2+ is true.| |+assert_not_equal( obj1, obj2, [msg] )+ |Ensures that +obj1 == obj2+ is false.| -|+assert_same( obj1, obj2, [msg] )+ |Ensures that +obj1.equal?(obj2)+ is true.| +|+assert_same( obj1, obj2, [msg] )+ |Ensures that +obj1.equal?(obj2)+ is true.| |+assert_not_same( obj1, obj2, [msg] )+ |Ensures that +obj1.equal?(obj2)+ is false.| |+assert_nil( obj, [msg] )+ |Ensures that +obj.nil?+ is true.| |+assert_not_nil( obj, [msg] )+ |Ensures that +obj.nil?+ is false.| @@ -389,7 +394,7 @@ There are a bunch of different types of assertions you can use. Here's the compl |+assert_no_match( regexp, string, [msg] )+ |Ensures that a string doesn't matches the regular expression.| |+assert_in_delta( expecting, actual, delta, [msg] )+ |Ensures that the numbers +expecting+ and +actual+ are within +delta+ of each other.| |+assert_throws( symbol, [msg] ) { block }+ |Ensures that the given block throws the symbol.| -|+assert_raise( exception1, exception2, ... ) { block }+ |Ensures that the given block raises one of the given exceptions.| +|+assert_raise( exception1, exception2, ... ) { block }+ |Ensures that the given block raises one of the given exceptions.| |+assert_nothing_raised( exception1, exception2, ... ) { block }+ |Ensures that the given block doesn't raise one of the given exceptions.| |+assert_instance_of( class, obj, [msg] )+ |Ensures that +obj+ is of the +class+ type.| |+assert_kind_of( class, obj, [msg] )+ |Ensures that +obj+ is or descends from +class+.| @@ -495,6 +500,8 @@ If you're familiar with the HTTP protocol, you'll know that +get+ is a type of r All of request types are methods that you can use, however, you'll probably end up using the first two more often than the others. +NOTE: Functional tests do not verify whether the specified request type should be accepted by the action. Request types in this context exist to make your tests more descriptive. + h4. The Four Hashes of the Apocalypse After a request has been made by using one of the 5 methods (+get+, +post+, etc.) and processed, you will have 4 Hash objects ready for use: @@ -507,12 +514,12 @@ After a request has been made by using one of the 5 methods (+get+, +post+, etc. As is the case with normal Hash objects, you can access the values by referencing the keys by string. You can also reference them by symbol name, except for +assigns+. For example: <ruby> - flash["gordon"] flash[:gordon] - session["shmession"] session[:shmession] - cookies["are_good_for_u"] cookies[:are_good_for_u] +flash["gordon"] flash[:gordon] +session["shmession"] session[:shmession] +cookies["are_good_for_u"] cookies[:are_good_for_u] # Because you can't use assigns[:something] for historical reasons: - assigns["something"] assigns(:something) +assigns["something"] assigns(:something) </ruby> h4. Instance Variables Available @@ -577,7 +584,7 @@ assert_select "ol" do end </ruby> -The +assert_select+ assertion is quite powerful. For more advanced usage, refer to its "documentation":http://api.rubyonrails.org/classes/ActionController/Assertions/SelectorAssertions.html. +The +assert_select+ assertion is quite powerful. For more advanced usage, refer to its "documentation":http://api.rubyonrails.org/classes/ActionDispatch/Assertions/SelectorAssertions.html. h5. Additional View-Based Assertions @@ -614,7 +621,7 @@ Here's what a freshly-generated integration test looks like: <ruby> require 'test_helper' -class UserFlowsTest < ActionController::IntegrationTest +class UserFlowsTest < ActionDispatch::IntegrationTest fixtures :all # Replace this with your real tests. @@ -624,7 +631,7 @@ class UserFlowsTest < ActionController::IntegrationTest end </ruby> -Integration tests inherit from +ActionController::IntegrationTest+. This makes available some additional helpers to use in your integration tests. Also you need to explicitly include the fixtures to be made available to the test. +Integration tests inherit from +ActionDispatch::IntegrationTest+. This makes available some additional helpers to use in your integration tests. Also you need to explicitly include the fixtures to be made available to the test. h4. Helpers Available for Integration Tests @@ -650,7 +657,7 @@ A simple integration test that exercises multiple controllers: <ruby> require 'test_helper' -class UserFlowsTest < ActionController::IntegrationTest +class UserFlowsTest < ActionDispatch::IntegrationTest fixtures :users test "login and browse site" do @@ -678,7 +685,7 @@ Here's an example of multiple sessions and custom DSL in an integration test <ruby> require 'test_helper' -class UserFlowsTest < ActionController::IntegrationTest +class UserFlowsTest < ActionDispatch::IntegrationTest fixtures :users test "login and browse site" do @@ -735,7 +742,7 @@ You don't need to set up and run your tests by hand on a test-by-test basis. Rai |+rake test:plugins+ |Run all the plugin tests from +vendor/plugins/*/**/test+ (or specify with +PLUGIN=_name_+)| |+rake test:profile+ |Profile the performance tests| |+rake test:recent+ |Tests recent changes| -|+rake test:uncommitted+ |Runs all the tests which are uncommitted. Only supports Subversion| +|+rake test:uncommitted+ |Runs all the tests which are uncommitted. Supports Subversion and Git| |+rake test:units+ |Runs all the unit tests from +test/unit+| @@ -934,15 +941,13 @@ h3. Other Testing Approaches The built-in +test/unit+ based testing is not the only way to test Rails applications. Rails developers have come up with a wide variety of other approaches and aids for testing, including: * "NullDB":http://avdi.org/projects/nulldb/, a way to speed up testing by avoiding database use. -* "Factory Girl":http://github.com/thoughtbot/factory_girl/tree/master, as replacement for fixtures. -* "Machinist":http://github.com/notahat/machinist/tree/master, another replacement for fixtures. +* "Factory Girl":https://github.com/thoughtbot/factory_girl/tree/master, as replacement for fixtures. +* "Machinist":https://github.com/notahat/machinist/tree/master, another replacement for fixtures. * "Shoulda":http://www.thoughtbot.com/projects/shoulda, an extension to +test/unit+ with additional helpers, macros, and assertions. * "RSpec":http://rspec.info/, a behavior-driven development framework h3. Changelog -"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/8 - * April 4, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com * November 13, 2008: Revised based on feedback from Pratik Naik by "Akshay Surve":credits.html#asurve (not yet approved for publication) * October 14, 2008: Edit and formatting pass by "Mike Gunderloy":credits.html#mgunderloy (not yet approved for publication) diff --git a/railties/guides/w3c_validator.rb b/railties/guides/w3c_validator.rb index 4da48bf3fb..f1fe1e0f33 100644 --- a/railties/guides/w3c_validator.rb +++ b/railties/guides/w3c_validator.rb @@ -21,7 +21,7 @@ # # Separate many using commas: # -# # validates only +# # validates only association_basics.html and migrations.html # ONLY=assoc,migrations rake validate_guides # # --------------------------------------------------------------------------- @@ -32,13 +32,13 @@ include W3CValidators module RailsGuides class Validator - + def validate validator = MarkupValidator.new STDOUT.sync = true errors_on_guides = {} - guides_to_validate.each do |f| + guides_to_validate.each do |f| results = validator.validate_file(f) if results.validity @@ -48,10 +48,10 @@ module RailsGuides errors_on_guides[f] = results.errors end end - + show_results(errors_on_guides) end - + private def guides_to_validate guides = Dir["./guides/output/*.html"] @@ -65,13 +65,13 @@ module RailsGuides prefixes.any? {|p| guide.start_with?("./guides/output/#{p}")} end end - + def show_results(error_list) if error_list.size == 0 puts "\n\nAll checked guides validate OK!" else error_summary = error_detail = "" - + error_list.each_pair do |name, errors| error_summary += "\n #{name}" error_detail += "\n\n #{name} has #{errors.size} validation error(s):\n" @@ -79,13 +79,13 @@ module RailsGuides error_detail += "\n "+error.to_s.gsub("\n", "") end end - + puts "\n\nThere are #{error_list.size} guides with validation errors:\n" + error_summary puts "\nHere are the detailed errors for each guide:" + error_detail end end - + end end -RailsGuides::Validator.new.validate
\ No newline at end of file +RailsGuides::Validator.new.validate diff --git a/railties/lib/rails.rb b/railties/lib/rails.rb index bbf28a8c08..cca0891835 100644 --- a/railties/lib/rails.rb +++ b/railties/lib/rails.rb @@ -8,7 +8,6 @@ require 'active_support/core_ext/logger' require 'rails/application' require 'rails/version' -require 'rails/deprecation' require 'active_support/railtie' require 'action_dispatch/railtie' @@ -93,12 +92,7 @@ module Rails end def public_path - application && application.paths.public.to_a.first - end - - def public_path=(path) - ActiveSupport::Deprecation.warn "Setting Rails.public_path= is deprecated. " << - "Please set paths.public = in config/application.rb instead.", caller + application && application.paths["public"].first end end end diff --git a/railties/lib/rails/application.rb b/railties/lib/rails/application.rb index 5b26333486..94819820bc 100644 --- a/railties/lib/rails/application.rb +++ b/railties/lib/rails/application.rb @@ -35,30 +35,12 @@ module Rails # class Application < Engine autoload :Bootstrap, 'rails/application/bootstrap' - autoload :Configurable, 'rails/application/configurable' autoload :Configuration, 'rails/application/configuration' autoload :Finisher, 'rails/application/finisher' autoload :Railties, 'rails/application/railties' + autoload :RoutesReloader, 'rails/application/routes_reloader' class << self - private :new - - def configure(&block) - class_eval(&block) - end - - def instance - if self == Rails::Application - if Rails.application - ActiveSupport::Deprecation.warn "Calling a method in Rails::Application is deprecated, " << - "please call it directly in your application constant #{Rails.application.class.name}.", caller - end - Rails.application - else - @@instance ||= new - end - end - def inherited(base) raise "You cannot have more than one Rails::Application" if Rails.application super @@ -66,19 +48,9 @@ module Rails Rails.application.add_lib_to_load_path! ActiveSupport.run_load_hooks(:before_configuration, base.instance) end - - def respond_to?(*args) - super || instance.respond_to?(*args) - end - - protected - - def method_missing(*args, &block) - instance.send(*args, &block) - end end - delegate :middleware, :to => :config + delegate :default_url_options, :default_url_options=, :to => :routes # This method is called just after an application inherits from Rails::Application, # allowing the developer to load classes in lib and use them during application @@ -99,7 +71,7 @@ module Rails end def require_environment! #:nodoc: - environment = paths.config.environment.to_a.first + environment = paths["config/environment"].existent.first require environment if environment end @@ -108,30 +80,18 @@ module Rails super end - def routes - @routes ||= ActionDispatch::Routing::RouteSet.new - end - - def railties - @railties ||= Railties.new(config) + def reload_routes! + routes_reloader.reload! end def routes_reloader - @routes_reloader ||= ActiveSupport::FileUpdateChecker.new([]){ reload_routes! } - end - - def reload_routes! - _routes = self.routes - _routes.disable_clear_and_finalize = true - _routes.clear! - routes_reloader.paths.each { |path| load(path) } - ActiveSupport.on_load(:action_controller) { _routes.finalize! } - ensure - _routes.disable_clear_and_finalize = false + @routes_reloader ||= RoutesReloader.new end def initialize! + raise "Application has been already initialized." if @initialized run_initializers(self) + @initialized = true self end @@ -156,45 +116,52 @@ module Rails self end - def app - @app ||= begin - config.middleware = config.middleware.merge_into(default_middleware_stack) - config.middleware.build(routes) - end - end alias :build_middleware_stack :app - def call(env) - app.call(env.reverse_merge!(env_defaults)) - end - - def env_defaults - @env_defaults ||= { + def env_config + @env_config ||= super.merge({ "action_dispatch.parameter_filter" => config.filter_parameters, - "action_dispatch.secret_token" => config.secret_token - } + "action_dispatch.secret_token" => config.secret_token, + "action_dispatch.asset_path" => nil, + "action_dispatch.show_exceptions" => config.action_dispatch.show_exceptions + }) end def initializers - initializers = Bootstrap.initializers_for(self) - railties.all { |r| initializers += r.initializers } - initializers += super - initializers += Finisher.initializers_for(self) - initializers + Bootstrap.initializers_for(self) + + super + + Finisher.initializers_for(self) + end + + def config + @config ||= Application::Configuration.new(find_root_with_flag("config.ru", Dir.pwd)) end protected + def default_asset_path + nil + end + def default_middleware_stack ActionDispatch::MiddlewareStack.new.tap do |middleware| - middleware.use ::ActionDispatch::Static, paths.public.to_a.first if config.serve_static_assets - middleware.use ::Rack::Lock if !config.allow_concurrency + rack_cache = config.action_controller.perform_caching && config.action_dispatch.rack_cache + + require "action_dispatch/http/rack_cache" if rack_cache + middleware.use ::Rack::Cache, rack_cache if rack_cache + + if config.serve_static_assets + asset_paths = ActiveSupport::OrderedHash[config.static_asset_paths.to_a.reverse] + middleware.use ::ActionDispatch::Static, asset_paths + end + middleware.use ::Rack::Lock unless config.allow_concurrency middleware.use ::Rack::Runtime middleware.use ::Rails::Rack::Logger - middleware.use ::ActionDispatch::ShowExceptions, config.consider_all_requests_local if config.action_dispatch.show_exceptions + middleware.use ::ActionDispatch::ShowExceptions, config.consider_all_requests_local middleware.use ::ActionDispatch::RemoteIp, config.action_dispatch.ip_spoofing_check, config.action_dispatch.trusted_proxies middleware.use ::Rack::Sendfile, config.action_dispatch.x_sendfile_header - middleware.use ::ActionDispatch::Callbacks, !config.cache_classes + middleware.use ::ActionDispatch::Reloader unless config.cache_classes + middleware.use ::ActionDispatch::Callbacks middleware.use ::ActionDispatch::Cookies if config.session_store @@ -205,6 +172,8 @@ module Rails middleware.use ::ActionDispatch::ParamsParser middleware.use ::Rack::MethodOverride middleware.use ::ActionDispatch::Head + middleware.use ::Rack::ConditionalGet + middleware.use ::Rack::ETag, "no-cache" middleware.use ::ActionDispatch::BestStandardsSupport, config.action_dispatch.best_standards_support if config.action_dispatch.best_standards_support end end diff --git a/railties/lib/rails/application/bootstrap.rb b/railties/lib/rails/application/bootstrap.rb index 44e26b5713..9c9d85eed6 100644 --- a/railties/lib/rails/application/bootstrap.rb +++ b/railties/lib/rails/application/bootstrap.rb @@ -6,10 +6,7 @@ module Rails module Bootstrap include Initializable - initializer :load_environment_config do - environment = config.paths.config.environments.to_a.first - require environment if environment - end + initializer :load_environment_hook do end initializer :load_active_support do require 'active_support/dependencies' @@ -26,7 +23,7 @@ module Rails # Initialize the logger early in the stack in case we need to log some deprecation. initializer :initialize_logger do Rails.logger ||= config.logger || begin - path = config.paths.log.to_a.first + path = config.paths["log"].first logger = ActiveSupport::BufferedLogger.new(path) logger.level = ActiveSupport::BufferedLogger.const_get(config.log_level.to_s.upcase) logger.auto_flushing = false if Rails.env.production? @@ -54,11 +51,9 @@ module Rails end initializer :set_clear_dependencies_hook do - unless config.cache_classes - ActionDispatch::Callbacks.after do - ActiveSupport::DescendantsTracker.clear - ActiveSupport::Dependencies.clear - end + ActionDispatch::Reloader.to_cleanup do + ActiveSupport::DescendantsTracker.clear + ActiveSupport::Dependencies.clear end end @@ -73,4 +68,4 @@ module Rails end end end -end
\ No newline at end of file +end diff --git a/railties/lib/rails/application/configurable.rb b/railties/lib/rails/application/configurable.rb deleted file mode 100644 index f598e33965..0000000000 --- a/railties/lib/rails/application/configurable.rb +++ /dev/null @@ -1,19 +0,0 @@ -module Rails - class Application - module Configurable - def self.included(base) - base.extend ClassMethods - end - - module ClassMethods - def inherited(base) - raise "You cannot inherit from a Rails::Application child" - end - end - - def config - @config ||= Application::Configuration.new(self.class.find_root_with_flag("config.ru", Dir.pwd)) - end - end - end -end
\ No newline at end of file diff --git a/railties/lib/rails/application/configuration.rb b/railties/lib/rails/application/configuration.rb index 465851c0e6..c74bcbedf2 100644 --- a/railties/lib/rails/application/configuration.rb +++ b/railties/lib/rails/application/configuration.rb @@ -1,31 +1,37 @@ -require 'active_support/deprecation' require 'active_support/core_ext/string/encoding' require 'rails/engine/configuration' module Rails class Application class Configuration < ::Rails::Engine::Configuration - include ::Rails::Configuration::Deprecated - - attr_accessor :allow_concurrency, :cache_classes, :cache_store, + attr_accessor :allow_concurrency, :asset_host, :cache_classes, :cache_store, :encoding, :consider_all_requests_local, :dependency_loading, - :filter_parameters, :log_level, :logger, :middleware, - :plugins, :preload_frameworks, :reload_plugins, + :filter_parameters, :helpers_paths, :logger, + :preload_frameworks, :reload_plugins, :secret_token, :serve_static_assets, :session_options, :time_zone, :whiny_nils + attr_writer :log_level + def initialize(*) super - @allow_concurrency = false + self.encoding = "utf-8" + @allow_concurrency = false @consider_all_requests_local = false - @encoding = "utf-8" - @filter_parameters = [] - @dependency_loading = true - @serve_static_assets = true - @session_store = :cookie_store - @session_options = {} - @time_zone = "UTC" - @middleware = app_middleware + @filter_parameters = [] + @helpers_paths = [] + @dependency_loading = true + @serve_static_assets = true + @session_store = :cookie_store + @session_options = {} + @time_zone = "UTC" + @log_level = nil + @middleware = app_middleware + @generators = app_generators + end + + def compiled_asset_path + "/" end def encoding=(value) @@ -45,23 +51,12 @@ module Rails def paths @paths ||= begin paths = super - paths.app.controllers << builtin_controller if builtin_controller - paths.config.database "config/database.yml" - paths.config.environment "config/environment.rb" - paths.config.environments "config/environments", :glob => "#{Rails.env}.rb" - paths.lib.templates "lib/templates" - paths.log "log/#{Rails.env}.log" - paths.tmp "tmp" - paths.tmp.cache "tmp/cache" - paths.vendor "vendor", :load_path => true - paths.vendor.plugins "vendor/plugins" - - if File.exists?("#{root}/test/mocks/#{Rails.env}") - ActiveSupport::Deprecation.warn "\"Rails.root/test/mocks/#{Rails.env}\" won't be added " << - "automatically to load paths anymore in future releases" - paths.mocks_path "test/mocks", :autoload => true, :glob => Rails.env - end - + paths.add "config/database", :with => "config/database.yml" + paths.add "config/environment", :with => "config/environment.rb" + paths.add "lib/templates" + paths.add "log", :with => "log/#{Rails.env}.log" + paths.add "tmp" + paths.add "tmp/cache" paths end end @@ -83,7 +78,7 @@ module Rails # YAML::load. def database_configuration require 'erb' - YAML::load(ERB.new(IO.read(paths.config.database.to_a.first)).result) + YAML::load(ERB.new(IO.read(paths["config/database"].first)).result) end def cache_store @@ -96,10 +91,6 @@ module Rails end end - def builtin_controller - File.expand_path('../info_routes', __FILE__) if Rails.env.development? - end - def log_level @log_level ||= Rails.env.production? ? :info : :debug end diff --git a/railties/lib/rails/application/finisher.rb b/railties/lib/rails/application/finisher.rb index 855467227b..a45b61c99c 100644 --- a/railties/lib/rails/application/finisher.rb +++ b/railties/lib/rails/application/finisher.rb @@ -4,7 +4,7 @@ module Rails include Initializable initializer :add_generator_templates do - config.generators.templates.unshift(*paths.lib.templates.to_a) + config.generators.templates.unshift(*paths["lib/templates"].existent) end initializer :ensure_autoload_once_paths_as_subset do @@ -21,13 +21,15 @@ module Rails initializer :add_to_prepare_blocks do config.to_prepare_blocks.each do |block| - ActionDispatch::Callbacks.to_prepare(&block) + ActionDispatch::Reloader.to_prepare(&block) end end initializer :add_builtin_route do |app| if Rails.env.development? - app.routes_reloader.paths << File.expand_path('../../info_routes.rb', __FILE__) + app.routes.append do + match '/rails/info/properties' => "rails/info#properties" + end end end @@ -35,6 +37,10 @@ module Rails build_middleware_stack end + initializer :run_prepare_callbacks do + ActionDispatch::Reloader.prepare! + end + initializer :eager_load! do if config.cache_classes && !$rails_rake_task ActiveSupport.run_load_hooks(:before_eager_load, self) @@ -46,6 +52,13 @@ module Rails ActiveSupport.run_load_hooks(:after_initialize, self) end + # Force routes to be loaded just at the end and add it to to_prepare callbacks + initializer :set_routes_reloader do |app| + reloader = lambda { app.routes_reloader.execute_if_updated } + reloader.call + ActionDispatch::Reloader.to_prepare(&reloader) + end + # Disable dependency loading during request cycle initializer :disable_dependency_loading do if config.cache_classes && !config.dependency_loading diff --git a/railties/lib/rails/application/railties.rb b/railties/lib/rails/application/railties.rb index b3e6693f89..4fc5e92837 100644 --- a/railties/lib/rails/application/railties.rb +++ b/railties/lib/rails/application/railties.rb @@ -1,31 +1,13 @@ -module Rails - class Application - class Railties - # TODO Write tests for this behavior extracted from Application - def initialize(config) - @config = config - end +require 'rails/engine/railties' +module Rails + class Application < Engine + class Railties < Rails::Engine::Railties def all(&block) - @all ||= railties + engines + plugins + @all ||= railties + engines + super @all.each(&block) if block @all end - - def railties - @railties ||= ::Rails::Railtie.subclasses.map(&:new) - end - - def engines - @engines ||= ::Rails::Engine.subclasses.map(&:new) - end - - def plugins - @plugins ||= begin - plugin_names = (@config.plugins || [:all]).map { |p| p.to_sym } - Plugin.all(plugin_names, @config.paths.vendor.plugins) - end - end end end -end
\ No newline at end of file +end diff --git a/railties/lib/rails/application/routes_reloader.rb b/railties/lib/rails/application/routes_reloader.rb new file mode 100644 index 0000000000..1d1f5e1b06 --- /dev/null +++ b/railties/lib/rails/application/routes_reloader.rb @@ -0,0 +1,45 @@ +module Rails + class Application + class RoutesReloader < ::ActiveSupport::FileUpdateChecker + attr_reader :route_sets + + def initialize + super([]) { reload! } + @route_sets = [] + end + + def reload! + clear! + load_paths + finalize! + ensure + revert + end + + protected + + def clear! + route_sets.each do |routes| + routes.disable_clear_and_finalize = true + routes.clear! + end + end + + def load_paths + paths.each { |path| load(path) } + end + + def finalize! + route_sets.each do |routes| + ActiveSupport.on_load(:action_controller) { routes.finalize! } + end + end + + def revert + route_sets.each do |routes| + routes.disable_clear_and_finalize = false + end + end + end + end +end diff --git a/railties/lib/rails/backtrace_cleaner.rb b/railties/lib/rails/backtrace_cleaner.rb index bedefaa51c..36fd9aea19 100644 --- a/railties/lib/rails/backtrace_cleaner.rb +++ b/railties/lib/rails/backtrace_cleaner.rb @@ -22,7 +22,7 @@ module Rails gems_paths = (Gem.path + [Gem.default_dir]).uniq.map!{ |p| Regexp.escape(p) } return if gems_paths.empty? - gems_regexp = %r{(#{gems_paths.join('|')})/gems/([^/]+)-([\w\.]+)/(.*)} + gems_regexp = %r{(#{gems_paths.join('|')})/gems/([^/]+)-([\w.]+)/(.*)} add_filter { |line| line.sub(gems_regexp, '\2 (\3) \4') } end end diff --git a/railties/lib/rails/cli.rb b/railties/lib/rails/cli.rb index d49431919d..443d6f47ad 100644 --- a/railties/lib/rails/cli.rb +++ b/railties/lib/rails/cli.rb @@ -1,12 +1,16 @@ require 'rbconfig' require 'rails/script_rails_loader' +# If we are inside a Rails application this method performs an exec and thus +# the rest of this script is not run. Rails::ScriptRailsLoader.exec_script_rails! -railties_path = File.expand_path('../../lib', __FILE__) -$:.unshift(railties_path) if File.directory?(railties_path) && !$:.include?(railties_path) - require 'rails/ruby_version_check' -Signal.trap("INT") { puts; exit } +Signal.trap("INT") { puts; exit(1) } -require 'rails/commands/application' +if ARGV.first == 'plugin' + ARGV.shift + require 'rails/commands/plugin_new' +else + require 'rails/commands/application' +end diff --git a/railties/lib/rails/code_statistics.rb b/railties/lib/rails/code_statistics.rb index 740d8a1767..40416dd83a 100644 --- a/railties/lib/rails/code_statistics.rb +++ b/railties/lib/rails/code_statistics.rb @@ -12,7 +12,7 @@ class CodeStatistics #:nodoc: print_header @pairs.each { |pair| print_line(pair.first, @statistics[pair.first]) } print_splitter - + if @total print_line("Total", @total) print_splitter @@ -23,13 +23,13 @@ class CodeStatistics #:nodoc: private def calculate_statistics - @pairs.inject({}) { |stats, pair| stats[pair.first] = calculate_directory_statistics(pair.last); stats } + Hash[@pairs.map{|pair| [pair.first, calculate_directory_statistics(pair.last)]}] end def calculate_directory_statistics(directory, pattern = /.*\.rb$/) stats = { "lines" => 0, "codelines" => 0, "classes" => 0, "methods" => 0 } - Dir.foreach(directory) do |file_name| + Dir.foreach(directory) do |file_name| if File.stat(directory + "/" + file_name).directory? and (/^\./ !~ file_name) newstats = calculate_directory_statistics(directory + "/" + file_name, pattern) stats.each { |k, v| stats[k] += newstats[k] } @@ -85,10 +85,10 @@ class CodeStatistics #:nodoc: start = if TEST_TYPES.include? name "| #{name.ljust(20)} " else - "| #{name.ljust(20)} " + "| #{name.ljust(20)} " end - puts start + + puts start + "| #{statistics["lines"].to_s.rjust(5)} " + "| #{statistics["codelines"].to_s.rjust(5)} " + "| #{statistics["classes"].to_s.rjust(7)} " + diff --git a/railties/lib/rails/commands.rb b/railties/lib/rails/commands.rb index 60a93c9848..02ccdf8060 100644 --- a/railties/lib/rails/commands.rb +++ b/railties/lib/rails/commands.rb @@ -11,7 +11,21 @@ command = ARGV.shift command = aliases[command] || command case command -when 'generate', 'destroy', 'plugin', 'benchmarker', 'profiler' +when 'generate', 'destroy', 'plugin' + if command == 'plugin' && ARGV.first == 'new' + require "rails/commands/plugin_new" + else + require APP_PATH + Rails.application.require_environment! + + if defined?(ENGINE_PATH) && engine = Rails::Engine.find(ENGINE_PATH) + Rails.application = engine + end + + require "rails/commands/#{command}" + end + +when 'benchmarker', 'profiler' require APP_PATH Rails.application.require_environment! require "rails/commands/#{command}" @@ -23,8 +37,15 @@ when 'console' Rails::Console.start(Rails.application) when 'server' + # Change to the application's path if there is no config.ru file in current dir. + # This allows us to run script/rails server from other directories, but still get + # the main config.ru and properly set the tmp directory. + Dir.chdir(File.expand_path('../../', APP_PATH)) unless File.exists?(File.expand_path("config.ru")) + require 'rails/commands/server' Rails::Server.new.tap { |server| + # We need to require application after the server sets environment, + # otherwise the --environment option given to the server won't propagate. require APP_PATH Dir.chdir(Rails.application.root) server.start @@ -41,6 +62,7 @@ when 'application', 'runner' when 'new' puts "Can't initialize a new Rails application within the directory of another, please change to a non-Rails directory first.\n" puts "Type 'rails' for help." + exit(1) when '--version', '-v' ARGV.unshift '--version' @@ -70,4 +92,5 @@ In addition to those, there are: All commands can be run with -h for more information. EOT + exit(1) end diff --git a/railties/lib/rails/commands/application.rb b/railties/lib/rails/commands/application.rb index 47c6752ca3..3b57b925ba 100644 --- a/railties/lib/rails/commands/application.rb +++ b/railties/lib/rails/commands/application.rb @@ -15,4 +15,16 @@ require 'rubygems' if ARGV.include?("--dev") require 'rails/generators' require 'rails/generators/rails/app/app_generator' +module Rails + module Generators + class AppGenerator + # We want to exit on failure to be kind to other libraries + # This is only when accessing via CLI + def self.exit_on_failure? + true + end + end + end +end + Rails::Generators::AppGenerator.start diff --git a/railties/lib/rails/commands/console.rb b/railties/lib/rails/commands/console.rb index 834a120c01..de2f190ad5 100644 --- a/railties/lib/rails/commands/console.rb +++ b/railties/lib/rails/commands/console.rb @@ -48,5 +48,5 @@ end # Has to set the RAILS_ENV before config/application is required if ARGV.first && !ARGV.first.index("-") && env = ARGV.pop # has to pop the env ARGV so IRB doesn't freak - ENV['RAILS_ENV'] = %w(production development test).find { |e| e.index(env) } || env + ENV['RAILS_ENV'] = %w(production development test).detect {|e| e =~ /^#{env}/} || env end diff --git a/railties/lib/rails/commands/dbconsole.rb b/railties/lib/rails/commands/dbconsole.rb index 5bbaf725df..f0d6ea1687 100644 --- a/railties/lib/rails/commands/dbconsole.rb +++ b/railties/lib/rails/commands/dbconsole.rb @@ -1,4 +1,10 @@ require 'erb' + +begin + require 'psych' +rescue LoadError +end + require 'yaml' require 'optparse' require 'rbconfig' @@ -42,7 +48,7 @@ module Rails def find_cmd(*commands) dirs_on_path = ENV['PATH'].to_s.split(File::PATH_SEPARATOR) - commands += commands.map{|cmd| "#{cmd}.exe"} if Config::CONFIG['host_os'] =~ /mswin|mingw/ + commands += commands.map{|cmd| "#{cmd}.exe"} if RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ full_path_command = nil found = commands.detect do |cmd| @@ -74,7 +80,7 @@ module Rails exec(find_cmd('mysql', 'mysql5'), *args) - when "postgresql" + when "postgresql", "postgres" ENV['PGUSER'] = config["username"] if config["username"] ENV['PGHOST'] = config["host"] if config["host"] ENV['PGPORT'] = config["port"].to_s if config["port"] @@ -113,5 +119,5 @@ end # Has to set the RAILS_ENV before config/application is required if ARGV.first && !ARGV.first.index("-") && env = ARGV.first - ENV['RAILS_ENV'] = %w(production development test).find { |e| e.index(env) } || env + ENV['RAILS_ENV'] = %w(production development test).detect {|e| e =~ /^#{env}/} || env end diff --git a/railties/lib/rails/commands/plugin.rb b/railties/lib/rails/commands/plugin.rb index 96b6f9c372..048af7cbef 100644 --- a/railties/lib/rails/commands/plugin.rb +++ b/railties/lib/rails/commands/plugin.rb @@ -58,7 +58,7 @@ class RailsEnvironment else plugin = name_uri_or_plugin end - unless plugin.nil? + if plugin plugin.install else puts "Plugin not found: #{name_uri_or_plugin}" @@ -276,12 +276,11 @@ end require 'optparse' module Commands class Plugin - attr_reader :environment, :script_name, :sources + attr_reader :environment, :script_name def initialize @environment = RailsEnvironment.default @rails_root = RailsEnvironment.default.root @script_name = File.basename($0) - @sources = [] end def environment=(value) @@ -301,8 +300,6 @@ module Commands o.on("-r", "--root=DIR", String, "Set an explicit rails app directory.", "Default: #{@rails_root}") { |rails_root| @rails_root = rails_root; self.environment = RailsEnvironment.new(@rails_root) } - o.on("-s", "--source=URL1,URL2", Array, - "Use the specified plugin repositories instead of the defaults.") { |sources| @sources = sources} o.on("-v", "--verbose", "Turn on verbose output.") { |verbose| $verbose = verbose } o.on("-h", "--help", "Show this help message.") { puts o; exit } @@ -315,8 +312,6 @@ module Commands o.separator "" o.separator "EXAMPLES" - o.separator " Install a plugin:" - o.separator " #{@script_name} plugin install continuous_builder\n" o.separator " Install a plugin from a subversion URL:" o.separator " #{@script_name} plugin install http://dev.rubyonrails.com/svn/rails/plugins/continuous_builder\n" o.separator " Install a plugin from a git URL:" @@ -375,7 +370,7 @@ module Commands "Enables updating but does not add a svn:externals entry.") { |v| @method = :checkout } o.on( "-e", "--export", "Use svn export to grab the plugin.", - "Exports the plugin, allowing you to check it into your local repository. Does not enable updates, or add an svn:externals entry.") { |v| @method = :export } + "Exports the plugin, allowing you to check it into your local repository. Does not enable updates or add an svn:externals entry.") { |v| @method = :export } o.on( "-q", "--quiet", "Suppresses the output from installation.", "Ignored if -v is passed (rails plugin -v install ...)") { |v| @options[:quiet] = true } diff --git a/railties/lib/rails/commands/plugin_new.rb b/railties/lib/rails/commands/plugin_new.rb new file mode 100644 index 0000000000..8baa8ebfd4 --- /dev/null +++ b/railties/lib/rails/commands/plugin_new.rb @@ -0,0 +1,10 @@ +if ARGV.first != "new" + ARGV[0] = "--help" +else + ARGV.shift +end + +require 'rails/generators' +require 'rails/generators/rails/plugin_new/plugin_new_generator' + +Rails::Generators::PluginNewGenerator.start diff --git a/railties/lib/rails/commands/runner.rb b/railties/lib/rails/commands/runner.rb index c43a233bc3..1a91d477ec 100644 --- a/railties/lib/rails/commands/runner.rb +++ b/railties/lib/rails/commands/runner.rb @@ -17,13 +17,13 @@ ARGV.clone.options do |opts| opts.separator "" opts.on("-h", "--help", - "Show this help message.") { $stderr.puts opts; exit } + "Show this help message.") { $stdout.puts opts; exit } - if Config::CONFIG['host_os'] !~ /mswin|mingw/ + if RbConfig::CONFIG['host_os'] !~ /mswin|mingw/ opts.separator "" opts.separator "You can also use runner as a shebang line for your scripts like this:" opts.separator "-------------------------------------------------------------" - opts.separator "#!/usr/bin/env #{File.expand_path($0)}" + opts.separator "#!/usr/bin/env #{File.expand_path($0)} runner" opts.separator "" opts.separator "Product.find(:all).each { |p| p.price *= 2 ; p.save! }" opts.separator "-------------------------------------------------------------" diff --git a/railties/lib/rails/commands/server.rb b/railties/lib/rails/commands/server.rb index c3927b6613..e447209242 100644 --- a/railties/lib/rails/commands/server.rb +++ b/railties/lib/rails/commands/server.rb @@ -42,6 +42,10 @@ module Rails set_environment end + def app + @app ||= super.instance + end + def opt_parser Options.new end diff --git a/railties/lib/rails/configuration.rb b/railties/lib/rails/configuration.rb index e5af12b901..66fab0a760 100644 --- a/railties/lib/rails/configuration.rb +++ b/railties/lib/rails/configuration.rb @@ -1,5 +1,6 @@ require 'active_support/deprecation' require 'active_support/ordered_options' +require 'active_support/core_ext/hash/deep_dup' require 'rails/paths' require 'rails/rack' @@ -51,6 +52,13 @@ module Rails @colorize_logging = true end + def initialize_copy(source) + @aliases = @aliases.deep_dup + @options = @options.deep_dup + @fallbacks = @fallbacks.deep_dup + @templates = @templates.dup + end + def method_missing(method, *args) method = method.to_s.sub(/=$/, '').to_sym @@ -71,86 +79,5 @@ module Rails end end end - - module Deprecated - def frameworks(*args) - raise "config.frameworks in no longer supported. See the generated " \ - "config/boot.rb for steps on how to limit the frameworks that " \ - "will be loaded" - end - alias :frameworks= :frameworks - - def view_path=(value) - ActiveSupport::Deprecation.warn "config.view_path= is deprecated, " << - "please do paths.app.views= instead", caller - paths.app.views = value - end - - def view_path - ActiveSupport::Deprecation.warn "config.view_path is deprecated, " << - "please do paths.app.views instead", caller - paths.app.views.to_a.first - end - - def routes_configuration_file=(value) - ActiveSupport::Deprecation.warn "config.routes_configuration_file= is deprecated, " << - "please do paths.config.routes= instead", caller - paths.config.routes = value - end - - def routes_configuration_file - ActiveSupport::Deprecation.warn "config.routes_configuration_file is deprecated, " << - "please do paths.config.routes instead", caller - paths.config.routes.to_a.first - end - - def database_configuration_file=(value) - ActiveSupport::Deprecation.warn "config.database_configuration_file= is deprecated, " << - "please do paths.config.database= instead", caller - paths.config.database = value - end - - def database_configuration_file - ActiveSupport::Deprecation.warn "config.database_configuration_file is deprecated, " << - "please do paths.config.database instead", caller - paths.config.database.to_a.first - end - - def log_path=(value) - ActiveSupport::Deprecation.warn "config.log_path= is deprecated, " << - "please do paths.log= instead", caller - paths.config.log = value - end - - def log_path - ActiveSupport::Deprecation.warn "config.log_path is deprecated, " << - "please do paths.log instead", caller - paths.config.log.to_a.first - end - - def controller_paths=(value) - ActiveSupport::Deprecation.warn "config.controller_paths= is deprecated, " << - "please do paths.app.controllers= instead", caller - paths.app.controllers = value - end - - def controller_paths - ActiveSupport::Deprecation.warn "config.controller_paths is deprecated, " << - "please do paths.app.controllers instead", caller - paths.app.controllers.to_a.uniq - end - - def cookie_secret=(value) - ActiveSupport::Deprecation.warn "config.cookie_secret= is deprecated, " << - "please use config.secret_token= instead", caller - self.secret_token = value - end - - def cookie_secret - ActiveSupport::Deprecation.warn "config.cookie_secret is deprecated, " << - "please use config.secret_token instead", caller - self.secret_token - end - end end end diff --git a/railties/lib/rails/console/app.rb b/railties/lib/rails/console/app.rb index 9d9763699d..95c74baae2 100644 --- a/railties/lib/rails/console/app.rb +++ b/railties/lib/rails/console/app.rb @@ -26,7 +26,7 @@ end # reloads the environment def reload!(print=true) puts "Reloading..." if print - # This triggers the to_prepare callbacks - ActionDispatch::Callbacks.new(Proc.new {}, false).call({}) + ActionDispatch::Reloader.cleanup! + ActionDispatch::Reloader.prepare! true end diff --git a/railties/lib/rails/deprecation.rb b/railties/lib/rails/deprecation.rb deleted file mode 100644 index 1eb6d804b6..0000000000 --- a/railties/lib/rails/deprecation.rb +++ /dev/null @@ -1,62 +0,0 @@ -require "active_support/string_inquirer" -require "active_support/deprecation" - -RAILS_ROOT = (Class.new(ActiveSupport::Deprecation::DeprecationProxy) do - cattr_accessor :warned - self.warned = false - - def target - Rails.root - end - - def replace(*args) - warn(caller, :replace, *args) - end - - def warn(callstack, called, args) - unless warned - ActiveSupport::Deprecation.warn("RAILS_ROOT is deprecated! Use Rails.root instead", callstack) - self.warned = true - end - end -end).new - -RAILS_ENV = (Class.new(ActiveSupport::Deprecation::DeprecationProxy) do - cattr_accessor :warned - self.warned = false - - def target - Rails.env - end - - def replace(*args) - warn(caller, :replace, *args) - end - - def warn(callstack, called, args) - unless warned - ActiveSupport::Deprecation.warn("RAILS_ENV is deprecated! Use Rails.env instead", callstack) - self.warned = true - end - end -end).new - -RAILS_DEFAULT_LOGGER = (Class.new(ActiveSupport::Deprecation::DeprecationProxy) do - cattr_accessor :warned - self.warned = false - - def target - Rails.logger - end - - def replace(*args) - warn(caller, :replace, *args) - end - - def warn(callstack, called, args) - unless warned - ActiveSupport::Deprecation.warn("RAILS_DEFAULT_LOGGER is deprecated! Use Rails.logger instead", callstack) - self.warned = true - end - end -end).new diff --git a/railties/lib/rails/engine.rb b/railties/lib/rails/engine.rb index ee3e3ba040..4fc23fe277 100644 --- a/railties/lib/rails/engine.rb +++ b/railties/lib/rails/engine.rb @@ -2,21 +2,23 @@ require 'rails/railtie' require 'active_support/core_ext/module/delegation' require 'pathname' require 'rbconfig' +require 'rails/engine/railties' module Rails - # Rails::Engine allows you to wrap a specific Rails application and share it accross - # different applications. Since Rails 3.0, every Rails::Application is nothing - # more than an Engine, allowing you to share it very easily. + # Rails::Engine allows you to wrap a specific Rails application and share it across + # different applications. Since Rails 3.0, every <tt>Rails::Application</tt> is nothing + # more than an engine, allowing you to share it very easily. # - # Any Rails::Engine is also a Rails::Railtie, so the same methods (like rake_tasks and - # generators) and configuration available in the latter can also be used in the former. + # Any <tt>Rails::Engine</tt> is also a <tt>Rails::Railtie</tt>, so the same methods + # (like <tt>rake_tasks</tt> and +generators+) and configuration available in the + # latter can also be used in the former. # # == Creating an Engine # - # In Rails versions before to 3.0, your gems automatically behaved as Engine, however + # In Rails versions prior to 3.0, your gems automatically behaved as engines, however, # this coupled Rails to Rubygems. Since Rails 3.0, if you want a gem to automatically - # behave as Engine, you have to specify an Engine for it somewhere inside your plugin - # lib folder (similar with how we spceify a Railtie): + # behave as an engine, you have to specify an +Engine+ for it somewhere inside + # your plugin's +lib+ folder (similar to how we specify a +Railtie+): # # # lib/my_engine.rb # module MyEngine @@ -24,16 +26,17 @@ module Rails # end # end # - # Then ensure that this file is loaded at the top of your config/application.rb (or in - # your Gemfile) and it will automatically load models, controllers and helpers - # inside app, load routes at "config/routes.rb", load locales at "config/locales/*", - # load tasks at "lib/tasks/*". + # Then ensure that this file is loaded at the top of your <tt>config/application.rb</tt> + # (or in your +Gemfile+) and it will automatically load models, controllers and helpers + # inside +app+, load routes at <tt>config/routes.rb</tt>, load locales at + # <tt>config/locales/*</tt>, and load tasks at <tt>lib/tasks/*</tt>. # # == Configuration # - # Besides the Railtie configuration which is shared across the application, in a - # Rails::Engine you can access autoload_paths, eager_load_paths and autoload_once_paths, - # which differently from a Railtie, are scoped to the current Engine. + # Besides the +Railtie+ configuration which is shared across the application, in a + # <tt>Rails::Engine</tt> you can access <tt>autoload_paths</tt>, <tt>eager_load_paths</tt> + # and <tt>autoload_once_paths</tt>, which, differently from a <tt>Railtie</tt>, are scoped to + # the current engine. # # Example: # @@ -46,89 +49,352 @@ module Rails # end # end # + # == Generators + # + # You can set up generators for engines with <tt>config.generators</tt> method: + # + # class MyEngine < Rails::Engine + # config.generators do |g| + # g.orm :active_record + # g.template_engine :erb + # g.test_framework :test_unit + # end + # end + # + # You can also set generators for an application by using <tt>config.app_generators</tt>: + # + # class MyEngine < Rails::Engine + # # note that you can also pass block to app_generators in the same way you + # # can pass it to generators method + # config.app_generators.orm :datamapper + # end + # # == Paths # - # Since Rails 3.0, both your Application and Engines do not have hardcoded paths. - # This means that you are not required to place your controllers at "app/controllers", + # Since Rails 3.0, both your application and engines do not have hardcoded paths. + # This means that you are not required to place your controllers at <tt>app/controllers</tt>, # but in any place which you find convenient. # - # For example, let's suppose you want to lay your controllers at lib/controllers, all - # you need to do is: + # For example, let's suppose you want to place your controllers in <tt>lib/controllers</tt>. + # All you would need to do is: # # class MyEngine < Rails::Engine - # paths.app.controllers = "lib/controllers" + # paths["app/controllers"] = "lib/controllers" # end # - # You can also have your controllers being loaded from both "app/controllers" and - # "lib/controllers": + # You can also have your controllers loaded from both <tt>app/controllers</tt> and + # <tt>lib/controllers</tt>: # # class MyEngine < Rails::Engine - # paths.app.controllers << "lib/controllers" + # paths["app/controllers"] << "lib/controllers" # end # - # The available paths in an Engine are: + # The available paths in an engine are: # # class MyEngine < Rails::Engine - # paths.app = "app" - # paths.app.controllers = "app/controllers" - # paths.app.helpers = "app/helpers" - # paths.app.models = "app/models" - # paths.app.views = "app/views" - # paths.lib = "lib" - # paths.lib.tasks = "lib/tasks" - # paths.config = "config" - # paths.config.initializers = "config/initializers" - # paths.config.locales = "config/locales" - # paths.config.routes = "config/routes.rb" - # end - # - # Your Application class adds a couple more paths to this set. And as in your Application, - # all folders under "app" are automatically added to the load path. So if you have - # "app/observers", it's added by default. + # paths["app"] #=> ["app"] + # paths["app/controllers"] #=> ["app/controllers"] + # paths["app/helpers"] #=> ["app/helpers"] + # paths["app/models"] #=> ["app/models"] + # paths["app/views"] #=> ["app/views"] + # paths["lib"] #=> ["lib"] + # paths["lib/tasks"] #=> ["lib/tasks"] + # paths["config"] #=> ["config"] + # paths["config/initializers"] #=> ["config/initializers"] + # paths["config/locales"] #=> ["config/locales"] + # paths["config/routes"] #=> ["config/routes.rb"] + # end + # + # Your <tt>Application</tt> class adds a couple more paths to this set. And as in your + # <tt>Application</tt>,all folders under +app+ are automatically added to the load path. + # So if you have <tt>app/observers</tt>, it's added by default. + # + # == Endpoint + # + # An engine can be also a rack application. It can be useful if you have a rack application that + # you would like to wrap with +Engine+ and provide some of the +Engine+'s features. + # + # To do that, use the +endpoint+ method: + # + # module MyEngine + # class Engine < Rails::Engine + # endpoint MyRackApplication + # end + # end + # + # Now you can mount your engine in application's routes just like that: + # + # MyRailsApp::Application.routes.draw do + # mount MyEngine::Engine => "/engine" + # end + # + # == Middleware stack + # + # As an engine can now be rack endpoint, it can also have a middleware stack. The usage is exactly + # the same as in <tt>Application</tt>: + # + # module MyEngine + # class Engine < Rails::Engine + # middleware.use SomeMiddleware + # end + # end + # + # == Routes + # + # If you don't specify an endpoint, routes will be used as the default endpoint. You can use them + # just like you use an application's routes: + # + # # ENGINE/config/routes.rb + # MyEngine::Engine.routes.draw do + # match "/" => "posts#index" + # end + # + # == Mount priority + # + # Note that now there can be more than one router in your application, and it's better to avoid + # passing requests through many routers. Consider this situation: + # + # MyRailsApp::Application.routes.draw do + # mount MyEngine::Engine => "/blog" + # match "/blog/omg" => "main#omg" + # end + # + # +MyEngine+ is mounted at <tt>/blog</tt>, and <tt>/blog/omg</tt> points to application's + # controller. In such a situation, requests to <tt>/blog/omg</tt> will go through +MyEngine+, + # and if there is no such route in +Engine+'s routes, it will be dispatched to <tt>main#omg</tt>. + # It's much better to swap that: + # + # MyRailsApp::Application.routes.draw do + # match "/blog/omg" => "main#omg" + # mount MyEngine::Engine => "/blog" + # end + # + # Now, +Engine+ will get only requests that were not handled by +Application+. + # + # == Asset path + # + # When you use +Engine+ with its own public directory, you will probably want to copy or symlink it + # to application's public directory. To simplify generating paths for assets, you can set <tt>asset_path</tt> + # for an engine: + # + # module MyEngine + # class Engine < Rails::Engine + # config.asset_path = "/my_engine/%s" + # end + # end + # + # With such a config, asset paths will be automatically modified inside +Engine+: + # + # image_path("foo.jpg") #=> "/my_engine/images/foo.jpg" + # + # == Serving static files + # + # By default, Rails uses <tt>ActionDispatch::Static</tt> to serve static files in development mode. This is ok + # while you develop your application, but when you want to deploy it, assets from an engine will not be + # served by default. You should choose one of the two following strategies: + # + # * enable serving static files by setting config.serve_static_assets to true + # * copy engine's public files to application's public folder with <tt>rake ENGINE_NAME:install:assets</tt>, for example + # <tt>rake my_engine:install:assets</tt> + # + # == Engine name + # + # There are some places where an Engine's name is used: + # * routes: when you mount an Engine with <tt>mount(MyEngine::Engine => '/my_engine')</tt>, + # it's used as default :as option + # * some of the rake tasks are based on engine name, e.g. <tt>my_engine:install:migrations</tt>, + # <tt>my_engine:install:assets</tt> + # + # Engine name is set by default based on class name. For <tt>MyEngine::Engine</tt> it will be + # <tt>my_engine_engine</tt>. You can change it manually it manually using the <tt>engine_name</tt> method: + # + # module MyEngine + # class Engine < Rails::Engine + # engine_name "my_engine" + # end + # end + # + # == Isolated Engine + # + # Normally when you create controllers, helpers and models inside an engine, they are treated + # as they were created inside the application. This means all application helpers and named routes + # will be available to your engine's controllers. + # + # However, sometimes you want to isolate your engine from the application, especially if your engine + # has its own router. To do that, you simply need to call +isolate_namespace+. This method requires + # you to pass a module where all your controllers, helpers and models should be nested to: + # + # module MyEngine + # class Engine < Rails::Engine + # isolate_namespace MyEngine + # end + # end + # + # With such an engine, everything that is inside the +MyEngine+ module will be isolated from + # the application. + # + # Consider such controller: + # + # module MyEngine + # class FooController < ActionController::Base + # end + # end + # + # If an engine is marked as isolated, +FooController+ has access only to helpers from +Engine+ and + # <tt>url_helpers</tt> from <tt>MyEngine::Engine.routes</tt>. + # + # The next thing that changes in isolated engines is the behaviour of routes. Normally, when you namespace + # your controllers, you also need to do namespace all your routes. With an isolated engine, + # the namespace is applied by default, so you can ignore it in routes: + # + # MyEngine::Engine.routes.draw do + # resources :articles + # end + # + # The routes above will automatically point to <tt>MyEngine::ApplicationContoller</tt>. Furthermore, you don't + # need to use longer url helpers like <tt>my_engine_articles_path</tt>. Instead, you should simply use + # <tt>articles_path</tt> as you would do with your application. + # + # To make that behaviour consistent with other parts of the framework, an isolated engine also has influence on + # <tt>ActiveModel::Naming</tt>. When you use a namespaced model, like <tt>MyEngine::Article</tt>, it will normally + # use the prefix "my_engine". In an isolated engine, the prefix will be omitted in url helpers and + # form fields for convenience. + # + # polymorphic_url(MyEngine::Article.new) #=> "articles_path" + # + # form_for(MyEngine::Article.new) do + # text_field :title #=> <input type="text" name="article[title]" id="article_title" /> + # end + # + # Additionally isolated engine will set its name according to namespace, so + # MyEngine::Engine.engine_name #=> "my_engine". It will also set MyEngine.table_name_prefix + # to "my_engine_", changing MyEngine::Article model to use my_engine_article table. + # + # == Using Engine's routes outside Engine + # + # Since you can now mount an engine inside application's routes, you do not have direct access to +Engine+'s + # <tt>url_helpers</tt> inside +Application+. When you mount an engine in an application's routes, a special helper is + # created to allow you to do that. Consider such a scenario: + # + # # APP/config/routes.rb + # MyApplication::Application.routes.draw do + # mount MyEngine::Engine => "/my_engine", :as => "my_engine" + # match "/foo" => "foo#index" + # end + # + # Now, you can use the <tt>my_engine</tt> helper inside your application: + # + # class FooController < ApplicationController + # def index + # my_engine.root_url #=> /my_engine/ + # end + # end + # + # There is also a <tt>main_app</tt> helper that gives you access to application's routes inside Engine: + # + # module MyEngine + # class BarController + # def index + # main_app.foo_path #=> /foo + # end + # end + # end + # + # Note that the <tt>:as</tt> option given to mount takes the <tt>engine_name</tT> as default, so most of the time + # you can simply omit it. + # + # Finally, if you want to generate a url to an engine's route using <tt>polymorphic_url</tt>, you also need + # to pass the engine helper. Let's say that you want to create a form pointing to one of the + # engine's routes. All you need to do is pass the helper as the first element in array with + # attributes for url: + # + # form_for([my_engine, @user]) + # + # This code will use <tt>my_engine.user_path(@user)</tt> to generate the proper route. + # + # == Migrations & seed data + # + # Engines can have their own migrations. The default path for migrations is exactly the same + # as in application: <tt>db/migrate</tt> + # + # To use engine's migrations in application you can use rake task, which copies them to + # application's dir: + # + # rake ENGINE_NAME:install:migrations + # + # Note that some of the migrations may be skipped if a migration with the same name already exists + # in application. In such a situation you must decide whether to leave that migration or rename the + # migration in application and rerun copying migrations. + # + # If your engine has migrations, you may also want to prepare data for the database in + # the <tt>seeds.rb</tt> file. You can load that data using the <tt>load_seed</tt> method, e.g. + # + # MyEngine::Engine.load_seed # class Engine < Railtie - autoload :Configurable, "rails/engine/configurable" autoload :Configuration, "rails/engine/configuration" + autoload :Railties, "rails/engine/railties" class << self - attr_accessor :called_from - - # TODO Remove this. It's deprecated. + attr_accessor :called_from, :isolated + alias :isolated? :isolated alias :engine_name :railtie_name def inherited(base) unless base.abstract_railtie? base.called_from = begin # Remove the line number from backtraces making sure we don't leave anything behind - call_stack = caller.map { |p| p.split(':')[0..-2].join(':') } - File.dirname(call_stack.detect { |p| p !~ %r[railties[\w\-\.]*/lib/rails|rack[\w\-\.]*/lib/rack] }) + call_stack = caller.map { |p| p.sub(/:\d+.*/, '') } + File.dirname(call_stack.detect { |p| p !~ %r[railties[\w.-]*/lib/rails|rack[\w.-]*/lib/rack] }) end end super end - def find_root_with_flag(flag, default=nil) - root_path = self.called_from + def endpoint(endpoint = nil) + @endpoint = endpoint if endpoint + @endpoint + end - while root_path && File.directory?(root_path) && !File.exist?("#{root_path}/#{flag}") - parent = File.dirname(root_path) - root_path = parent != root_path && parent - end + def isolate_namespace(mod) + engine_name(generate_railtie_name(mod)) + + name = engine_name + self.routes.default_scope = {:module => name} + self.isolated = true - root = File.exist?("#{root_path}/#{flag}") ? root_path : default - raise "Could not find root path for #{self}" unless root + unless mod.respond_to?(:_railtie) + _railtie = self + mod.singleton_class.instance_eval do + define_method(:_railtie) do + _railtie + end - Config::CONFIG['host_os'] =~ /mswin|mingw/ ? - Pathname.new(root).expand_path : Pathname.new(root).realpath + unless mod.respond_to?(:table_name_prefix) + define_method(:table_name_prefix) do + "#{name}_" + end + end + end + end + end + + # Finds engine with given path + def find(path) + expanded_path = File.expand_path path.to_s + Rails::Engine::Railties.engines.find { |engine| + File.expand_path(engine.root.to_s) == expanded_path + } end end - delegate :paths, :root, :to => :config + delegate :middleware, :root, :paths, :to => :config + delegate :engine_name, :isolated?, :to => "self.class" def load_tasks super - config.paths.lib.tasks.to_a.sort.each { |ext| load(ext) } + paths["lib/tasks"].existent.sort.each { |ext| load(ext) } end def eager_load! @@ -140,6 +406,58 @@ module Rails end end + def railties + @railties ||= self.class::Railties.new(config) + end + + def app + @app ||= begin + config.middleware = config.middleware.merge_into(default_middleware_stack) + config.middleware.build(endpoint) + end + end + + def endpoint + self.class.endpoint || routes + end + + def call(env) + app.call(env.merge!(env_config)) + end + + def env_config + @env_config ||= { + 'action_dispatch.routes' => routes, + 'action_dispatch.asset_path' => config.asset_path + } + end + + def routes + @routes ||= ActionDispatch::Routing::RouteSet.new + @routes.append(&Proc.new) if block_given? + @routes + end + + def initializers + initializers = [] + railties.all { |r| initializers += r.initializers } + initializers += super + initializers + end + + def config + @config ||= Engine::Configuration.new(find_root_with_flag("lib")) + end + + # Load data from db/seeds.rb file. It can be used in to load engines' + # seeds, e.g.: + # + # Blog::Engine.load_seed + def load_seed + seed_file = paths["db/seeds"].existent.first + load(seed_file) if File.exist?(seed_file) + end + # Add configured load paths to ruby load paths and remove duplicates. initializer :set_load_path, :before => :bootstrap_hook do _all_load_paths.reverse_each do |path| @@ -155,7 +473,7 @@ module Rails # per engine and get the engine as a block parameter initializer :set_autoload_paths, :before => :bootstrap_hook do |app| ActiveSupport::Dependencies.autoload_paths.unshift(*_all_autoload_paths) - ActiveSupport::Dependencies.autoload_once_paths.unshift(*config.autoload_once_paths) + ActiveSupport::Dependencies.autoload_once_paths.unshift(*_all_autoload_once_paths) # Freeze so future modifications will fail rather than do nothing mysteriously config.autoload_paths.freeze @@ -164,40 +482,50 @@ module Rails end initializer :add_routing_paths do |app| - paths.config.routes.to_a.each do |route| - app.routes_reloader.paths.unshift(route) if File.exists?(route) - end - end + paths = self.paths["config/routes"].existent - # DEPRECATED: Remove in 3.1 - initializer :add_routing_namespaces do |app| - paths.app.controllers.to_a.each do |load_path| - load_path = File.expand_path(load_path) - Dir["#{load_path}/*/**/*_controller.rb"].collect do |path| - namespace = File.dirname(path).sub(/#{Regexp.escape(load_path)}\/?/, '') - app.routes.controller_namespaces << namespace unless namespace.empty? - end + if routes? || paths.any? + app.routes_reloader.paths.unshift(*paths) + app.routes_reloader.route_sets << routes end end # I18n load paths are a special case since the ones added # later have higher priority. initializer :add_locales do - config.i18n.railties_load_path.concat(paths.config.locales.to_a) + config.i18n.railties_load_path.concat(paths["config/locales"].existent) end initializer :add_view_paths do - views = paths.app.views.to_a - ActiveSupport.on_load(:action_controller) do - prepend_view_path(views) + views = paths["app/views"].existent + unless views.empty? + ActiveSupport.on_load(:action_controller){ prepend_view_path(views) } + ActiveSupport.on_load(:action_mailer){ prepend_view_path(views) } end - ActiveSupport.on_load(:action_mailer) do - prepend_view_path(views) + end + + initializer :load_environment_config, :before => :load_environment_hook do + environment = paths["config/environments"].existent.first + require environment if environment + end + + initializer :append_asset_paths do + config.asset_path ||= default_asset_path + + public_path = paths["public"].first + if config.compiled_asset_path && File.exist?(public_path) + config.static_asset_paths[config.compiled_asset_path] = public_path + end + end + + initializer :prepend_helpers_path do |app| + if !isolated? || (app == self) + app.config.helpers_paths.unshift(*paths["app/helpers"].existent) end end initializer :load_config_initializers do - paths.config.initializers.to_a.sort.each do |initializer| + config.paths["config/initializers"].existent.sort.each do |initializer| load(initializer) end end @@ -207,8 +535,67 @@ module Rails # consistently executed after all the initializers above across all engines. end + rake_tasks do + next if self.is_a?(Rails::Application) + + namespace railtie_name do + desc "Shortcut for running both rake #{railtie_name}:install:migrations and #{railtie_name}:install:assets" + task :install do + Rake::Task["#{railtie_name}:install:migrations"].invoke + Rake::Task["#{railtie_name}:install:assets"].invoke + end + + namespace :install do + # TODO Add assets copying to this list + # TODO Skip this if there is no paths["db/migrate"] for the engine + desc "Copy migrations from #{railtie_name} to application" + task :migrations do + ENV["FROM"] = railtie_name + Rake::Task["railties:install:migrations"].invoke + end + + desc "Copy assets from #{railtie_name} to application" + task :assets do + ENV["FROM"] = railtie_name + Rake::Task["railties:install:assets"].invoke + end + end + end + end + protected + def default_asset_path + "/#{railtie_name}%s" + end + + def routes? + defined?(@routes) + end + + def find_root_with_flag(flag, default=nil) + root_path = self.class.called_from + + while root_path && File.directory?(root_path) && !File.exist?("#{root_path}/#{flag}") + parent = File.dirname(root_path) + root_path = parent != root_path && parent + end + + root = File.exist?("#{root_path}/#{flag}") ? root_path : default + raise "Could not find root path for #{self}" unless root + + RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ ? + Pathname.new(root).expand_path : Pathname.new(root).realpath + end + + def default_middleware_stack + ActionDispatch::MiddlewareStack.new + end + + def _all_autoload_once_paths + config.autoload_once_paths + end + def _all_autoload_paths @_all_autoload_paths ||= (config.autoload_paths + config.eager_load_paths + config.autoload_once_paths).uniq end diff --git a/railties/lib/rails/engine/configurable.rb b/railties/lib/rails/engine/configurable.rb deleted file mode 100644 index 9a370f0abb..0000000000 --- a/railties/lib/rails/engine/configurable.rb +++ /dev/null @@ -1,25 +0,0 @@ -module Rails - class Engine - module Configurable - def self.included(base) - base.extend ClassMethods - end - - module ClassMethods - delegate :middleware, :root, :paths, :to => :config - - def config - @config ||= Engine::Configuration.new(find_root_with_flag("lib")) - end - - def inherited(base) - raise "You cannot inherit from a Rails::Engine child" - end - end - - def config - self.class.config - end - end - end -end
\ No newline at end of file diff --git a/railties/lib/rails/engine/configuration.rb b/railties/lib/rails/engine/configuration.rb index 521ed95447..4f458b0aee 100644 --- a/railties/lib/rails/engine/configuration.rb +++ b/railties/lib/rails/engine/configuration.rb @@ -4,31 +4,62 @@ module Rails class Engine class Configuration < ::Rails::Railtie::Configuration attr_reader :root - attr_writer :eager_load_paths, :autoload_once_paths, :autoload_paths + attr_writer :middleware, :eager_load_paths, :autoload_once_paths, :autoload_paths + attr_accessor :plugins, :asset_path def initialize(root=nil) super() @root = root + @generators = app_generators.dup + end + + # Returns the middleware stack for the engine. + def middleware + @middleware ||= Rails::Configuration::MiddlewareStackProxy.new + end + + # Holds generators configuration: + # + # config.generators do |g| + # g.orm :datamapper, :migration => true + # g.template_engine :haml + # g.test_framework :rspec + # end + # + # If you want to disable color in console, do: + # + # config.generators.colorize_logging = false + # + def generators #:nodoc + @generators ||= Rails::Configuration::Generators.new + yield(@generators) if block_given? + @generators end def paths @paths ||= begin paths = Rails::Paths::Root.new(@root) - paths.app "app", :eager_load => true, :glob => "*" - paths.app.controllers "app/controllers", :eager_load => true - paths.app.helpers "app/helpers", :eager_load => true - paths.app.models "app/models", :eager_load => true - paths.app.mailers "app/mailers", :eager_load => true - paths.app.views "app/views" - paths.lib "lib", :load_path => true - paths.lib.tasks "lib/tasks", :glob => "**/*.rake" - paths.config "config" - paths.config.initializers "config/initializers", :glob => "**/*.rb" - paths.config.locales "config/locales", :glob => "*.{rb,yml}" - paths.config.routes "config/routes.rb" - paths.public "public" - paths.public.javascripts "public/javascripts" - paths.public.stylesheets "public/stylesheets" + paths.add "app", :eager_load => true, :glob => "*" + paths.add "app/controllers", :eager_load => true + paths.add "app/helpers", :eager_load => true + paths.add "app/models", :eager_load => true + paths.add "app/mailers", :eager_load => true + paths.add "app/views" + paths.add "lib", :load_path => true + paths.add "lib/tasks", :glob => "**/*.rake" + paths.add "config" + paths.add "config/environments", :glob => "#{Rails.env}.rb" + paths.add "config/initializers", :glob => "**/*.rb" + paths.add "config/locales", :glob => "*.{rb,yml}" + paths.add "config/routes", :with => "config/routes.rb" + paths.add "db" + paths.add "db/migrate" + paths.add "db/seeds", :with => "db/seeds.rb" + paths.add "public" + paths.add "public/javascripts" + paths.add "public/stylesheets" + paths.add "vendor", :load_path => true + paths.add "vendor/plugins" paths end end @@ -48,6 +79,10 @@ module Rails def autoload_paths @autoload_paths ||= paths.autoload_paths end + + def compiled_asset_path + asset_path % "" if asset_path + end end end end diff --git a/railties/lib/rails/engine/railties.rb b/railties/lib/rails/engine/railties.rb new file mode 100644 index 0000000000..d5ecd2e48d --- /dev/null +++ b/railties/lib/rails/engine/railties.rb @@ -0,0 +1,33 @@ +module Rails + class Engine < Railtie + class Railties + # TODO Write tests for this behavior extracted from Application + def initialize(config) + @config = config + end + + def all(&block) + @all ||= plugins + @all.each(&block) if block + @all + end + + def plugins + @plugins ||= begin + plugin_names = (@config.plugins || [:all]).map { |p| p.to_sym } + Plugin.all(plugin_names, @config.paths["vendor/plugins"].existent) + end + end + + def self.railties + @railties ||= ::Rails::Railtie.subclasses.map(&:instance) + end + + def self.engines + @engines ||= ::Rails::Engine.subclasses.map(&:instance) + end + + delegate :railties, :engines, :to => "self.class" + end + end +end diff --git a/railties/lib/rails/generators.rb b/railties/lib/rails/generators.rb index 8794392a7d..29e693dfb0 100644 --- a/railties/lib/rails/generators.rb +++ b/railties/lib/rails/generators.rb @@ -140,10 +140,7 @@ module Rails lookup(lookups) - namespaces = subclasses.inject({}) do |hash, klass| - hash[klass.namespace] = klass - hash - end + namespaces = Hash[subclasses.map { |klass| [klass.namespace, klass] }] lookups.each do |namespace| klass = namespaces[namespace] @@ -158,7 +155,7 @@ module Rails # commands. def self.invoke(namespace, args=ARGV, config={}) names = namespace.to_s.split(':') - if klass = find_by_namespace(names.pop, names.shift) + if klass = find_by_namespace(names.pop, names.any? && names.join(':')) args << "--help" if args.empty? && klass.arguments.any? { |a| a.required? } klass.start(args, config) else @@ -218,11 +215,11 @@ module Rails puts "Usage: rails #{command} GENERATOR [args] [options]" puts puts "General options:" - puts " -h, [--help] # Print generators options and usage" + puts " -h, [--help] # Print generator's options and usage" puts " -p, [--pretend] # Run but do not make any changes" puts " -f, [--force] # Overwrite files that already exist" puts " -s, [--skip] # Skip files that already exist" - puts " -q, [--quiet] # Supress status output" + puts " -q, [--quiet] # Suppress status output" puts puts "Please choose a generator below." puts @@ -231,6 +228,7 @@ module Rails rails = groups.delete("rails") rails.map! { |n| n.sub(/^rails:/, '') } rails.delete("app") + rails.delete("plugin_new") print_list("rails", rails) hidden_namespaces.each {|n| groups.delete(n.to_s) } @@ -304,6 +302,7 @@ module Rails $LOAD_PATH.each do |base| Dir[File.join(base, "{rails/generators,generators}", "**", "*_generator.rb")].each do |path| begin + path = path.sub("#{base}/", "") require path rescue Exception => e # No problem diff --git a/railties/lib/rails/generators/actions.rb b/railties/lib/rails/generators/actions.rb index 668ef48892..c323df3e95 100644 --- a/railties/lib/rails/generators/actions.rb +++ b/railties/lib/rails/generators/actions.rb @@ -1,5 +1,4 @@ require 'open-uri' -require 'active_support/deprecation' require 'rbconfig' module Rails @@ -45,7 +44,7 @@ module Rails # # ==== Example # - # gem "rspec", :env => :test + # gem "rspec", :group => :test # gem "technoweenie-restful-authentication", :lib => "restful-authentication", :source => "http://gems.github.com/" # gem "rails", "3.0", :git => "git://github.com/rails/rails" # @@ -53,20 +52,6 @@ module Rails options = args.extract_options! name, version = args - # Deal with deprecated options - { :env => :group, :only => :group, - :lib => :require, :require_as => :require }.each do |old, new| - next unless options[old] - options[new] = options.delete(old) - ActiveSupport::Deprecation.warn "#{old.inspect} option in gem is deprecated, use #{new.inspect} instead" - end - - # Deal with deprecated source - if source = options.delete(:source) - ActiveSupport::Deprecation.warn ":source option in gem is deprecated, use add_source method instead" - add_source(source) - end - # Set the message to be shown in logs. Uses the git repo if one is given, # otherwise use name (version). parts, message = [ name.inspect ], name @@ -202,8 +187,8 @@ module Rails # initializer("globals.rb") do # data = "" # - # ['MY_WORK', 'ADMINS', 'BEST_COMPANY_EVAR'].each do - # data << "#{const} = :entp" + # ['MY_WORK', 'ADMINS', 'BEST_COMPANY_EVAR'].each do |const| + # data << "#{const} = :entp\n" # end # # data @@ -242,7 +227,7 @@ module Rails def rake(command, options={}) log :rake, command env = options[:env] || 'development' - sudo = options[:sudo] && Config::CONFIG['host_os'] !~ /mswin|mingw/ ? 'sudo ' : '' + sudo = options[:sudo] && RbConfig::CONFIG['host_os'] !~ /mswin|mingw/ ? 'sudo ' : '' in_root { run("#{sudo}#{extify(:rake)} #{command} RAILS_ENV=#{env}", :verbose => false) } end @@ -257,16 +242,6 @@ module Rails in_root { run("#{extify(:capify)} .", :verbose => false) } end - # Add Rails to /vendor/rails - # - # ==== Example - # - # freeze! - # - def freeze!(args={}) - ActiveSupport::Deprecation.warn "freeze! is deprecated since your rails app now comes bundled with Rails by default, please check your Gemfile" - end - # Make an entry in Rails routing file config/routes.rb # # === Example @@ -289,17 +264,18 @@ module Rails # readme "README" # def readme(path) - say File.read(find_in_source_paths(path)) + log File.read(find_in_source_paths(path)) end protected # Define log for backwards compatibility. If just one argument is sent, - # invoke say, otherwise invoke say_status. + # invoke say, otherwise invoke say_status. Differently from say and + # similarly to say_status, this method respects the quiet? option given. # def log(*args) if args.size == 1 - say args.first.to_s + say args.first.to_s unless options.quiet? else args << (self.behavior == :invoke ? :green : :red) say_status *args @@ -309,7 +285,7 @@ module Rails # Add an extension to the given name based on the platform. # def extify(name) - if Config::CONFIG['host_os'] =~ /mswin|mingw/ + if RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ "#{name}.bat" else name diff --git a/railties/lib/rails/generators/app_base.rb b/railties/lib/rails/generators/app_base.rb new file mode 100644 index 0000000000..ab7ed4eb9e --- /dev/null +++ b/railties/lib/rails/generators/app_base.rb @@ -0,0 +1,170 @@ +require 'digest/md5' +require 'active_support/secure_random' +require 'rails/version' unless defined?(Rails::VERSION) +require 'rbconfig' +require 'open-uri' +require 'uri' + +module Rails + module Generators + class AppBase < Base + DATABASES = %w( mysql oracle postgresql sqlite3 frontbase ibm_db ) + JAVASCRIPTS = %w( prototype jquery ) + + attr_accessor :rails_template + add_shebang_option! + + argument :app_path, :type => :string + + def self.add_shared_options_for(name) + class_option :builder, :type => :string, :aliases => "-b", + :desc => "Path to a #{name} builder (can be a filesystem path or URL)" + + class_option :template, :type => :string, :aliases => "-m", + :desc => "Path to an #{name} template (can be a filesystem path or URL)" + + class_option :skip_gemfile, :type => :boolean, :default => false, + :desc => "Don't create a Gemfile" + + class_option :skip_git, :type => :boolean, :aliases => "-G", :default => false, + :desc => "Skip Git ignores and keeps" + + class_option :skip_active_record, :type => :boolean, :aliases => "-O", :default => false, + :desc => "Skip Active Record files" + + class_option :database, :type => :string, :aliases => "-d", :default => "sqlite3", + :desc => "Preconfigure for selected database (options: #{DATABASES.join('/')})" + + class_option :javascript, :type => :string, :aliases => "-j", :default => "prototype", + :desc => "Preconfigure for selected javascript library (options: #{JAVASCRIPTS.join('/')})" + + class_option :skip_javascript, :type => :boolean, :aliases => "-J", :default => false, + :desc => "Skip javascript files" + + class_option :dev, :type => :boolean, :default => false, + :desc => "Setup the #{name} with Gemfile pointing to your Rails checkout" + + class_option :edge, :type => :boolean, :default => false, + :desc => "Setup the #{name} with Gemfile pointing to Rails repository" + + class_option :skip_test_unit, :type => :boolean, :aliases => "-T", :default => false, + :desc => "Skip Test::Unit files" + + class_option :help, :type => :boolean, :aliases => "-h", :group => :rails, + :desc => "Show this help message and quit" + end + + def initialize(*args) + @original_wd = Dir.pwd + + super + end + + protected + + def builder + @builder ||= begin + if path = options[:builder] + if URI(path).is_a?(URI::HTTP) + contents = open(path, "Accept" => "application/x-thor-template") {|io| io.read } + else + contents = open(File.expand_path(path, @original_wd)) {|io| io.read } + end + + prok = eval("proc { #{contents} }", TOPLEVEL_BINDING, path, 1) + instance_eval(&prok) + end + + builder_class = get_builder_class + builder_class.send(:include, ActionMethods) + builder_class.new(self) + end + end + + def build(meth, *args) + builder.send(meth, *args) if builder.respond_to?(meth) + end + + def create_root + self.destination_root = File.expand_path(app_path, destination_root) + valid_const? + + empty_directory '.' + set_default_accessors! + FileUtils.cd(destination_root) unless options[:pretend] + end + + def apply_rails_template + apply rails_template if rails_template + rescue Thor::Error, LoadError, Errno::ENOENT => e + raise Error, "The template [#{rails_template}] could not be loaded. Error: #{e}" + end + + def set_default_accessors! + self.rails_template = case options[:template] + when /^https?:\/\// + options[:template] + when String + File.expand_path(options[:template], Dir.pwd) + else + options[:template] + end + end + + def database_gemfile_entry + options[:skip_active_record] ? "" : "gem '#{gem_for_database}'" + end + + def rails_gemfile_entry + if options.dev? + <<-GEMFILE +gem 'rails', :path => '#{Rails::Generators::RAILS_DEV_PATH}' +gem 'arel', :git => 'git://github.com/rails/arel.git' +gem "rack", :git => "git://github.com/rack/rack.git" + GEMFILE + elsif options.edge? + <<-GEMFILE +gem 'rails', :git => 'git://github.com/rails/rails.git' +gem 'arel', :git => 'git://github.com/rails/arel.git' +gem "rack", :git => "git://github.com/rack/rack.git" + GEMFILE + else + <<-GEMFILE +gem 'rails', '#{Rails::VERSION::STRING}' + +# Bundle edge Rails instead: +# gem 'rails', :git => 'git://github.com/rails/rails.git' +# gem 'arel', :git => 'git://github.com/rails/arel.git' +# gem "rack", :git => "git://github.com/rack/rack.git" + GEMFILE + end + end + + def gem_for_database + # %w( mysql oracle postgresql sqlite3 frontbase ibm_db ) + case options[:database] + when "oracle" then "ruby-oci8" + when "postgresql" then "pg" + when "frontbase" then "ruby-frontbase" + when "mysql" then "mysql2" + else options[:database] + end + end + + def bundle_if_dev_or_edge + bundle_command = File.basename(Thor::Util.ruby_command).sub(/ruby/, 'bundle') + run "#{bundle_command} install" if dev_or_edge? + end + + def dev_or_edge? + options.dev? || options.edge? + end + + def empty_directory_with_gitkeep(destination, config = {}) + empty_directory(destination, config) + create_file("#{destination}/.gitkeep") unless options[:skip_git] + end + + end + end +end diff --git a/railties/lib/rails/generators/base.rb b/railties/lib/rails/generators/base.rb index fdfceb14ce..dfecd2a6e4 100644 --- a/railties/lib/rails/generators/base.rb +++ b/railties/lib/rails/generators/base.rb @@ -3,7 +3,7 @@ begin rescue LoadError puts "Thor is not available.\nIf you ran this command from a git checkout " \ "of Rails, please make sure thor is installed,\nand run this command " \ - "as `ruby #{$0} #{ARGV.join(" ")} --dev`" + "as `ruby #{$0} #{(ARGV | ['--dev']).join(" ")}`" exit end @@ -81,7 +81,7 @@ module Rails # guessed based on class invokes hook_for, as noticed in the example above. # This can be customized with two options: :base and :as. # - # Let's suppose you are creating a generator that needs to invoke the + # Let's suppose you are creating a generator that needs to invoke the # controller generator from test unit. Your first attempt is: # # class AwesomeGenerator < Rails::Generators::Base @@ -274,7 +274,7 @@ module Rails # Use Rails default banner. # def self.banner - "rails generate #{generator_name} #{self.arguments.map{ |a| a.usage }.join(' ')} [options]" + "rails generate #{namespace.sub(/^rails:/,'')} #{self.arguments.map{ |a| a.usage }.join(' ')} [options]".gsub(/\s+/, ' ') end # Sets the base_name taking into account the current class namespace. diff --git a/railties/lib/rails/generators/generated_attribute.rb b/railties/lib/rails/generators/generated_attribute.rb index 3b9fff2f4a..64273e4ca4 100644 --- a/railties/lib/rails/generators/generated_attribute.rb +++ b/railties/lib/rails/generators/generated_attribute.rb @@ -6,6 +6,7 @@ module Rails attr_accessor :name, :type def initialize(name, type) + raise Thor::Error, "Missing type for attribute '#{name}'.\nExample: '#{name}:string' where string is the type." if type.blank? @name, @type = name, type.to_sym end diff --git a/railties/lib/rails/generators/migration.rb b/railties/lib/rails/generators/migration.rb index 9244307261..0c5c4f6e09 100644 --- a/railties/lib/rails/generators/migration.rb +++ b/railties/lib/rails/generators/migration.rb @@ -52,8 +52,12 @@ module Rails destination = self.class.migration_exists?(migration_dir, @migration_file_name) - if behavior == :invoke - raise Error, "Another migration is already named #{@migration_file_name}: #{destination}" if destination + if !(destination && options[:skip]) && behavior == :invoke + if destination && options.force? + remove_file(destination) + elsif destination + raise Error, "Another migration is already named #{@migration_file_name}: #{destination}" + end destination = File.join(migration_dir, "#{@migration_number}_#{@migration_file_name}.rb") end diff --git a/railties/lib/rails/generators/named_base.rb b/railties/lib/rails/generators/named_base.rb index 44f831e6f3..2af7f85463 100644 --- a/railties/lib/rails/generators/named_base.rb +++ b/railties/lib/rails/generators/named_base.rb @@ -5,6 +5,8 @@ module Rails module Generators class NamedBase < Base argument :name, :type => :string + class_option :skip_namespace, :type => :boolean, :default => false, + :desc => "Skip namespace (affects only isolated applications)" def initialize(args, *options) #:nodoc: # Unfreeze name in case it's given as a frozen string @@ -14,17 +16,78 @@ module Rails parse_attributes! if respond_to?(:attributes) end - protected + no_tasks do + def template(source, *args, &block) + inside_template do + super + end + end + end - attr_reader :class_path, :file_name + protected + attr_reader :file_name alias :singular_name :file_name + # Wrap block with namespace of current application + # if namespace exists and is not skipped + def module_namespacing(&block) + content = capture(&block) + content = wrap_with_namespace(content) if namespaced? + concat(content) + end + + def indent(content, multiplier = 2) + spaces = " " * multiplier + content = content.each_line.map {|line| "#{spaces}#{line}" }.join + end + + def wrap_with_namespace(content) + content = indent(content).chomp + "module #{namespace.name}\n#{content}\nend\n" + end + + def inside_template + @inside_template = true + yield + ensure + @inside_template = false + end + + def inside_template? + @inside_template + end + + def namespace + @namespace ||= if defined?(Rails) && Rails.application + Rails.application.class.parents.detect { |n| n.respond_to?(:_railtie) } + end + end + + def namespaced? + !options[:skip_namespace] && namespace + end + def file_path @file_path ||= (class_path + [file_name]).join('/') end + def class_path + inside_template? || !namespaced? ? regular_class_path : namespaced_class_path + end + + def regular_class_path + @class_path + end + + def namespaced_class_path + @namespaced_class_path ||= begin + namespace_path = namespace.name.split("::").map {|m| m.underscore } + namespace_path + @class_path + end + end + def class_name - @class_name ||= (class_path + [file_name]).map!{ |m| m.camelize }.join('::') + (class_path + [file_name]).map!{ |m| m.camelize }.join('::') end def human_name @@ -55,11 +118,11 @@ module Rails end def singular_table_name - @singular_table_name ||= table_name.singularize + @singular_table_name ||= (pluralize_table_names? ? table_name.singularize : table_name) end def plural_table_name - @plural_table_name ||= table_name.pluralize + @plural_table_name ||= (pluralize_table_names? ? table_name : table_name.pluralize) end def plural_file_name diff --git a/railties/lib/rails/generators/rails/app/app_generator.rb b/railties/lib/rails/generators/rails/app/app_generator.rb index a90f109844..3f6ff35a86 100644 --- a/railties/lib/rails/generators/rails/app/app_generator.rb +++ b/railties/lib/rails/generators/rails/app/app_generator.rb @@ -1,9 +1,4 @@ -require 'digest/md5' -require 'active_support/secure_random' -require 'rails/version' unless defined?(Rails::VERSION) -require 'rbconfig' -require 'open-uri' -require 'uri' +require 'rails/generators/app_base' module Rails module ActionMethods @@ -14,23 +9,20 @@ module Rails @options = generator.options end - private - %w(template copy_file directory empty_directory inside - empty_directory_with_gitkeep create_file chmod shebang).each do |method| - class_eval <<-RUBY, __FILE__, __LINE__ + 1 - def #{method}(*args, &block) - @generator.send(:#{method}, *args, &block) - end - RUBY - end + private - # TODO: Remove once this is fully in place - def method_missing(meth, *args, &block) - STDERR.puts "Calling #{meth} with #{args.inspect} with #{block}" - @generator.send(meth, *args, &block) - end + def method_missing(meth, *args, &block) + @generator.send(meth, *args, &block) + end end + # The application builder allows you to override elements of the application + # generator without being forced to reverse the operations of the default + # generator. + # + # This allows you to override entire operations, like the creation of the + # Gemfile, README, or javascript files, without needing to know exactly + # what those operations do so you can create another template action. class AppBuilder def rakefile template "Rakefile" @@ -71,7 +63,7 @@ module Rails end def database_yml - template "config/databases/#{@options[:database]}.yml", "config/database.yml" + template "config/databases/#{options[:database]}.yml", "config/database.yml" end def db @@ -111,12 +103,20 @@ module Rails end def javascripts - unless options[:skip_prototype] - directory "public/javascripts" - else - empty_directory_with_gitkeep "public/javascripts" - create_file "public/javascripts/application.js" + empty_directory "public/javascripts" + + unless options[:skip_javascript] + copy_file "public/javascripts/#{options[:javascript]}.js" + copy_file "public/javascripts/#{options[:javascript]}_ujs.js", "public/javascripts/rails.js" + + if options[:javascript] == "prototype" + copy_file "public/javascripts/controls.js" + copy_file "public/javascripts/dragdrop.js" + copy_file "public/javascripts/effects.js" + end end + + copy_file "public/javascripts/application.js" end def script @@ -153,71 +153,28 @@ module Rails RESERVED_NAMES = %w[application destroy benchmarker profiler plugin runner test] - class AppGenerator < Base - DATABASES = %w( mysql oracle postgresql sqlite3 frontbase ibm_db ) - - attr_accessor :rails_template - add_shebang_option! - - argument :app_path, :type => :string - - class_option :database, :type => :string, :aliases => "-d", :default => "sqlite3", - :desc => "Preconfigure for selected database (options: #{DATABASES.join('/')})" - - class_option :builder, :type => :string, :aliases => "-b", - :desc => "Path to an application builder (can be a filesystem path or URL)" - - class_option :template, :type => :string, :aliases => "-m", - :desc => "Path to an application template (can be a filesystem path or URL)" - - class_option :dev, :type => :boolean, :default => false, - :desc => "Setup the application with Gemfile pointing to your Rails checkout" - - class_option :edge, :type => :boolean, :default => false, - :desc => "Setup the application with Gemfile pointing to Rails repository" - - class_option :skip_gemfile, :type => :boolean, :default => false, - :desc => "Don't create a Gemfile" - - class_option :skip_active_record, :type => :boolean, :aliases => "-O", :default => false, - :desc => "Skip Active Record files" - - class_option :skip_test_unit, :type => :boolean, :aliases => "-T", :default => false, - :desc => "Skip Test::Unit files" - - class_option :skip_prototype, :type => :boolean, :aliases => "-J", :default => false, - :desc => "Skip Prototype files" - - class_option :skip_git, :type => :boolean, :aliases => "-G", :default => false, - :desc => "Skip Git ignores and keeps" + class AppGenerator < AppBase + add_shared_options_for "application" # Add bin/rails options class_option :version, :type => :boolean, :aliases => "-v", :group => :rails, :desc => "Show Rails version number and quit" - class_option :help, :type => :boolean, :aliases => "-h", :group => :rails, - :desc => "Show this help message and quit" - def initialize(*args) raise Error, "Options should be given after the application name. For details run: rails --help" if args[0].blank? - @original_wd = Dir.pwd - super if !options[:skip_active_record] && !DATABASES.include?(options[:database]) raise Error, "Invalid value for --database option. Supported for preconfiguration are: #{DATABASES.join(", ")}." end + + if !options[:skip_javascript] && !JAVASCRIPTS.include?(options[:javascript]) + raise Error, "Invalid value for --javascript option. Supported for preconfiguration are: #{JAVASCRIPTS.join(", ")}." + end end - def create_root - self.destination_root = File.expand_path(app_path, destination_root) - valid_app_const? - - empty_directory '.' - set_default_accessors! - FileUtils.cd(destination_root) unless options[:pretend] - end + public_task :create_root def create_root_files build(:readme) @@ -272,7 +229,7 @@ module Rails build(:stylesheets) end - def create_prototype_files + def create_javascript_files build(:javascripts) end @@ -296,16 +253,7 @@ module Rails build(:leftovers) end - def apply_rails_template - apply rails_template if rails_template - rescue Thor::Error, LoadError, Errno::ENOENT => e - raise Error, "The template [#{rails_template}] could not be loaded. Error: #{e}" - end - - def bundle_if_dev_or_edge - bundle_command = File.basename(Thor::Util.ruby_command).sub(/ruby/, 'bundle') - run "#{bundle_command} install" if dev_or_edge? - end + public_task :apply_rails_template, :bundle_if_dev_or_edge protected @@ -313,47 +261,17 @@ module Rails "rails new #{self.arguments.map(&:usage).join(' ')} [options]" end - def builder - @builder ||= begin - if path = options[:builder] - if URI(path).is_a?(URI::HTTP) - contents = open(path, "Accept" => "application/x-thor-template") {|io| io.read } - else - contents = open(File.expand_path(path, @original_wd)) {|io| io.read } - end - - prok = eval("proc { #{contents} }", TOPLEVEL_BINDING, path, 1) - instance_eval(&prok) - end - - builder_class = defined?(::AppBuilder) ? ::AppBuilder : Rails::AppBuilder - builder_class.send(:include, ActionMethods) - builder_class.new(self) - end - end - - def build(meth, *args) - builder.send(meth, *args) if builder.respond_to?(meth) - end - - def set_default_accessors! - self.rails_template = case options[:template] - when /^http:\/\// - options[:template] - when String - File.expand_path(options[:template], Dir.pwd) - else - options[:template] - end - end - # Define file as an alias to create_file for backwards compatibility. def file(*args, &block) create_file(*args, &block) end def app_name - @app_name ||= File.basename(destination_root) + @app_name ||= defined_app_const_base? ? defined_app_name : File.basename(destination_root) + end + + def defined_app_name + defined_app_const_base.underscore end def defined_app_const_base @@ -361,15 +279,18 @@ module Rails Rails.application.is_a?(Rails::Application) && Rails.application.class.name.sub(/::Application$/, "") end + alias :defined_app_const_base? :defined_app_const_base + def app_const_base @app_const_base ||= defined_app_const_base || app_name.gsub(/\W/, '_').squeeze('_').camelize end + alias :camelized :app_const_base def app_const @app_const ||= "#{app_const_base}::Application" end - def valid_app_const? + def valid_const? if app_const =~ /^\d/ raise Error, "Invalid application name #{app_name}. Please give a name which does not start with numbers." elsif RESERVED_NAMES.include?(app_name) @@ -383,27 +304,6 @@ module Rails ActiveSupport::SecureRandom.hex(64) end - def dev_or_edge? - options.dev? || options.edge? - end - - def gem_for_database - # %w( mysql oracle postgresql sqlite3 frontbase ibm_db ) - case options[:database] - when "oracle" then "ruby-oci8" - when "postgresql" then "pg" - when "sqlite3" then "sqlite3-ruby" - when "frontbase" then "ruby-frontbase" - else options[:database] - end - end - - def require_for_database - case options[:database] - when "sqlite3" then "sqlite3" - end - end - def mysql_socket @mysql_socket ||= [ "/tmp/mysql.sock", # default @@ -415,12 +315,11 @@ module Rails "/opt/local/var/run/mysql4/mysqld.sock", # mac + darwinports + mysql4 "/opt/local/var/run/mysql5/mysqld.sock", # mac + darwinports + mysql5 "/opt/lampp/var/mysql/mysql.sock" # xampp for linux - ].find { |f| File.exist?(f) } unless Config::CONFIG['host_os'] =~ /mswin|mingw/ + ].find { |f| File.exist?(f) } unless RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ end - def empty_directory_with_gitkeep(destination, config = {}) - empty_directory(destination, config) - create_file("#{destination}/.gitkeep") unless options[:skip_git] + def get_builder_class + defined?(::AppBuilder) ? ::AppBuilder : Rails::AppBuilder end end end diff --git a/railties/lib/rails/generators/rails/app/templates/Gemfile b/railties/lib/rails/generators/rails/app/templates/Gemfile index 1980684a94..c383d4842f 100644 --- a/railties/lib/rails/generators/rails/app/templates/Gemfile +++ b/railties/lib/rails/generators/rails/app/templates/Gemfile @@ -1,21 +1,8 @@ source 'http://rubygems.org' -<%- if options.dev? -%> -gem 'rails', :path => '<%= Rails::Generators::RAILS_DEV_PATH %>' -gem 'arel', :git => 'git://github.com/rails/arel.git' -<%- elsif options.edge? -%> -gem 'rails', :git => 'git://github.com/rails/rails.git' -gem 'arel', :git => 'git://github.com/rails/arel.git' -<%- else -%> -gem 'rails', '<%= Rails::VERSION::STRING %>' - -# Bundle edge Rails instead: -# gem 'rails', :git => 'git://github.com/rails/rails.git' -<%- end -%> - -<% unless options[:skip_activerecord] -%> -gem '<%= gem_for_database %>'<% if require_for_database %>, :require => '<%= require_for_database %>'<% end %> -<% end -%> +<%= rails_gemfile_entry -%> + +<%= database_gemfile_entry -%> # Use unicorn as the web server # gem 'unicorn' @@ -23,14 +10,15 @@ gem '<%= gem_for_database %>'<% if require_for_database %>, :require => '<%= req # Deploy with Capistrano # gem 'capistrano' -# To use debugger +# To use debugger (ruby-debug for Ruby 1.8.7+, ruby-debug19 for Ruby 1.9.2+) # gem 'ruby-debug' +# gem 'ruby-debug19', :require => 'ruby-debug' # Bundle the extra gems: # gem 'bj' # gem 'nokogiri' -# gem 'sqlite3-ruby', :require => 'sqlite3' -# gem 'aws-s3', :require => 'aws/s3' +# gem 'sqlite3' +# gem 'rack-bug', :require => 'rack/bug' # Bundle gems for the local environment. Make sure to # put test-only gems in this group so their generators @@ -38,3 +26,6 @@ gem '<%= gem_for_database %>'<% if require_for_database %>, :require => '<%= req # group :development, :test do # gem 'webrat' # end + +# Needed for guides generation +# gem "RedCloth", "~> 4.2" diff --git a/railties/lib/rails/generators/rails/app/templates/README b/railties/lib/rails/generators/rails/app/templates/README index 6966fe987e..9f0f1d0e38 100644 --- a/railties/lib/rails/generators/rails/app/templates/README +++ b/railties/lib/rails/generators/rails/app/templates/README @@ -91,7 +91,7 @@ mode. With gems, use <tt>sudo gem install ruby-debug</tt>. Example: class WeblogController < ActionController::Base def index - @posts = Post.find(:all) + @posts = Post.all debugger end end @@ -139,7 +139,7 @@ To reload your controllers and models after launching the console run <tt>reload!</tt> More information about irb can be found at: -link:http://www.rubycentral.com/pickaxe/irb.html +link:http://www.rubycentral.org/pickaxe/irb.html == dbconsole @@ -158,6 +158,7 @@ The default directory structure of a generated Ruby on Rails application: |-- app | |-- controllers | |-- helpers + | |-- mailers | |-- models | `-- views | `-- layouts @@ -175,7 +176,6 @@ The default directory structure of a generated Ruby on Rails application: | |-- javascripts | `-- stylesheets |-- script - | `-- performance |-- test | |-- fixtures | |-- functional diff --git a/railties/lib/rails/generators/rails/app/templates/Rakefile b/railties/lib/rails/generators/rails/app/templates/Rakefile index d83cafc3be..4dc1023f1f 100644..100755 --- a/railties/lib/rails/generators/rails/app/templates/Rakefile +++ b/railties/lib/rails/generators/rails/app/templates/Rakefile @@ -1,7 +1,7 @@ +#!/usr/bin/env rake # Add your own tasks in files placed in lib/tasks ending in .rake, # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. require File.expand_path('../config/application', __FILE__) -require 'rake' <%= app_const %>.load_tasks diff --git a/railties/lib/rails/generators/rails/app/templates/app/views/layouts/application.html.erb.tt b/railties/lib/rails/generators/rails/app/templates/app/views/layouts/application.html.erb.tt index 1dd112b4a6..6d56c331c1 100644 --- a/railties/lib/rails/generators/rails/app/templates/app/views/layouts/application.html.erb.tt +++ b/railties/lib/rails/generators/rails/app/templates/app/views/layouts/application.html.erb.tt @@ -1,10 +1,10 @@ <!DOCTYPE html> <html> <head> - <title><%= app_const_base %></title> + <title><%= camelized %></title> <%%= stylesheet_link_tag :all %> <%%= javascript_include_tag :defaults %> - <%%= csrf_meta_tag %> + <%%= csrf_meta_tags %> </head> <body> diff --git a/railties/lib/rails/generators/rails/app/templates/config/application.rb b/railties/lib/rails/generators/rails/app/templates/config/application.rb index 7d63e99e05..b7f64af339 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/application.rb +++ b/railties/lib/rails/generators/rails/app/templates/config/application.rb @@ -40,16 +40,27 @@ module <%= app_const_base %> # config.i18n.default_locale = :de # JavaScript files you want as :defaults (application.js is always included). -<% if options[:skip_prototype] -%> +<% if options[:skip_javascript] -%> config.action_view.javascript_expansions[:defaults] = %w() +<% elsif options[:javascript] == 'jquery' -%> + config.action_view.javascript_expansions[:defaults] = %w(jquery rails) <% else -%> # config.action_view.javascript_expansions[:defaults] = %w(jquery rails) <% end -%> +<% if options[:skip_test_unit] -%> + config.generators.test_framework = false +<% end -%> + # Configure the default encoding used in templates for Ruby 1.9. config.encoding = "utf-8" # Configure sensitive parameters which will be filtered from the log file. config.filter_parameters += [:password] + +<% unless options[:skip_active_record] -%> + # Enable IdentityMap for Active Record, to disable set to false or remove the line below. + config.active_record.identity_map = true +<% end -%> end end diff --git a/railties/lib/rails/generators/rails/app/templates/config/boot.rb b/railties/lib/rails/generators/rails/app/templates/config/boot.rb index ab6cb374de..4489e58688 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/boot.rb +++ b/railties/lib/rails/generators/rails/app/templates/config/boot.rb @@ -1,13 +1,6 @@ require 'rubygems' # Set up gems listed in the Gemfile. -gemfile = File.expand_path('../../Gemfile', __FILE__) -begin - ENV['BUNDLE_GEMFILE'] = gemfile - require 'bundler' - Bundler.setup -rescue Bundler::GemNotFound => e - STDERR.puts e.message - STDERR.puts "Try running `bundle install`." - exit! -end if File.exist?(gemfile) +ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) + +require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE']) diff --git a/railties/lib/rails/generators/rails/app/templates/config/databases/mysql.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/mysql.yml index ffc8a0a8cb..5d28c7c312 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/databases/mysql.yml +++ b/railties/lib/rails/generators/rails/app/templates/config/databases/mysql.yml @@ -1,21 +1,12 @@ # MySQL. Versions 4.1 and 5.0 are recommended. # # Install the MySQL driver: -# gem install mysql -# On Mac OS X: -# sudo gem install mysql -- --with-mysql-dir=/usr/local/mysql -# On Mac OS X Leopard: -# sudo env ARCHFLAGS="-arch i386" gem install mysql -- --with-mysql-config=/usr/local/mysql/bin/mysql_config -# This sets the ARCHFLAGS environment variable to your native architecture -# On Windows: -# gem install mysql -# Choose the win32 build. -# Install MySQL and put its /bin directory on your path. +# gem install mysql2 # # And be sure to use new-style password hashing: # http://dev.mysql.com/doc/refman/5.0/en/old-client.html development: - adapter: mysql + adapter: mysql2 encoding: utf8 reconnect: false database: <%= app_name %>_development @@ -32,7 +23,7 @@ development: # re-generated from your development database when you run "rake". # Do not set this db to the same as development or production. test: - adapter: mysql + adapter: mysql2 encoding: utf8 reconnect: false database: <%= app_name %>_test @@ -46,7 +37,7 @@ test: <% end -%> production: - adapter: mysql + adapter: mysql2 encoding: utf8 reconnect: false database: <%= app_name %>_production diff --git a/railties/lib/rails/generators/rails/app/templates/config/databases/oracle.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/oracle.yml index fddf8b8144..b661a60389 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/databases/oracle.yml +++ b/railties/lib/rails/generators/rails/app/templates/config/databases/oracle.yml @@ -10,7 +10,7 @@ # # By default prefetch_rows (OCI_ATTR_PREFETCH_ROWS) is set to 100. And # until true bind variables are supported, cursor_sharing is set by default -# to 'similar'. Both can be changed in the configation below; the defaults +# to 'similar'. Both can be changed in the configuration below; the defaults # are equivalent to specifying: # # prefetch_rows: 100 diff --git a/railties/lib/rails/generators/rails/app/templates/config/databases/sqlite3.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/sqlite3.yml index 025d62a8d8..90d87cc295 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/databases/sqlite3.yml +++ b/railties/lib/rails/generators/rails/app/templates/config/databases/sqlite3.yml @@ -1,5 +1,5 @@ # SQLite version 3.x -# gem install sqlite3-ruby (not necessary on OS X Leopard) +# gem install sqlite3 development: adapter: sqlite3 database: db/development.sqlite3 diff --git a/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt index 7616614aff..91d3133ea4 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt +++ b/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt @@ -1,5 +1,5 @@ <%= app_const %>.configure do - # Settings specified here will take precedence over those in config/environment.rb + # Settings specified here will take precedence over those in config/application.rb # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development diff --git a/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt index 500fc4d860..89bb891ddd 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt +++ b/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt @@ -1,5 +1,5 @@ <%= app_const %>.configure do - # Settings specified here will take precedence over those in config/environment.rb + # Settings specified here will take precedence over those in config/application.rb # The production environment is meant for finished, "live" apps. # Code is not reloaded between requests diff --git a/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt index 26cdef071a..d8d1e55157 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt +++ b/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt @@ -1,5 +1,5 @@ <%= app_const %>.configure do - # Settings specified here will take precedence over those in config/environment.rb + # Settings specified here will take precedence over those in config/application.rb # The test environment is used exclusively to run your application's # test suite. You never need to work with it otherwise. Remember that diff --git a/railties/lib/rails/generators/rails/app/templates/config/initializers/session_store.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/initializers/session_store.rb.tt index 0aed79bb70..62aa06dc3e 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/initializers/session_store.rb.tt +++ b/railties/lib/rails/generators/rails/app/templates/config/initializers/session_store.rb.tt @@ -4,5 +4,5 @@ # Use the database for sessions instead of the cookie-based default, # which shouldn't be used to store highly confidential information -# (create the session table with "rake db:sessions:create") +# (create the session table with "rails generate session_migration") # <%= app_const %>.config.session_store :active_record_store diff --git a/railties/lib/rails/generators/rails/app/templates/config/locales/en.yml b/railties/lib/rails/generators/rails/app/templates/config/locales/en.yml index a747bfa698..179c14ca52 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/locales/en.yml +++ b/railties/lib/rails/generators/rails/app/templates/config/locales/en.yml @@ -1,5 +1,5 @@ # Sample localization file for English. Add more files in this directory for other locales. -# See http://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points. +# See https://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points. en: hello: "Hello world" diff --git a/railties/lib/rails/generators/rails/app/templates/config/routes.rb b/railties/lib/rails/generators/rails/app/templates/config/routes.rb index d42cf3bfdf..d50f536164 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/routes.rb +++ b/railties/lib/rails/generators/rails/app/templates/config/routes.rb @@ -16,12 +16,12 @@ # Sample resource route with options: # resources :products do # member do - # get :short - # post :toggle + # get 'short' + # post 'toggle' # end # # collection do - # get :sold + # get 'sold' # end # end @@ -35,7 +35,7 @@ # resources :products do # resources :comments # resources :sales do - # get :recent, :on => :collection + # get 'recent', :on => :collection # end # end @@ -48,7 +48,7 @@ # You can have the root of your site routed with "root" # just remember to delete public/index.html. - # root :to => "welcome#index" + # root :to => 'welcome#index' # See how all your routes lay out with "rake routes" diff --git a/railties/lib/rails/generators/rails/app/templates/gitignore b/railties/lib/rails/generators/rails/app/templates/gitignore index af64fae5e7..f0fa30c536 100644 --- a/railties/lib/rails/generators/rails/app/templates/gitignore +++ b/railties/lib/rails/generators/rails/app/templates/gitignore @@ -1,4 +1,4 @@ .bundle db/*.sqlite3 log/*.log -tmp/**/* +tmp/ diff --git a/railties/lib/rails/generators/rails/app/templates/public/index.html b/railties/lib/rails/generators/rails/app/templates/public/index.html index 75d5edd06d..13a203dd08 100644 --- a/railties/lib/rails/generators/rails/app/templates/public/index.html +++ b/railties/lib/rails/generators/rails/app/templates/public/index.html @@ -52,7 +52,6 @@ clear: both; } - #header, #about, #getting-started { padding-left: 75px; padding-right: 30px; @@ -168,6 +167,9 @@ margin-bottom: 5px; } + .filename { + font-style: italic; + } </style> <script type="text/javascript"> function about() { @@ -190,10 +192,10 @@ <li> <h3>Browse the documentation</h3> <ul class="links"> - <li><a href="http://api.rubyonrails.org/">Rails API</a></li> - <li><a href="http://stdlib.rubyonrails.org/">Ruby standard library</a></li> - <li><a href="http://corelib.rubyonrails.org/">Ruby core</a></li> <li><a href="http://guides.rubyonrails.org/">Rails Guides</a></li> + <li><a href="http://api.rubyonrails.org/">Rails API</a></li> + <li><a href="http://www.ruby-doc.org/core/">Ruby core</a></li> + <li><a href="http://www.ruby-doc.org/stdlib/">Ruby standard library</a></li> </ul> </li> </ul> @@ -221,13 +223,13 @@ </li> <li> - <h2>Set up a default route and remove or rename this file</h2> - <p>Routes are set up in config/routes.rb.</p> + <h2>Set up a default route and remove <span class="filename">public/index.html</span></h2> + <p>Routes are set up in <span class="filename">config/routes.rb</span>.</p> </li> <li> <h2>Create your database</h2> - <p>Run <code>rake db:migrate</code> to create your database. If you're not using SQLite (the default), edit <code>config/database.yml</code> with your username and password.</p> + <p>Run <code>rake db:create</code> to create your database. If you're not using SQLite (the default), edit <span class="filename">config/database.yml</span> with your username and password.</p> </li> </ol> </div> diff --git a/railties/lib/rails/generators/rails/app/templates/public/javascripts/effects.js b/railties/lib/rails/generators/rails/app/templates/public/javascripts/effects.js index 066ee5909c..c81e6c7d5f 100644 --- a/railties/lib/rails/generators/rails/app/templates/public/javascripts/effects.js +++ b/railties/lib/rails/generators/rails/app/templates/public/javascripts/effects.js @@ -150,7 +150,7 @@ var Effect = { toggle: function(element, effect, options) { element = $(element); effect = (effect || 'appear').toLowerCase(); - + return Effect[ Effect.PAIRS[ effect ][ element.visible() ? 1 : 0 ] ](element, Object.extend({ queue: { position:'end', scope:(element.id || 'global'), limit: 1 } }, options || {})); diff --git a/railties/lib/rails/generators/rails/app/templates/public/javascripts/jquery.js b/railties/lib/rails/generators/rails/app/templates/public/javascripts/jquery.js new file mode 100644 index 0000000000..aa3a4f34fd --- /dev/null +++ b/railties/lib/rails/generators/rails/app/templates/public/javascripts/jquery.js @@ -0,0 +1,8176 @@ +/*! + * jQuery JavaScript Library v1.5 + * http://jquery.com/ + * + * Copyright 2011, John Resig + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * Includes Sizzle.js + * http://sizzlejs.com/ + * Copyright 2011, The Dojo Foundation + * Released under the MIT, BSD, and GPL Licenses. + * + * Date: Mon Jan 31 08:31:29 2011 -0500 + */ +(function( window, undefined ) { + +// Use the correct document accordingly with window argument (sandbox) +var document = window.document; +var jQuery = (function() { + +// Define a local copy of jQuery +var jQuery = function( selector, context ) { + // The jQuery object is actually just the init constructor 'enhanced' + return new jQuery.fn.init( selector, context, rootjQuery ); + }, + + // Map over jQuery in case of overwrite + _jQuery = window.jQuery, + + // Map over the $ in case of overwrite + _$ = window.$, + + // A central reference to the root jQuery(document) + rootjQuery, + + // A simple way to check for HTML strings or ID strings + // (both of which we optimize for) + quickExpr = /^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/, + + // Check if a string has a non-whitespace character in it + rnotwhite = /\S/, + + // Used for trimming whitespace + trimLeft = /^\s+/, + trimRight = /\s+$/, + + // Check for digits + rdigit = /\d/, + + // Match a standalone tag + rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, + + // JSON RegExp + rvalidchars = /^[\],:{}\s]*$/, + rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, + rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, + rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, + + // Useragent RegExp + rwebkit = /(webkit)[ \/]([\w.]+)/, + ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/, + rmsie = /(msie) ([\w.]+)/, + rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/, + + // Keep a UserAgent string for use with jQuery.browser + userAgent = navigator.userAgent, + + // For matching the engine and version of the browser + browserMatch, + + // Has the ready events already been bound? + readyBound = false, + + // The deferred used on DOM ready + readyList, + + // Promise methods + promiseMethods = "then done fail isResolved isRejected promise".split( " " ), + + // The ready event handler + DOMContentLoaded, + + // Save a reference to some core methods + toString = Object.prototype.toString, + hasOwn = Object.prototype.hasOwnProperty, + push = Array.prototype.push, + slice = Array.prototype.slice, + trim = String.prototype.trim, + indexOf = Array.prototype.indexOf, + + // [[Class]] -> type pairs + class2type = {}; + +jQuery.fn = jQuery.prototype = { + constructor: jQuery, + init: function( selector, context, rootjQuery ) { + var match, elem, ret, doc; + + // Handle $(""), $(null), or $(undefined) + if ( !selector ) { + return this; + } + + // Handle $(DOMElement) + if ( selector.nodeType ) { + this.context = this[0] = selector; + this.length = 1; + return this; + } + + // The body element only exists once, optimize finding it + if ( selector === "body" && !context && document.body ) { + this.context = document; + this[0] = document.body; + this.selector = "body"; + this.length = 1; + return this; + } + + // Handle HTML strings + if ( typeof selector === "string" ) { + // Are we dealing with HTML string or an ID? + match = quickExpr.exec( selector ); + + // Verify a match, and that no context was specified for #id + if ( match && (match[1] || !context) ) { + + // HANDLE: $(html) -> $(array) + if ( match[1] ) { + context = context instanceof jQuery ? context[0] : context; + doc = (context ? context.ownerDocument || context : document); + + // If a single string is passed in and it's a single tag + // just do a createElement and skip the rest + ret = rsingleTag.exec( selector ); + + if ( ret ) { + if ( jQuery.isPlainObject( context ) ) { + selector = [ document.createElement( ret[1] ) ]; + jQuery.fn.attr.call( selector, context, true ); + + } else { + selector = [ doc.createElement( ret[1] ) ]; + } + + } else { + ret = jQuery.buildFragment( [ match[1] ], [ doc ] ); + selector = (ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment).childNodes; + } + + return jQuery.merge( this, selector ); + + // HANDLE: $("#id") + } else { + elem = document.getElementById( match[2] ); + + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + if ( elem && elem.parentNode ) { + // Handle the case where IE and Opera return items + // by name instead of ID + if ( elem.id !== match[2] ) { + return rootjQuery.find( selector ); + } + + // Otherwise, we inject the element directly into the jQuery object + this.length = 1; + this[0] = elem; + } + + this.context = document; + this.selector = selector; + return this; + } + + // HANDLE: $(expr, $(...)) + } else if ( !context || context.jquery ) { + return (context || rootjQuery).find( selector ); + + // HANDLE: $(expr, context) + // (which is just equivalent to: $(context).find(expr) + } else { + return this.constructor( context ).find( selector ); + } + + // HANDLE: $(function) + // Shortcut for document ready + } else if ( jQuery.isFunction( selector ) ) { + return rootjQuery.ready( selector ); + } + + if (selector.selector !== undefined) { + this.selector = selector.selector; + this.context = selector.context; + } + + return jQuery.makeArray( selector, this ); + }, + + // Start with an empty selector + selector: "", + + // The current version of jQuery being used + jquery: "1.5", + + // The default length of a jQuery object is 0 + length: 0, + + // The number of elements contained in the matched element set + size: function() { + return this.length; + }, + + toArray: function() { + return slice.call( this, 0 ); + }, + + // Get the Nth element in the matched element set OR + // Get the whole matched element set as a clean array + get: function( num ) { + return num == null ? + + // Return a 'clean' array + this.toArray() : + + // Return just the object + ( num < 0 ? this[ this.length + num ] : this[ num ] ); + }, + + // Take an array of elements and push it onto the stack + // (returning the new matched element set) + pushStack: function( elems, name, selector ) { + // Build a new jQuery matched element set + var ret = this.constructor(); + + if ( jQuery.isArray( elems ) ) { + push.apply( ret, elems ); + + } else { + jQuery.merge( ret, elems ); + } + + // Add the old object onto the stack (as a reference) + ret.prevObject = this; + + ret.context = this.context; + + if ( name === "find" ) { + ret.selector = this.selector + (this.selector ? " " : "") + selector; + } else if ( name ) { + ret.selector = this.selector + "." + name + "(" + selector + ")"; + } + + // Return the newly-formed element set + return ret; + }, + + // Execute a callback for every element in the matched set. + // (You can seed the arguments with an array of args, but this is + // only used internally.) + each: function( callback, args ) { + return jQuery.each( this, callback, args ); + }, + + ready: function( fn ) { + // Attach the listeners + jQuery.bindReady(); + + // Add the callback + readyList.done( fn ); + + return this; + }, + + eq: function( i ) { + return i === -1 ? + this.slice( i ) : + this.slice( i, +i + 1 ); + }, + + first: function() { + return this.eq( 0 ); + }, + + last: function() { + return this.eq( -1 ); + }, + + slice: function() { + return this.pushStack( slice.apply( this, arguments ), + "slice", slice.call(arguments).join(",") ); + }, + + map: function( callback ) { + return this.pushStack( jQuery.map(this, function( elem, i ) { + return callback.call( elem, i, elem ); + })); + }, + + end: function() { + return this.prevObject || this.constructor(null); + }, + + // For internal use only. + // Behaves like an Array's method, not like a jQuery method. + push: push, + sort: [].sort, + splice: [].splice +}; + +// Give the init function the jQuery prototype for later instantiation +jQuery.fn.init.prototype = jQuery.fn; + +jQuery.extend = jQuery.fn.extend = function() { + var options, name, src, copy, copyIsArray, clone, + target = arguments[0] || {}, + i = 1, + length = arguments.length, + deep = false; + + // Handle a deep copy situation + if ( typeof target === "boolean" ) { + deep = target; + target = arguments[1] || {}; + // skip the boolean and the target + i = 2; + } + + // Handle case when target is a string or something (possible in deep copy) + if ( typeof target !== "object" && !jQuery.isFunction(target) ) { + target = {}; + } + + // extend jQuery itself if only one argument is passed + if ( length === i ) { + target = this; + --i; + } + + for ( ; i < length; i++ ) { + // Only deal with non-null/undefined values + if ( (options = arguments[ i ]) != null ) { + // Extend the base object + for ( name in options ) { + src = target[ name ]; + copy = options[ name ]; + + // Prevent never-ending loop + if ( target === copy ) { + continue; + } + + // Recurse if we're merging plain objects or arrays + if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { + if ( copyIsArray ) { + copyIsArray = false; + clone = src && jQuery.isArray(src) ? src : []; + + } else { + clone = src && jQuery.isPlainObject(src) ? src : {}; + } + + // Never move original objects, clone them + target[ name ] = jQuery.extend( deep, clone, copy ); + + // Don't bring in undefined values + } else if ( copy !== undefined ) { + target[ name ] = copy; + } + } + } + } + + // Return the modified object + return target; +}; + +jQuery.extend({ + noConflict: function( deep ) { + window.$ = _$; + + if ( deep ) { + window.jQuery = _jQuery; + } + + return jQuery; + }, + + // Is the DOM ready to be used? Set to true once it occurs. + isReady: false, + + // A counter to track how many items to wait for before + // the ready event fires. See #6781 + readyWait: 1, + + // Handle when the DOM is ready + ready: function( wait ) { + // A third-party is pushing the ready event forwards + if ( wait === true ) { + jQuery.readyWait--; + } + + // Make sure that the DOM is not already loaded + if ( !jQuery.readyWait || (wait !== true && !jQuery.isReady) ) { + // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). + if ( !document.body ) { + return setTimeout( jQuery.ready, 1 ); + } + + // Remember that the DOM is ready + jQuery.isReady = true; + + // If a normal DOM Ready event fired, decrement, and wait if need be + if ( wait !== true && --jQuery.readyWait > 0 ) { + return; + } + + // If there are functions bound, to execute + readyList.resolveWith( document, [ jQuery ] ); + + // Trigger any bound ready events + if ( jQuery.fn.trigger ) { + jQuery( document ).trigger( "ready" ).unbind( "ready" ); + } + } + }, + + bindReady: function() { + if ( readyBound ) { + return; + } + + readyBound = true; + + // Catch cases where $(document).ready() is called after the + // browser event has already occurred. + if ( document.readyState === "complete" ) { + // Handle it asynchronously to allow scripts the opportunity to delay ready + return setTimeout( jQuery.ready, 1 ); + } + + // Mozilla, Opera and webkit nightlies currently support this event + if ( document.addEventListener ) { + // Use the handy event callback + document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); + + // A fallback to window.onload, that will always work + window.addEventListener( "load", jQuery.ready, false ); + + // If IE event model is used + } else if ( document.attachEvent ) { + // ensure firing before onload, + // maybe late but safe also for iframes + document.attachEvent("onreadystatechange", DOMContentLoaded); + + // A fallback to window.onload, that will always work + window.attachEvent( "onload", jQuery.ready ); + + // If IE and not a frame + // continually check to see if the document is ready + var toplevel = false; + + try { + toplevel = window.frameElement == null; + } catch(e) {} + + if ( document.documentElement.doScroll && toplevel ) { + doScrollCheck(); + } + } + }, + + // See test/unit/core.js for details concerning isFunction. + // Since version 1.3, DOM methods and functions like alert + // aren't supported. They return false on IE (#2968). + isFunction: function( obj ) { + return jQuery.type(obj) === "function"; + }, + + isArray: Array.isArray || function( obj ) { + return jQuery.type(obj) === "array"; + }, + + // A crude way of determining if an object is a window + isWindow: function( obj ) { + return obj && typeof obj === "object" && "setInterval" in obj; + }, + + isNaN: function( obj ) { + return obj == null || !rdigit.test( obj ) || isNaN( obj ); + }, + + type: function( obj ) { + return obj == null ? + String( obj ) : + class2type[ toString.call(obj) ] || "object"; + }, + + isPlainObject: function( obj ) { + // Must be an Object. + // Because of IE, we also have to check the presence of the constructor property. + // Make sure that DOM nodes and window objects don't pass through, as well + if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { + return false; + } + + // Not own constructor property must be Object + if ( obj.constructor && + !hasOwn.call(obj, "constructor") && + !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { + return false; + } + + // Own properties are enumerated firstly, so to speed up, + // if last one is own, then all properties are own. + + var key; + for ( key in obj ) {} + + return key === undefined || hasOwn.call( obj, key ); + }, + + isEmptyObject: function( obj ) { + for ( var name in obj ) { + return false; + } + return true; + }, + + error: function( msg ) { + throw msg; + }, + + parseJSON: function( data ) { + if ( typeof data !== "string" || !data ) { + return null; + } + + // Make sure leading/trailing whitespace is removed (IE can't handle it) + data = jQuery.trim( data ); + + // Make sure the incoming data is actual JSON + // Logic borrowed from http://json.org/json2.js + if ( rvalidchars.test(data.replace(rvalidescape, "@") + .replace(rvalidtokens, "]") + .replace(rvalidbraces, "")) ) { + + // Try to use the native JSON parser first + return window.JSON && window.JSON.parse ? + window.JSON.parse( data ) : + (new Function("return " + data))(); + + } else { + jQuery.error( "Invalid JSON: " + data ); + } + }, + + // Cross-browser xml parsing + // (xml & tmp used internally) + parseXML: function( data , xml , tmp ) { + + if ( window.DOMParser ) { // Standard + tmp = new DOMParser(); + xml = tmp.parseFromString( data , "text/xml" ); + } else { // IE + xml = new ActiveXObject( "Microsoft.XMLDOM" ); + xml.async = "false"; + xml.loadXML( data ); + } + + tmp = xml.documentElement; + + if ( ! tmp || ! tmp.nodeName || tmp.nodeName === "parsererror" ) { + jQuery.error( "Invalid XML: " + data ); + } + + return xml; + }, + + noop: function() {}, + + // Evalulates a script in a global context + globalEval: function( data ) { + if ( data && rnotwhite.test(data) ) { + // Inspired by code by Andrea Giammarchi + // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html + var head = document.getElementsByTagName("head")[0] || document.documentElement, + script = document.createElement("script"); + + script.type = "text/javascript"; + + if ( jQuery.support.scriptEval() ) { + script.appendChild( document.createTextNode( data ) ); + } else { + script.text = data; + } + + // Use insertBefore instead of appendChild to circumvent an IE6 bug. + // This arises when a base node is used (#2709). + head.insertBefore( script, head.firstChild ); + head.removeChild( script ); + } + }, + + nodeName: function( elem, name ) { + return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase(); + }, + + // args is for internal usage only + each: function( object, callback, args ) { + var name, i = 0, + length = object.length, + isObj = length === undefined || jQuery.isFunction(object); + + if ( args ) { + if ( isObj ) { + for ( name in object ) { + if ( callback.apply( object[ name ], args ) === false ) { + break; + } + } + } else { + for ( ; i < length; ) { + if ( callback.apply( object[ i++ ], args ) === false ) { + break; + } + } + } + + // A special, fast, case for the most common use of each + } else { + if ( isObj ) { + for ( name in object ) { + if ( callback.call( object[ name ], name, object[ name ] ) === false ) { + break; + } + } + } else { + for ( var value = object[0]; + i < length && callback.call( value, i, value ) !== false; value = object[++i] ) {} + } + } + + return object; + }, + + // Use native String.trim function wherever possible + trim: trim ? + function( text ) { + return text == null ? + "" : + trim.call( text ); + } : + + // Otherwise use our own trimming functionality + function( text ) { + return text == null ? + "" : + text.toString().replace( trimLeft, "" ).replace( trimRight, "" ); + }, + + // results is for internal usage only + makeArray: function( array, results ) { + var ret = results || []; + + if ( array != null ) { + // The window, strings (and functions) also have 'length' + // The extra typeof function check is to prevent crashes + // in Safari 2 (See: #3039) + // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 + var type = jQuery.type(array); + + if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) { + push.call( ret, array ); + } else { + jQuery.merge( ret, array ); + } + } + + return ret; + }, + + inArray: function( elem, array ) { + if ( array.indexOf ) { + return array.indexOf( elem ); + } + + for ( var i = 0, length = array.length; i < length; i++ ) { + if ( array[ i ] === elem ) { + return i; + } + } + + return -1; + }, + + merge: function( first, second ) { + var i = first.length, + j = 0; + + if ( typeof second.length === "number" ) { + for ( var l = second.length; j < l; j++ ) { + first[ i++ ] = second[ j ]; + } + + } else { + while ( second[j] !== undefined ) { + first[ i++ ] = second[ j++ ]; + } + } + + first.length = i; + + return first; + }, + + grep: function( elems, callback, inv ) { + var ret = [], retVal; + inv = !!inv; + + // Go through the array, only saving the items + // that pass the validator function + for ( var i = 0, length = elems.length; i < length; i++ ) { + retVal = !!callback( elems[ i ], i ); + if ( inv !== retVal ) { + ret.push( elems[ i ] ); + } + } + + return ret; + }, + + // arg is for internal usage only + map: function( elems, callback, arg ) { + var ret = [], value; + + // Go through the array, translating each of the items to their + // new value (or values). + for ( var i = 0, length = elems.length; i < length; i++ ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret[ ret.length ] = value; + } + } + + // Flatten any nested arrays + return ret.concat.apply( [], ret ); + }, + + // A global GUID counter for objects + guid: 1, + + proxy: function( fn, proxy, thisObject ) { + if ( arguments.length === 2 ) { + if ( typeof proxy === "string" ) { + thisObject = fn; + fn = thisObject[ proxy ]; + proxy = undefined; + + } else if ( proxy && !jQuery.isFunction( proxy ) ) { + thisObject = proxy; + proxy = undefined; + } + } + + if ( !proxy && fn ) { + proxy = function() { + return fn.apply( thisObject || this, arguments ); + }; + } + + // Set the guid of unique handler to the same of original handler, so it can be removed + if ( fn ) { + proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; + } + + // So proxy can be declared as an argument + return proxy; + }, + + // Mutifunctional method to get and set values to a collection + // The value/s can be optionally by executed if its a function + access: function( elems, key, value, exec, fn, pass ) { + var length = elems.length; + + // Setting many attributes + if ( typeof key === "object" ) { + for ( var k in key ) { + jQuery.access( elems, k, key[k], exec, fn, value ); + } + return elems; + } + + // Setting one attribute + if ( value !== undefined ) { + // Optionally, function values get executed if exec is true + exec = !pass && exec && jQuery.isFunction(value); + + for ( var i = 0; i < length; i++ ) { + fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); + } + + return elems; + } + + // Getting an attribute + return length ? fn( elems[0], key ) : undefined; + }, + + now: function() { + return (new Date()).getTime(); + }, + + // Create a simple deferred (one callbacks list) + _Deferred: function() { + var // callbacks list + callbacks = [], + // stored [ context , args ] + fired, + // to avoid firing when already doing so + firing, + // flag to know if the deferred has been cancelled + cancelled, + // the deferred itself + deferred = { + + // done( f1, f2, ...) + done: function() { + if ( !cancelled ) { + var args = arguments, + i, + length, + elem, + type, + _fired; + if ( fired ) { + _fired = fired; + fired = 0; + } + for ( i = 0, length = args.length; i < length; i++ ) { + elem = args[ i ]; + type = jQuery.type( elem ); + if ( type === "array" ) { + deferred.done.apply( deferred, elem ); + } else if ( type === "function" ) { + callbacks.push( elem ); + } + } + if ( _fired ) { + deferred.resolveWith( _fired[ 0 ], _fired[ 1 ] ); + } + } + return this; + }, + + // resolve with given context and args + resolveWith: function( context, args ) { + if ( !cancelled && !fired && !firing ) { + firing = 1; + try { + while( callbacks[ 0 ] ) { + callbacks.shift().apply( context, args ); + } + } + finally { + fired = [ context, args ]; + firing = 0; + } + } + return this; + }, + + // resolve with this as context and given arguments + resolve: function() { + deferred.resolveWith( jQuery.isFunction( this.promise ) ? this.promise() : this, arguments ); + return this; + }, + + // Has this deferred been resolved? + isResolved: function() { + return !!( firing || fired ); + }, + + // Cancel + cancel: function() { + cancelled = 1; + callbacks = []; + return this; + } + }; + + return deferred; + }, + + // Full fledged deferred (two callbacks list) + Deferred: function( func ) { + var deferred = jQuery._Deferred(), + failDeferred = jQuery._Deferred(), + promise; + // Add errorDeferred methods, then and promise + jQuery.extend( deferred, { + then: function( doneCallbacks, failCallbacks ) { + deferred.done( doneCallbacks ).fail( failCallbacks ); + return this; + }, + fail: failDeferred.done, + rejectWith: failDeferred.resolveWith, + reject: failDeferred.resolve, + isRejected: failDeferred.isResolved, + // Get a promise for this deferred + // If obj is provided, the promise aspect is added to the object + promise: function( obj , i /* internal */ ) { + if ( obj == null ) { + if ( promise ) { + return promise; + } + promise = obj = {}; + } + i = promiseMethods.length; + while( i-- ) { + obj[ promiseMethods[ i ] ] = deferred[ promiseMethods[ i ] ]; + } + return obj; + } + } ); + // Make sure only one callback list will be used + deferred.then( failDeferred.cancel, deferred.cancel ); + // Unexpose cancel + delete deferred.cancel; + // Call given func if any + if ( func ) { + func.call( deferred, deferred ); + } + return deferred; + }, + + // Deferred helper + when: function( object ) { + var args = arguments, + length = args.length, + deferred = length <= 1 && object && jQuery.isFunction( object.promise ) ? + object : + jQuery.Deferred(), + promise = deferred.promise(), + resolveArray; + + if ( length > 1 ) { + resolveArray = new Array( length ); + jQuery.each( args, function( index, element ) { + jQuery.when( element ).then( function( value ) { + resolveArray[ index ] = arguments.length > 1 ? slice.call( arguments, 0 ) : value; + if( ! --length ) { + deferred.resolveWith( promise, resolveArray ); + } + }, deferred.reject ); + } ); + } else if ( deferred !== object ) { + deferred.resolve( object ); + } + return promise; + }, + + // Use of jQuery.browser is frowned upon. + // More details: http://docs.jquery.com/Utilities/jQuery.browser + uaMatch: function( ua ) { + ua = ua.toLowerCase(); + + var match = rwebkit.exec( ua ) || + ropera.exec( ua ) || + rmsie.exec( ua ) || + ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) || + []; + + return { browser: match[1] || "", version: match[2] || "0" }; + }, + + sub: function() { + function jQuerySubclass( selector, context ) { + return new jQuerySubclass.fn.init( selector, context ); + } + jQuery.extend( true, jQuerySubclass, this ); + jQuerySubclass.superclass = this; + jQuerySubclass.fn = jQuerySubclass.prototype = this(); + jQuerySubclass.fn.constructor = jQuerySubclass; + jQuerySubclass.subclass = this.subclass; + jQuerySubclass.fn.init = function init( selector, context ) { + if ( context && context instanceof jQuery && !(context instanceof jQuerySubclass) ) { + context = jQuerySubclass(context); + } + + return jQuery.fn.init.call( this, selector, context, rootjQuerySubclass ); + }; + jQuerySubclass.fn.init.prototype = jQuerySubclass.fn; + var rootjQuerySubclass = jQuerySubclass(document); + return jQuerySubclass; + }, + + browser: {} +}); + +// Create readyList deferred +readyList = jQuery._Deferred(); + +// Populate the class2type map +jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { + class2type[ "[object " + name + "]" ] = name.toLowerCase(); +}); + +browserMatch = jQuery.uaMatch( userAgent ); +if ( browserMatch.browser ) { + jQuery.browser[ browserMatch.browser ] = true; + jQuery.browser.version = browserMatch.version; +} + +// Deprecated, use jQuery.browser.webkit instead +if ( jQuery.browser.webkit ) { + jQuery.browser.safari = true; +} + +if ( indexOf ) { + jQuery.inArray = function( elem, array ) { + return indexOf.call( array, elem ); + }; +} + +// IE doesn't match non-breaking spaces with \s +if ( rnotwhite.test( "\xA0" ) ) { + trimLeft = /^[\s\xA0]+/; + trimRight = /[\s\xA0]+$/; +} + +// All jQuery objects should point back to these +rootjQuery = jQuery(document); + +// Cleanup functions for the document ready method +if ( document.addEventListener ) { + DOMContentLoaded = function() { + document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); + jQuery.ready(); + }; + +} else if ( document.attachEvent ) { + DOMContentLoaded = function() { + // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). + if ( document.readyState === "complete" ) { + document.detachEvent( "onreadystatechange", DOMContentLoaded ); + jQuery.ready(); + } + }; +} + +// The DOM ready check for Internet Explorer +function doScrollCheck() { + if ( jQuery.isReady ) { + return; + } + + try { + // If IE is used, use the trick by Diego Perini + // http://javascript.nwbox.com/IEContentLoaded/ + document.documentElement.doScroll("left"); + } catch(e) { + setTimeout( doScrollCheck, 1 ); + return; + } + + // and execute any waiting functions + jQuery.ready(); +} + +// Expose jQuery to the global object +return (window.jQuery = window.$ = jQuery); + +})(); + + +(function() { + + jQuery.support = {}; + + var div = document.createElement("div"); + + div.style.display = "none"; + div.innerHTML = " <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>"; + + var all = div.getElementsByTagName("*"), + a = div.getElementsByTagName("a")[0], + select = document.createElement("select"), + opt = select.appendChild( document.createElement("option") ); + + // Can't get basic test support + if ( !all || !all.length || !a ) { + return; + } + + jQuery.support = { + // IE strips leading whitespace when .innerHTML is used + leadingWhitespace: div.firstChild.nodeType === 3, + + // Make sure that tbody elements aren't automatically inserted + // IE will insert them into empty tables + tbody: !div.getElementsByTagName("tbody").length, + + // Make sure that link elements get serialized correctly by innerHTML + // This requires a wrapper element in IE + htmlSerialize: !!div.getElementsByTagName("link").length, + + // Get the style information from getAttribute + // (IE uses .cssText insted) + style: /red/.test( a.getAttribute("style") ), + + // Make sure that URLs aren't manipulated + // (IE normalizes it by default) + hrefNormalized: a.getAttribute("href") === "/a", + + // Make sure that element opacity exists + // (IE uses filter instead) + // Use a regex to work around a WebKit issue. See #5145 + opacity: /^0.55$/.test( a.style.opacity ), + + // Verify style float existence + // (IE uses styleFloat instead of cssFloat) + cssFloat: !!a.style.cssFloat, + + // Make sure that if no value is specified for a checkbox + // that it defaults to "on". + // (WebKit defaults to "" instead) + checkOn: div.getElementsByTagName("input")[0].value === "on", + + // Make sure that a selected-by-default option has a working selected property. + // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) + optSelected: opt.selected, + + // Will be defined later + deleteExpando: true, + optDisabled: false, + checkClone: false, + _scriptEval: null, + noCloneEvent: true, + boxModel: null, + inlineBlockNeedsLayout: false, + shrinkWrapBlocks: false, + reliableHiddenOffsets: true + }; + + // Make sure that the options inside disabled selects aren't marked as disabled + // (WebKit marks them as diabled) + select.disabled = true; + jQuery.support.optDisabled = !opt.disabled; + + jQuery.support.scriptEval = function() { + if ( jQuery.support._scriptEval === null ) { + var root = document.documentElement, + script = document.createElement("script"), + id = "script" + jQuery.now(); + + script.type = "text/javascript"; + try { + script.appendChild( document.createTextNode( "window." + id + "=1;" ) ); + } catch(e) {} + + root.insertBefore( script, root.firstChild ); + + // Make sure that the execution of code works by injecting a script + // tag with appendChild/createTextNode + // (IE doesn't support this, fails, and uses .text instead) + if ( window[ id ] ) { + jQuery.support._scriptEval = true; + delete window[ id ]; + } else { + jQuery.support._scriptEval = false; + } + + root.removeChild( script ); + // release memory in IE + root = script = id = null; + } + + return jQuery.support._scriptEval; + }; + + // Test to see if it's possible to delete an expando from an element + // Fails in Internet Explorer + try { + delete div.test; + + } catch(e) { + jQuery.support.deleteExpando = false; + } + + if ( div.attachEvent && div.fireEvent ) { + div.attachEvent("onclick", function click() { + // Cloning a node shouldn't copy over any + // bound event handlers (IE does this) + jQuery.support.noCloneEvent = false; + div.detachEvent("onclick", click); + }); + div.cloneNode(true).fireEvent("onclick"); + } + + div = document.createElement("div"); + div.innerHTML = "<input type='radio' name='radiotest' checked='checked'/>"; + + var fragment = document.createDocumentFragment(); + fragment.appendChild( div.firstChild ); + + // WebKit doesn't clone checked state correctly in fragments + jQuery.support.checkClone = fragment.cloneNode(true).cloneNode(true).lastChild.checked; + + // Figure out if the W3C box model works as expected + // document.body must exist before we can do this + jQuery(function() { + var div = document.createElement("div"), + body = document.getElementsByTagName("body")[0]; + + // Frameset documents with no body should not run this code + if ( !body ) { + return; + } + + div.style.width = div.style.paddingLeft = "1px"; + body.appendChild( div ); + jQuery.boxModel = jQuery.support.boxModel = div.offsetWidth === 2; + + if ( "zoom" in div.style ) { + // Check if natively block-level elements act like inline-block + // elements when setting their display to 'inline' and giving + // them layout + // (IE < 8 does this) + div.style.display = "inline"; + div.style.zoom = 1; + jQuery.support.inlineBlockNeedsLayout = div.offsetWidth === 2; + + // Check if elements with layout shrink-wrap their children + // (IE 6 does this) + div.style.display = ""; + div.innerHTML = "<div style='width:4px;'></div>"; + jQuery.support.shrinkWrapBlocks = div.offsetWidth !== 2; + } + + div.innerHTML = "<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>"; + var tds = div.getElementsByTagName("td"); + + // Check if table cells still have offsetWidth/Height when they are set + // to display:none and there are still other visible table cells in a + // table row; if so, offsetWidth/Height are not reliable for use when + // determining if an element has been hidden directly using + // display:none (it is still safe to use offsets if a parent element is + // hidden; don safety goggles and see bug #4512 for more information). + // (only IE 8 fails this test) + jQuery.support.reliableHiddenOffsets = tds[0].offsetHeight === 0; + + tds[0].style.display = ""; + tds[1].style.display = "none"; + + // Check if empty table cells still have offsetWidth/Height + // (IE < 8 fail this test) + jQuery.support.reliableHiddenOffsets = jQuery.support.reliableHiddenOffsets && tds[0].offsetHeight === 0; + div.innerHTML = ""; + + body.removeChild( div ).style.display = "none"; + div = tds = null; + }); + + // Technique from Juriy Zaytsev + // http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/ + var eventSupported = function( eventName ) { + var el = document.createElement("div"); + eventName = "on" + eventName; + + // We only care about the case where non-standard event systems + // are used, namely in IE. Short-circuiting here helps us to + // avoid an eval call (in setAttribute) which can cause CSP + // to go haywire. See: https://developer.mozilla.org/en/Security/CSP + if ( !el.attachEvent ) { + return true; + } + + var isSupported = (eventName in el); + if ( !isSupported ) { + el.setAttribute(eventName, "return;"); + isSupported = typeof el[eventName] === "function"; + } + el = null; + + return isSupported; + }; + + jQuery.support.submitBubbles = eventSupported("submit"); + jQuery.support.changeBubbles = eventSupported("change"); + + // release memory in IE + div = all = a = null; +})(); + + + +var rbrace = /^(?:\{.*\}|\[.*\])$/; + +jQuery.extend({ + cache: {}, + + // Please use with caution + uuid: 0, + + // Unique for each copy of jQuery on the page + // Non-digits removed to match rinlinejQuery + expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ), + + // The following elements throw uncatchable exceptions if you + // attempt to add expando properties to them. + noData: { + "embed": true, + // Ban all objects except for Flash (which handle expandos) + "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", + "applet": true + }, + + hasData: function( elem ) { + elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; + + return !!elem && !jQuery.isEmptyObject(elem); + }, + + data: function( elem, name, data, pvt /* Internal Use Only */ ) { + if ( !jQuery.acceptData( elem ) ) { + return; + } + + var internalKey = jQuery.expando, getByName = typeof name === "string", thisCache, + + // We have to handle DOM nodes and JS objects differently because IE6-7 + // can't GC object references properly across the DOM-JS boundary + isNode = elem.nodeType, + + // Only DOM nodes need the global jQuery cache; JS object data is + // attached directly to the object so GC can occur automatically + cache = isNode ? jQuery.cache : elem, + + // Only defining an ID for JS objects if its cache already exists allows + // the code to shortcut on the same path as a DOM node with no cache + id = isNode ? elem[ jQuery.expando ] : elem[ jQuery.expando ] && jQuery.expando; + + // Avoid doing any more work than we need to when trying to get data on an + // object that has no data at all + if ( (!id || (pvt && id && !cache[ id ][ internalKey ])) && getByName && data === undefined ) { + return; + } + + if ( !id ) { + // Only DOM nodes need a new unique ID for each element since their data + // ends up in the global cache + if ( isNode ) { + elem[ jQuery.expando ] = id = ++jQuery.uuid; + } else { + id = jQuery.expando; + } + } + + if ( !cache[ id ] ) { + cache[ id ] = {}; + } + + // An object can be passed to jQuery.data instead of a key/value pair; this gets + // shallow copied over onto the existing cache + if ( typeof name === "object" ) { + if ( pvt ) { + cache[ id ][ internalKey ] = jQuery.extend(cache[ id ][ internalKey ], name); + } else { + cache[ id ] = jQuery.extend(cache[ id ], name); + } + } + + thisCache = cache[ id ]; + + // Internal jQuery data is stored in a separate object inside the object's data + // cache in order to avoid key collisions between internal data and user-defined + // data + if ( pvt ) { + if ( !thisCache[ internalKey ] ) { + thisCache[ internalKey ] = {}; + } + + thisCache = thisCache[ internalKey ]; + } + + if ( data !== undefined ) { + thisCache[ name ] = data; + } + + // TODO: This is a hack for 1.5 ONLY. It will be removed in 1.6. Users should + // not attempt to inspect the internal events object using jQuery.data, as this + // internal data object is undocumented and subject to change. + if ( name === "events" && !thisCache[name] ) { + return thisCache[ internalKey ] && thisCache[ internalKey ].events; + } + + return getByName ? thisCache[ name ] : thisCache; + }, + + removeData: function( elem, name, pvt /* Internal Use Only */ ) { + if ( !jQuery.acceptData( elem ) ) { + return; + } + + var internalKey = jQuery.expando, isNode = elem.nodeType, + + // See jQuery.data for more information + cache = isNode ? jQuery.cache : elem, + + // See jQuery.data for more information + id = isNode ? elem[ jQuery.expando ] : jQuery.expando; + + // If there is already no cache entry for this object, there is no + // purpose in continuing + if ( !cache[ id ] ) { + return; + } + + if ( name ) { + var thisCache = pvt ? cache[ id ][ internalKey ] : cache[ id ]; + + if ( thisCache ) { + delete thisCache[ name ]; + + // If there is no data left in the cache, we want to continue + // and let the cache object itself get destroyed + if ( !jQuery.isEmptyObject(thisCache) ) { + return; + } + } + } + + // See jQuery.data for more information + if ( pvt ) { + delete cache[ id ][ internalKey ]; + + // Don't destroy the parent cache unless the internal data object + // had been the only thing left in it + if ( !jQuery.isEmptyObject(cache[ id ]) ) { + return; + } + } + + var internalCache = cache[ id ][ internalKey ]; + + // Browsers that fail expando deletion also refuse to delete expandos on + // the window, but it will allow it on all other JS objects; other browsers + // don't care + if ( jQuery.support.deleteExpando || cache != window ) { + delete cache[ id ]; + } else { + cache[ id ] = null; + } + + // We destroyed the entire user cache at once because it's faster than + // iterating through each key, but we need to continue to persist internal + // data if it existed + if ( internalCache ) { + cache[ id ] = {}; + cache[ id ][ internalKey ] = internalCache; + + // Otherwise, we need to eliminate the expando on the node to avoid + // false lookups in the cache for entries that no longer exist + } else if ( isNode ) { + // IE does not allow us to delete expando properties from nodes, + // nor does it have a removeAttribute function on Document nodes; + // we must handle all of these cases + if ( jQuery.support.deleteExpando ) { + delete elem[ jQuery.expando ]; + } else if ( elem.removeAttribute ) { + elem.removeAttribute( jQuery.expando ); + } else { + elem[ jQuery.expando ] = null; + } + } + }, + + // For internal use only. + _data: function( elem, name, data ) { + return jQuery.data( elem, name, data, true ); + }, + + // A method for determining if a DOM node can handle the data expando + acceptData: function( elem ) { + if ( elem.nodeName ) { + var match = jQuery.noData[ elem.nodeName.toLowerCase() ]; + + if ( match ) { + return !(match === true || elem.getAttribute("classid") !== match); + } + } + + return true; + } +}); + +jQuery.fn.extend({ + data: function( key, value ) { + var data = null; + + if ( typeof key === "undefined" ) { + if ( this.length ) { + data = jQuery.data( this[0] ); + + if ( this[0].nodeType === 1 ) { + var attr = this[0].attributes, name; + for ( var i = 0, l = attr.length; i < l; i++ ) { + name = attr[i].name; + + if ( name.indexOf( "data-" ) === 0 ) { + name = name.substr( 5 ); + dataAttr( this[0], name, data[ name ] ); + } + } + } + } + + return data; + + } else if ( typeof key === "object" ) { + return this.each(function() { + jQuery.data( this, key ); + }); + } + + var parts = key.split("."); + parts[1] = parts[1] ? "." + parts[1] : ""; + + if ( value === undefined ) { + data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]); + + // Try to fetch any internally stored data first + if ( data === undefined && this.length ) { + data = jQuery.data( this[0], key ); + data = dataAttr( this[0], key, data ); + } + + return data === undefined && parts[1] ? + this.data( parts[0] ) : + data; + + } else { + return this.each(function() { + var $this = jQuery( this ), + args = [ parts[0], value ]; + + $this.triggerHandler( "setData" + parts[1] + "!", args ); + jQuery.data( this, key, value ); + $this.triggerHandler( "changeData" + parts[1] + "!", args ); + }); + } + }, + + removeData: function( key ) { + return this.each(function() { + jQuery.removeData( this, key ); + }); + } +}); + +function dataAttr( elem, key, data ) { + // If nothing was found internally, try to fetch any + // data from the HTML5 data-* attribute + if ( data === undefined && elem.nodeType === 1 ) { + data = elem.getAttribute( "data-" + key ); + + if ( typeof data === "string" ) { + try { + data = data === "true" ? true : + data === "false" ? false : + data === "null" ? null : + !jQuery.isNaN( data ) ? parseFloat( data ) : + rbrace.test( data ) ? jQuery.parseJSON( data ) : + data; + } catch( e ) {} + + // Make sure we set the data so it isn't changed later + jQuery.data( elem, key, data ); + + } else { + data = undefined; + } + } + + return data; +} + + + + +jQuery.extend({ + queue: function( elem, type, data ) { + if ( !elem ) { + return; + } + + type = (type || "fx") + "queue"; + var q = jQuery._data( elem, type ); + + // Speed up dequeue by getting out quickly if this is just a lookup + if ( !data ) { + return q || []; + } + + if ( !q || jQuery.isArray(data) ) { + q = jQuery._data( elem, type, jQuery.makeArray(data) ); + + } else { + q.push( data ); + } + + return q; + }, + + dequeue: function( elem, type ) { + type = type || "fx"; + + var queue = jQuery.queue( elem, type ), + fn = queue.shift(); + + // If the fx queue is dequeued, always remove the progress sentinel + if ( fn === "inprogress" ) { + fn = queue.shift(); + } + + if ( fn ) { + // Add a progress sentinel to prevent the fx queue from being + // automatically dequeued + if ( type === "fx" ) { + queue.unshift("inprogress"); + } + + fn.call(elem, function() { + jQuery.dequeue(elem, type); + }); + } + + if ( !queue.length ) { + jQuery.removeData( elem, type + "queue", true ); + } + } +}); + +jQuery.fn.extend({ + queue: function( type, data ) { + if ( typeof type !== "string" ) { + data = type; + type = "fx"; + } + + if ( data === undefined ) { + return jQuery.queue( this[0], type ); + } + return this.each(function( i ) { + var queue = jQuery.queue( this, type, data ); + + if ( type === "fx" && queue[0] !== "inprogress" ) { + jQuery.dequeue( this, type ); + } + }); + }, + dequeue: function( type ) { + return this.each(function() { + jQuery.dequeue( this, type ); + }); + }, + + // Based off of the plugin by Clint Helfers, with permission. + // http://blindsignals.com/index.php/2009/07/jquery-delay/ + delay: function( time, type ) { + time = jQuery.fx ? jQuery.fx.speeds[time] || time : time; + type = type || "fx"; + + return this.queue( type, function() { + var elem = this; + setTimeout(function() { + jQuery.dequeue( elem, type ); + }, time ); + }); + }, + + clearQueue: function( type ) { + return this.queue( type || "fx", [] ); + } +}); + + + + +var rclass = /[\n\t\r]/g, + rspaces = /\s+/, + rreturn = /\r/g, + rspecialurl = /^(?:href|src|style)$/, + rtype = /^(?:button|input)$/i, + rfocusable = /^(?:button|input|object|select|textarea)$/i, + rclickable = /^a(?:rea)?$/i, + rradiocheck = /^(?:radio|checkbox)$/i; + +jQuery.props = { + "for": "htmlFor", + "class": "className", + readonly: "readOnly", + maxlength: "maxLength", + cellspacing: "cellSpacing", + rowspan: "rowSpan", + colspan: "colSpan", + tabindex: "tabIndex", + usemap: "useMap", + frameborder: "frameBorder" +}; + +jQuery.fn.extend({ + attr: function( name, value ) { + return jQuery.access( this, name, value, true, jQuery.attr ); + }, + + removeAttr: function( name, fn ) { + return this.each(function(){ + jQuery.attr( this, name, "" ); + if ( this.nodeType === 1 ) { + this.removeAttribute( name ); + } + }); + }, + + addClass: function( value ) { + if ( jQuery.isFunction(value) ) { + return this.each(function(i) { + var self = jQuery(this); + self.addClass( value.call(this, i, self.attr("class")) ); + }); + } + + if ( value && typeof value === "string" ) { + var classNames = (value || "").split( rspaces ); + + for ( var i = 0, l = this.length; i < l; i++ ) { + var elem = this[i]; + + if ( elem.nodeType === 1 ) { + if ( !elem.className ) { + elem.className = value; + + } else { + var className = " " + elem.className + " ", + setClass = elem.className; + + for ( var c = 0, cl = classNames.length; c < cl; c++ ) { + if ( className.indexOf( " " + classNames[c] + " " ) < 0 ) { + setClass += " " + classNames[c]; + } + } + elem.className = jQuery.trim( setClass ); + } + } + } + } + + return this; + }, + + removeClass: function( value ) { + if ( jQuery.isFunction(value) ) { + return this.each(function(i) { + var self = jQuery(this); + self.removeClass( value.call(this, i, self.attr("class")) ); + }); + } + + if ( (value && typeof value === "string") || value === undefined ) { + var classNames = (value || "").split( rspaces ); + + for ( var i = 0, l = this.length; i < l; i++ ) { + var elem = this[i]; + + if ( elem.nodeType === 1 && elem.className ) { + if ( value ) { + var className = (" " + elem.className + " ").replace(rclass, " "); + for ( var c = 0, cl = classNames.length; c < cl; c++ ) { + className = className.replace(" " + classNames[c] + " ", " "); + } + elem.className = jQuery.trim( className ); + + } else { + elem.className = ""; + } + } + } + } + + return this; + }, + + toggleClass: function( value, stateVal ) { + var type = typeof value, + isBool = typeof stateVal === "boolean"; + + if ( jQuery.isFunction( value ) ) { + return this.each(function(i) { + var self = jQuery(this); + self.toggleClass( value.call(this, i, self.attr("class"), stateVal), stateVal ); + }); + } + + return this.each(function() { + if ( type === "string" ) { + // toggle individual class names + var className, + i = 0, + self = jQuery( this ), + state = stateVal, + classNames = value.split( rspaces ); + + while ( (className = classNames[ i++ ]) ) { + // check each className given, space seperated list + state = isBool ? state : !self.hasClass( className ); + self[ state ? "addClass" : "removeClass" ]( className ); + } + + } else if ( type === "undefined" || type === "boolean" ) { + if ( this.className ) { + // store className if set + jQuery._data( this, "__className__", this.className ); + } + + // toggle whole className + this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; + } + }); + }, + + hasClass: function( selector ) { + var className = " " + selector + " "; + for ( var i = 0, l = this.length; i < l; i++ ) { + if ( (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { + return true; + } + } + + return false; + }, + + val: function( value ) { + if ( !arguments.length ) { + var elem = this[0]; + + if ( elem ) { + if ( jQuery.nodeName( elem, "option" ) ) { + // attributes.value is undefined in Blackberry 4.7 but + // uses .value. See #6932 + var val = elem.attributes.value; + return !val || val.specified ? elem.value : elem.text; + } + + // We need to handle select boxes special + if ( jQuery.nodeName( elem, "select" ) ) { + var index = elem.selectedIndex, + values = [], + options = elem.options, + one = elem.type === "select-one"; + + // Nothing was selected + if ( index < 0 ) { + return null; + } + + // Loop through all the selected options + for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) { + var option = options[ i ]; + + // Don't return options that are disabled or in a disabled optgroup + if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) && + (!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) { + + // Get the specific value for the option + value = jQuery(option).val(); + + // We don't need an array for one selects + if ( one ) { + return value; + } + + // Multi-Selects return an array + values.push( value ); + } + } + + return values; + } + + // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified + if ( rradiocheck.test( elem.type ) && !jQuery.support.checkOn ) { + return elem.getAttribute("value") === null ? "on" : elem.value; + } + + // Everything else, we just grab the value + return (elem.value || "").replace(rreturn, ""); + + } + + return undefined; + } + + var isFunction = jQuery.isFunction(value); + + return this.each(function(i) { + var self = jQuery(this), val = value; + + if ( this.nodeType !== 1 ) { + return; + } + + if ( isFunction ) { + val = value.call(this, i, self.val()); + } + + // Treat null/undefined as ""; convert numbers to string + if ( val == null ) { + val = ""; + } else if ( typeof val === "number" ) { + val += ""; + } else if ( jQuery.isArray(val) ) { + val = jQuery.map(val, function (value) { + return value == null ? "" : value + ""; + }); + } + + if ( jQuery.isArray(val) && rradiocheck.test( this.type ) ) { + this.checked = jQuery.inArray( self.val(), val ) >= 0; + + } else if ( jQuery.nodeName( this, "select" ) ) { + var values = jQuery.makeArray(val); + + jQuery( "option", this ).each(function() { + this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; + }); + + if ( !values.length ) { + this.selectedIndex = -1; + } + + } else { + this.value = val; + } + }); + } +}); + +jQuery.extend({ + attrFn: { + val: true, + css: true, + html: true, + text: true, + data: true, + width: true, + height: true, + offset: true + }, + + attr: function( elem, name, value, pass ) { + // don't get/set attributes on text, comment and attribute nodes + if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || elem.nodeType === 2 ) { + return undefined; + } + + if ( pass && name in jQuery.attrFn ) { + return jQuery(elem)[name](value); + } + + var notxml = elem.nodeType !== 1 || !jQuery.isXMLDoc( elem ), + // Whether we are setting (or getting) + set = value !== undefined; + + // Try to normalize/fix the name + name = notxml && jQuery.props[ name ] || name; + + // Only do all the following if this is a node (faster for style) + if ( elem.nodeType === 1 ) { + // These attributes require special treatment + var special = rspecialurl.test( name ); + + // Safari mis-reports the default selected property of an option + // Accessing the parent's selectedIndex property fixes it + if ( name === "selected" && !jQuery.support.optSelected ) { + var parent = elem.parentNode; + if ( parent ) { + parent.selectedIndex; + + // Make sure that it also works with optgroups, see #5701 + if ( parent.parentNode ) { + parent.parentNode.selectedIndex; + } + } + } + + // If applicable, access the attribute via the DOM 0 way + // 'in' checks fail in Blackberry 4.7 #6931 + if ( (name in elem || elem[ name ] !== undefined) && notxml && !special ) { + if ( set ) { + // We can't allow the type property to be changed (since it causes problems in IE) + if ( name === "type" && rtype.test( elem.nodeName ) && elem.parentNode ) { + jQuery.error( "type property can't be changed" ); + } + + if ( value === null ) { + if ( elem.nodeType === 1 ) { + elem.removeAttribute( name ); + } + + } else { + elem[ name ] = value; + } + } + + // browsers index elements by id/name on forms, give priority to attributes. + if ( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) ) { + return elem.getAttributeNode( name ).nodeValue; + } + + // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set + // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ + if ( name === "tabIndex" ) { + var attributeNode = elem.getAttributeNode( "tabIndex" ); + + return attributeNode && attributeNode.specified ? + attributeNode.value : + rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? + 0 : + undefined; + } + + return elem[ name ]; + } + + if ( !jQuery.support.style && notxml && name === "style" ) { + if ( set ) { + elem.style.cssText = "" + value; + } + + return elem.style.cssText; + } + + if ( set ) { + // convert the value to a string (all browsers do this but IE) see #1070 + elem.setAttribute( name, "" + value ); + } + + // Ensure that missing attributes return undefined + // Blackberry 4.7 returns "" from getAttribute #6938 + if ( !elem.attributes[ name ] && (elem.hasAttribute && !elem.hasAttribute( name )) ) { + return undefined; + } + + var attr = !jQuery.support.hrefNormalized && notxml && special ? + // Some attributes require a special call on IE + elem.getAttribute( name, 2 ) : + elem.getAttribute( name ); + + // Non-existent attributes return null, we normalize to undefined + return attr === null ? undefined : attr; + } + // Handle everything which isn't a DOM element node + if ( set ) { + elem[ name ] = value; + } + return elem[ name ]; + } +}); + + + + +var rnamespaces = /\.(.*)$/, + rformElems = /^(?:textarea|input|select)$/i, + rperiod = /\./g, + rspace = / /g, + rescape = /[^\w\s.|`]/g, + fcleanup = function( nm ) { + return nm.replace(rescape, "\\$&"); + }, + eventKey = "events"; + +/* + * A number of helper functions used for managing events. + * Many of the ideas behind this code originated from + * Dean Edwards' addEvent library. + */ +jQuery.event = { + + // Bind an event to an element + // Original by Dean Edwards + add: function( elem, types, handler, data ) { + if ( elem.nodeType === 3 || elem.nodeType === 8 ) { + return; + } + + // For whatever reason, IE has trouble passing the window object + // around, causing it to be cloned in the process + if ( jQuery.isWindow( elem ) && ( elem !== window && !elem.frameElement ) ) { + elem = window; + } + + if ( handler === false ) { + handler = returnFalse; + } else if ( !handler ) { + // Fixes bug #7229. Fix recommended by jdalton + return; + } + + var handleObjIn, handleObj; + + if ( handler.handler ) { + handleObjIn = handler; + handler = handleObjIn.handler; + } + + // Make sure that the function being executed has a unique ID + if ( !handler.guid ) { + handler.guid = jQuery.guid++; + } + + // Init the element's event structure + var elemData = jQuery._data( elem ); + + // If no elemData is found then we must be trying to bind to one of the + // banned noData elements + if ( !elemData ) { + return; + } + + var events = elemData[ eventKey ], + eventHandle = elemData.handle; + + if ( typeof events === "function" ) { + // On plain objects events is a fn that holds the data + // which prevents this data from being JSON serialized + // the function does not need to be called, it just contains the data + eventHandle = events.handle; + events = events.events; + + } else if ( !events ) { + if ( !elem.nodeType ) { + // On plain objects, create a fn that acts as the holder + // of the values to avoid JSON serialization of event data + elemData[ eventKey ] = elemData = function(){}; + } + + elemData.events = events = {}; + } + + if ( !eventHandle ) { + elemData.handle = eventHandle = function() { + // Handle the second event of a trigger and when + // an event is called after a page has unloaded + return typeof jQuery !== "undefined" && !jQuery.event.triggered ? + jQuery.event.handle.apply( eventHandle.elem, arguments ) : + undefined; + }; + } + + // Add elem as a property of the handle function + // This is to prevent a memory leak with non-native events in IE. + eventHandle.elem = elem; + + // Handle multiple events separated by a space + // jQuery(...).bind("mouseover mouseout", fn); + types = types.split(" "); + + var type, i = 0, namespaces; + + while ( (type = types[ i++ ]) ) { + handleObj = handleObjIn ? + jQuery.extend({}, handleObjIn) : + { handler: handler, data: data }; + + // Namespaced event handlers + if ( type.indexOf(".") > -1 ) { + namespaces = type.split("."); + type = namespaces.shift(); + handleObj.namespace = namespaces.slice(0).sort().join("."); + + } else { + namespaces = []; + handleObj.namespace = ""; + } + + handleObj.type = type; + if ( !handleObj.guid ) { + handleObj.guid = handler.guid; + } + + // Get the current list of functions bound to this event + var handlers = events[ type ], + special = jQuery.event.special[ type ] || {}; + + // Init the event handler queue + if ( !handlers ) { + handlers = events[ type ] = []; + + // Check for a special event handler + // Only use addEventListener/attachEvent if the special + // events handler returns false + if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { + // Bind the global event handler to the element + if ( elem.addEventListener ) { + elem.addEventListener( type, eventHandle, false ); + + } else if ( elem.attachEvent ) { + elem.attachEvent( "on" + type, eventHandle ); + } + } + } + + if ( special.add ) { + special.add.call( elem, handleObj ); + + if ( !handleObj.handler.guid ) { + handleObj.handler.guid = handler.guid; + } + } + + // Add the function to the element's handler list + handlers.push( handleObj ); + + // Keep track of which events have been used, for global triggering + jQuery.event.global[ type ] = true; + } + + // Nullify elem to prevent memory leaks in IE + elem = null; + }, + + global: {}, + + // Detach an event or set of events from an element + remove: function( elem, types, handler, pos ) { + // don't do events on text and comment nodes + if ( elem.nodeType === 3 || elem.nodeType === 8 ) { + return; + } + + if ( handler === false ) { + handler = returnFalse; + } + + var ret, type, fn, j, i = 0, all, namespaces, namespace, special, eventType, handleObj, origType, + elemData = jQuery.hasData( elem ) && jQuery._data( elem ), + events = elemData && elemData[ eventKey ]; + + if ( !elemData || !events ) { + return; + } + + if ( typeof events === "function" ) { + elemData = events; + events = events.events; + } + + // types is actually an event object here + if ( types && types.type ) { + handler = types.handler; + types = types.type; + } + + // Unbind all events for the element + if ( !types || typeof types === "string" && types.charAt(0) === "." ) { + types = types || ""; + + for ( type in events ) { + jQuery.event.remove( elem, type + types ); + } + + return; + } + + // Handle multiple events separated by a space + // jQuery(...).unbind("mouseover mouseout", fn); + types = types.split(" "); + + while ( (type = types[ i++ ]) ) { + origType = type; + handleObj = null; + all = type.indexOf(".") < 0; + namespaces = []; + + if ( !all ) { + // Namespaced event handlers + namespaces = type.split("."); + type = namespaces.shift(); + + namespace = new RegExp("(^|\\.)" + + jQuery.map( namespaces.slice(0).sort(), fcleanup ).join("\\.(?:.*\\.)?") + "(\\.|$)"); + } + + eventType = events[ type ]; + + if ( !eventType ) { + continue; + } + + if ( !handler ) { + for ( j = 0; j < eventType.length; j++ ) { + handleObj = eventType[ j ]; + + if ( all || namespace.test( handleObj.namespace ) ) { + jQuery.event.remove( elem, origType, handleObj.handler, j ); + eventType.splice( j--, 1 ); + } + } + + continue; + } + + special = jQuery.event.special[ type ] || {}; + + for ( j = pos || 0; j < eventType.length; j++ ) { + handleObj = eventType[ j ]; + + if ( handler.guid === handleObj.guid ) { + // remove the given handler for the given type + if ( all || namespace.test( handleObj.namespace ) ) { + if ( pos == null ) { + eventType.splice( j--, 1 ); + } + + if ( special.remove ) { + special.remove.call( elem, handleObj ); + } + } + + if ( pos != null ) { + break; + } + } + } + + // remove generic event handler if no more handlers exist + if ( eventType.length === 0 || pos != null && eventType.length === 1 ) { + if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) { + jQuery.removeEvent( elem, type, elemData.handle ); + } + + ret = null; + delete events[ type ]; + } + } + + // Remove the expando if it's no longer used + if ( jQuery.isEmptyObject( events ) ) { + var handle = elemData.handle; + if ( handle ) { + handle.elem = null; + } + + delete elemData.events; + delete elemData.handle; + + if ( typeof elemData === "function" ) { + jQuery.removeData( elem, eventKey, true ); + + } else if ( jQuery.isEmptyObject( elemData ) ) { + jQuery.removeData( elem, undefined, true ); + } + } + }, + + // bubbling is internal + trigger: function( event, data, elem /*, bubbling */ ) { + // Event object or event type + var type = event.type || event, + bubbling = arguments[3]; + + if ( !bubbling ) { + event = typeof event === "object" ? + // jQuery.Event object + event[ jQuery.expando ] ? event : + // Object literal + jQuery.extend( jQuery.Event(type), event ) : + // Just the event type (string) + jQuery.Event(type); + + if ( type.indexOf("!") >= 0 ) { + event.type = type = type.slice(0, -1); + event.exclusive = true; + } + + // Handle a global trigger + if ( !elem ) { + // Don't bubble custom events when global (to avoid too much overhead) + event.stopPropagation(); + + // Only trigger if we've ever bound an event for it + if ( jQuery.event.global[ type ] ) { + // XXX This code smells terrible. event.js should not be directly + // inspecting the data cache + jQuery.each( jQuery.cache, function() { + // internalKey variable is just used to make it easier to find + // and potentially change this stuff later; currently it just + // points to jQuery.expando + var internalKey = jQuery.expando, + internalCache = this[ internalKey ]; + if ( internalCache && internalCache.events && internalCache.events[type] ) { + jQuery.event.trigger( event, data, internalCache.handle.elem ); + } + }); + } + } + + // Handle triggering a single element + + // don't do events on text and comment nodes + if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) { + return undefined; + } + + // Clean up in case it is reused + event.result = undefined; + event.target = elem; + + // Clone the incoming data, if any + data = jQuery.makeArray( data ); + data.unshift( event ); + } + + event.currentTarget = elem; + + // Trigger the event, it is assumed that "handle" is a function + var handle = elem.nodeType ? + jQuery._data( elem, "handle" ) : + (jQuery._data( elem, eventKey ) || {}).handle; + + if ( handle ) { + handle.apply( elem, data ); + } + + var parent = elem.parentNode || elem.ownerDocument; + + // Trigger an inline bound script + try { + if ( !(elem && elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()]) ) { + if ( elem[ "on" + type ] && elem[ "on" + type ].apply( elem, data ) === false ) { + event.result = false; + event.preventDefault(); + } + } + + // prevent IE from throwing an error for some elements with some event types, see #3533 + } catch (inlineError) {} + + if ( !event.isPropagationStopped() && parent ) { + jQuery.event.trigger( event, data, parent, true ); + + } else if ( !event.isDefaultPrevented() ) { + var old, + target = event.target, + targetType = type.replace( rnamespaces, "" ), + isClick = jQuery.nodeName( target, "a" ) && targetType === "click", + special = jQuery.event.special[ targetType ] || {}; + + if ( (!special._default || special._default.call( elem, event ) === false) && + !isClick && !(target && target.nodeName && jQuery.noData[target.nodeName.toLowerCase()]) ) { + + try { + if ( target[ targetType ] ) { + // Make sure that we don't accidentally re-trigger the onFOO events + old = target[ "on" + targetType ]; + + if ( old ) { + target[ "on" + targetType ] = null; + } + + jQuery.event.triggered = true; + target[ targetType ](); + } + + // prevent IE from throwing an error for some elements with some event types, see #3533 + } catch (triggerError) {} + + if ( old ) { + target[ "on" + targetType ] = old; + } + + jQuery.event.triggered = false; + } + } + }, + + handle: function( event ) { + var all, handlers, namespaces, namespace_re, events, + namespace_sort = [], + args = jQuery.makeArray( arguments ); + + event = args[0] = jQuery.event.fix( event || window.event ); + event.currentTarget = this; + + // Namespaced event handlers + all = event.type.indexOf(".") < 0 && !event.exclusive; + + if ( !all ) { + namespaces = event.type.split("."); + event.type = namespaces.shift(); + namespace_sort = namespaces.slice(0).sort(); + namespace_re = new RegExp("(^|\\.)" + namespace_sort.join("\\.(?:.*\\.)?") + "(\\.|$)"); + } + + event.namespace = event.namespace || namespace_sort.join("."); + + events = jQuery._data(this, eventKey); + + if ( typeof events === "function" ) { + events = events.events; + } + + handlers = (events || {})[ event.type ]; + + if ( events && handlers ) { + // Clone the handlers to prevent manipulation + handlers = handlers.slice(0); + + for ( var j = 0, l = handlers.length; j < l; j++ ) { + var handleObj = handlers[ j ]; + + // Filter the functions by class + if ( all || namespace_re.test( handleObj.namespace ) ) { + // Pass in a reference to the handler function itself + // So that we can later remove it + event.handler = handleObj.handler; + event.data = handleObj.data; + event.handleObj = handleObj; + + var ret = handleObj.handler.apply( this, args ); + + if ( ret !== undefined ) { + event.result = ret; + if ( ret === false ) { + event.preventDefault(); + event.stopPropagation(); + } + } + + if ( event.isImmediatePropagationStopped() ) { + break; + } + } + } + } + + return event.result; + }, + + props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "), + + fix: function( event ) { + if ( event[ jQuery.expando ] ) { + return event; + } + + // store a copy of the original event object + // and "clone" to set read-only properties + var originalEvent = event; + event = jQuery.Event( originalEvent ); + + for ( var i = this.props.length, prop; i; ) { + prop = this.props[ --i ]; + event[ prop ] = originalEvent[ prop ]; + } + + // Fix target property, if necessary + if ( !event.target ) { + // Fixes #1925 where srcElement might not be defined either + event.target = event.srcElement || document; + } + + // check if target is a textnode (safari) + if ( event.target.nodeType === 3 ) { + event.target = event.target.parentNode; + } + + // Add relatedTarget, if necessary + if ( !event.relatedTarget && event.fromElement ) { + event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement; + } + + // Calculate pageX/Y if missing and clientX/Y available + if ( event.pageX == null && event.clientX != null ) { + var doc = document.documentElement, + body = document.body; + + event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0); + event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0); + } + + // Add which for key events + if ( event.which == null && (event.charCode != null || event.keyCode != null) ) { + event.which = event.charCode != null ? event.charCode : event.keyCode; + } + + // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs) + if ( !event.metaKey && event.ctrlKey ) { + event.metaKey = event.ctrlKey; + } + + // Add which for click: 1 === left; 2 === middle; 3 === right + // Note: button is not normalized, so don't use it + if ( !event.which && event.button !== undefined ) { + event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) )); + } + + return event; + }, + + // Deprecated, use jQuery.guid instead + guid: 1E8, + + // Deprecated, use jQuery.proxy instead + proxy: jQuery.proxy, + + special: { + ready: { + // Make sure the ready event is setup + setup: jQuery.bindReady, + teardown: jQuery.noop + }, + + live: { + add: function( handleObj ) { + jQuery.event.add( this, + liveConvert( handleObj.origType, handleObj.selector ), + jQuery.extend({}, handleObj, {handler: liveHandler, guid: handleObj.handler.guid}) ); + }, + + remove: function( handleObj ) { + jQuery.event.remove( this, liveConvert( handleObj.origType, handleObj.selector ), handleObj ); + } + }, + + beforeunload: { + setup: function( data, namespaces, eventHandle ) { + // We only want to do this special case on windows + if ( jQuery.isWindow( this ) ) { + this.onbeforeunload = eventHandle; + } + }, + + teardown: function( namespaces, eventHandle ) { + if ( this.onbeforeunload === eventHandle ) { + this.onbeforeunload = null; + } + } + } + } +}; + +jQuery.removeEvent = document.removeEventListener ? + function( elem, type, handle ) { + if ( elem.removeEventListener ) { + elem.removeEventListener( type, handle, false ); + } + } : + function( elem, type, handle ) { + if ( elem.detachEvent ) { + elem.detachEvent( "on" + type, handle ); + } + }; + +jQuery.Event = function( src ) { + // Allow instantiation without the 'new' keyword + if ( !this.preventDefault ) { + return new jQuery.Event( src ); + } + + // Event object + if ( src && src.type ) { + this.originalEvent = src; + this.type = src.type; + + // Events bubbling up the document may have been marked as prevented + // by a handler lower down the tree; reflect the correct value. + this.isDefaultPrevented = (src.defaultPrevented || src.returnValue === false || + src.getPreventDefault && src.getPreventDefault()) ? returnTrue : returnFalse; + + // Event type + } else { + this.type = src; + } + + // timeStamp is buggy for some events on Firefox(#3843) + // So we won't rely on the native value + this.timeStamp = jQuery.now(); + + // Mark it as fixed + this[ jQuery.expando ] = true; +}; + +function returnFalse() { + return false; +} +function returnTrue() { + return true; +} + +// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding +// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html +jQuery.Event.prototype = { + preventDefault: function() { + this.isDefaultPrevented = returnTrue; + + var e = this.originalEvent; + if ( !e ) { + return; + } + + // if preventDefault exists run it on the original event + if ( e.preventDefault ) { + e.preventDefault(); + + // otherwise set the returnValue property of the original event to false (IE) + } else { + e.returnValue = false; + } + }, + stopPropagation: function() { + this.isPropagationStopped = returnTrue; + + var e = this.originalEvent; + if ( !e ) { + return; + } + // if stopPropagation exists run it on the original event + if ( e.stopPropagation ) { + e.stopPropagation(); + } + // otherwise set the cancelBubble property of the original event to true (IE) + e.cancelBubble = true; + }, + stopImmediatePropagation: function() { + this.isImmediatePropagationStopped = returnTrue; + this.stopPropagation(); + }, + isDefaultPrevented: returnFalse, + isPropagationStopped: returnFalse, + isImmediatePropagationStopped: returnFalse +}; + +// Checks if an event happened on an element within another element +// Used in jQuery.event.special.mouseenter and mouseleave handlers +var withinElement = function( event ) { + // Check if mouse(over|out) are still within the same parent element + var parent = event.relatedTarget; + + // Firefox sometimes assigns relatedTarget a XUL element + // which we cannot access the parentNode property of + try { + // Traverse up the tree + while ( parent && parent !== this ) { + parent = parent.parentNode; + } + + if ( parent !== this ) { + // set the correct event type + event.type = event.data; + + // handle event if we actually just moused on to a non sub-element + jQuery.event.handle.apply( this, arguments ); + } + + // assuming we've left the element since we most likely mousedover a xul element + } catch(e) { } +}, + +// In case of event delegation, we only need to rename the event.type, +// liveHandler will take care of the rest. +delegate = function( event ) { + event.type = event.data; + jQuery.event.handle.apply( this, arguments ); +}; + +// Create mouseenter and mouseleave events +jQuery.each({ + mouseenter: "mouseover", + mouseleave: "mouseout" +}, function( orig, fix ) { + jQuery.event.special[ orig ] = { + setup: function( data ) { + jQuery.event.add( this, fix, data && data.selector ? delegate : withinElement, orig ); + }, + teardown: function( data ) { + jQuery.event.remove( this, fix, data && data.selector ? delegate : withinElement ); + } + }; +}); + +// submit delegation +if ( !jQuery.support.submitBubbles ) { + + jQuery.event.special.submit = { + setup: function( data, namespaces ) { + if ( this.nodeName && this.nodeName.toLowerCase() !== "form" ) { + jQuery.event.add(this, "click.specialSubmit", function( e ) { + var elem = e.target, + type = elem.type; + + if ( (type === "submit" || type === "image") && jQuery( elem ).closest("form").length ) { + e.liveFired = undefined; + return trigger( "submit", this, arguments ); + } + }); + + jQuery.event.add(this, "keypress.specialSubmit", function( e ) { + var elem = e.target, + type = elem.type; + + if ( (type === "text" || type === "password") && jQuery( elem ).closest("form").length && e.keyCode === 13 ) { + e.liveFired = undefined; + return trigger( "submit", this, arguments ); + } + }); + + } else { + return false; + } + }, + + teardown: function( namespaces ) { + jQuery.event.remove( this, ".specialSubmit" ); + } + }; + +} + +// change delegation, happens here so we have bind. +if ( !jQuery.support.changeBubbles ) { + + var changeFilters, + + getVal = function( elem ) { + var type = elem.type, val = elem.value; + + if ( type === "radio" || type === "checkbox" ) { + val = elem.checked; + + } else if ( type === "select-multiple" ) { + val = elem.selectedIndex > -1 ? + jQuery.map( elem.options, function( elem ) { + return elem.selected; + }).join("-") : + ""; + + } else if ( elem.nodeName.toLowerCase() === "select" ) { + val = elem.selectedIndex; + } + + return val; + }, + + testChange = function testChange( e ) { + var elem = e.target, data, val; + + if ( !rformElems.test( elem.nodeName ) || elem.readOnly ) { + return; + } + + data = jQuery._data( elem, "_change_data" ); + val = getVal(elem); + + // the current data will be also retrieved by beforeactivate + if ( e.type !== "focusout" || elem.type !== "radio" ) { + jQuery._data( elem, "_change_data", val ); + } + + if ( data === undefined || val === data ) { + return; + } + + if ( data != null || val ) { + e.type = "change"; + e.liveFired = undefined; + return jQuery.event.trigger( e, arguments[1], elem ); + } + }; + + jQuery.event.special.change = { + filters: { + focusout: testChange, + + beforedeactivate: testChange, + + click: function( e ) { + var elem = e.target, type = elem.type; + + if ( type === "radio" || type === "checkbox" || elem.nodeName.toLowerCase() === "select" ) { + return testChange.call( this, e ); + } + }, + + // Change has to be called before submit + // Keydown will be called before keypress, which is used in submit-event delegation + keydown: function( e ) { + var elem = e.target, type = elem.type; + + if ( (e.keyCode === 13 && elem.nodeName.toLowerCase() !== "textarea") || + (e.keyCode === 32 && (type === "checkbox" || type === "radio")) || + type === "select-multiple" ) { + return testChange.call( this, e ); + } + }, + + // Beforeactivate happens also before the previous element is blurred + // with this event you can't trigger a change event, but you can store + // information + beforeactivate: function( e ) { + var elem = e.target; + jQuery._data( elem, "_change_data", getVal(elem) ); + } + }, + + setup: function( data, namespaces ) { + if ( this.type === "file" ) { + return false; + } + + for ( var type in changeFilters ) { + jQuery.event.add( this, type + ".specialChange", changeFilters[type] ); + } + + return rformElems.test( this.nodeName ); + }, + + teardown: function( namespaces ) { + jQuery.event.remove( this, ".specialChange" ); + + return rformElems.test( this.nodeName ); + } + }; + + changeFilters = jQuery.event.special.change.filters; + + // Handle when the input is .focus()'d + changeFilters.focus = changeFilters.beforeactivate; +} + +function trigger( type, elem, args ) { + args[0].type = type; + return jQuery.event.handle.apply( elem, args ); +} + +// Create "bubbling" focus and blur events +if ( document.addEventListener ) { + jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { + jQuery.event.special[ fix ] = { + setup: function() { + this.addEventListener( orig, handler, true ); + }, + teardown: function() { + this.removeEventListener( orig, handler, true ); + } + }; + + function handler( e ) { + e = jQuery.event.fix( e ); + e.type = fix; + return jQuery.event.handle.call( this, e ); + } + }); +} + +jQuery.each(["bind", "one"], function( i, name ) { + jQuery.fn[ name ] = function( type, data, fn ) { + // Handle object literals + if ( typeof type === "object" ) { + for ( var key in type ) { + this[ name ](key, data, type[key], fn); + } + return this; + } + + if ( jQuery.isFunction( data ) || data === false ) { + fn = data; + data = undefined; + } + + var handler = name === "one" ? jQuery.proxy( fn, function( event ) { + jQuery( this ).unbind( event, handler ); + return fn.apply( this, arguments ); + }) : fn; + + if ( type === "unload" && name !== "one" ) { + this.one( type, data, fn ); + + } else { + for ( var i = 0, l = this.length; i < l; i++ ) { + jQuery.event.add( this[i], type, handler, data ); + } + } + + return this; + }; +}); + +jQuery.fn.extend({ + unbind: function( type, fn ) { + // Handle object literals + if ( typeof type === "object" && !type.preventDefault ) { + for ( var key in type ) { + this.unbind(key, type[key]); + } + + } else { + for ( var i = 0, l = this.length; i < l; i++ ) { + jQuery.event.remove( this[i], type, fn ); + } + } + + return this; + }, + + delegate: function( selector, types, data, fn ) { + return this.live( types, data, fn, selector ); + }, + + undelegate: function( selector, types, fn ) { + if ( arguments.length === 0 ) { + return this.unbind( "live" ); + + } else { + return this.die( types, null, fn, selector ); + } + }, + + trigger: function( type, data ) { + return this.each(function() { + jQuery.event.trigger( type, data, this ); + }); + }, + + triggerHandler: function( type, data ) { + if ( this[0] ) { + var event = jQuery.Event( type ); + event.preventDefault(); + event.stopPropagation(); + jQuery.event.trigger( event, data, this[0] ); + return event.result; + } + }, + + toggle: function( fn ) { + // Save reference to arguments for access in closure + var args = arguments, + i = 1; + + // link all the functions, so any of them can unbind this click handler + while ( i < args.length ) { + jQuery.proxy( fn, args[ i++ ] ); + } + + return this.click( jQuery.proxy( fn, function( event ) { + // Figure out which function to execute + var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i; + jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 ); + + // Make sure that clicks stop + event.preventDefault(); + + // and execute the function + return args[ lastToggle ].apply( this, arguments ) || false; + })); + }, + + hover: function( fnOver, fnOut ) { + return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); + } +}); + +var liveMap = { + focus: "focusin", + blur: "focusout", + mouseenter: "mouseover", + mouseleave: "mouseout" +}; + +jQuery.each(["live", "die"], function( i, name ) { + jQuery.fn[ name ] = function( types, data, fn, origSelector /* Internal Use Only */ ) { + var type, i = 0, match, namespaces, preType, + selector = origSelector || this.selector, + context = origSelector ? this : jQuery( this.context ); + + if ( typeof types === "object" && !types.preventDefault ) { + for ( var key in types ) { + context[ name ]( key, data, types[key], selector ); + } + + return this; + } + + if ( jQuery.isFunction( data ) ) { + fn = data; + data = undefined; + } + + types = (types || "").split(" "); + + while ( (type = types[ i++ ]) != null ) { + match = rnamespaces.exec( type ); + namespaces = ""; + + if ( match ) { + namespaces = match[0]; + type = type.replace( rnamespaces, "" ); + } + + if ( type === "hover" ) { + types.push( "mouseenter" + namespaces, "mouseleave" + namespaces ); + continue; + } + + preType = type; + + if ( type === "focus" || type === "blur" ) { + types.push( liveMap[ type ] + namespaces ); + type = type + namespaces; + + } else { + type = (liveMap[ type ] || type) + namespaces; + } + + if ( name === "live" ) { + // bind live handler + for ( var j = 0, l = context.length; j < l; j++ ) { + jQuery.event.add( context[j], "live." + liveConvert( type, selector ), + { data: data, selector: selector, handler: fn, origType: type, origHandler: fn, preType: preType } ); + } + + } else { + // unbind live handler + context.unbind( "live." + liveConvert( type, selector ), fn ); + } + } + + return this; + }; +}); + +function liveHandler( event ) { + var stop, maxLevel, related, match, handleObj, elem, j, i, l, data, close, namespace, ret, + elems = [], + selectors = [], + events = jQuery._data( this, eventKey ); + + if ( typeof events === "function" ) { + events = events.events; + } + + // Make sure we avoid non-left-click bubbling in Firefox (#3861) and disabled elements in IE (#6911) + if ( event.liveFired === this || !events || !events.live || event.target.disabled || event.button && event.type === "click" ) { + return; + } + + if ( event.namespace ) { + namespace = new RegExp("(^|\\.)" + event.namespace.split(".").join("\\.(?:.*\\.)?") + "(\\.|$)"); + } + + event.liveFired = this; + + var live = events.live.slice(0); + + for ( j = 0; j < live.length; j++ ) { + handleObj = live[j]; + + if ( handleObj.origType.replace( rnamespaces, "" ) === event.type ) { + selectors.push( handleObj.selector ); + + } else { + live.splice( j--, 1 ); + } + } + + match = jQuery( event.target ).closest( selectors, event.currentTarget ); + + for ( i = 0, l = match.length; i < l; i++ ) { + close = match[i]; + + for ( j = 0; j < live.length; j++ ) { + handleObj = live[j]; + + if ( close.selector === handleObj.selector && (!namespace || namespace.test( handleObj.namespace )) ) { + elem = close.elem; + related = null; + + // Those two events require additional checking + if ( handleObj.preType === "mouseenter" || handleObj.preType === "mouseleave" ) { + event.type = handleObj.preType; + related = jQuery( event.relatedTarget ).closest( handleObj.selector )[0]; + } + + if ( !related || related !== elem ) { + elems.push({ elem: elem, handleObj: handleObj, level: close.level }); + } + } + } + } + + for ( i = 0, l = elems.length; i < l; i++ ) { + match = elems[i]; + + if ( maxLevel && match.level > maxLevel ) { + break; + } + + event.currentTarget = match.elem; + event.data = match.handleObj.data; + event.handleObj = match.handleObj; + + ret = match.handleObj.origHandler.apply( match.elem, arguments ); + + if ( ret === false || event.isPropagationStopped() ) { + maxLevel = match.level; + + if ( ret === false ) { + stop = false; + } + if ( event.isImmediatePropagationStopped() ) { + break; + } + } + } + + return stop; +} + +function liveConvert( type, selector ) { + return (type && type !== "*" ? type + "." : "") + selector.replace(rperiod, "`").replace(rspace, "&"); +} + +jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + + "change select submit keydown keypress keyup error").split(" "), function( i, name ) { + + // Handle event binding + jQuery.fn[ name ] = function( data, fn ) { + if ( fn == null ) { + fn = data; + data = null; + } + + return arguments.length > 0 ? + this.bind( name, data, fn ) : + this.trigger( name ); + }; + + if ( jQuery.attrFn ) { + jQuery.attrFn[ name ] = true; + } +}); + + +/*! + * Sizzle CSS Selector Engine + * Copyright 2011, The Dojo Foundation + * Released under the MIT, BSD, and GPL Licenses. + * More information: http://sizzlejs.com/ + */ +(function(){ + +var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, + done = 0, + toString = Object.prototype.toString, + hasDuplicate = false, + baseHasDuplicate = true; + +// Here we check if the JavaScript engine is using some sort of +// optimization where it does not always call our comparision +// function. If that is the case, discard the hasDuplicate value. +// Thus far that includes Google Chrome. +[0, 0].sort(function() { + baseHasDuplicate = false; + return 0; +}); + +var Sizzle = function( selector, context, results, seed ) { + results = results || []; + context = context || document; + + var origContext = context; + + if ( context.nodeType !== 1 && context.nodeType !== 9 ) { + return []; + } + + if ( !selector || typeof selector !== "string" ) { + return results; + } + + var m, set, checkSet, extra, ret, cur, pop, i, + prune = true, + contextXML = Sizzle.isXML( context ), + parts = [], + soFar = selector; + + // Reset the position of the chunker regexp (start from head) + do { + chunker.exec( "" ); + m = chunker.exec( soFar ); + + if ( m ) { + soFar = m[3]; + + parts.push( m[1] ); + + if ( m[2] ) { + extra = m[3]; + break; + } + } + } while ( m ); + + if ( parts.length > 1 && origPOS.exec( selector ) ) { + + if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { + set = posProcess( parts[0] + parts[1], context ); + + } else { + set = Expr.relative[ parts[0] ] ? + [ context ] : + Sizzle( parts.shift(), context ); + + while ( parts.length ) { + selector = parts.shift(); + + if ( Expr.relative[ selector ] ) { + selector += parts.shift(); + } + + set = posProcess( selector, set ); + } + } + + } else { + // Take a shortcut and set the context if the root selector is an ID + // (but not if it'll be faster if the inner selector is an ID) + if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && + Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { + + ret = Sizzle.find( parts.shift(), context, contextXML ); + context = ret.expr ? + Sizzle.filter( ret.expr, ret.set )[0] : + ret.set[0]; + } + + if ( context ) { + ret = seed ? + { expr: parts.pop(), set: makeArray(seed) } : + Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); + + set = ret.expr ? + Sizzle.filter( ret.expr, ret.set ) : + ret.set; + + if ( parts.length > 0 ) { + checkSet = makeArray( set ); + + } else { + prune = false; + } + + while ( parts.length ) { + cur = parts.pop(); + pop = cur; + + if ( !Expr.relative[ cur ] ) { + cur = ""; + } else { + pop = parts.pop(); + } + + if ( pop == null ) { + pop = context; + } + + Expr.relative[ cur ]( checkSet, pop, contextXML ); + } + + } else { + checkSet = parts = []; + } + } + + if ( !checkSet ) { + checkSet = set; + } + + if ( !checkSet ) { + Sizzle.error( cur || selector ); + } + + if ( toString.call(checkSet) === "[object Array]" ) { + if ( !prune ) { + results.push.apply( results, checkSet ); + + } else if ( context && context.nodeType === 1 ) { + for ( i = 0; checkSet[i] != null; i++ ) { + if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) { + results.push( set[i] ); + } + } + + } else { + for ( i = 0; checkSet[i] != null; i++ ) { + if ( checkSet[i] && checkSet[i].nodeType === 1 ) { + results.push( set[i] ); + } + } + } + + } else { + makeArray( checkSet, results ); + } + + if ( extra ) { + Sizzle( extra, origContext, results, seed ); + Sizzle.uniqueSort( results ); + } + + return results; +}; + +Sizzle.uniqueSort = function( results ) { + if ( sortOrder ) { + hasDuplicate = baseHasDuplicate; + results.sort( sortOrder ); + + if ( hasDuplicate ) { + for ( var i = 1; i < results.length; i++ ) { + if ( results[i] === results[ i - 1 ] ) { + results.splice( i--, 1 ); + } + } + } + } + + return results; +}; + +Sizzle.matches = function( expr, set ) { + return Sizzle( expr, null, null, set ); +}; + +Sizzle.matchesSelector = function( node, expr ) { + return Sizzle( expr, null, null, [node] ).length > 0; +}; + +Sizzle.find = function( expr, context, isXML ) { + var set; + + if ( !expr ) { + return []; + } + + for ( var i = 0, l = Expr.order.length; i < l; i++ ) { + var match, + type = Expr.order[i]; + + if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { + var left = match[1]; + match.splice( 1, 1 ); + + if ( left.substr( left.length - 1 ) !== "\\" ) { + match[1] = (match[1] || "").replace(/\\/g, ""); + set = Expr.find[ type ]( match, context, isXML ); + + if ( set != null ) { + expr = expr.replace( Expr.match[ type ], "" ); + break; + } + } + } + } + + if ( !set ) { + set = typeof context.getElementsByTagName !== "undefined" ? + context.getElementsByTagName( "*" ) : + []; + } + + return { set: set, expr: expr }; +}; + +Sizzle.filter = function( expr, set, inplace, not ) { + var match, anyFound, + old = expr, + result = [], + curLoop = set, + isXMLFilter = set && set[0] && Sizzle.isXML( set[0] ); + + while ( expr && set.length ) { + for ( var type in Expr.filter ) { + if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { + var found, item, + filter = Expr.filter[ type ], + left = match[1]; + + anyFound = false; + + match.splice(1,1); + + if ( left.substr( left.length - 1 ) === "\\" ) { + continue; + } + + if ( curLoop === result ) { + result = []; + } + + if ( Expr.preFilter[ type ] ) { + match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); + + if ( !match ) { + anyFound = found = true; + + } else if ( match === true ) { + continue; + } + } + + if ( match ) { + for ( var i = 0; (item = curLoop[i]) != null; i++ ) { + if ( item ) { + found = filter( item, match, i, curLoop ); + var pass = not ^ !!found; + + if ( inplace && found != null ) { + if ( pass ) { + anyFound = true; + + } else { + curLoop[i] = false; + } + + } else if ( pass ) { + result.push( item ); + anyFound = true; + } + } + } + } + + if ( found !== undefined ) { + if ( !inplace ) { + curLoop = result; + } + + expr = expr.replace( Expr.match[ type ], "" ); + + if ( !anyFound ) { + return []; + } + + break; + } + } + } + + // Improper expression + if ( expr === old ) { + if ( anyFound == null ) { + Sizzle.error( expr ); + + } else { + break; + } + } + + old = expr; + } + + return curLoop; +}; + +Sizzle.error = function( msg ) { + throw "Syntax error, unrecognized expression: " + msg; +}; + +var Expr = Sizzle.selectors = { + order: [ "ID", "NAME", "TAG" ], + + match: { + ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, + CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, + NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/, + ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/, + TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/, + CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/, + POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/, + PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ + }, + + leftMatch: {}, + + attrMap: { + "class": "className", + "for": "htmlFor" + }, + + attrHandle: { + href: function( elem ) { + return elem.getAttribute( "href" ); + } + }, + + relative: { + "+": function(checkSet, part){ + var isPartStr = typeof part === "string", + isTag = isPartStr && !/\W/.test( part ), + isPartStrNotTag = isPartStr && !isTag; + + if ( isTag ) { + part = part.toLowerCase(); + } + + for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { + if ( (elem = checkSet[i]) ) { + while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} + + checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? + elem || false : + elem === part; + } + } + + if ( isPartStrNotTag ) { + Sizzle.filter( part, checkSet, true ); + } + }, + + ">": function( checkSet, part ) { + var elem, + isPartStr = typeof part === "string", + i = 0, + l = checkSet.length; + + if ( isPartStr && !/\W/.test( part ) ) { + part = part.toLowerCase(); + + for ( ; i < l; i++ ) { + elem = checkSet[i]; + + if ( elem ) { + var parent = elem.parentNode; + checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; + } + } + + } else { + for ( ; i < l; i++ ) { + elem = checkSet[i]; + + if ( elem ) { + checkSet[i] = isPartStr ? + elem.parentNode : + elem.parentNode === part; + } + } + + if ( isPartStr ) { + Sizzle.filter( part, checkSet, true ); + } + } + }, + + "": function(checkSet, part, isXML){ + var nodeCheck, + doneName = done++, + checkFn = dirCheck; + + if ( typeof part === "string" && !/\W/.test(part) ) { + part = part.toLowerCase(); + nodeCheck = part; + checkFn = dirNodeCheck; + } + + checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML ); + }, + + "~": function( checkSet, part, isXML ) { + var nodeCheck, + doneName = done++, + checkFn = dirCheck; + + if ( typeof part === "string" && !/\W/.test( part ) ) { + part = part.toLowerCase(); + nodeCheck = part; + checkFn = dirNodeCheck; + } + + checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML ); + } + }, + + find: { + ID: function( match, context, isXML ) { + if ( typeof context.getElementById !== "undefined" && !isXML ) { + var m = context.getElementById(match[1]); + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + return m && m.parentNode ? [m] : []; + } + }, + + NAME: function( match, context ) { + if ( typeof context.getElementsByName !== "undefined" ) { + var ret = [], + results = context.getElementsByName( match[1] ); + + for ( var i = 0, l = results.length; i < l; i++ ) { + if ( results[i].getAttribute("name") === match[1] ) { + ret.push( results[i] ); + } + } + + return ret.length === 0 ? null : ret; + } + }, + + TAG: function( match, context ) { + if ( typeof context.getElementsByTagName !== "undefined" ) { + return context.getElementsByTagName( match[1] ); + } + } + }, + preFilter: { + CLASS: function( match, curLoop, inplace, result, not, isXML ) { + match = " " + match[1].replace(/\\/g, "") + " "; + + if ( isXML ) { + return match; + } + + for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { + if ( elem ) { + if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) { + if ( !inplace ) { + result.push( elem ); + } + + } else if ( inplace ) { + curLoop[i] = false; + } + } + } + + return false; + }, + + ID: function( match ) { + return match[1].replace(/\\/g, ""); + }, + + TAG: function( match, curLoop ) { + return match[1].toLowerCase(); + }, + + CHILD: function( match ) { + if ( match[1] === "nth" ) { + if ( !match[2] ) { + Sizzle.error( match[0] ); + } + + match[2] = match[2].replace(/^\+|\s*/g, ''); + + // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' + var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec( + match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || + !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); + + // calculate the numbers (first)n+(last) including if they are negative + match[2] = (test[1] + (test[2] || 1)) - 0; + match[3] = test[3] - 0; + } + else if ( match[2] ) { + Sizzle.error( match[0] ); + } + + // TODO: Move to normal caching system + match[0] = done++; + + return match; + }, + + ATTR: function( match, curLoop, inplace, result, not, isXML ) { + var name = match[1] = match[1].replace(/\\/g, ""); + + if ( !isXML && Expr.attrMap[name] ) { + match[1] = Expr.attrMap[name]; + } + + // Handle if an un-quoted value was used + match[4] = ( match[4] || match[5] || "" ).replace(/\\/g, ""); + + if ( match[2] === "~=" ) { + match[4] = " " + match[4] + " "; + } + + return match; + }, + + PSEUDO: function( match, curLoop, inplace, result, not ) { + if ( match[1] === "not" ) { + // If we're dealing with a complex expression, or a simple one + if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { + match[3] = Sizzle(match[3], null, null, curLoop); + + } else { + var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); + + if ( !inplace ) { + result.push.apply( result, ret ); + } + + return false; + } + + } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { + return true; + } + + return match; + }, + + POS: function( match ) { + match.unshift( true ); + + return match; + } + }, + + filters: { + enabled: function( elem ) { + return elem.disabled === false && elem.type !== "hidden"; + }, + + disabled: function( elem ) { + return elem.disabled === true; + }, + + checked: function( elem ) { + return elem.checked === true; + }, + + selected: function( elem ) { + // Accessing this property makes selected-by-default + // options in Safari work properly + elem.parentNode.selectedIndex; + + return elem.selected === true; + }, + + parent: function( elem ) { + return !!elem.firstChild; + }, + + empty: function( elem ) { + return !elem.firstChild; + }, + + has: function( elem, i, match ) { + return !!Sizzle( match[3], elem ).length; + }, + + header: function( elem ) { + return (/h\d/i).test( elem.nodeName ); + }, + + text: function( elem ) { + return "text" === elem.type; + }, + radio: function( elem ) { + return "radio" === elem.type; + }, + + checkbox: function( elem ) { + return "checkbox" === elem.type; + }, + + file: function( elem ) { + return "file" === elem.type; + }, + password: function( elem ) { + return "password" === elem.type; + }, + + submit: function( elem ) { + return "submit" === elem.type; + }, + + image: function( elem ) { + return "image" === elem.type; + }, + + reset: function( elem ) { + return "reset" === elem.type; + }, + + button: function( elem ) { + return "button" === elem.type || elem.nodeName.toLowerCase() === "button"; + }, + + input: function( elem ) { + return (/input|select|textarea|button/i).test( elem.nodeName ); + } + }, + setFilters: { + first: function( elem, i ) { + return i === 0; + }, + + last: function( elem, i, match, array ) { + return i === array.length - 1; + }, + + even: function( elem, i ) { + return i % 2 === 0; + }, + + odd: function( elem, i ) { + return i % 2 === 1; + }, + + lt: function( elem, i, match ) { + return i < match[3] - 0; + }, + + gt: function( elem, i, match ) { + return i > match[3] - 0; + }, + + nth: function( elem, i, match ) { + return match[3] - 0 === i; + }, + + eq: function( elem, i, match ) { + return match[3] - 0 === i; + } + }, + filter: { + PSEUDO: function( elem, match, i, array ) { + var name = match[1], + filter = Expr.filters[ name ]; + + if ( filter ) { + return filter( elem, i, match, array ); + + } else if ( name === "contains" ) { + return (elem.textContent || elem.innerText || Sizzle.getText([ elem ]) || "").indexOf(match[3]) >= 0; + + } else if ( name === "not" ) { + var not = match[3]; + + for ( var j = 0, l = not.length; j < l; j++ ) { + if ( not[j] === elem ) { + return false; + } + } + + return true; + + } else { + Sizzle.error( name ); + } + }, + + CHILD: function( elem, match ) { + var type = match[1], + node = elem; + + switch ( type ) { + case "only": + case "first": + while ( (node = node.previousSibling) ) { + if ( node.nodeType === 1 ) { + return false; + } + } + + if ( type === "first" ) { + return true; + } + + node = elem; + + case "last": + while ( (node = node.nextSibling) ) { + if ( node.nodeType === 1 ) { + return false; + } + } + + return true; + + case "nth": + var first = match[2], + last = match[3]; + + if ( first === 1 && last === 0 ) { + return true; + } + + var doneName = match[0], + parent = elem.parentNode; + + if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) { + var count = 0; + + for ( node = parent.firstChild; node; node = node.nextSibling ) { + if ( node.nodeType === 1 ) { + node.nodeIndex = ++count; + } + } + + parent.sizcache = doneName; + } + + var diff = elem.nodeIndex - last; + + if ( first === 0 ) { + return diff === 0; + + } else { + return ( diff % first === 0 && diff / first >= 0 ); + } + } + }, + + ID: function( elem, match ) { + return elem.nodeType === 1 && elem.getAttribute("id") === match; + }, + + TAG: function( elem, match ) { + return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match; + }, + + CLASS: function( elem, match ) { + return (" " + (elem.className || elem.getAttribute("class")) + " ") + .indexOf( match ) > -1; + }, + + ATTR: function( elem, match ) { + var name = match[1], + result = Expr.attrHandle[ name ] ? + Expr.attrHandle[ name ]( elem ) : + elem[ name ] != null ? + elem[ name ] : + elem.getAttribute( name ), + value = result + "", + type = match[2], + check = match[4]; + + return result == null ? + type === "!=" : + type === "=" ? + value === check : + type === "*=" ? + value.indexOf(check) >= 0 : + type === "~=" ? + (" " + value + " ").indexOf(check) >= 0 : + !check ? + value && result !== false : + type === "!=" ? + value !== check : + type === "^=" ? + value.indexOf(check) === 0 : + type === "$=" ? + value.substr(value.length - check.length) === check : + type === "|=" ? + value === check || value.substr(0, check.length + 1) === check + "-" : + false; + }, + + POS: function( elem, match, i, array ) { + var name = match[2], + filter = Expr.setFilters[ name ]; + + if ( filter ) { + return filter( elem, i, match, array ); + } + } + } +}; + +var origPOS = Expr.match.POS, + fescape = function(all, num){ + return "\\" + (num - 0 + 1); + }; + +for ( var type in Expr.match ) { + Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) ); + Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) ); +} + +var makeArray = function( array, results ) { + array = Array.prototype.slice.call( array, 0 ); + + if ( results ) { + results.push.apply( results, array ); + return results; + } + + return array; +}; + +// Perform a simple check to determine if the browser is capable of +// converting a NodeList to an array using builtin methods. +// Also verifies that the returned array holds DOM nodes +// (which is not the case in the Blackberry browser) +try { + Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType; + +// Provide a fallback method if it does not work +} catch( e ) { + makeArray = function( array, results ) { + var i = 0, + ret = results || []; + + if ( toString.call(array) === "[object Array]" ) { + Array.prototype.push.apply( ret, array ); + + } else { + if ( typeof array.length === "number" ) { + for ( var l = array.length; i < l; i++ ) { + ret.push( array[i] ); + } + + } else { + for ( ; array[i]; i++ ) { + ret.push( array[i] ); + } + } + } + + return ret; + }; +} + +var sortOrder, siblingCheck; + +if ( document.documentElement.compareDocumentPosition ) { + sortOrder = function( a, b ) { + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { + return a.compareDocumentPosition ? -1 : 1; + } + + return a.compareDocumentPosition(b) & 4 ? -1 : 1; + }; + +} else { + sortOrder = function( a, b ) { + var al, bl, + ap = [], + bp = [], + aup = a.parentNode, + bup = b.parentNode, + cur = aup; + + // The nodes are identical, we can exit early + if ( a === b ) { + hasDuplicate = true; + return 0; + + // If the nodes are siblings (or identical) we can do a quick check + } else if ( aup === bup ) { + return siblingCheck( a, b ); + + // If no parents were found then the nodes are disconnected + } else if ( !aup ) { + return -1; + + } else if ( !bup ) { + return 1; + } + + // Otherwise they're somewhere else in the tree so we need + // to build up a full list of the parentNodes for comparison + while ( cur ) { + ap.unshift( cur ); + cur = cur.parentNode; + } + + cur = bup; + + while ( cur ) { + bp.unshift( cur ); + cur = cur.parentNode; + } + + al = ap.length; + bl = bp.length; + + // Start walking down the tree looking for a discrepancy + for ( var i = 0; i < al && i < bl; i++ ) { + if ( ap[i] !== bp[i] ) { + return siblingCheck( ap[i], bp[i] ); + } + } + + // We ended someplace up the tree so do a sibling check + return i === al ? + siblingCheck( a, bp[i], -1 ) : + siblingCheck( ap[i], b, 1 ); + }; + + siblingCheck = function( a, b, ret ) { + if ( a === b ) { + return ret; + } + + var cur = a.nextSibling; + + while ( cur ) { + if ( cur === b ) { + return -1; + } + + cur = cur.nextSibling; + } + + return 1; + }; +} + +// Utility function for retreiving the text value of an array of DOM nodes +Sizzle.getText = function( elems ) { + var ret = "", elem; + + for ( var i = 0; elems[i]; i++ ) { + elem = elems[i]; + + // Get the text from text nodes and CDATA nodes + if ( elem.nodeType === 3 || elem.nodeType === 4 ) { + ret += elem.nodeValue; + + // Traverse everything else, except comment nodes + } else if ( elem.nodeType !== 8 ) { + ret += Sizzle.getText( elem.childNodes ); + } + } + + return ret; +}; + +// Check to see if the browser returns elements by name when +// querying by getElementById (and provide a workaround) +(function(){ + // We're going to inject a fake input element with a specified name + var form = document.createElement("div"), + id = "script" + (new Date()).getTime(), + root = document.documentElement; + + form.innerHTML = "<a name='" + id + "'/>"; + + // Inject it into the root element, check its status, and remove it quickly + root.insertBefore( form, root.firstChild ); + + // The workaround has to do additional checks after a getElementById + // Which slows things down for other browsers (hence the branching) + if ( document.getElementById( id ) ) { + Expr.find.ID = function( match, context, isXML ) { + if ( typeof context.getElementById !== "undefined" && !isXML ) { + var m = context.getElementById(match[1]); + + return m ? + m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? + [m] : + undefined : + []; + } + }; + + Expr.filter.ID = function( elem, match ) { + var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); + + return elem.nodeType === 1 && node && node.nodeValue === match; + }; + } + + root.removeChild( form ); + + // release memory in IE + root = form = null; +})(); + +(function(){ + // Check to see if the browser returns only elements + // when doing getElementsByTagName("*") + + // Create a fake element + var div = document.createElement("div"); + div.appendChild( document.createComment("") ); + + // Make sure no comments are found + if ( div.getElementsByTagName("*").length > 0 ) { + Expr.find.TAG = function( match, context ) { + var results = context.getElementsByTagName( match[1] ); + + // Filter out possible comments + if ( match[1] === "*" ) { + var tmp = []; + + for ( var i = 0; results[i]; i++ ) { + if ( results[i].nodeType === 1 ) { + tmp.push( results[i] ); + } + } + + results = tmp; + } + + return results; + }; + } + + // Check to see if an attribute returns normalized href attributes + div.innerHTML = "<a href='#'></a>"; + + if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && + div.firstChild.getAttribute("href") !== "#" ) { + + Expr.attrHandle.href = function( elem ) { + return elem.getAttribute( "href", 2 ); + }; + } + + // release memory in IE + div = null; +})(); + +if ( document.querySelectorAll ) { + (function(){ + var oldSizzle = Sizzle, + div = document.createElement("div"), + id = "__sizzle__"; + + div.innerHTML = "<p class='TEST'></p>"; + + // Safari can't handle uppercase or unicode characters when + // in quirks mode. + if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { + return; + } + + Sizzle = function( query, context, extra, seed ) { + context = context || document; + + // Only use querySelectorAll on non-XML documents + // (ID selectors don't work in non-HTML documents) + if ( !seed && !Sizzle.isXML(context) ) { + // See if we find a selector to speed up + var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query ); + + if ( match && (context.nodeType === 1 || context.nodeType === 9) ) { + // Speed-up: Sizzle("TAG") + if ( match[1] ) { + return makeArray( context.getElementsByTagName( query ), extra ); + + // Speed-up: Sizzle(".CLASS") + } else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) { + return makeArray( context.getElementsByClassName( match[2] ), extra ); + } + } + + if ( context.nodeType === 9 ) { + // Speed-up: Sizzle("body") + // The body element only exists once, optimize finding it + if ( query === "body" && context.body ) { + return makeArray( [ context.body ], extra ); + + // Speed-up: Sizzle("#ID") + } else if ( match && match[3] ) { + var elem = context.getElementById( match[3] ); + + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + if ( elem && elem.parentNode ) { + // Handle the case where IE and Opera return items + // by name instead of ID + if ( elem.id === match[3] ) { + return makeArray( [ elem ], extra ); + } + + } else { + return makeArray( [], extra ); + } + } + + try { + return makeArray( context.querySelectorAll(query), extra ); + } catch(qsaError) {} + + // qSA works strangely on Element-rooted queries + // We can work around this by specifying an extra ID on the root + // and working up from there (Thanks to Andrew Dupont for the technique) + // IE 8 doesn't work on object elements + } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { + var old = context.getAttribute( "id" ), + nid = old || id, + hasParent = context.parentNode, + relativeHierarchySelector = /^\s*[+~]/.test( query ); + + if ( !old ) { + context.setAttribute( "id", nid ); + } else { + nid = nid.replace( /'/g, "\\$&" ); + } + if ( relativeHierarchySelector && hasParent ) { + context = context.parentNode; + } + + try { + if ( !relativeHierarchySelector || hasParent ) { + return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra ); + } + + } catch(pseudoError) { + } finally { + if ( !old ) { + context.removeAttribute( "id" ); + } + } + } + } + + return oldSizzle(query, context, extra, seed); + }; + + for ( var prop in oldSizzle ) { + Sizzle[ prop ] = oldSizzle[ prop ]; + } + + // release memory in IE + div = null; + })(); +} + +(function(){ + var html = document.documentElement, + matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector, + pseudoWorks = false; + + try { + // This should fail with an exception + // Gecko does not error, returns false instead + matches.call( document.documentElement, "[test!='']:sizzle" ); + + } catch( pseudoError ) { + pseudoWorks = true; + } + + if ( matches ) { + Sizzle.matchesSelector = function( node, expr ) { + // Make sure that attribute selectors are quoted + expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']"); + + if ( !Sizzle.isXML( node ) ) { + try { + if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) { + return matches.call( node, expr ); + } + } catch(e) {} + } + + return Sizzle(expr, null, null, [node]).length > 0; + }; + } +})(); + +(function(){ + var div = document.createElement("div"); + + div.innerHTML = "<div class='test e'></div><div class='test'></div>"; + + // Opera can't find a second classname (in 9.6) + // Also, make sure that getElementsByClassName actually exists + if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { + return; + } + + // Safari caches class attributes, doesn't catch changes (in 3.2) + div.lastChild.className = "e"; + + if ( div.getElementsByClassName("e").length === 1 ) { + return; + } + + Expr.order.splice(1, 0, "CLASS"); + Expr.find.CLASS = function( match, context, isXML ) { + if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { + return context.getElementsByClassName(match[1]); + } + }; + + // release memory in IE + div = null; +})(); + +function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { + for ( var i = 0, l = checkSet.length; i < l; i++ ) { + var elem = checkSet[i]; + + if ( elem ) { + var match = false; + + elem = elem[dir]; + + while ( elem ) { + if ( elem.sizcache === doneName ) { + match = checkSet[elem.sizset]; + break; + } + + if ( elem.nodeType === 1 && !isXML ){ + elem.sizcache = doneName; + elem.sizset = i; + } + + if ( elem.nodeName.toLowerCase() === cur ) { + match = elem; + break; + } + + elem = elem[dir]; + } + + checkSet[i] = match; + } + } +} + +function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { + for ( var i = 0, l = checkSet.length; i < l; i++ ) { + var elem = checkSet[i]; + + if ( elem ) { + var match = false; + + elem = elem[dir]; + + while ( elem ) { + if ( elem.sizcache === doneName ) { + match = checkSet[elem.sizset]; + break; + } + + if ( elem.nodeType === 1 ) { + if ( !isXML ) { + elem.sizcache = doneName; + elem.sizset = i; + } + + if ( typeof cur !== "string" ) { + if ( elem === cur ) { + match = true; + break; + } + + } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { + match = elem; + break; + } + } + + elem = elem[dir]; + } + + checkSet[i] = match; + } + } +} + +if ( document.documentElement.contains ) { + Sizzle.contains = function( a, b ) { + return a !== b && (a.contains ? a.contains(b) : true); + }; + +} else if ( document.documentElement.compareDocumentPosition ) { + Sizzle.contains = function( a, b ) { + return !!(a.compareDocumentPosition(b) & 16); + }; + +} else { + Sizzle.contains = function() { + return false; + }; +} + +Sizzle.isXML = function( elem ) { + // documentElement is verified for cases where it doesn't yet exist + // (such as loading iframes in IE - #4833) + var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement; + + return documentElement ? documentElement.nodeName !== "HTML" : false; +}; + +var posProcess = function( selector, context ) { + var match, + tmpSet = [], + later = "", + root = context.nodeType ? [context] : context; + + // Position selectors must be done after the filter + // And so must :not(positional) so we move all PSEUDOs to the end + while ( (match = Expr.match.PSEUDO.exec( selector )) ) { + later += match[0]; + selector = selector.replace( Expr.match.PSEUDO, "" ); + } + + selector = Expr.relative[selector] ? selector + "*" : selector; + + for ( var i = 0, l = root.length; i < l; i++ ) { + Sizzle( selector, root[i], tmpSet ); + } + + return Sizzle.filter( later, tmpSet ); +}; + +// EXPOSE +jQuery.find = Sizzle; +jQuery.expr = Sizzle.selectors; +jQuery.expr[":"] = jQuery.expr.filters; +jQuery.unique = Sizzle.uniqueSort; +jQuery.text = Sizzle.getText; +jQuery.isXMLDoc = Sizzle.isXML; +jQuery.contains = Sizzle.contains; + + +})(); + + +var runtil = /Until$/, + rparentsprev = /^(?:parents|prevUntil|prevAll)/, + // Note: This RegExp should be improved, or likely pulled from Sizzle + rmultiselector = /,/, + isSimple = /^.[^:#\[\.,]*$/, + slice = Array.prototype.slice, + POS = jQuery.expr.match.POS, + // methods guaranteed to produce a unique set when starting from a unique set + guaranteedUnique = { + children: true, + contents: true, + next: true, + prev: true + }; + +jQuery.fn.extend({ + find: function( selector ) { + var ret = this.pushStack( "", "find", selector ), + length = 0; + + for ( var i = 0, l = this.length; i < l; i++ ) { + length = ret.length; + jQuery.find( selector, this[i], ret ); + + if ( i > 0 ) { + // Make sure that the results are unique + for ( var n = length; n < ret.length; n++ ) { + for ( var r = 0; r < length; r++ ) { + if ( ret[r] === ret[n] ) { + ret.splice(n--, 1); + break; + } + } + } + } + } + + return ret; + }, + + has: function( target ) { + var targets = jQuery( target ); + return this.filter(function() { + for ( var i = 0, l = targets.length; i < l; i++ ) { + if ( jQuery.contains( this, targets[i] ) ) { + return true; + } + } + }); + }, + + not: function( selector ) { + return this.pushStack( winnow(this, selector, false), "not", selector); + }, + + filter: function( selector ) { + return this.pushStack( winnow(this, selector, true), "filter", selector ); + }, + + is: function( selector ) { + return !!selector && jQuery.filter( selector, this ).length > 0; + }, + + closest: function( selectors, context ) { + var ret = [], i, l, cur = this[0]; + + if ( jQuery.isArray( selectors ) ) { + var match, selector, + matches = {}, + level = 1; + + if ( cur && selectors.length ) { + for ( i = 0, l = selectors.length; i < l; i++ ) { + selector = selectors[i]; + + if ( !matches[selector] ) { + matches[selector] = jQuery.expr.match.POS.test( selector ) ? + jQuery( selector, context || this.context ) : + selector; + } + } + + while ( cur && cur.ownerDocument && cur !== context ) { + for ( selector in matches ) { + match = matches[selector]; + + if ( match.jquery ? match.index(cur) > -1 : jQuery(cur).is(match) ) { + ret.push({ selector: selector, elem: cur, level: level }); + } + } + + cur = cur.parentNode; + level++; + } + } + + return ret; + } + + var pos = POS.test( selectors ) ? + jQuery( selectors, context || this.context ) : null; + + for ( i = 0, l = this.length; i < l; i++ ) { + cur = this[i]; + + while ( cur ) { + if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { + ret.push( cur ); + break; + + } else { + cur = cur.parentNode; + if ( !cur || !cur.ownerDocument || cur === context ) { + break; + } + } + } + } + + ret = ret.length > 1 ? jQuery.unique(ret) : ret; + + return this.pushStack( ret, "closest", selectors ); + }, + + // Determine the position of an element within + // the matched set of elements + index: function( elem ) { + if ( !elem || typeof elem === "string" ) { + return jQuery.inArray( this[0], + // If it receives a string, the selector is used + // If it receives nothing, the siblings are used + elem ? jQuery( elem ) : this.parent().children() ); + } + // Locate the position of the desired element + return jQuery.inArray( + // If it receives a jQuery object, the first element is used + elem.jquery ? elem[0] : elem, this ); + }, + + add: function( selector, context ) { + var set = typeof selector === "string" ? + jQuery( selector, context ) : + jQuery.makeArray( selector ), + all = jQuery.merge( this.get(), set ); + + return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? + all : + jQuery.unique( all ) ); + }, + + andSelf: function() { + return this.add( this.prevObject ); + } +}); + +// A painfully simple check to see if an element is disconnected +// from a document (should be improved, where feasible). +function isDisconnected( node ) { + return !node || !node.parentNode || node.parentNode.nodeType === 11; +} + +jQuery.each({ + parent: function( elem ) { + var parent = elem.parentNode; + return parent && parent.nodeType !== 11 ? parent : null; + }, + parents: function( elem ) { + return jQuery.dir( elem, "parentNode" ); + }, + parentsUntil: function( elem, i, until ) { + return jQuery.dir( elem, "parentNode", until ); + }, + next: function( elem ) { + return jQuery.nth( elem, 2, "nextSibling" ); + }, + prev: function( elem ) { + return jQuery.nth( elem, 2, "previousSibling" ); + }, + nextAll: function( elem ) { + return jQuery.dir( elem, "nextSibling" ); + }, + prevAll: function( elem ) { + return jQuery.dir( elem, "previousSibling" ); + }, + nextUntil: function( elem, i, until ) { + return jQuery.dir( elem, "nextSibling", until ); + }, + prevUntil: function( elem, i, until ) { + return jQuery.dir( elem, "previousSibling", until ); + }, + siblings: function( elem ) { + return jQuery.sibling( elem.parentNode.firstChild, elem ); + }, + children: function( elem ) { + return jQuery.sibling( elem.firstChild ); + }, + contents: function( elem ) { + return jQuery.nodeName( elem, "iframe" ) ? + elem.contentDocument || elem.contentWindow.document : + jQuery.makeArray( elem.childNodes ); + } +}, function( name, fn ) { + jQuery.fn[ name ] = function( until, selector ) { + var ret = jQuery.map( this, fn, until ), + // The variable 'args' was introduced in + // https://github.com/jquery/jquery/commit/52a0238 + // to work around a bug in Chrome 10 (Dev) and should be removed when the bug is fixed. + // http://code.google.com/p/v8/issues/detail?id=1050 + args = slice.call(arguments); + + if ( !runtil.test( name ) ) { + selector = until; + } + + if ( selector && typeof selector === "string" ) { + ret = jQuery.filter( selector, ret ); + } + + ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; + + if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) { + ret = ret.reverse(); + } + + return this.pushStack( ret, name, args.join(",") ); + }; +}); + +jQuery.extend({ + filter: function( expr, elems, not ) { + if ( not ) { + expr = ":not(" + expr + ")"; + } + + return elems.length === 1 ? + jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : + jQuery.find.matches(expr, elems); + }, + + dir: function( elem, dir, until ) { + var matched = [], + cur = elem[ dir ]; + + while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { + if ( cur.nodeType === 1 ) { + matched.push( cur ); + } + cur = cur[dir]; + } + return matched; + }, + + nth: function( cur, result, dir, elem ) { + result = result || 1; + var num = 0; + + for ( ; cur; cur = cur[dir] ) { + if ( cur.nodeType === 1 && ++num === result ) { + break; + } + } + + return cur; + }, + + sibling: function( n, elem ) { + var r = []; + + for ( ; n; n = n.nextSibling ) { + if ( n.nodeType === 1 && n !== elem ) { + r.push( n ); + } + } + + return r; + } +}); + +// Implement the identical functionality for filter and not +function winnow( elements, qualifier, keep ) { + if ( jQuery.isFunction( qualifier ) ) { + return jQuery.grep(elements, function( elem, i ) { + var retVal = !!qualifier.call( elem, i, elem ); + return retVal === keep; + }); + + } else if ( qualifier.nodeType ) { + return jQuery.grep(elements, function( elem, i ) { + return (elem === qualifier) === keep; + }); + + } else if ( typeof qualifier === "string" ) { + var filtered = jQuery.grep(elements, function( elem ) { + return elem.nodeType === 1; + }); + + if ( isSimple.test( qualifier ) ) { + return jQuery.filter(qualifier, filtered, !keep); + } else { + qualifier = jQuery.filter( qualifier, filtered ); + } + } + + return jQuery.grep(elements, function( elem, i ) { + return (jQuery.inArray( elem, qualifier ) >= 0) === keep; + }); +} + + + + +var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g, + rleadingWhitespace = /^\s+/, + rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig, + rtagName = /<([\w:]+)/, + rtbody = /<tbody/i, + rhtml = /<|&#?\w+;/, + rnocache = /<(?:script|object|embed|option|style)/i, + // checked="checked" or checked (html5) + rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, + wrapMap = { + option: [ 1, "<select multiple='multiple'>", "</select>" ], + legend: [ 1, "<fieldset>", "</fieldset>" ], + thead: [ 1, "<table>", "</table>" ], + tr: [ 2, "<table><tbody>", "</tbody></table>" ], + td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], + col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], + area: [ 1, "<map>", "</map>" ], + _default: [ 0, "", "" ] + }; + +wrapMap.optgroup = wrapMap.option; +wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; +wrapMap.th = wrapMap.td; + +// IE can't serialize <link> and <script> tags normally +if ( !jQuery.support.htmlSerialize ) { + wrapMap._default = [ 1, "div<div>", "</div>" ]; +} + +jQuery.fn.extend({ + text: function( text ) { + if ( jQuery.isFunction(text) ) { + return this.each(function(i) { + var self = jQuery( this ); + + self.text( text.call(this, i, self.text()) ); + }); + } + + if ( typeof text !== "object" && text !== undefined ) { + return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) ); + } + + return jQuery.text( this ); + }, + + wrapAll: function( html ) { + if ( jQuery.isFunction( html ) ) { + return this.each(function(i) { + jQuery(this).wrapAll( html.call(this, i) ); + }); + } + + if ( this[0] ) { + // The elements to wrap the target around + var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); + + if ( this[0].parentNode ) { + wrap.insertBefore( this[0] ); + } + + wrap.map(function() { + var elem = this; + + while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { + elem = elem.firstChild; + } + + return elem; + }).append(this); + } + + return this; + }, + + wrapInner: function( html ) { + if ( jQuery.isFunction( html ) ) { + return this.each(function(i) { + jQuery(this).wrapInner( html.call(this, i) ); + }); + } + + return this.each(function() { + var self = jQuery( this ), + contents = self.contents(); + + if ( contents.length ) { + contents.wrapAll( html ); + + } else { + self.append( html ); + } + }); + }, + + wrap: function( html ) { + return this.each(function() { + jQuery( this ).wrapAll( html ); + }); + }, + + unwrap: function() { + return this.parent().each(function() { + if ( !jQuery.nodeName( this, "body" ) ) { + jQuery( this ).replaceWith( this.childNodes ); + } + }).end(); + }, + + append: function() { + return this.domManip(arguments, true, function( elem ) { + if ( this.nodeType === 1 ) { + this.appendChild( elem ); + } + }); + }, + + prepend: function() { + return this.domManip(arguments, true, function( elem ) { + if ( this.nodeType === 1 ) { + this.insertBefore( elem, this.firstChild ); + } + }); + }, + + before: function() { + if ( this[0] && this[0].parentNode ) { + return this.domManip(arguments, false, function( elem ) { + this.parentNode.insertBefore( elem, this ); + }); + } else if ( arguments.length ) { + var set = jQuery(arguments[0]); + set.push.apply( set, this.toArray() ); + return this.pushStack( set, "before", arguments ); + } + }, + + after: function() { + if ( this[0] && this[0].parentNode ) { + return this.domManip(arguments, false, function( elem ) { + this.parentNode.insertBefore( elem, this.nextSibling ); + }); + } else if ( arguments.length ) { + var set = this.pushStack( this, "after", arguments ); + set.push.apply( set, jQuery(arguments[0]).toArray() ); + return set; + } + }, + + // keepData is for internal use only--do not document + remove: function( selector, keepData ) { + for ( var i = 0, elem; (elem = this[i]) != null; i++ ) { + if ( !selector || jQuery.filter( selector, [ elem ] ).length ) { + if ( !keepData && elem.nodeType === 1 ) { + jQuery.cleanData( elem.getElementsByTagName("*") ); + jQuery.cleanData( [ elem ] ); + } + + if ( elem.parentNode ) { + elem.parentNode.removeChild( elem ); + } + } + } + + return this; + }, + + empty: function() { + for ( var i = 0, elem; (elem = this[i]) != null; i++ ) { + // Remove element nodes and prevent memory leaks + if ( elem.nodeType === 1 ) { + jQuery.cleanData( elem.getElementsByTagName("*") ); + } + + // Remove any remaining nodes + while ( elem.firstChild ) { + elem.removeChild( elem.firstChild ); + } + } + + return this; + }, + + clone: function( dataAndEvents, deepDataAndEvents ) { + dataAndEvents = dataAndEvents == null ? true : dataAndEvents; + deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; + + return this.map( function () { + return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); + }); + }, + + html: function( value ) { + if ( value === undefined ) { + return this[0] && this[0].nodeType === 1 ? + this[0].innerHTML.replace(rinlinejQuery, "") : + null; + + // See if we can take a shortcut and just use innerHTML + } else if ( typeof value === "string" && !rnocache.test( value ) && + (jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) && + !wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) { + + value = value.replace(rxhtmlTag, "<$1></$2>"); + + try { + for ( var i = 0, l = this.length; i < l; i++ ) { + // Remove element nodes and prevent memory leaks + if ( this[i].nodeType === 1 ) { + jQuery.cleanData( this[i].getElementsByTagName("*") ); + this[i].innerHTML = value; + } + } + + // If using innerHTML throws an exception, use the fallback method + } catch(e) { + this.empty().append( value ); + } + + } else if ( jQuery.isFunction( value ) ) { + this.each(function(i){ + var self = jQuery( this ); + + self.html( value.call(this, i, self.html()) ); + }); + + } else { + this.empty().append( value ); + } + + return this; + }, + + replaceWith: function( value ) { + if ( this[0] && this[0].parentNode ) { + // Make sure that the elements are removed from the DOM before they are inserted + // this can help fix replacing a parent with child elements + if ( jQuery.isFunction( value ) ) { + return this.each(function(i) { + var self = jQuery(this), old = self.html(); + self.replaceWith( value.call( this, i, old ) ); + }); + } + + if ( typeof value !== "string" ) { + value = jQuery( value ).detach(); + } + + return this.each(function() { + var next = this.nextSibling, + parent = this.parentNode; + + jQuery( this ).remove(); + + if ( next ) { + jQuery(next).before( value ); + } else { + jQuery(parent).append( value ); + } + }); + } else { + return this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ); + } + }, + + detach: function( selector ) { + return this.remove( selector, true ); + }, + + domManip: function( args, table, callback ) { + var results, first, fragment, parent, + value = args[0], + scripts = []; + + // We can't cloneNode fragments that contain checked, in WebKit + if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) { + return this.each(function() { + jQuery(this).domManip( args, table, callback, true ); + }); + } + + if ( jQuery.isFunction(value) ) { + return this.each(function(i) { + var self = jQuery(this); + args[0] = value.call(this, i, table ? self.html() : undefined); + self.domManip( args, table, callback ); + }); + } + + if ( this[0] ) { + parent = value && value.parentNode; + + // If we're in a fragment, just use that instead of building a new one + if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) { + results = { fragment: parent }; + + } else { + results = jQuery.buildFragment( args, this, scripts ); + } + + fragment = results.fragment; + + if ( fragment.childNodes.length === 1 ) { + first = fragment = fragment.firstChild; + } else { + first = fragment.firstChild; + } + + if ( first ) { + table = table && jQuery.nodeName( first, "tr" ); + + for ( var i = 0, l = this.length, lastIndex = l - 1; i < l; i++ ) { + callback.call( + table ? + root(this[i], first) : + this[i], + // Make sure that we do not leak memory by inadvertently discarding + // the original fragment (which might have attached data) instead of + // using it; in addition, use the original fragment object for the last + // item instead of first because it can end up being emptied incorrectly + // in certain situations (Bug #8070). + // Fragments from the fragment cache must always be cloned and never used + // in place. + results.cacheable || (l > 1 && i < lastIndex) ? + jQuery.clone( fragment, true, true ) : + fragment + ); + } + } + + if ( scripts.length ) { + jQuery.each( scripts, evalScript ); + } + } + + return this; + } +}); + +function root( elem, cur ) { + return jQuery.nodeName(elem, "table") ? + (elem.getElementsByTagName("tbody")[0] || + elem.appendChild(elem.ownerDocument.createElement("tbody"))) : + elem; +} + +function cloneCopyEvent( src, dest ) { + + if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { + return; + } + + var internalKey = jQuery.expando, + oldData = jQuery.data( src ), + curData = jQuery.data( dest, oldData ); + + // Switch to use the internal data object, if it exists, for the next + // stage of data copying + if ( (oldData = oldData[ internalKey ]) ) { + var events = oldData.events; + curData = curData[ internalKey ] = jQuery.extend({}, oldData); + + if ( events ) { + delete curData.handle; + curData.events = {}; + + for ( var type in events ) { + for ( var i = 0, l = events[ type ].length; i < l; i++ ) { + jQuery.event.add( dest, type, events[ type ][ i ], events[ type ][ i ].data ); + } + } + } + } +} + +function cloneFixAttributes(src, dest) { + // We do not need to do anything for non-Elements + if ( dest.nodeType !== 1 ) { + return; + } + + var nodeName = dest.nodeName.toLowerCase(); + + // clearAttributes removes the attributes, which we don't want, + // but also removes the attachEvent events, which we *do* want + dest.clearAttributes(); + + // mergeAttributes, in contrast, only merges back on the + // original attributes, not the events + dest.mergeAttributes(src); + + // IE6-8 fail to clone children inside object elements that use + // the proprietary classid attribute value (rather than the type + // attribute) to identify the type of content to display + if ( nodeName === "object" ) { + dest.outerHTML = src.outerHTML; + + } else if ( nodeName === "input" && (src.type === "checkbox" || src.type === "radio") ) { + // IE6-8 fails to persist the checked state of a cloned checkbox + // or radio button. Worse, IE6-7 fail to give the cloned element + // a checked appearance if the defaultChecked value isn't also set + if ( src.checked ) { + dest.defaultChecked = dest.checked = src.checked; + } + + // IE6-7 get confused and end up setting the value of a cloned + // checkbox/radio button to an empty string instead of "on" + if ( dest.value !== src.value ) { + dest.value = src.value; + } + + // IE6-8 fails to return the selected option to the default selected + // state when cloning options + } else if ( nodeName === "option" ) { + dest.selected = src.defaultSelected; + + // IE6-8 fails to set the defaultValue to the correct value when + // cloning other types of input fields + } else if ( nodeName === "input" || nodeName === "textarea" ) { + dest.defaultValue = src.defaultValue; + } + + // Event data gets referenced instead of copied if the expando + // gets copied too + dest.removeAttribute( jQuery.expando ); +} + +jQuery.buildFragment = function( args, nodes, scripts ) { + var fragment, cacheable, cacheresults, + doc = (nodes && nodes[0] ? nodes[0].ownerDocument || nodes[0] : document); + + // Only cache "small" (1/2 KB) HTML strings that are associated with the main document + // Cloning options loses the selected state, so don't cache them + // IE 6 doesn't like it when you put <object> or <embed> elements in a fragment + // Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache + if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && doc === document && + args[0].charAt(0) === "<" && !rnocache.test( args[0] ) && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) { + + cacheable = true; + cacheresults = jQuery.fragments[ args[0] ]; + if ( cacheresults ) { + if ( cacheresults !== 1 ) { + fragment = cacheresults; + } + } + } + + if ( !fragment ) { + fragment = doc.createDocumentFragment(); + jQuery.clean( args, doc, fragment, scripts ); + } + + if ( cacheable ) { + jQuery.fragments[ args[0] ] = cacheresults ? fragment : 1; + } + + return { fragment: fragment, cacheable: cacheable }; +}; + +jQuery.fragments = {}; + +jQuery.each({ + appendTo: "append", + prependTo: "prepend", + insertBefore: "before", + insertAfter: "after", + replaceAll: "replaceWith" +}, function( name, original ) { + jQuery.fn[ name ] = function( selector ) { + var ret = [], + insert = jQuery( selector ), + parent = this.length === 1 && this[0].parentNode; + + if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) { + insert[ original ]( this[0] ); + return this; + + } else { + for ( var i = 0, l = insert.length; i < l; i++ ) { + var elems = (i > 0 ? this.clone(true) : this).get(); + jQuery( insert[i] )[ original ]( elems ); + ret = ret.concat( elems ); + } + + return this.pushStack( ret, name, insert.selector ); + } + }; +}); + +jQuery.extend({ + clone: function( elem, dataAndEvents, deepDataAndEvents ) { + var clone = elem.cloneNode(true), + srcElements, + destElements, + i; + + if ( !jQuery.support.noCloneEvent && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { + // IE copies events bound via attachEvent when using cloneNode. + // Calling detachEvent on the clone will also remove the events + // from the original. In order to get around this, we use some + // proprietary methods to clear the events. Thanks to MooTools + // guys for this hotness. + + // Using Sizzle here is crazy slow, so we use getElementsByTagName + // instead + srcElements = elem.getElementsByTagName("*"); + destElements = clone.getElementsByTagName("*"); + + // Weird iteration because IE will replace the length property + // with an element if you are cloning the body and one of the + // elements on the page has a name or id of "length" + for ( i = 0; srcElements[i]; ++i ) { + cloneFixAttributes( srcElements[i], destElements[i] ); + } + + cloneFixAttributes( elem, clone ); + } + + // Copy the events from the original to the clone + if ( dataAndEvents ) { + + cloneCopyEvent( elem, clone ); + + if ( deepDataAndEvents && "getElementsByTagName" in elem ) { + + srcElements = elem.getElementsByTagName("*"); + destElements = clone.getElementsByTagName("*"); + + if ( srcElements.length ) { + for ( i = 0; srcElements[i]; ++i ) { + cloneCopyEvent( srcElements[i], destElements[i] ); + } + } + } + } + // Return the cloned set + return clone; + }, + clean: function( elems, context, fragment, scripts ) { + context = context || document; + + // !context.createElement fails in IE with an error but returns typeof 'object' + if ( typeof context.createElement === "undefined" ) { + context = context.ownerDocument || context[0] && context[0].ownerDocument || document; + } + + var ret = []; + + for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { + if ( typeof elem === "number" ) { + elem += ""; + } + + if ( !elem ) { + continue; + } + + // Convert html string into DOM nodes + if ( typeof elem === "string" && !rhtml.test( elem ) ) { + elem = context.createTextNode( elem ); + + } else if ( typeof elem === "string" ) { + // Fix "XHTML"-style tags in all browsers + elem = elem.replace(rxhtmlTag, "<$1></$2>"); + + // Trim whitespace, otherwise indexOf won't work as expected + var tag = (rtagName.exec( elem ) || ["", ""])[1].toLowerCase(), + wrap = wrapMap[ tag ] || wrapMap._default, + depth = wrap[0], + div = context.createElement("div"); + + // Go to html and back, then peel off extra wrappers + div.innerHTML = wrap[1] + elem + wrap[2]; + + // Move to the right depth + while ( depth-- ) { + div = div.lastChild; + } + + // Remove IE's autoinserted <tbody> from table fragments + if ( !jQuery.support.tbody ) { + + // String was a <table>, *may* have spurious <tbody> + var hasBody = rtbody.test(elem), + tbody = tag === "table" && !hasBody ? + div.firstChild && div.firstChild.childNodes : + + // String was a bare <thead> or <tfoot> + wrap[1] === "<table>" && !hasBody ? + div.childNodes : + []; + + for ( var j = tbody.length - 1; j >= 0 ; --j ) { + if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) { + tbody[ j ].parentNode.removeChild( tbody[ j ] ); + } + } + + } + + // IE completely kills leading whitespace when innerHTML is used + if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { + div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild ); + } + + elem = div.childNodes; + } + + if ( elem.nodeType ) { + ret.push( elem ); + } else { + ret = jQuery.merge( ret, elem ); + } + } + + if ( fragment ) { + for ( i = 0; ret[i]; i++ ) { + if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) { + scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] ); + + } else { + if ( ret[i].nodeType === 1 ) { + ret.splice.apply( ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))) ); + } + fragment.appendChild( ret[i] ); + } + } + } + + return ret; + }, + + cleanData: function( elems ) { + var data, id, cache = jQuery.cache, internalKey = jQuery.expando, special = jQuery.event.special, + deleteExpando = jQuery.support.deleteExpando; + + for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { + if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) { + continue; + } + + id = elem[ jQuery.expando ]; + + if ( id ) { + data = cache[ id ] && cache[ id ][ internalKey ]; + + if ( data && data.events ) { + for ( var type in data.events ) { + if ( special[ type ] ) { + jQuery.event.remove( elem, type ); + + // This is a shortcut to avoid jQuery.event.remove's overhead + } else { + jQuery.removeEvent( elem, type, data.handle ); + } + } + + // Null the DOM reference to avoid IE6/7/8 leak (#7054) + if ( data.handle ) { + data.handle.elem = null; + } + } + + if ( deleteExpando ) { + delete elem[ jQuery.expando ]; + + } else if ( elem.removeAttribute ) { + elem.removeAttribute( jQuery.expando ); + } + + delete cache[ id ]; + } + } + } +}); + +function evalScript( i, elem ) { + if ( elem.src ) { + jQuery.ajax({ + url: elem.src, + async: false, + dataType: "script" + }); + } else { + jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" ); + } + + if ( elem.parentNode ) { + elem.parentNode.removeChild( elem ); + } +} + + + + +var ralpha = /alpha\([^)]*\)/i, + ropacity = /opacity=([^)]*)/, + rdashAlpha = /-([a-z])/ig, + rupper = /([A-Z])/g, + rnumpx = /^-?\d+(?:px)?$/i, + rnum = /^-?\d/, + + cssShow = { position: "absolute", visibility: "hidden", display: "block" }, + cssWidth = [ "Left", "Right" ], + cssHeight = [ "Top", "Bottom" ], + curCSS, + + getComputedStyle, + currentStyle, + + fcamelCase = function( all, letter ) { + return letter.toUpperCase(); + }; + +jQuery.fn.css = function( name, value ) { + // Setting 'undefined' is a no-op + if ( arguments.length === 2 && value === undefined ) { + return this; + } + + return jQuery.access( this, name, value, true, function( elem, name, value ) { + return value !== undefined ? + jQuery.style( elem, name, value ) : + jQuery.css( elem, name ); + }); +}; + +jQuery.extend({ + // Add in style property hooks for overriding the default + // behavior of getting and setting a style property + cssHooks: { + opacity: { + get: function( elem, computed ) { + if ( computed ) { + // We should always get a number back from opacity + var ret = curCSS( elem, "opacity", "opacity" ); + return ret === "" ? "1" : ret; + + } else { + return elem.style.opacity; + } + } + } + }, + + // Exclude the following css properties to add px + cssNumber: { + "zIndex": true, + "fontWeight": true, + "opacity": true, + "zoom": true, + "lineHeight": true + }, + + // Add in properties whose names you wish to fix before + // setting or getting the value + cssProps: { + // normalize float css property + "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" + }, + + // Get and set the style property on a DOM Node + style: function( elem, name, value, extra ) { + // Don't set styles on text and comment nodes + if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { + return; + } + + // Make sure that we're working with the right name + var ret, origName = jQuery.camelCase( name ), + style = elem.style, hooks = jQuery.cssHooks[ origName ]; + + name = jQuery.cssProps[ origName ] || origName; + + // Check if we're setting a value + if ( value !== undefined ) { + // Make sure that NaN and null values aren't set. See: #7116 + if ( typeof value === "number" && isNaN( value ) || value == null ) { + return; + } + + // If a number was passed in, add 'px' to the (except for certain CSS properties) + if ( typeof value === "number" && !jQuery.cssNumber[ origName ] ) { + value += "px"; + } + + // If a hook was provided, use that value, otherwise just set the specified value + if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value )) !== undefined ) { + // Wrapped to prevent IE from throwing errors when 'invalid' values are provided + // Fixes bug #5509 + try { + style[ name ] = value; + } catch(e) {} + } + + } else { + // If a hook was provided get the non-computed value from there + if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { + return ret; + } + + // Otherwise just get the value from the style object + return style[ name ]; + } + }, + + css: function( elem, name, extra ) { + // Make sure that we're working with the right name + var ret, origName = jQuery.camelCase( name ), + hooks = jQuery.cssHooks[ origName ]; + + name = jQuery.cssProps[ origName ] || origName; + + // If a hook was provided get the computed value from there + if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) { + return ret; + + // Otherwise, if a way to get the computed value exists, use that + } else if ( curCSS ) { + return curCSS( elem, name, origName ); + } + }, + + // A method for quickly swapping in/out CSS properties to get correct calculations + swap: function( elem, options, callback ) { + var old = {}; + + // Remember the old values, and insert the new ones + for ( var name in options ) { + old[ name ] = elem.style[ name ]; + elem.style[ name ] = options[ name ]; + } + + callback.call( elem ); + + // Revert the old values + for ( name in options ) { + elem.style[ name ] = old[ name ]; + } + }, + + camelCase: function( string ) { + return string.replace( rdashAlpha, fcamelCase ); + } +}); + +// DEPRECATED, Use jQuery.css() instead +jQuery.curCSS = jQuery.css; + +jQuery.each(["height", "width"], function( i, name ) { + jQuery.cssHooks[ name ] = { + get: function( elem, computed, extra ) { + var val; + + if ( computed ) { + if ( elem.offsetWidth !== 0 ) { + val = getWH( elem, name, extra ); + + } else { + jQuery.swap( elem, cssShow, function() { + val = getWH( elem, name, extra ); + }); + } + + if ( val <= 0 ) { + val = curCSS( elem, name, name ); + + if ( val === "0px" && currentStyle ) { + val = currentStyle( elem, name, name ); + } + + if ( val != null ) { + // Should return "auto" instead of 0, use 0 for + // temporary backwards-compat + return val === "" || val === "auto" ? "0px" : val; + } + } + + if ( val < 0 || val == null ) { + val = elem.style[ name ]; + + // Should return "auto" instead of 0, use 0 for + // temporary backwards-compat + return val === "" || val === "auto" ? "0px" : val; + } + + return typeof val === "string" ? val : val + "px"; + } + }, + + set: function( elem, value ) { + if ( rnumpx.test( value ) ) { + // ignore negative width and height values #1599 + value = parseFloat(value); + + if ( value >= 0 ) { + return value + "px"; + } + + } else { + return value; + } + } + }; +}); + +if ( !jQuery.support.opacity ) { + jQuery.cssHooks.opacity = { + get: function( elem, computed ) { + // IE uses filters for opacity + return ropacity.test((computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "") ? + (parseFloat(RegExp.$1) / 100) + "" : + computed ? "1" : ""; + }, + + set: function( elem, value ) { + var style = elem.style; + + // IE has trouble with opacity if it does not have layout + // Force it by setting the zoom level + style.zoom = 1; + + // Set the alpha filter to set the opacity + var opacity = jQuery.isNaN(value) ? + "" : + "alpha(opacity=" + value * 100 + ")", + filter = style.filter || ""; + + style.filter = ralpha.test(filter) ? + filter.replace(ralpha, opacity) : + style.filter + ' ' + opacity; + } + }; +} + +if ( document.defaultView && document.defaultView.getComputedStyle ) { + getComputedStyle = function( elem, newName, name ) { + var ret, defaultView, computedStyle; + + name = name.replace( rupper, "-$1" ).toLowerCase(); + + if ( !(defaultView = elem.ownerDocument.defaultView) ) { + return undefined; + } + + if ( (computedStyle = defaultView.getComputedStyle( elem, null )) ) { + ret = computedStyle.getPropertyValue( name ); + if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) { + ret = jQuery.style( elem, name ); + } + } + + return ret; + }; +} + +if ( document.documentElement.currentStyle ) { + currentStyle = function( elem, name ) { + var left, + ret = elem.currentStyle && elem.currentStyle[ name ], + rsLeft = elem.runtimeStyle && elem.runtimeStyle[ name ], + style = elem.style; + + // From the awesome hack by Dean Edwards + // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 + + // If we're not dealing with a regular pixel number + // but a number that has a weird ending, we need to convert it to pixels + if ( !rnumpx.test( ret ) && rnum.test( ret ) ) { + // Remember the original values + left = style.left; + + // Put in the new values to get a computed value out + if ( rsLeft ) { + elem.runtimeStyle.left = elem.currentStyle.left; + } + style.left = name === "fontSize" ? "1em" : (ret || 0); + ret = style.pixelLeft + "px"; + + // Revert the changed values + style.left = left; + if ( rsLeft ) { + elem.runtimeStyle.left = rsLeft; + } + } + + return ret === "" ? "auto" : ret; + }; +} + +curCSS = getComputedStyle || currentStyle; + +function getWH( elem, name, extra ) { + var which = name === "width" ? cssWidth : cssHeight, + val = name === "width" ? elem.offsetWidth : elem.offsetHeight; + + if ( extra === "border" ) { + return val; + } + + jQuery.each( which, function() { + if ( !extra ) { + val -= parseFloat(jQuery.css( elem, "padding" + this )) || 0; + } + + if ( extra === "margin" ) { + val += parseFloat(jQuery.css( elem, "margin" + this )) || 0; + + } else { + val -= parseFloat(jQuery.css( elem, "border" + this + "Width" )) || 0; + } + }); + + return val; +} + +if ( jQuery.expr && jQuery.expr.filters ) { + jQuery.expr.filters.hidden = function( elem ) { + var width = elem.offsetWidth, + height = elem.offsetHeight; + + return (width === 0 && height === 0) || (!jQuery.support.reliableHiddenOffsets && (elem.style.display || jQuery.css( elem, "display" )) === "none"); + }; + + jQuery.expr.filters.visible = function( elem ) { + return !jQuery.expr.filters.hidden( elem ); + }; +} + + + + +var r20 = /%20/g, + rbracket = /\[\]$/, + rCRLF = /\r?\n/g, + rhash = /#.*$/, + rheaders = /^(.*?):\s*(.*?)\r?$/mg, // IE leaves an \r character at EOL + rinput = /^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i, + rnoContent = /^(?:GET|HEAD)$/, + rprotocol = /^\/\//, + rquery = /\?/, + rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, + rselectTextarea = /^(?:select|textarea)/i, + rspacesAjax = /\s+/, + rts = /([?&])_=[^&]*/, + rurl = /^(\w+:)\/\/([^\/?#:]+)(?::(\d+))?/, + + // Keep a copy of the old load method + _load = jQuery.fn.load, + + /* Prefilters + * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) + * 2) These are called: + * - BEFORE asking for a transport + * - AFTER param serialization (s.data is a string if s.processData is true) + * 3) key is the dataType + * 4) the catchall symbol "*" can be used + * 5) execution will start with transport dataType and THEN continue down to "*" if needed + */ + prefilters = {}, + + /* Transports bindings + * 1) key is the dataType + * 2) the catchall symbol "*" can be used + * 3) selection will start with transport dataType and THEN go to "*" if needed + */ + transports = {}; + +// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport +function addToPrefiltersOrTransports( structure ) { + + // dataTypeExpression is optional and defaults to "*" + return function( dataTypeExpression, func ) { + + if ( typeof dataTypeExpression !== "string" ) { + func = dataTypeExpression; + dataTypeExpression = "*"; + } + + if ( jQuery.isFunction( func ) ) { + var dataTypes = dataTypeExpression.toLowerCase().split( rspacesAjax ), + i = 0, + length = dataTypes.length, + dataType, + list, + placeBefore; + + // For each dataType in the dataTypeExpression + for(; i < length; i++ ) { + dataType = dataTypes[ i ]; + // We control if we're asked to add before + // any existing element + placeBefore = /^\+/.test( dataType ); + if ( placeBefore ) { + dataType = dataType.substr( 1 ) || "*"; + } + list = structure[ dataType ] = structure[ dataType ] || []; + // then we add to the structure accordingly + list[ placeBefore ? "unshift" : "push" ]( func ); + } + } + }; +} + +//Base inspection function for prefilters and transports +function inspectPrefiltersOrTransports( structure, options, originalOptions, jXHR, + dataType /* internal */, inspected /* internal */ ) { + + dataType = dataType || options.dataTypes[ 0 ]; + inspected = inspected || {}; + + inspected[ dataType ] = true; + + var list = structure[ dataType ], + i = 0, + length = list ? list.length : 0, + executeOnly = ( structure === prefilters ), + selection; + + for(; i < length && ( executeOnly || !selection ); i++ ) { + selection = list[ i ]( options, originalOptions, jXHR ); + // If we got redirected to another dataType + // we try there if not done already + if ( typeof selection === "string" ) { + if ( inspected[ selection ] ) { + selection = undefined; + } else { + options.dataTypes.unshift( selection ); + selection = inspectPrefiltersOrTransports( + structure, options, originalOptions, jXHR, selection, inspected ); + } + } + } + // If we're only executing or nothing was selected + // we try the catchall dataType if not done already + if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) { + selection = inspectPrefiltersOrTransports( + structure, options, originalOptions, jXHR, "*", inspected ); + } + // unnecessary when only executing (prefilters) + // but it'll be ignored by the caller in that case + return selection; +} + +jQuery.fn.extend({ + load: function( url, params, callback ) { + if ( typeof url !== "string" && _load ) { + return _load.apply( this, arguments ); + + // Don't do a request if no elements are being requested + } else if ( !this.length ) { + return this; + } + + var off = url.indexOf( " " ); + if ( off >= 0 ) { + var selector = url.slice( off, url.length ); + url = url.slice( 0, off ); + } + + // Default to a GET request + var type = "GET"; + + // If the second parameter was provided + if ( params ) { + // If it's a function + if ( jQuery.isFunction( params ) ) { + // We assume that it's the callback + callback = params; + params = null; + + // Otherwise, build a param string + } else if ( typeof params === "object" ) { + params = jQuery.param( params, jQuery.ajaxSettings.traditional ); + type = "POST"; + } + } + + var self = this; + + // Request the remote document + jQuery.ajax({ + url: url, + type: type, + dataType: "html", + data: params, + // Complete callback (responseText is used internally) + complete: function( jXHR, status, responseText ) { + // Store the response as specified by the jXHR object + responseText = jXHR.responseText; + // If successful, inject the HTML into all the matched elements + if ( jXHR.isResolved() ) { + // #4825: Get the actual response in case + // a dataFilter is present in ajaxSettings + jXHR.done(function( r ) { + responseText = r; + }); + // See if a selector was specified + self.html( selector ? + // Create a dummy div to hold the results + jQuery("<div>") + // inject the contents of the document in, removing the scripts + // to avoid any 'Permission Denied' errors in IE + .append(responseText.replace(rscript, "")) + + // Locate the specified elements + .find(selector) : + + // If not, just inject the full result + responseText ); + } + + if ( callback ) { + self.each( callback, [ responseText, status, jXHR ] ); + } + } + }); + + return this; + }, + + serialize: function() { + return jQuery.param( this.serializeArray() ); + }, + + serializeArray: function() { + return this.map(function(){ + return this.elements ? jQuery.makeArray( this.elements ) : this; + }) + .filter(function(){ + return this.name && !this.disabled && + ( this.checked || rselectTextarea.test( this.nodeName ) || + rinput.test( this.type ) ); + }) + .map(function( i, elem ){ + var val = jQuery( this ).val(); + + return val == null ? + null : + jQuery.isArray( val ) ? + jQuery.map( val, function( val, i ){ + return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; + }) : + { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; + }).get(); + } +}); + +// Attach a bunch of functions for handling common AJAX events +jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){ + jQuery.fn[ o ] = function( f ){ + return this.bind( o, f ); + }; +} ); + +jQuery.each( [ "get", "post" ], function( i, method ) { + jQuery[ method ] = function( url, data, callback, type ) { + // shift arguments if data argument was omitted + if ( jQuery.isFunction( data ) ) { + type = type || callback; + callback = data; + data = null; + } + + return jQuery.ajax({ + type: method, + url: url, + data: data, + success: callback, + dataType: type + }); + }; +} ); + +jQuery.extend({ + + getScript: function( url, callback ) { + return jQuery.get( url, null, callback, "script" ); + }, + + getJSON: function( url, data, callback ) { + return jQuery.get( url, data, callback, "json" ); + }, + + ajaxSetup: function( settings ) { + jQuery.extend( true, jQuery.ajaxSettings, settings ); + if ( settings.context ) { + jQuery.ajaxSettings.context = settings.context; + } + }, + + ajaxSettings: { + url: location.href, + global: true, + type: "GET", + contentType: "application/x-www-form-urlencoded", + processData: true, + async: true, + /* + timeout: 0, + data: null, + dataType: null, + username: null, + password: null, + cache: null, + traditional: false, + headers: {}, + crossDomain: null, + */ + + accepts: { + xml: "application/xml, text/xml", + html: "text/html", + text: "text/plain", + json: "application/json, text/javascript", + "*": "*/*" + }, + + contents: { + xml: /xml/, + html: /html/, + json: /json/ + }, + + responseFields: { + xml: "responseXML", + text: "responseText" + }, + + // List of data converters + // 1) key format is "source_type destination_type" (a single space in-between) + // 2) the catchall symbol "*" can be used for source_type + converters: { + + // Convert anything to text + "* text": window.String, + + // Text to html (true = no transformation) + "text html": true, + + // Evaluate text as a json expression + "text json": jQuery.parseJSON, + + // Parse text as xml + "text xml": jQuery.parseXML + } + }, + + ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), + ajaxTransport: addToPrefiltersOrTransports( transports ), + + // Main method + ajax: function( url, options ) { + + // If options is not an object, + // we simulate pre-1.5 signature + if ( typeof options !== "object" ) { + options = url; + url = undefined; + } + + // Force options to be an object + options = options || {}; + + var // Create the final options object + s = jQuery.extend( true, {}, jQuery.ajaxSettings, options ), + // Callbacks contexts + // We force the original context if it exists + // or take it from jQuery.ajaxSettings otherwise + // (plain objects used as context get extended) + callbackContext = + ( s.context = ( "context" in options ? options : jQuery.ajaxSettings ).context ) || s, + globalEventContext = callbackContext === s ? jQuery.event : jQuery( callbackContext ), + // Deferreds + deferred = jQuery.Deferred(), + completeDeferred = jQuery._Deferred(), + // Status-dependent callbacks + statusCode = s.statusCode || {}, + // Headers (they are sent all at once) + requestHeaders = {}, + // Response headers + responseHeadersString, + responseHeaders, + // transport + transport, + // timeout handle + timeoutTimer, + // Cross-domain detection vars + loc = document.location, + protocol = loc.protocol || "http:", + parts, + // The jXHR state + state = 0, + // Loop variable + i, + // Fake xhr + jXHR = { + + readyState: 0, + + // Caches the header + setRequestHeader: function( name, value ) { + if ( state === 0 ) { + requestHeaders[ name.toLowerCase() ] = value; + } + return this; + }, + + // Raw string + getAllResponseHeaders: function() { + return state === 2 ? responseHeadersString : null; + }, + + // Builds headers hashtable if needed + getResponseHeader: function( key ) { + var match; + if ( state === 2 ) { + if ( !responseHeaders ) { + responseHeaders = {}; + while( ( match = rheaders.exec( responseHeadersString ) ) ) { + responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; + } + } + match = responseHeaders[ key.toLowerCase() ]; + } + return match || null; + }, + + // Cancel the request + abort: function( statusText ) { + statusText = statusText || "abort"; + if ( transport ) { + transport.abort( statusText ); + } + done( 0, statusText ); + return this; + } + }; + + // Callback for when everything is done + // It is defined here because jslint complains if it is declared + // at the end of the function (which would be more logical and readable) + function done( status, statusText, responses, headers) { + + // Called once + if ( state === 2 ) { + return; + } + + // State is "done" now + state = 2; + + // Clear timeout if it exists + if ( timeoutTimer ) { + clearTimeout( timeoutTimer ); + } + + // Dereference transport for early garbage collection + // (no matter how long the jXHR object will be used) + transport = undefined; + + // Cache response headers + responseHeadersString = headers || ""; + + // Set readyState + jXHR.readyState = status ? 4 : 0; + + var isSuccess, + success, + error, + response = responses ? ajaxHandleResponses( s, jXHR, responses ) : undefined, + lastModified, + etag; + + // If successful, handle type chaining + if ( status >= 200 && status < 300 || status === 304 ) { + + // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. + if ( s.ifModified ) { + + if ( ( lastModified = jXHR.getResponseHeader( "Last-Modified" ) ) ) { + jQuery.lastModified[ s.url ] = lastModified; + } + if ( ( etag = jXHR.getResponseHeader( "Etag" ) ) ) { + jQuery.etag[ s.url ] = etag; + } + } + + // If not modified + if ( status === 304 ) { + + statusText = "notmodified"; + isSuccess = true; + + // If we have data + } else { + + try { + success = ajaxConvert( s, response ); + statusText = "success"; + isSuccess = true; + } catch(e) { + // We have a parsererror + statusText = "parsererror"; + error = e; + } + } + } else { + // We extract error from statusText + // then normalize statusText and status for non-aborts + error = statusText; + if( status ) { + statusText = "error"; + if ( status < 0 ) { + status = 0; + } + } + } + + // Set data for the fake xhr object + jXHR.status = status; + jXHR.statusText = statusText; + + // Success/Error + if ( isSuccess ) { + deferred.resolveWith( callbackContext, [ success, statusText, jXHR ] ); + } else { + deferred.rejectWith( callbackContext, [ jXHR, statusText, error ] ); + } + + // Status-dependent callbacks + jXHR.statusCode( statusCode ); + statusCode = undefined; + + if ( s.global ) { + globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ), + [ jXHR, s, isSuccess ? success : error ] ); + } + + // Complete + completeDeferred.resolveWith( callbackContext, [ jXHR, statusText ] ); + + if ( s.global ) { + globalEventContext.trigger( "ajaxComplete", [ jXHR, s] ); + // Handle the global AJAX counter + if ( !( --jQuery.active ) ) { + jQuery.event.trigger( "ajaxStop" ); + } + } + } + + // Attach deferreds + deferred.promise( jXHR ); + jXHR.success = jXHR.done; + jXHR.error = jXHR.fail; + jXHR.complete = completeDeferred.done; + + // Status-dependent callbacks + jXHR.statusCode = function( map ) { + if ( map ) { + var tmp; + if ( state < 2 ) { + for( tmp in map ) { + statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ]; + } + } else { + tmp = map[ jXHR.status ]; + jXHR.then( tmp, tmp ); + } + } + return this; + }; + + // Remove hash character (#7531: and string promotion) + // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) + // We also use the url parameter if available + s.url = ( "" + ( url || s.url ) ).replace( rhash, "" ).replace( rprotocol, protocol + "//" ); + + // Extract dataTypes list + s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax ); + + // Determine if a cross-domain request is in order + if ( !s.crossDomain ) { + parts = rurl.exec( s.url.toLowerCase() ); + s.crossDomain = !!( parts && + ( parts[ 1 ] != protocol || parts[ 2 ] != loc.hostname || + ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) != + ( loc.port || ( protocol === "http:" ? 80 : 443 ) ) ) + ); + } + + // Convert data if not already a string + if ( s.data && s.processData && typeof s.data !== "string" ) { + s.data = jQuery.param( s.data, s.traditional ); + } + + // Apply prefilters + inspectPrefiltersOrTransports( prefilters, s, options, jXHR ); + + // Uppercase the type + s.type = s.type.toUpperCase(); + + // Determine if request has content + s.hasContent = !rnoContent.test( s.type ); + + // Watch for a new set of requests + if ( s.global && jQuery.active++ === 0 ) { + jQuery.event.trigger( "ajaxStart" ); + } + + // More options handling for requests with no content + if ( !s.hasContent ) { + + // If data is available, append data to url + if ( s.data ) { + s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data; + } + + // Add anti-cache in url if needed + if ( s.cache === false ) { + + var ts = jQuery.now(), + // try replacing _= if it is there + ret = s.url.replace( rts, "$1_=" + ts ); + + // if nothing was replaced, add timestamp to the end + s.url = ret + ( (ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" ); + } + } + + // Set the correct header, if data is being sent + if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { + requestHeaders[ "content-type" ] = s.contentType; + } + + // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. + if ( s.ifModified ) { + if ( jQuery.lastModified[ s.url ] ) { + requestHeaders[ "if-modified-since" ] = jQuery.lastModified[ s.url ]; + } + if ( jQuery.etag[ s.url ] ) { + requestHeaders[ "if-none-match" ] = jQuery.etag[ s.url ]; + } + } + + // Set the Accepts header for the server, depending on the dataType + requestHeaders.accept = s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? + s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", */*; q=0.01" : "" ) : + s.accepts[ "*" ]; + + // Check for headers option + for ( i in s.headers ) { + requestHeaders[ i.toLowerCase() ] = s.headers[ i ]; + } + + // Allow custom headers/mimetypes and early abort + if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jXHR, s ) === false || state === 2 ) ) { + // Abort if not done already + done( 0, "abort" ); + // Return false + jXHR = false; + + } else { + + // Install callbacks on deferreds + for ( i in { success: 1, error: 1, complete: 1 } ) { + jXHR[ i ]( s[ i ] ); + } + + // Get transport + transport = inspectPrefiltersOrTransports( transports, s, options, jXHR ); + + // If no transport, we auto-abort + if ( !transport ) { + done( -1, "No Transport" ); + } else { + // Set state as sending + state = jXHR.readyState = 1; + // Send global event + if ( s.global ) { + globalEventContext.trigger( "ajaxSend", [ jXHR, s ] ); + } + // Timeout + if ( s.async && s.timeout > 0 ) { + timeoutTimer = setTimeout( function(){ + jXHR.abort( "timeout" ); + }, s.timeout ); + } + + try { + transport.send( requestHeaders, done ); + } catch (e) { + // Propagate exception as error if not done + if ( status < 2 ) { + done( -1, e ); + // Simply rethrow otherwise + } else { + jQuery.error( e ); + } + } + } + } + return jXHR; + }, + + // Serialize an array of form elements or a set of + // key/values into a query string + param: function( a, traditional ) { + var s = [], + add = function( key, value ) { + // If value is a function, invoke it and return its value + value = jQuery.isFunction( value ) ? value() : value; + s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); + }; + + // Set traditional to true for jQuery <= 1.3.2 behavior. + if ( traditional === undefined ) { + traditional = jQuery.ajaxSettings.traditional; + } + + // If an array was passed in, assume that it is an array of form elements. + if ( jQuery.isArray( a ) || a.jquery ) { + // Serialize the form elements + jQuery.each( a, function() { + add( this.name, this.value ); + } ); + + } else { + // If traditional, encode the "old" way (the way 1.3.2 or older + // did it), otherwise encode params recursively. + for ( var prefix in a ) { + buildParams( prefix, a[ prefix ], traditional, add ); + } + } + + // Return the resulting serialization + return s.join( "&" ).replace( r20, "+" ); + } +}); + +function buildParams( prefix, obj, traditional, add ) { + if ( jQuery.isArray( obj ) && obj.length ) { + // Serialize array item. + jQuery.each( obj, function( i, v ) { + if ( traditional || rbracket.test( prefix ) ) { + // Treat each array item as a scalar. + add( prefix, v ); + + } else { + // If array item is non-scalar (array or object), encode its + // numeric index to resolve deserialization ambiguity issues. + // Note that rack (as of 1.0.0) can't currently deserialize + // nested arrays properly, and attempting to do so may cause + // a server error. Possible fixes are to modify rack's + // deserialization algorithm or to provide an option or flag + // to force array serialization to be shallow. + buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add ); + } + }); + + } else if ( !traditional && obj != null && typeof obj === "object" ) { + // If we see an array here, it is empty and should be treated as an empty + // object + if ( jQuery.isArray( obj ) || jQuery.isEmptyObject( obj ) ) { + add( prefix, "" ); + + // Serialize object item. + } else { + jQuery.each( obj, function( k, v ) { + buildParams( prefix + "[" + k + "]", v, traditional, add ); + }); + } + + } else { + // Serialize scalar item. + add( prefix, obj ); + } +} + +// This is still on the jQuery object... for now +// Want to move this to jQuery.ajax some day +jQuery.extend({ + + // Counter for holding the number of active queries + active: 0, + + // Last-Modified header cache for next request + lastModified: {}, + etag: {} + +}); + +/* Handles responses to an ajax request: + * - sets all responseXXX fields accordingly + * - finds the right dataType (mediates between content-type and expected dataType) + * - returns the corresponding response + */ +function ajaxHandleResponses( s, jXHR, responses ) { + + var contents = s.contents, + dataTypes = s.dataTypes, + responseFields = s.responseFields, + ct, + type, + finalDataType, + firstDataType; + + // Fill responseXXX fields + for( type in responseFields ) { + if ( type in responses ) { + jXHR[ responseFields[type] ] = responses[ type ]; + } + } + + // Remove auto dataType and get content-type in the process + while( dataTypes[ 0 ] === "*" ) { + dataTypes.shift(); + if ( ct === undefined ) { + ct = jXHR.getResponseHeader( "content-type" ); + } + } + + // Check if we're dealing with a known content-type + if ( ct ) { + for ( type in contents ) { + if ( contents[ type ] && contents[ type ].test( ct ) ) { + dataTypes.unshift( type ); + break; + } + } + } + + // Check to see if we have a response for the expected dataType + if ( dataTypes[ 0 ] in responses ) { + finalDataType = dataTypes[ 0 ]; + } else { + // Try convertible dataTypes + for ( type in responses ) { + if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { + finalDataType = type; + break; + } + if ( !firstDataType ) { + firstDataType = type; + } + } + // Or just use first one + finalDataType = finalDataType || firstDataType; + } + + // If we found a dataType + // We add the dataType to the list if needed + // and return the corresponding response + if ( finalDataType ) { + if ( finalDataType !== dataTypes[ 0 ] ) { + dataTypes.unshift( finalDataType ); + } + return responses[ finalDataType ]; + } +} + +// Chain conversions given the request and the original response +function ajaxConvert( s, response ) { + + // Apply the dataFilter if provided + if ( s.dataFilter ) { + response = s.dataFilter( response, s.dataType ); + } + + var dataTypes = s.dataTypes, + converters = s.converters, + i, + length = dataTypes.length, + tmp, + // Current and previous dataTypes + current = dataTypes[ 0 ], + prev, + // Conversion expression + conversion, + // Conversion function + conv, + // Conversion functions (transitive conversion) + conv1, + conv2; + + // For each dataType in the chain + for( i = 1; i < length; i++ ) { + + // Get the dataTypes + prev = current; + current = dataTypes[ i ]; + + // If current is auto dataType, update it to prev + if( current === "*" ) { + current = prev; + // If no auto and dataTypes are actually different + } else if ( prev !== "*" && prev !== current ) { + + // Get the converter + conversion = prev + " " + current; + conv = converters[ conversion ] || converters[ "* " + current ]; + + // If there is no direct converter, search transitively + if ( !conv ) { + conv2 = undefined; + for( conv1 in converters ) { + tmp = conv1.split( " " ); + if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) { + conv2 = converters[ tmp[1] + " " + current ]; + if ( conv2 ) { + conv1 = converters[ conv1 ]; + if ( conv1 === true ) { + conv = conv2; + } else if ( conv2 === true ) { + conv = conv1; + } + break; + } + } + } + } + // If we found no converter, dispatch an error + if ( !( conv || conv2 ) ) { + jQuery.error( "No conversion from " + conversion.replace(" "," to ") ); + } + // If found converter is not an equivalence + if ( conv !== true ) { + // Convert with 1 or 2 converters accordingly + response = conv ? conv( response ) : conv2( conv1(response) ); + } + } + } + return response; +} + + + + +var jsc = jQuery.now(), + jsre = /(\=)\?(&|$)|()\?\?()/i; + +// Default jsonp settings +jQuery.ajaxSetup({ + jsonp: "callback", + jsonpCallback: function() { + return jQuery.expando + "_" + ( jsc++ ); + } +}); + +// Detect, normalize options and install callbacks for jsonp requests +jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, dataIsString /* internal */ ) { + + dataIsString = ( typeof s.data === "string" ); + + if ( s.dataTypes[ 0 ] === "jsonp" || + originalSettings.jsonpCallback || + originalSettings.jsonp != null || + s.jsonp !== false && ( jsre.test( s.url ) || + dataIsString && jsre.test( s.data ) ) ) { + + var responseContainer, + jsonpCallback = s.jsonpCallback = + jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback, + previous = window[ jsonpCallback ], + url = s.url, + data = s.data, + replace = "$1" + jsonpCallback + "$2"; + + if ( s.jsonp !== false ) { + url = url.replace( jsre, replace ); + if ( s.url === url ) { + if ( dataIsString ) { + data = data.replace( jsre, replace ); + } + if ( s.data === data ) { + // Add callback manually + url += (/\?/.test( url ) ? "&" : "?") + s.jsonp + "=" + jsonpCallback; + } + } + } + + s.url = url; + s.data = data; + + window[ jsonpCallback ] = function( response ) { + responseContainer = [ response ]; + }; + + s.complete = [ function() { + + // Set callback back to previous value + window[ jsonpCallback ] = previous; + + // Call if it was a function and we have a response + if ( previous) { + if ( responseContainer && jQuery.isFunction( previous ) ) { + window[ jsonpCallback ] ( responseContainer[ 0 ] ); + } + } else { + // else, more memory leak avoidance + try{ + delete window[ jsonpCallback ]; + } catch( e ) {} + } + + }, s.complete ]; + + // Use data converter to retrieve json after script execution + s.converters["script json"] = function() { + if ( ! responseContainer ) { + jQuery.error( jsonpCallback + " was not called" ); + } + return responseContainer[ 0 ]; + }; + + // force json dataType + s.dataTypes[ 0 ] = "json"; + + // Delegate to script + return "script"; + } +} ); + + + + +// Install script dataType +jQuery.ajaxSetup({ + accepts: { + script: "text/javascript, application/javascript" + }, + contents: { + script: /javascript/ + }, + converters: { + "text script": function( text ) { + jQuery.globalEval( text ); + return text; + } + } +}); + +// Handle cache's special case and global +jQuery.ajaxPrefilter( "script", function( s ) { + if ( s.cache === undefined ) { + s.cache = false; + } + if ( s.crossDomain ) { + s.type = "GET"; + s.global = false; + } +} ); + +// Bind script tag hack transport +jQuery.ajaxTransport( "script", function(s) { + + // This transport only deals with cross domain requests + if ( s.crossDomain ) { + + var script, + head = document.getElementsByTagName( "head" )[ 0 ] || document.documentElement; + + return { + + send: function( _, callback ) { + + script = document.createElement( "script" ); + + script.async = "async"; + + if ( s.scriptCharset ) { + script.charset = s.scriptCharset; + } + + script.src = s.url; + + // Attach handlers for all browsers + script.onload = script.onreadystatechange = function( _, isAbort ) { + + if ( !script.readyState || /loaded|complete/.test( script.readyState ) ) { + + // Handle memory leak in IE + script.onload = script.onreadystatechange = null; + + // Remove the script + if ( head && script.parentNode ) { + head.removeChild( script ); + } + + // Dereference the script + script = undefined; + + // Callback if not abort + if ( !isAbort ) { + callback( 200, "success" ); + } + } + }; + // Use insertBefore instead of appendChild to circumvent an IE6 bug. + // This arises when a base node is used (#2709 and #4378). + head.insertBefore( script, head.firstChild ); + }, + + abort: function() { + if ( script ) { + script.onload( 0, 1 ); + } + } + }; + } +} ); + + + + +var // Next active xhr id + xhrId = jQuery.now(), + + // active xhrs + xhrs = {}, + + // #5280: see below + xhrUnloadAbortInstalled, + + // XHR used to determine supports properties + testXHR; + +// Create the request object +// (This is still attached to ajaxSettings for backward compatibility) +jQuery.ajaxSettings.xhr = window.ActiveXObject ? + /* Microsoft failed to properly + * implement the XMLHttpRequest in IE7 (can't request local files), + * so we use the ActiveXObject when it is available + * Additionally XMLHttpRequest can be disabled in IE7/IE8 so + * we need a fallback. + */ + function() { + if ( window.location.protocol !== "file:" ) { + try { + return new window.XMLHttpRequest(); + } catch( xhrError ) {} + } + + try { + return new window.ActiveXObject("Microsoft.XMLHTTP"); + } catch( activeError ) {} + } : + // For all other browsers, use the standard XMLHttpRequest object + function() { + return new window.XMLHttpRequest(); + }; + +// Test if we can create an xhr object +try { + testXHR = jQuery.ajaxSettings.xhr(); +} catch( xhrCreationException ) {} + +//Does this browser support XHR requests? +jQuery.support.ajax = !!testXHR; + +// Does this browser support crossDomain XHR requests +jQuery.support.cors = testXHR && ( "withCredentials" in testXHR ); + +// No need for the temporary xhr anymore +testXHR = undefined; + +// Create transport if the browser can provide an xhr +if ( jQuery.support.ajax ) { + + jQuery.ajaxTransport(function( s ) { + // Cross domain only allowed if supported through XMLHttpRequest + if ( !s.crossDomain || jQuery.support.cors ) { + + var callback; + + return { + send: function( headers, complete ) { + + // #5280: we need to abort on unload or IE will keep connections alive + if ( !xhrUnloadAbortInstalled ) { + + xhrUnloadAbortInstalled = 1; + + jQuery(window).bind( "unload", function() { + + // Abort all pending requests + jQuery.each( xhrs, function( _, xhr ) { + if ( xhr.onreadystatechange ) { + xhr.onreadystatechange( 1 ); + } + } ); + + } ); + } + + // Get a new xhr + var xhr = s.xhr(), + handle; + + // Open the socket + // Passing null username, generates a login popup on Opera (#2865) + if ( s.username ) { + xhr.open( s.type, s.url, s.async, s.username, s.password ); + } else { + xhr.open( s.type, s.url, s.async ); + } + + // Requested-With header + // Not set for crossDomain requests with no content + // (see why at http://trac.dojotoolkit.org/ticket/9486) + // Won't change header if already provided + if ( !( s.crossDomain && !s.hasContent ) && !headers["x-requested-with"] ) { + headers[ "x-requested-with" ] = "XMLHttpRequest"; + } + + // Need an extra try/catch for cross domain requests in Firefox 3 + try { + jQuery.each( headers, function( key, value ) { + xhr.setRequestHeader( key, value ); + } ); + } catch( _ ) {} + + // Do send the request + // This may raise an exception which is actually + // handled in jQuery.ajax (so no try/catch here) + xhr.send( ( s.hasContent && s.data ) || null ); + + // Listener + callback = function( _, isAbort ) { + + // Was never called and is aborted or complete + if ( callback && ( isAbort || xhr.readyState === 4 ) ) { + + // Only called once + callback = 0; + + // Do not keep as active anymore + if ( handle ) { + xhr.onreadystatechange = jQuery.noop; + delete xhrs[ handle ]; + } + + // If it's an abort + if ( isAbort ) { + // Abort it manually if needed + if ( xhr.readyState !== 4 ) { + xhr.abort(); + } + } else { + // Get info + var status = xhr.status, + statusText, + responseHeaders = xhr.getAllResponseHeaders(), + responses = {}, + xml = xhr.responseXML; + + // Construct response list + if ( xml && xml.documentElement /* #4958 */ ) { + responses.xml = xml; + } + responses.text = xhr.responseText; + + // Firefox throws an exception when accessing + // statusText for faulty cross-domain requests + try { + statusText = xhr.statusText; + } catch( e ) { + // We normalize with Webkit giving an empty statusText + statusText = ""; + } + + // Filter status for non standard behaviours + status = + // Opera returns 0 when it should be 304 + // Webkit returns 0 for failing cross-domain no matter the real status + status === 0 ? + ( + // Webkit, Firefox: filter out faulty cross-domain requests + !s.crossDomain || statusText ? + ( + // Opera: filter out real aborts #6060 + responseHeaders ? + 304 : + 0 + ) : + // We assume 302 but could be anything cross-domain related + 302 + ) : + ( + // IE sometimes returns 1223 when it should be 204 (see #1450) + status == 1223 ? + 204 : + status + ); + + // Call complete + complete( status, statusText, responses, responseHeaders ); + } + } + }; + + // if we're in sync mode or it's in cache + // and has been retrieved directly (IE6 & IE7) + // we need to manually fire the callback + if ( !s.async || xhr.readyState === 4 ) { + callback(); + } else { + // Add to list of active xhrs + handle = xhrId++; + xhrs[ handle ] = xhr; + xhr.onreadystatechange = callback; + } + }, + + abort: function() { + if ( callback ) { + callback(0,1); + } + } + }; + } + }); +} + + + + +var elemdisplay = {}, + rfxtypes = /^(?:toggle|show|hide)$/, + rfxnum = /^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i, + timerId, + fxAttrs = [ + // height animations + [ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ], + // width animations + [ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ], + // opacity animations + [ "opacity" ] + ]; + +jQuery.fn.extend({ + show: function( speed, easing, callback ) { + var elem, display; + + if ( speed || speed === 0 ) { + return this.animate( genFx("show", 3), speed, easing, callback); + + } else { + for ( var i = 0, j = this.length; i < j; i++ ) { + elem = this[i]; + display = elem.style.display; + + // Reset the inline display of this element to learn if it is + // being hidden by cascaded rules or not + if ( !jQuery._data(elem, "olddisplay") && display === "none" ) { + display = elem.style.display = ""; + } + + // Set elements which have been overridden with display: none + // in a stylesheet to whatever the default browser style is + // for such an element + if ( display === "" && jQuery.css( elem, "display" ) === "none" ) { + jQuery._data(elem, "olddisplay", defaultDisplay(elem.nodeName)); + } + } + + // Set the display of most of the elements in a second loop + // to avoid the constant reflow + for ( i = 0; i < j; i++ ) { + elem = this[i]; + display = elem.style.display; + + if ( display === "" || display === "none" ) { + elem.style.display = jQuery._data(elem, "olddisplay") || ""; + } + } + + return this; + } + }, + + hide: function( speed, easing, callback ) { + if ( speed || speed === 0 ) { + return this.animate( genFx("hide", 3), speed, easing, callback); + + } else { + for ( var i = 0, j = this.length; i < j; i++ ) { + var display = jQuery.css( this[i], "display" ); + + if ( display !== "none" && !jQuery._data( this[i], "olddisplay" ) ) { + jQuery._data( this[i], "olddisplay", display ); + } + } + + // Set the display of the elements in a second loop + // to avoid the constant reflow + for ( i = 0; i < j; i++ ) { + this[i].style.display = "none"; + } + + return this; + } + }, + + // Save the old toggle function + _toggle: jQuery.fn.toggle, + + toggle: function( fn, fn2, callback ) { + var bool = typeof fn === "boolean"; + + if ( jQuery.isFunction(fn) && jQuery.isFunction(fn2) ) { + this._toggle.apply( this, arguments ); + + } else if ( fn == null || bool ) { + this.each(function() { + var state = bool ? fn : jQuery(this).is(":hidden"); + jQuery(this)[ state ? "show" : "hide" ](); + }); + + } else { + this.animate(genFx("toggle", 3), fn, fn2, callback); + } + + return this; + }, + + fadeTo: function( speed, to, easing, callback ) { + return this.filter(":hidden").css("opacity", 0).show().end() + .animate({opacity: to}, speed, easing, callback); + }, + + animate: function( prop, speed, easing, callback ) { + var optall = jQuery.speed(speed, easing, callback); + + if ( jQuery.isEmptyObject( prop ) ) { + return this.each( optall.complete ); + } + + return this[ optall.queue === false ? "each" : "queue" ](function() { + // XXX 'this' does not always have a nodeName when running the + // test suite + + var opt = jQuery.extend({}, optall), p, + isElement = this.nodeType === 1, + hidden = isElement && jQuery(this).is(":hidden"), + self = this; + + for ( p in prop ) { + var name = jQuery.camelCase( p ); + + if ( p !== name ) { + prop[ name ] = prop[ p ]; + delete prop[ p ]; + p = name; + } + + if ( prop[p] === "hide" && hidden || prop[p] === "show" && !hidden ) { + return opt.complete.call(this); + } + + if ( isElement && ( p === "height" || p === "width" ) ) { + // Make sure that nothing sneaks out + // Record all 3 overflow attributes because IE does not + // change the overflow attribute when overflowX and + // overflowY are set to the same value + opt.overflow = [ this.style.overflow, this.style.overflowX, this.style.overflowY ]; + + // Set display property to inline-block for height/width + // animations on inline elements that are having width/height + // animated + if ( jQuery.css( this, "display" ) === "inline" && + jQuery.css( this, "float" ) === "none" ) { + if ( !jQuery.support.inlineBlockNeedsLayout ) { + this.style.display = "inline-block"; + + } else { + var display = defaultDisplay(this.nodeName); + + // inline-level elements accept inline-block; + // block-level elements need to be inline with layout + if ( display === "inline" ) { + this.style.display = "inline-block"; + + } else { + this.style.display = "inline"; + this.style.zoom = 1; + } + } + } + } + + if ( jQuery.isArray( prop[p] ) ) { + // Create (if needed) and add to specialEasing + (opt.specialEasing = opt.specialEasing || {})[p] = prop[p][1]; + prop[p] = prop[p][0]; + } + } + + if ( opt.overflow != null ) { + this.style.overflow = "hidden"; + } + + opt.curAnim = jQuery.extend({}, prop); + + jQuery.each( prop, function( name, val ) { + var e = new jQuery.fx( self, opt, name ); + + if ( rfxtypes.test(val) ) { + e[ val === "toggle" ? hidden ? "show" : "hide" : val ]( prop ); + + } else { + var parts = rfxnum.exec(val), + start = e.cur() || 0; + + if ( parts ) { + var end = parseFloat( parts[2] ), + unit = parts[3] || "px"; + + // We need to compute starting value + if ( unit !== "px" ) { + jQuery.style( self, name, (end || 1) + unit); + start = ((end || 1) / e.cur()) * start; + jQuery.style( self, name, start + unit); + } + + // If a +=/-= token was provided, we're doing a relative animation + if ( parts[1] ) { + end = ((parts[1] === "-=" ? -1 : 1) * end) + start; + } + + e.custom( start, end, unit ); + + } else { + e.custom( start, val, "" ); + } + } + }); + + // For JS strict compliance + return true; + }); + }, + + stop: function( clearQueue, gotoEnd ) { + var timers = jQuery.timers; + + if ( clearQueue ) { + this.queue([]); + } + + this.each(function() { + // go in reverse order so anything added to the queue during the loop is ignored + for ( var i = timers.length - 1; i >= 0; i-- ) { + if ( timers[i].elem === this ) { + if (gotoEnd) { + // force the next step to be the last + timers[i](true); + } + + timers.splice(i, 1); + } + } + }); + + // start the next in the queue if the last step wasn't forced + if ( !gotoEnd ) { + this.dequeue(); + } + + return this; + } + +}); + +function genFx( type, num ) { + var obj = {}; + + jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice(0,num)), function() { + obj[ this ] = type; + }); + + return obj; +} + +// Generate shortcuts for custom animations +jQuery.each({ + slideDown: genFx("show", 1), + slideUp: genFx("hide", 1), + slideToggle: genFx("toggle", 1), + fadeIn: { opacity: "show" }, + fadeOut: { opacity: "hide" }, + fadeToggle: { opacity: "toggle" } +}, function( name, props ) { + jQuery.fn[ name ] = function( speed, easing, callback ) { + return this.animate( props, speed, easing, callback ); + }; +}); + +jQuery.extend({ + speed: function( speed, easing, fn ) { + var opt = speed && typeof speed === "object" ? jQuery.extend({}, speed) : { + complete: fn || !fn && easing || + jQuery.isFunction( speed ) && speed, + duration: speed, + easing: fn && easing || easing && !jQuery.isFunction(easing) && easing + }; + + opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : + opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[opt.duration] : jQuery.fx.speeds._default; + + // Queueing + opt.old = opt.complete; + opt.complete = function() { + if ( opt.queue !== false ) { + jQuery(this).dequeue(); + } + if ( jQuery.isFunction( opt.old ) ) { + opt.old.call( this ); + } + }; + + return opt; + }, + + easing: { + linear: function( p, n, firstNum, diff ) { + return firstNum + diff * p; + }, + swing: function( p, n, firstNum, diff ) { + return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum; + } + }, + + timers: [], + + fx: function( elem, options, prop ) { + this.options = options; + this.elem = elem; + this.prop = prop; + + if ( !options.orig ) { + options.orig = {}; + } + } + +}); + +jQuery.fx.prototype = { + // Simple function for setting a style value + update: function() { + if ( this.options.step ) { + this.options.step.call( this.elem, this.now, this ); + } + + (jQuery.fx.step[this.prop] || jQuery.fx.step._default)( this ); + }, + + // Get the current size + cur: function() { + if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) ) { + return this.elem[ this.prop ]; + } + + var r = parseFloat( jQuery.css( this.elem, this.prop ) ); + return r || 0; + }, + + // Start an animation from one number to another + custom: function( from, to, unit ) { + var self = this, + fx = jQuery.fx; + + this.startTime = jQuery.now(); + this.start = from; + this.end = to; + this.unit = unit || this.unit || "px"; + this.now = this.start; + this.pos = this.state = 0; + + function t( gotoEnd ) { + return self.step(gotoEnd); + } + + t.elem = this.elem; + + if ( t() && jQuery.timers.push(t) && !timerId ) { + timerId = setInterval(fx.tick, fx.interval); + } + }, + + // Simple 'show' function + show: function() { + // Remember where we started, so that we can go back to it later + this.options.orig[this.prop] = jQuery.style( this.elem, this.prop ); + this.options.show = true; + + // Begin the animation + // Make sure that we start at a small width/height to avoid any + // flash of content + this.custom(this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur()); + + // Start by showing the element + jQuery( this.elem ).show(); + }, + + // Simple 'hide' function + hide: function() { + // Remember where we started, so that we can go back to it later + this.options.orig[this.prop] = jQuery.style( this.elem, this.prop ); + this.options.hide = true; + + // Begin the animation + this.custom(this.cur(), 0); + }, + + // Each step of an animation + step: function( gotoEnd ) { + var t = jQuery.now(), done = true; + + if ( gotoEnd || t >= this.options.duration + this.startTime ) { + this.now = this.end; + this.pos = this.state = 1; + this.update(); + + this.options.curAnim[ this.prop ] = true; + + for ( var i in this.options.curAnim ) { + if ( this.options.curAnim[i] !== true ) { + done = false; + } + } + + if ( done ) { + // Reset the overflow + if ( this.options.overflow != null && !jQuery.support.shrinkWrapBlocks ) { + var elem = this.elem, + options = this.options; + + jQuery.each( [ "", "X", "Y" ], function (index, value) { + elem.style[ "overflow" + value ] = options.overflow[index]; + } ); + } + + // Hide the element if the "hide" operation was done + if ( this.options.hide ) { + jQuery(this.elem).hide(); + } + + // Reset the properties, if the item has been hidden or shown + if ( this.options.hide || this.options.show ) { + for ( var p in this.options.curAnim ) { + jQuery.style( this.elem, p, this.options.orig[p] ); + } + } + + // Execute the complete function + this.options.complete.call( this.elem ); + } + + return false; + + } else { + var n = t - this.startTime; + this.state = n / this.options.duration; + + // Perform the easing function, defaults to swing + var specialEasing = this.options.specialEasing && this.options.specialEasing[this.prop]; + var defaultEasing = this.options.easing || (jQuery.easing.swing ? "swing" : "linear"); + this.pos = jQuery.easing[specialEasing || defaultEasing](this.state, n, 0, 1, this.options.duration); + this.now = this.start + ((this.end - this.start) * this.pos); + + // Perform the next step of the animation + this.update(); + } + + return true; + } +}; + +jQuery.extend( jQuery.fx, { + tick: function() { + var timers = jQuery.timers; + + for ( var i = 0; i < timers.length; i++ ) { + if ( !timers[i]() ) { + timers.splice(i--, 1); + } + } + + if ( !timers.length ) { + jQuery.fx.stop(); + } + }, + + interval: 13, + + stop: function() { + clearInterval( timerId ); + timerId = null; + }, + + speeds: { + slow: 600, + fast: 200, + // Default speed + _default: 400 + }, + + step: { + opacity: function( fx ) { + jQuery.style( fx.elem, "opacity", fx.now ); + }, + + _default: function( fx ) { + if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) { + fx.elem.style[ fx.prop ] = (fx.prop === "width" || fx.prop === "height" ? Math.max(0, fx.now) : fx.now) + fx.unit; + } else { + fx.elem[ fx.prop ] = fx.now; + } + } + } +}); + +if ( jQuery.expr && jQuery.expr.filters ) { + jQuery.expr.filters.animated = function( elem ) { + return jQuery.grep(jQuery.timers, function( fn ) { + return elem === fn.elem; + }).length; + }; +} + +function defaultDisplay( nodeName ) { + if ( !elemdisplay[ nodeName ] ) { + var elem = jQuery("<" + nodeName + ">").appendTo("body"), + display = elem.css("display"); + + elem.remove(); + + if ( display === "none" || display === "" ) { + display = "block"; + } + + elemdisplay[ nodeName ] = display; + } + + return elemdisplay[ nodeName ]; +} + + + + +var rtable = /^t(?:able|d|h)$/i, + rroot = /^(?:body|html)$/i; + +if ( "getBoundingClientRect" in document.documentElement ) { + jQuery.fn.offset = function( options ) { + var elem = this[0], box; + + if ( options ) { + return this.each(function( i ) { + jQuery.offset.setOffset( this, options, i ); + }); + } + + if ( !elem || !elem.ownerDocument ) { + return null; + } + + if ( elem === elem.ownerDocument.body ) { + return jQuery.offset.bodyOffset( elem ); + } + + try { + box = elem.getBoundingClientRect(); + } catch(e) {} + + var doc = elem.ownerDocument, + docElem = doc.documentElement; + + // Make sure we're not dealing with a disconnected DOM node + if ( !box || !jQuery.contains( docElem, elem ) ) { + return box ? { top: box.top, left: box.left } : { top: 0, left: 0 }; + } + + var body = doc.body, + win = getWindow(doc), + clientTop = docElem.clientTop || body.clientTop || 0, + clientLeft = docElem.clientLeft || body.clientLeft || 0, + scrollTop = (win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop ), + scrollLeft = (win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft), + top = box.top + scrollTop - clientTop, + left = box.left + scrollLeft - clientLeft; + + return { top: top, left: left }; + }; + +} else { + jQuery.fn.offset = function( options ) { + var elem = this[0]; + + if ( options ) { + return this.each(function( i ) { + jQuery.offset.setOffset( this, options, i ); + }); + } + + if ( !elem || !elem.ownerDocument ) { + return null; + } + + if ( elem === elem.ownerDocument.body ) { + return jQuery.offset.bodyOffset( elem ); + } + + jQuery.offset.initialize(); + + var computedStyle, + offsetParent = elem.offsetParent, + prevOffsetParent = elem, + doc = elem.ownerDocument, + docElem = doc.documentElement, + body = doc.body, + defaultView = doc.defaultView, + prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle, + top = elem.offsetTop, + left = elem.offsetLeft; + + while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) { + if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) { + break; + } + + computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle; + top -= elem.scrollTop; + left -= elem.scrollLeft; + + if ( elem === offsetParent ) { + top += elem.offsetTop; + left += elem.offsetLeft; + + if ( jQuery.offset.doesNotAddBorder && !(jQuery.offset.doesAddBorderForTableAndCells && rtable.test(elem.nodeName)) ) { + top += parseFloat( computedStyle.borderTopWidth ) || 0; + left += parseFloat( computedStyle.borderLeftWidth ) || 0; + } + + prevOffsetParent = offsetParent; + offsetParent = elem.offsetParent; + } + + if ( jQuery.offset.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) { + top += parseFloat( computedStyle.borderTopWidth ) || 0; + left += parseFloat( computedStyle.borderLeftWidth ) || 0; + } + + prevComputedStyle = computedStyle; + } + + if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) { + top += body.offsetTop; + left += body.offsetLeft; + } + + if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) { + top += Math.max( docElem.scrollTop, body.scrollTop ); + left += Math.max( docElem.scrollLeft, body.scrollLeft ); + } + + return { top: top, left: left }; + }; +} + +jQuery.offset = { + initialize: function() { + var body = document.body, container = document.createElement("div"), innerDiv, checkDiv, table, td, bodyMarginTop = parseFloat( jQuery.css(body, "marginTop") ) || 0, + html = "<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>"; + + jQuery.extend( container.style, { position: "absolute", top: 0, left: 0, margin: 0, border: 0, width: "1px", height: "1px", visibility: "hidden" } ); + + container.innerHTML = html; + body.insertBefore( container, body.firstChild ); + innerDiv = container.firstChild; + checkDiv = innerDiv.firstChild; + td = innerDiv.nextSibling.firstChild.firstChild; + + this.doesNotAddBorder = (checkDiv.offsetTop !== 5); + this.doesAddBorderForTableAndCells = (td.offsetTop === 5); + + checkDiv.style.position = "fixed"; + checkDiv.style.top = "20px"; + + // safari subtracts parent border width here which is 5px + this.supportsFixedPosition = (checkDiv.offsetTop === 20 || checkDiv.offsetTop === 15); + checkDiv.style.position = checkDiv.style.top = ""; + + innerDiv.style.overflow = "hidden"; + innerDiv.style.position = "relative"; + + this.subtractsBorderForOverflowNotVisible = (checkDiv.offsetTop === -5); + + this.doesNotIncludeMarginInBodyOffset = (body.offsetTop !== bodyMarginTop); + + body.removeChild( container ); + body = container = innerDiv = checkDiv = table = td = null; + jQuery.offset.initialize = jQuery.noop; + }, + + bodyOffset: function( body ) { + var top = body.offsetTop, + left = body.offsetLeft; + + jQuery.offset.initialize(); + + if ( jQuery.offset.doesNotIncludeMarginInBodyOffset ) { + top += parseFloat( jQuery.css(body, "marginTop") ) || 0; + left += parseFloat( jQuery.css(body, "marginLeft") ) || 0; + } + + return { top: top, left: left }; + }, + + setOffset: function( elem, options, i ) { + var position = jQuery.css( elem, "position" ); + + // set position first, in-case top/left are set even on static elem + if ( position === "static" ) { + elem.style.position = "relative"; + } + + var curElem = jQuery( elem ), + curOffset = curElem.offset(), + curCSSTop = jQuery.css( elem, "top" ), + curCSSLeft = jQuery.css( elem, "left" ), + calculatePosition = (position === "absolute" && jQuery.inArray('auto', [curCSSTop, curCSSLeft]) > -1), + props = {}, curPosition = {}, curTop, curLeft; + + // need to be able to calculate position if either top or left is auto and position is absolute + if ( calculatePosition ) { + curPosition = curElem.position(); + } + + curTop = calculatePosition ? curPosition.top : parseInt( curCSSTop, 10 ) || 0; + curLeft = calculatePosition ? curPosition.left : parseInt( curCSSLeft, 10 ) || 0; + + if ( jQuery.isFunction( options ) ) { + options = options.call( elem, i, curOffset ); + } + + if (options.top != null) { + props.top = (options.top - curOffset.top) + curTop; + } + if (options.left != null) { + props.left = (options.left - curOffset.left) + curLeft; + } + + if ( "using" in options ) { + options.using.call( elem, props ); + } else { + curElem.css( props ); + } + } +}; + + +jQuery.fn.extend({ + position: function() { + if ( !this[0] ) { + return null; + } + + var elem = this[0], + + // Get *real* offsetParent + offsetParent = this.offsetParent(), + + // Get correct offsets + offset = this.offset(), + parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset(); + + // Subtract element margins + // note: when an element has margin: auto the offsetLeft and marginLeft + // are the same in Safari causing offset.left to incorrectly be 0 + offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0; + offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0; + + // Add offsetParent borders + parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0; + parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0; + + // Subtract the two offsets + return { + top: offset.top - parentOffset.top, + left: offset.left - parentOffset.left + }; + }, + + offsetParent: function() { + return this.map(function() { + var offsetParent = this.offsetParent || document.body; + while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) { + offsetParent = offsetParent.offsetParent; + } + return offsetParent; + }); + } +}); + + +// Create scrollLeft and scrollTop methods +jQuery.each( ["Left", "Top"], function( i, name ) { + var method = "scroll" + name; + + jQuery.fn[ method ] = function(val) { + var elem = this[0], win; + + if ( !elem ) { + return null; + } + + if ( val !== undefined ) { + // Set the scroll offset + return this.each(function() { + win = getWindow( this ); + + if ( win ) { + win.scrollTo( + !i ? val : jQuery(win).scrollLeft(), + i ? val : jQuery(win).scrollTop() + ); + + } else { + this[ method ] = val; + } + }); + } else { + win = getWindow( elem ); + + // Return the scroll offset + return win ? ("pageXOffset" in win) ? win[ i ? "pageYOffset" : "pageXOffset" ] : + jQuery.support.boxModel && win.document.documentElement[ method ] || + win.document.body[ method ] : + elem[ method ]; + } + }; +}); + +function getWindow( elem ) { + return jQuery.isWindow( elem ) ? + elem : + elem.nodeType === 9 ? + elem.defaultView || elem.parentWindow : + false; +} + + + + +// Create innerHeight, innerWidth, outerHeight and outerWidth methods +jQuery.each([ "Height", "Width" ], function( i, name ) { + + var type = name.toLowerCase(); + + // innerHeight and innerWidth + jQuery.fn["inner" + name] = function() { + return this[0] ? + parseFloat( jQuery.css( this[0], type, "padding" ) ) : + null; + }; + + // outerHeight and outerWidth + jQuery.fn["outer" + name] = function( margin ) { + return this[0] ? + parseFloat( jQuery.css( this[0], type, margin ? "margin" : "border" ) ) : + null; + }; + + jQuery.fn[ type ] = function( size ) { + // Get window width or height + var elem = this[0]; + if ( !elem ) { + return size == null ? null : this; + } + + if ( jQuery.isFunction( size ) ) { + return this.each(function( i ) { + var self = jQuery( this ); + self[ type ]( size.call( this, i, self[ type ]() ) ); + }); + } + + if ( jQuery.isWindow( elem ) ) { + // Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode + // 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat + var docElemProp = elem.document.documentElement[ "client" + name ]; + return elem.document.compatMode === "CSS1Compat" && docElemProp || + elem.document.body[ "client" + name ] || docElemProp; + + // Get document width or height + } else if ( elem.nodeType === 9 ) { + // Either scroll[Width/Height] or offset[Width/Height], whichever is greater + return Math.max( + elem.documentElement["client" + name], + elem.body["scroll" + name], elem.documentElement["scroll" + name], + elem.body["offset" + name], elem.documentElement["offset" + name] + ); + + // Get or set width or height on the element + } else if ( size === undefined ) { + var orig = jQuery.css( elem, type ), + ret = parseFloat( orig ); + + return jQuery.isNaN( ret ) ? orig : ret; + + // Set the width or height on the element (default to pixels if value is unitless) + } else { + return this.css( type, typeof size === "string" ? size : size + "px" ); + } + }; + +}); + + +})(window); diff --git a/railties/lib/rails/generators/rails/app/templates/public/javascripts/jquery_ujs.js b/railties/lib/rails/generators/rails/app/templates/public/javascripts/jquery_ujs.js new file mode 100644 index 0000000000..4dcb3779a2 --- /dev/null +++ b/railties/lib/rails/generators/rails/app/templates/public/javascripts/jquery_ujs.js @@ -0,0 +1,148 @@ +/** + * Unobtrusive scripting adapter for jQuery + * + * Requires jQuery 1.4.3 or later. + * https://github.com/rails/jquery-ujs + */ + +(function($) { + // Triggers an event on an element and returns the event result + function fire(obj, name, data) { + var event = new $.Event(name); + obj.trigger(event, data); + return event.result !== false; + } + + // Submits "remote" forms and links with ajax + function handleRemote(element) { + var method, url, data, + dataType = element.attr('data-type') || ($.ajaxSettings && $.ajaxSettings.dataType); + + if (element.is('form')) { + method = element.attr('method'); + url = element.attr('action'); + data = element.serializeArray(); + // memoized value from clicked submit button + var button = element.data('ujs:submit-button'); + if (button) { + data.push(button); + element.data('ujs:submit-button', null); + } + } else { + method = element.attr('data-method'); + url = element.attr('href'); + data = null; + } + + $.ajax({ + url: url, type: method || 'GET', data: data, dataType: dataType, + // stopping the "ajax:beforeSend" event will cancel the ajax request + beforeSend: function(xhr, settings) { + if (settings.dataType === undefined) { + xhr.setRequestHeader('accept', '*/*;q=0.5, ' + settings.accepts.script); + } + return fire(element, 'ajax:beforeSend', [xhr, settings]); + }, + success: function(data, status, xhr) { + element.trigger('ajax:success', [data, status, xhr]); + }, + complete: function(xhr, status) { + element.trigger('ajax:complete', [xhr, status]); + }, + error: function(xhr, status, error) { + element.trigger('ajax:error', [xhr, status, error]); + } + }); + } + + // Handles "data-method" on links such as: + // <a href="/users/5" data-method="delete" rel="nofollow" data-confirm="Are you sure?">Delete</a> + function handleMethod(link) { + var href = link.attr('href'), + method = link.attr('data-method'), + csrf_token = $('meta[name=csrf-token]').attr('content'), + csrf_param = $('meta[name=csrf-param]').attr('content'), + form = $('<form method="post" action="' + href + '"></form>'), + metadata_input = '<input name="_method" value="' + method + '" type="hidden" />'; + + if (csrf_param !== undefined && csrf_token !== undefined) { + metadata_input += '<input name="' + csrf_param + '" value="' + csrf_token + '" type="hidden" />'; + } + + form.hide().append(metadata_input).appendTo('body'); + form.submit(); + } + + function disableFormElements(form) { + form.find('input[data-disable-with]').each(function() { + var input = $(this); + input.data('ujs:enable-with', input.val()) + .val(input.attr('data-disable-with')) + .attr('disabled', 'disabled'); + }); + } + + function enableFormElements(form) { + form.find('input[data-disable-with]').each(function() { + var input = $(this); + input.val(input.data('ujs:enable-with')).removeAttr('disabled'); + }); + } + + function allowAction(element) { + var message = element.attr('data-confirm'); + return !message || (fire(element, 'confirm') && confirm(message)); + } + + function requiredValuesMissing(form) { + var missing = false; + form.find('input[name][required]').each(function() { + if (!$(this).val()) missing = true; + }); + return missing; + } + + $('a[data-confirm], a[data-method], a[data-remote]').live('click.rails', function(e) { + var link = $(this); + if (!allowAction(link)) return false; + + if (link.attr('data-remote') != undefined) { + handleRemote(link); + return false; + } else if (link.attr('data-method')) { + handleMethod(link); + return false; + } + }); + + $('form').live('submit.rails', function(e) { + var form = $(this), remote = form.attr('data-remote') != undefined; + if (!allowAction(form)) return false; + + // skip other logic when required values are missing + if (requiredValuesMissing(form)) return !remote; + + if (remote) { + handleRemote(form); + return false; + } else { + disableFormElements(form); + } + }); + + $('form input[type=submit], form button[type=submit], form button:not([type])').live('click.rails', function() { + var button = $(this); + if (!allowAction(button)) return false; + // register the pressed submit button + var name = button.attr('name'), data = name ? {name:name, value:button.val()} : null; + button.closest('form').data('ujs:submit-button', data); + }); + + $('form').live('ajax:beforeSend.rails', function(event) { + if (this == event.target) disableFormElements($(this)); + }); + + $('form').live('ajax:complete.rails', function(event) { + if (this == event.target) enableFormElements($(this)); + }); +})( jQuery ); diff --git a/railties/lib/rails/generators/rails/app/templates/public/javascripts/prototype.js b/railties/lib/rails/generators/rails/app/templates/public/javascripts/prototype.js index 06249a6ae3..474b2231bb 100644 --- a/railties/lib/rails/generators/rails/app/templates/public/javascripts/prototype.js +++ b/railties/lib/rails/generators/rails/app/templates/public/javascripts/prototype.js @@ -1,4 +1,4 @@ -/* Prototype JavaScript framework, version 1.7_rc2 +/* Prototype JavaScript framework, version 1.7 * (c) 2005-2010 Sam Stephenson * * Prototype is freely distributable under the terms of an MIT-style license. @@ -8,7 +8,7 @@ var Prototype = { - Version: '1.7_rc2', + Version: '1.7', Browser: (function(){ var ua = navigator.userAgent; @@ -166,10 +166,12 @@ var Class = (function() { NUMBER_TYPE = 'Number', STRING_TYPE = 'String', OBJECT_TYPE = 'Object', + FUNCTION_CLASS = '[object Function]', BOOLEAN_CLASS = '[object Boolean]', NUMBER_CLASS = '[object Number]', STRING_CLASS = '[object String]', ARRAY_CLASS = '[object Array]', + DATE_CLASS = '[object Date]', NATIVE_JSON_STRINGIFY_SUPPORT = window.JSON && typeof JSON.stringify === 'function' && JSON.stringify(0) === '0' && @@ -322,7 +324,7 @@ var Class = (function() { } function isFunction(object) { - return typeof object === "function"; + return _toString.call(object) === FUNCTION_CLASS; } function isString(object) { @@ -333,6 +335,10 @@ var Class = (function() { return _toString.call(object) === NUMBER_CLASS; } + function isDate(object) { + return _toString.call(object) === DATE_CLASS; + } + function isUndefined(object) { return typeof object === "undefined"; } @@ -352,6 +358,7 @@ var Class = (function() { isFunction: isFunction, isString: isString, isNumber: isNumber, + isDate: isDate, isUndefined: isUndefined }); })(); @@ -1079,9 +1086,10 @@ Array.from = $A; slice = arrayProto.slice, _each = arrayProto.forEach; // use native browser JS 1.6 implementation if available - function each(iterator) { - for (var i = 0, length = this.length; i < length; i++) - iterator(this[i]); + function each(iterator, context) { + for (var i = 0, length = this.length >>> 0; i < length; i++) { + if (i in this) iterator.call(context, this[i], i, this); + } } if (!_each) _each = each; @@ -1287,8 +1295,14 @@ var Hash = Class.create(Enumerable, (function() { var key = encodeURIComponent(pair.key), values = pair.value; if (values && typeof values == 'object') { - if (Object.isArray(values)) - return results.concat(values.map(toQueryPair.curry(key))); + if (Object.isArray(values)) { + var queryValues = []; + for (var i = 0, len = values.length, value; i < len; i++) { + value = values[i]; + queryValues.push(toQueryPair(key, value)); + } + return results.concat(queryValues); + } } else results.push(toQueryPair(key, values)); return results; }).join('&'); @@ -1468,9 +1482,7 @@ Ajax.Base = Class.create({ this.options.method = this.options.method.toLowerCase(); - if (Object.isString(this.options.parameters)) - this.options.parameters = this.options.parameters.toQueryParams(); - else if (Object.isHash(this.options.parameters)) + if (Object.isHash(this.options.parameters)) this.options.parameters = this.options.parameters.toObject(); } }); @@ -1486,22 +1498,21 @@ Ajax.Request = Class.create(Ajax.Base, { request: function(url) { this.url = url; this.method = this.options.method; - var params = Object.clone(this.options.parameters); + var params = Object.isString(this.options.parameters) ? + this.options.parameters : + Object.toQueryString(this.options.parameters); if (!['get', 'post'].include(this.method)) { - params['_method'] = this.method; + params += (params ? '&' : '') + "_method=" + this.method; this.method = 'post'; } - this.parameters = params; - - if (params = Object.toQueryString(params)) { - if (this.method == 'get') - this.url += (this.url.include('?') ? '&' : '?') + params; - else if (/Konqueror|Safari|KHTML/.test(navigator.userAgent)) - params += '&_='; + if (params && this.method === 'get') { + this.url += (this.url.include('?') ? '&' : '?') + params; } + this.parameters = params.toQueryParams(); + try { var response = new Ajax.Response(this); if (this.options.onCreate) this.options.onCreate(response); @@ -1570,11 +1581,12 @@ Ajax.Request = Class.create(Ajax.Base, { success: function() { var status = this.getStatus(); - return !status || (status >= 200 && status < 300); + return !status || (status >= 200 && status < 300) || status == 304; }, getStatus: function() { try { + if (this.transport.status === 1223) return 204; return this.transport.status || 0; } catch (e) { return 0 } }, @@ -1849,6 +1861,11 @@ if (!Node.ELEMENT_NODE) { (function(global) { + function shouldUseCache(tagName, attributes) { + if (tagName === 'select') return false; + if ('type' in attributes) return false; + return true; + } var HAS_EXTENDED_CREATE_ELEMENT_SYNTAX = (function(){ try { @@ -1866,13 +1883,19 @@ if (!Node.ELEMENT_NODE) { attributes = attributes || { }; tagName = tagName.toLowerCase(); var cache = Element.cache; + if (HAS_EXTENDED_CREATE_ELEMENT_SYNTAX && attributes.name) { tagName = '<' + tagName + ' name="' + attributes.name + '">'; delete attributes.name; return Element.writeAttribute(document.createElement(tagName), attributes); } + if (!cache[tagName]) cache[tagName] = Element.extend(document.createElement(tagName)); - return Element.writeAttribute(cache[tagName].cloneNode(false), attributes); + + var node = shouldUseCache(tagName, attributes) ? + cache[tagName].cloneNode(false) : document.createElement(tagName); + + return Element.writeAttribute(node, attributes); }; Object.extend(global.Element, element || { }); @@ -1883,7 +1906,7 @@ if (!Node.ELEMENT_NODE) { Element.idCounter = 1; Element.cache = { }; -function purgeElement(element) { +Element._purgeElement = function(element) { var uid = element._prototypeUID; if (uid) { Element.stopObserving(element); @@ -1948,6 +1971,21 @@ Element.Methods = { } })(); + var LINK_ELEMENT_INNERHTML_BUGGY = (function() { + try { + var el = document.createElement('div'); + el.innerHTML = "<link>"; + var isBuggy = (el.childNodes.length === 0); + el = null; + return isBuggy; + } catch(e) { + return true; + } + })(); + + var ANY_INNERHTML_BUGGY = SELECT_ELEMENT_INNERHTML_BUGGY || + TABLE_ELEMENT_INNERHTML_BUGGY || LINK_ELEMENT_INNERHTML_BUGGY; + var SCRIPT_ELEMENT_REJECTS_TEXTNODE_APPENDING = (function () { var s = document.createElement("script"), isBuggy = false; @@ -1962,8 +2000,10 @@ Element.Methods = { return isBuggy; })(); + function update(element, content) { element = $(element); + var purgeElement = Element._purgeElement; var descendants = element.getElementsByTagName('*'), i = descendants.length; @@ -1984,7 +2024,7 @@ Element.Methods = { return element; } - if (SELECT_ELEMENT_INNERHTML_BUGGY || TABLE_ELEMENT_INNERHTML_BUGGY) { + if (ANY_INNERHTML_BUGGY) { if (tagName in Element._insertionTranslations.tags) { while (element.firstChild) { element.removeChild(element.firstChild); @@ -1993,6 +2033,12 @@ Element.Methods = { .each(function(node) { element.appendChild(node) }); + } else if (LINK_ELEMENT_INNERHTML_BUGGY && Object.isString(content) && content.indexOf('<link') > -1) { + while (element.firstChild) { + element.removeChild(element.firstChild); + } + var nodes = Element._getContentFromAnonymousElement(tagName, content.stripScripts(), true); + nodes.each(function(node) { element.appendChild(node) }); } else { element.innerHTML = content.stripScripts(); @@ -2402,117 +2448,6 @@ Element.Methods = { return element; }, - cumulativeOffset: function(element) { - var valueT = 0, valueL = 0; - if (element.parentNode) { - do { - valueT += element.offsetTop || 0; - valueL += element.offsetLeft || 0; - element = element.offsetParent; - } while (element); - } - return Element._returnOffset(valueL, valueT); - }, - - positionedOffset: function(element) { - var valueT = 0, valueL = 0; - do { - valueT += element.offsetTop || 0; - valueL += element.offsetLeft || 0; - element = element.offsetParent; - if (element) { - if (element.tagName.toUpperCase() == 'BODY') break; - var p = Element.getStyle(element, 'position'); - if (p !== 'static') break; - } - } while (element); - return Element._returnOffset(valueL, valueT); - }, - - absolutize: function(element) { - element = $(element); - if (Element.getStyle(element, 'position') == 'absolute') return element; - - var offsets = Element.positionedOffset(element), - top = offsets[1], - left = offsets[0], - width = element.clientWidth, - height = element.clientHeight; - - element._originalLeft = left - parseFloat(element.style.left || 0); - element._originalTop = top - parseFloat(element.style.top || 0); - element._originalWidth = element.style.width; - element._originalHeight = element.style.height; - - element.style.position = 'absolute'; - element.style.top = top + 'px'; - element.style.left = left + 'px'; - element.style.width = width + 'px'; - element.style.height = height + 'px'; - return element; - }, - - relativize: function(element) { - element = $(element); - if (Element.getStyle(element, 'position') == 'relative') return element; - - element.style.position = 'relative'; - var top = parseFloat(element.style.top || 0) - (element._originalTop || 0), - left = parseFloat(element.style.left || 0) - (element._originalLeft || 0); - - element.style.top = top + 'px'; - element.style.left = left + 'px'; - element.style.height = element._originalHeight; - element.style.width = element._originalWidth; - return element; - }, - - cumulativeScrollOffset: function(element) { - var valueT = 0, valueL = 0; - do { - valueT += element.scrollTop || 0; - valueL += element.scrollLeft || 0; - element = element.parentNode; - } while (element); - return Element._returnOffset(valueL, valueT); - }, - - getOffsetParent: function(element) { - if (element.offsetParent) return $(element.offsetParent); - if (element == document.body) return $(element); - - while ((element = element.parentNode) && element != document.body) - if (Element.getStyle(element, 'position') != 'static') - return $(element); - - return $(document.body); - }, - - viewportOffset: function(forElement) { - var valueT = 0, - valueL = 0, - element = forElement; - - do { - valueT += element.offsetTop || 0; - valueL += element.offsetLeft || 0; - - if (element.offsetParent == document.body && - Element.getStyle(element, 'position') == 'absolute') break; - - } while (element = element.offsetParent); - - element = forElement; - do { - if (!Prototype.Browser.Opera || (element.tagName && (element.tagName.toUpperCase() == 'BODY'))) { - valueT -= element.scrollTop || 0; - valueL -= element.scrollLeft || 0; - } - } while (element = element.parentNode); - - return Element._returnOffset(valueL, valueT); - }, - clonePosition: function(element, source) { var options = Object.extend({ setLeft: true, @@ -2566,8 +2501,6 @@ if (Prototype.Browser.Opera) { Element.Methods.getStyle = Element.Methods.getStyle.wrap( function(proceed, element, style) { switch (style) { - case 'left': case 'top': case 'right': case 'bottom': - if (proceed(element, 'position') === 'static') return null; case 'height': case 'width': if (!Element.visible(element)) return null; @@ -2603,37 +2536,6 @@ if (Prototype.Browser.Opera) { } else if (Prototype.Browser.IE) { - Element.Methods.getOffsetParent = Element.Methods.getOffsetParent.wrap( - function(proceed, element) { - element = $(element); - if (!element.parentNode) return $(document.body); - var position = element.getStyle('position'); - if (position !== 'static') return proceed(element); - element.setStyle({ position: 'relative' }); - var value = proceed(element); - element.setStyle({ position: position }); - return value; - } - ); - - $w('positionedOffset viewportOffset').each(function(method) { - Element.Methods[method] = Element.Methods[method].wrap( - function(proceed, element) { - element = $(element); - if (!element.parentNode) return Element._returnOffset(0, 0); - var position = element.getStyle('position'); - if (position !== 'static') return proceed(element); - var offsetParent = element.getOffsetParent(); - if (offsetParent && offsetParent.getStyle('position') === 'fixed') - offsetParent.setStyle({ zoom: 1 }); - element.setStyle({ position: 'relative' }); - var value = proceed(element); - element.setStyle({ position: position }); - return value; - } - ); - }); - Element.Methods.getStyle = function(element, style) { element = $(element); style = (style == 'float' || style == 'cssFloat') ? 'styleFloat' : style.camelize(); @@ -2862,20 +2764,6 @@ else if (Prototype.Browser.WebKit) { return element; }; - - Element.Methods.cumulativeOffset = function(element) { - var valueT = 0, valueL = 0; - do { - valueT += element.offsetTop || 0; - valueL += element.offsetLeft || 0; - if (element.offsetParent == document.body) - if (Element.getStyle(element, 'position') == 'absolute') break; - - element = element.offsetParent; - } while (element); - - return Element._returnOffset(valueL, valueT); - }; } if ('outerHTML' in document.documentElement) { @@ -2914,11 +2802,20 @@ Element._returnOffset = function(l, t) { return result; }; -Element._getContentFromAnonymousElement = function(tagName, html) { +Element._getContentFromAnonymousElement = function(tagName, html, force) { var div = new Element('div'), t = Element._insertionTranslations.tags[tagName]; - if (t) { - div.innerHTML = t[0] + html + t[1]; + + var workaround = false; + if (t) workaround = true; + else if (force) { + workaround = true; + t = ['', '', 0]; + } + + if (workaround) { + div.innerHTML = ' ' + t[0] + html + t[1]; + div.removeChild(div.firstChild); for (var i = t[2]; i--; ) { div = div.firstChild; } @@ -3077,7 +2974,8 @@ Element.addMethods = function(methods) { "FORM": Object.clone(Form.Methods), "INPUT": Object.clone(Form.Element.Methods), "SELECT": Object.clone(Form.Element.Methods), - "TEXTAREA": Object.clone(Form.Element.Methods) + "TEXTAREA": Object.clone(Form.Element.Methods), + "BUTTON": Object.clone(Form.Element.Methods) }); } @@ -3264,6 +3162,8 @@ Element.addMethods({ purge: function(element) { if (!(element = $(element))) return; + var purgeElement = Element._purgeElement; + purgeElement(element); var descendants = element.getElementsByTagName('*'), @@ -3283,11 +3183,13 @@ Element.addMethods({ return (Number(match[1]) / 100); } - function getPixelValue(value, property) { + function getPixelValue(value, property, context) { + var element = null; if (Object.isElement(value)) { element = value; value = element.getStyle(property); } + if (value === null) { return null; } @@ -3296,7 +3198,9 @@ Element.addMethods({ return window.parseFloat(value); } - if (/\d/.test(value) && element.runtimeStyle) { + var isPercentage = value.include('%'), isViewport = (context === document.viewport); + + if (/\d/.test(value) && element && element.runtimeStyle && !(isPercentage && isViewport)) { var style = element.style.left, rStyle = element.runtimeStyle.left; element.runtimeStyle.left = element.currentStyle.left; element.style.left = value || 0; @@ -3307,18 +3211,33 @@ Element.addMethods({ return value; } - if (value.include('%')) { + if (element && isPercentage) { + context = context || element.parentNode; var decimal = toDecimal(value); - var whole; - if (property.include('left') || property.include('right') || - property.include('width')) { - whole = $(element.parentNode).measure('width'); - } else if (property.include('top') || property.include('bottom') || - property.include('height')) { - whole = $(element.parentNode).measure('height'); + var whole = null; + var position = element.getStyle('position'); + + var isHorizontal = property.include('left') || property.include('right') || + property.include('width'); + + var isVertical = property.include('top') || property.include('bottom') || + property.include('height'); + + if (context === document.viewport) { + if (isHorizontal) { + whole = document.viewport.getWidth(); + } else if (isVertical) { + whole = document.viewport.getHeight(); + } + } else { + if (isHorizontal) { + whole = $(context).measure('width'); + } else if (isVertical) { + whole = $(context).measure('height'); + } } - return whole * decimal; + return (whole === null) ? 0 : whole * decimal; } return 0; @@ -3410,6 +3329,14 @@ Element.addMethods({ var position = element.getStyle('position'), width = element.getStyle('width'); + if (width === "0px" || width === null) { + element.style.display = 'block'; + width = element.getStyle('width'); + } + + var context = (position === 'fixed') ? document.viewport : + element.parentNode; + element.setStyle({ position: 'absolute', visibility: 'hidden', @@ -3420,9 +3347,9 @@ Element.addMethods({ var newWidth; if (width && (positionedWidth === width)) { - newWidth = getPixelValue(width); - } else if (width && (position === 'absolute' || position === 'fixed')) { - newWidth = getPixelValue(width); + newWidth = getPixelValue(element, 'width', context); + } else if (position === 'absolute' || position === 'fixed') { + newWidth = getPixelValue(element, 'width', context); } else { var parent = element.parentNode, pLayout = $(parent).getLayout(); @@ -3453,6 +3380,7 @@ Element.addMethods({ if (!(property in COMPUTATIONS)) { throw "Property not found."; } + return this._set(property, COMPUTATIONS[property].call(this, this.element)); }, @@ -3505,7 +3433,10 @@ Element.addMethods({ if (!this._preComputing) this._begin(); var bHeight = this.get('border-box-height'); - if (bHeight <= 0) return 0; + if (bHeight <= 0) { + if (!this._preComputing) this._end(); + return 0; + } var bTop = this.get('border-top'), bBottom = this.get('border-bottom'); @@ -3522,7 +3453,10 @@ Element.addMethods({ if (!this._preComputing) this._begin(); var bWidth = this.get('border-box-width'); - if (bWidth <= 0) return 0; + if (bWidth <= 0) { + if (!this._preComputing) this._end(); + return 0; + } var bLeft = this.get('border-left'), bRight = this.get('border-right'); @@ -3552,11 +3486,17 @@ Element.addMethods({ }, 'border-box-height': function(element) { - return element.offsetHeight; + if (!this._preComputing) this._begin(); + var height = element.offsetHeight; + if (!this._preComputing) this._end(); + return height; }, 'border-box-width': function(element) { - return element.offsetWidth; + if (!this._preComputing) this._begin(); + var width = element.offsetWidth; + if (!this._preComputing) this._end(); + return width; }, 'margin-box-height': function(element) { @@ -3626,23 +3566,19 @@ Element.addMethods({ }, 'border-top': function(element) { - return Object.isNumber(element.clientTop) ? element.clientTop : - getPixelValue(element, 'borderTopWidth'); + return getPixelValue(element, 'borderTopWidth'); }, 'border-bottom': function(element) { - return Object.isNumber(element.clientBottom) ? element.clientBottom : - getPixelValue(element, 'borderBottomWidth'); + return getPixelValue(element, 'borderBottomWidth'); }, 'border-left': function(element) { - return Object.isNumber(element.clientLeft) ? element.clientLeft : - getPixelValue(element, 'borderLeftWidth'); + return getPixelValue(element, 'borderLeftWidth'); }, 'border-right': function(element) { - return Object.isNumber(element.clientRight) ? element.clientRight : - getPixelValue(element, 'borderRightWidth'); + return getPixelValue(element, 'borderRightWidth'); }, 'margin-top': function(element) { @@ -3721,23 +3657,52 @@ Element.addMethods({ } function getDimensions(element) { - var layout = $(element).getLayout(); - return { - width: layout.get('width'), - height: layout.get('height') + element = $(element); + var display = Element.getStyle(element, 'display'); + + if (display && display !== 'none') { + return { width: element.offsetWidth, height: element.offsetHeight }; + } + + var style = element.style; + var originalStyles = { + visibility: style.visibility, + position: style.position, + display: style.display + }; + + var newStyles = { + visibility: 'hidden', + display: 'block' }; + + if (originalStyles.position !== 'fixed') + newStyles.position = 'absolute'; + + Element.setStyle(element, newStyles); + + var dimensions = { + width: element.offsetWidth, + height: element.offsetHeight + }; + + Element.setStyle(element, originalStyles); + + return dimensions; } function getOffsetParent(element) { - if (isDetached(element)) return $(document.body); + element = $(element); + + if (isDocument(element) || isDetached(element) || isBody(element) || isHtml(element)) + return $(document.body); var isInline = (Element.getStyle(element, 'display') === 'inline'); if (!isInline && element.offsetParent) return $(element.offsetParent); - if (element === document.body) return $(element); while ((element = element.parentNode) && element !== document.body) { if (Element.getStyle(element, 'position') !== 'static') { - return (element.nodeName === 'HTML') ? $(document.body) : $(element); + return isHtml(element) ? $(document.body) : $(element); } } @@ -3746,16 +3711,21 @@ Element.addMethods({ function cumulativeOffset(element) { + element = $(element); var valueT = 0, valueL = 0; - do { - valueT += element.offsetTop || 0; - valueL += element.offsetLeft || 0; - element = element.offsetParent; - } while (element); + if (element.parentNode) { + do { + valueT += element.offsetTop || 0; + valueL += element.offsetLeft || 0; + element = element.offsetParent; + } while (element); + } return new Element.Offset(valueL, valueT); } function positionedOffset(element) { + element = $(element); + var layout = element.getLayout(); var valueT = 0, valueL = 0; @@ -3787,6 +3757,7 @@ Element.addMethods({ } function viewportOffset(forElement) { + element = $(element); var valueT = 0, valueL = 0, docBody = document.body; var element = forElement; @@ -3852,6 +3823,57 @@ Element.addMethods({ return element; } + if (Prototype.Browser.IE) { + getOffsetParent = getOffsetParent.wrap( + function(proceed, element) { + element = $(element); + + if (isDocument(element) || isDetached(element) || isBody(element) || isHtml(element)) + return $(document.body); + + var position = element.getStyle('position'); + if (position !== 'static') return proceed(element); + + element.setStyle({ position: 'relative' }); + var value = proceed(element); + element.setStyle({ position: position }); + return value; + } + ); + + positionedOffset = positionedOffset.wrap(function(proceed, element) { + element = $(element); + if (!element.parentNode) return new Element.Offset(0, 0); + var position = element.getStyle('position'); + if (position !== 'static') return proceed(element); + + var offsetParent = element.getOffsetParent(); + if (offsetParent && offsetParent.getStyle('position') === 'fixed') + hasLayout(offsetParent); + + element.setStyle({ position: 'relative' }); + var value = proceed(element); + element.setStyle({ position: position }); + return value; + }); + } else if (Prototype.Browser.Webkit) { + cumulativeOffset = function(element) { + element = $(element); + var valueT = 0, valueL = 0; + do { + valueT += element.offsetTop || 0; + valueL += element.offsetLeft || 0; + if (element.offsetParent == document.body) + if (Element.getStyle(element, 'position') == 'absolute') break; + + element = element.offsetParent; + } while (element); + + return new Element.Offset(valueL, valueT); + }; + } + + Element.addMethods({ getLayout: getLayout, measure: measure, @@ -3869,6 +3891,14 @@ Element.addMethods({ return element.nodeName.toUpperCase() === 'BODY'; } + function isHtml(element) { + return element.nodeName.toUpperCase() === 'HTML'; + } + + function isDocument(element) { + return element.nodeType === Node.DOCUMENT_NODE; + } + function isDetached(element) { return element !== document.body && !Element.descendantOf(element, document.body); @@ -3880,32 +3910,10 @@ Element.addMethods({ element = $(element); if (isDetached(element)) return new Element.Offset(0, 0); - var rect = element.getBoundingClientRect(), + var rect = element.getBoundingClientRect(), docEl = document.documentElement; return new Element.Offset(rect.left - docEl.clientLeft, rect.top - docEl.clientTop); - }, - - positionedOffset: function(element) { - element = $(element); - var parent = element.getOffsetParent(); - if (isDetached(element)) return new Element.Offset(0, 0); - - if (element.offsetParent && - element.offsetParent.nodeName.toUpperCase() === 'HTML') { - return positionedOffset(element); - } - - var eOffset = element.viewportOffset(), - pOffset = isBody(parent) ? viewportOffset(parent) : - parent.viewportOffset(); - var retOffset = eOffset.relativeTo(pOffset); - - var layout = element.getLayout(); - var top = retOffset.top - layout.get('margin-top'); - var left = retOffset.left - layout.get('margin-left'); - - return new Element.Offset(left, top); } }); } @@ -4962,24 +4970,34 @@ var Form = { serializeElements: function(elements, options) { if (typeof options != 'object') options = { hash: !!options }; else if (Object.isUndefined(options.hash)) options.hash = true; - var key, value, submitted = false, submit = options.submit; + var key, value, submitted = false, submit = options.submit, accumulator, initial; + + if (options.hash) { + initial = {}; + accumulator = function(result, key, value) { + if (key in result) { + if (!Object.isArray(result[key])) result[key] = [result[key]]; + result[key].push(value); + } else result[key] = value; + return result; + }; + } else { + initial = ''; + accumulator = function(result, key, value) { + return result + (result ? '&' : '') + encodeURIComponent(key) + '=' + encodeURIComponent(value); + } + } - var data = elements.inject({ }, function(result, element) { + return elements.inject(initial, function(result, element) { if (!element.disabled && element.name) { key = element.name; value = $(element).getValue(); if (value != null && element.type != 'file' && (element.type != 'submit' || (!submitted && submit !== false && (!submit || key == submit) && (submitted = true)))) { - if (key in result) { - if (!Object.isArray(result[key])) result[key] = [result[key]]; - result[key].push(value); - } - else result[key] = value; + result = accumulator(result, key, value); } } return result; }); - - return options.hash ? data : Object.toQueryString(data); } }; @@ -5046,7 +5064,8 @@ Form.Methods = { focusFirstElement: function(form) { form = $(form); - form.findFirstElement().activate(); + var element = form.findFirstElement(); + if (element) element.activate(); return form; }, @@ -5153,67 +5172,77 @@ var $F = Form.Element.Methods.getValue; /*--------------------------------------------------------------------------*/ -Form.Element.Serializers = { - input: function(element, value) { +Form.Element.Serializers = (function() { + function input(element, value) { switch (element.type.toLowerCase()) { case 'checkbox': case 'radio': - return Form.Element.Serializers.inputSelector(element, value); + return inputSelector(element, value); default: - return Form.Element.Serializers.textarea(element, value); + return valueSelector(element, value); } - }, + } - inputSelector: function(element, value) { - if (Object.isUndefined(value)) return element.checked ? element.value : null; + function inputSelector(element, value) { + if (Object.isUndefined(value)) + return element.checked ? element.value : null; else element.checked = !!value; - }, + } - textarea: function(element, value) { + function valueSelector(element, value) { if (Object.isUndefined(value)) return element.value; else element.value = value; - }, + } - select: function(element, value) { + function select(element, value) { if (Object.isUndefined(value)) - return this[element.type == 'select-one' ? - 'selectOne' : 'selectMany'](element); - else { - var opt, currentValue, single = !Object.isArray(value); - for (var i = 0, length = element.length; i < length; i++) { - opt = element.options[i]; - currentValue = this.optionValue(opt); - if (single) { - if (currentValue == value) { - opt.selected = true; - return; - } + return (element.type === 'select-one' ? selectOne : selectMany)(element); + + var opt, currentValue, single = !Object.isArray(value); + for (var i = 0, length = element.length; i < length; i++) { + opt = element.options[i]; + currentValue = this.optionValue(opt); + if (single) { + if (currentValue == value) { + opt.selected = true; + return; } - else opt.selected = value.include(currentValue); } + else opt.selected = value.include(currentValue); } - }, + } - selectOne: function(element) { + function selectOne(element) { var index = element.selectedIndex; - return index >= 0 ? this.optionValue(element.options[index]) : null; - }, + return index >= 0 ? optionValue(element.options[index]) : null; + } - selectMany: function(element) { + function selectMany(element) { var values, length = element.length; if (!length) return null; for (var i = 0, values = []; i < length; i++) { var opt = element.options[i]; - if (opt.selected) values.push(this.optionValue(opt)); + if (opt.selected) values.push(optionValue(opt)); } return values; - }, + } - optionValue: function(opt) { - return Element.extend(opt).hasAttribute('value') ? opt.value : opt.text; + function optionValue(opt) { + return Element.hasAttribute(opt, 'value') ? opt.value : opt.text; } -}; + + return { + input: input, + inputSelector: inputSelector, + textarea: valueSelector, + select: select, + selectOne: selectOne, + selectMany: selectMany, + optionValue: optionValue, + button: valueSelector + }; +})(); /*--------------------------------------------------------------------------*/ @@ -5324,24 +5353,53 @@ Form.EventObserver = Class.create(Abstract.EventObserver, { var MOUSEENTER_MOUSELEAVE_EVENTS_SUPPORTED = 'onmouseenter' in docEl && 'onmouseleave' in docEl; + + + var isIELegacyEvent = function(event) { return false; }; + + if (window.attachEvent) { + if (window.addEventListener) { + isIELegacyEvent = function(event) { + return !(event instanceof window.Event); + }; + } else { + isIELegacyEvent = function(event) { return true; }; + } + } + var _isButton; - if (Prototype.Browser.IE) { - var buttonMap = { 0: 1, 1: 4, 2: 2 }; - _isButton = function(event, code) { - return event.button === buttonMap[code]; - }; - } else if (Prototype.Browser.WebKit) { - _isButton = function(event, code) { - switch (code) { - case 0: return event.which == 1 && !event.metaKey; - case 1: return event.which == 1 && event.metaKey; - default: return false; + + function _isButtonForDOMEvents(event, code) { + return event.which ? (event.which === code + 1) : (event.button === code); + } + + var legacyButtonMap = { 0: 1, 1: 4, 2: 2 }; + function _isButtonForLegacyEvents(event, code) { + return event.button === legacyButtonMap[code]; + } + + function _isButtonForWebKit(event, code) { + switch (code) { + case 0: return event.which == 1 && !event.metaKey; + case 1: return event.which == 2 || (event.which == 1 && event.metaKey); + case 2: return event.which == 3; + default: return false; + } + } + + if (window.attachEvent) { + if (!window.addEventListener) { + _isButton = _isButtonForLegacyEvents; + } else { + _isButton = function(event, code) { + return isIELegacyEvent(event) ? _isButtonForLegacyEvents(event, code) : + _isButtonForDOMEvents(event, code); } - }; + } + } else if (Prototype.Browser.WebKit) { + _isButton = _isButtonForWebKit; } else { - _isButton = function(event, code) { - return event.which ? (event.which === code + 1) : (event.button === code); - }; + _isButton = _isButtonForDOMEvents; } function isLeftClick(event) { return _isButton(event, 0) } @@ -5371,6 +5429,7 @@ Form.EventObserver = Class.create(Abstract.EventObserver, { function findElement(event, expression) { var element = Event.element(event); + if (!expression) return element; while (element) { if (Object.isElement(element) && Prototype.Selector.match(element, expression)) { @@ -5411,49 +5470,59 @@ Form.EventObserver = Class.create(Abstract.EventObserver, { event.stopped = true; } + Event.Methods = { - isLeftClick: isLeftClick, + isLeftClick: isLeftClick, isMiddleClick: isMiddleClick, - isRightClick: isRightClick, + isRightClick: isRightClick, - element: element, + element: element, findElement: findElement, - pointer: pointer, + pointer: pointer, pointerX: pointerX, pointerY: pointerY, stop: stop }; - var methods = Object.keys(Event.Methods).inject({ }, function(m, name) { m[name] = Event.Methods[name].methodize(); return m; }); - if (Prototype.Browser.IE) { + if (window.attachEvent) { function _relatedTarget(event) { var element; switch (event.type) { - case 'mouseover': element = event.fromElement; break; - case 'mouseout': element = event.toElement; break; - default: return null; + case 'mouseover': + case 'mouseenter': + element = event.fromElement; + break; + case 'mouseout': + case 'mouseleave': + element = event.toElement; + break; + default: + return null; } return Element.extend(element); } - Object.extend(methods, { + var additionalMethods = { stopPropagation: function() { this.cancelBubble = true }, preventDefault: function() { this.returnValue = false }, inspect: function() { return '[object Event]' } - }); + }; Event.extend = function(event, element) { if (!event) return false; - if (event._extendedByPrototype) return event; + if (!isIELegacyEvent(event)) return event; + + if (event._extendedByPrototype) return event; event._extendedByPrototype = Prototype.emptyFunction; + var pointer = Event.pointer(event); Object.extend(event, { @@ -5463,12 +5532,18 @@ Form.EventObserver = Class.create(Abstract.EventObserver, { pageY: pointer.y }); - return Object.extend(event, methods); + Object.extend(event, methods); + Object.extend(event, additionalMethods); + + return event; }; } else { + Event.extend = Prototype.K; + } + + if (window.addEventListener) { Event.prototype = window.Event.prototype || document.createEvent('HTMLEvents').__proto__; Object.extend(Event.prototype, methods); - Event.extend = Prototype.K; } function _createResponder(element, eventName, handler) { @@ -5567,7 +5642,7 @@ Form.EventObserver = Class.create(Abstract.EventObserver, { element.addEventListener("dataavailable", responder, false); else { element.attachEvent("ondataavailable", responder); - element.attachEvent("onfilterchange", responder); + element.attachEvent("onlosecapture", responder); } } else { var actualEventName = _getDOMEventName(eventName); @@ -5605,7 +5680,13 @@ Form.EventObserver = Class.create(Abstract.EventObserver, { return element; } - var responder = responders.find( function(r) { return r.handler === handler; }); + var i = responders.length, responder; + while (i--) { + if (responders[i].handler === handler) { + responder = responders[i]; + break; + } + } if (!responder) return element; if (eventName.include(':')) { @@ -5613,7 +5694,7 @@ Form.EventObserver = Class.create(Abstract.EventObserver, { element.removeEventListener("dataavailable", responder, false); else { element.detachEvent("ondataavailable", responder); - element.detachEvent("onfilterchange", responder); + element.detachEvent("onlosecapture", responder); } } else { var actualEventName = _getDOMEventName(eventName); @@ -5640,10 +5721,10 @@ Form.EventObserver = Class.create(Abstract.EventObserver, { var event; if (document.createEvent) { event = document.createEvent('HTMLEvents'); - event.initEvent('dataavailable', true, true); + event.initEvent('dataavailable', bubble, true); } else { event = document.createEventObject(); - event.eventType = bubble ? 'ondataavailable' : 'onfilterchange'; + event.eventType = bubble ? 'ondataavailable' : 'onlosecapture'; } event.eventName = eventName; @@ -5677,7 +5758,7 @@ Form.EventObserver = Class.create(Abstract.EventObserver, { }, handleEvent: function(event) { - var element = event.findElement(this.selector); + var element = Event.findElement(event, this.selector); if (element) this.callback.call(this.element, event, element); } }); diff --git a/railties/lib/rails/generators/rails/app/templates/public/javascripts/prototype_ujs.js b/railties/lib/rails/generators/rails/app/templates/public/javascripts/prototype_ujs.js new file mode 100644 index 0000000000..2cd1220786 --- /dev/null +++ b/railties/lib/rails/generators/rails/app/templates/public/javascripts/prototype_ujs.js @@ -0,0 +1,208 @@ +(function() { + // Technique from Juriy Zaytsev + // http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/ + function isEventSupported(eventName) { + var el = document.createElement('div'); + eventName = 'on' + eventName; + var isSupported = (eventName in el); + if (!isSupported) { + el.setAttribute(eventName, 'return;'); + isSupported = typeof el[eventName] == 'function'; + } + el = null; + return isSupported; + } + + function isForm(element) { + return Object.isElement(element) && element.nodeName.toUpperCase() == 'FORM'; + } + + function isInput(element) { + if (Object.isElement(element)) { + var name = element.nodeName.toUpperCase(); + return name == 'INPUT' || name == 'SELECT' || name == 'TEXTAREA'; + } + else return false; + } + + var submitBubbles = isEventSupported('submit'), + changeBubbles = isEventSupported('change'); + + if (!submitBubbles || !changeBubbles) { + // augment the Event.Handler class to observe custom events when needed + Event.Handler.prototype.initialize = Event.Handler.prototype.initialize.wrap( + function(init, element, eventName, selector, callback) { + init(element, eventName, selector, callback); + // is the handler being attached to an element that doesn't support this event? + if ( (!submitBubbles && this.eventName == 'submit' && !isForm(this.element)) || + (!changeBubbles && this.eventName == 'change' && !isInput(this.element)) ) { + // "submit" => "emulated:submit" + this.eventName = 'emulated:' + this.eventName; + } + } + ); + } + + if (!submitBubbles) { + // discover forms on the page by observing focus events which always bubble + document.on('focusin', 'form', function(focusEvent, form) { + // special handler for the real "submit" event (one-time operation) + if (!form.retrieve('emulated:submit')) { + form.on('submit', function(submitEvent) { + var emulated = form.fire('emulated:submit', submitEvent, true); + // if custom event received preventDefault, cancel the real one too + if (emulated.returnValue === false) submitEvent.preventDefault(); + }); + form.store('emulated:submit', true); + } + }); + } + + if (!changeBubbles) { + // discover form inputs on the page + document.on('focusin', 'input, select, textarea', function(focusEvent, input) { + // special handler for real "change" events + if (!input.retrieve('emulated:change')) { + input.on('change', function(changeEvent) { + input.fire('emulated:change', changeEvent, true); + }); + input.store('emulated:change', true); + } + }); + } + + function handleRemote(element) { + var method, url, params; + + var event = element.fire("ajax:before"); + if (event.stopped) return false; + + if (element.tagName.toLowerCase() === 'form') { + method = element.readAttribute('method') || 'post'; + url = element.readAttribute('action'); + // serialize the form with respect to the submit button that was pressed + params = element.serialize({ submit: element.retrieve('rails:submit-button') }); + // clear the pressed submit button information + element.store('rails:submit-button', null); + } else { + method = element.readAttribute('data-method') || 'get'; + url = element.readAttribute('href'); + params = {}; + } + + new Ajax.Request(url, { + method: method, + parameters: params, + evalScripts: true, + + onCreate: function(response) { element.fire("ajax:create", response); }, + onComplete: function(response) { element.fire("ajax:complete", response); }, + onSuccess: function(response) { element.fire("ajax:success", response); }, + onFailure: function(response) { element.fire("ajax:failure", response); } + }); + + element.fire("ajax:after"); + } + + function insertHiddenField(form, name, value) { + form.insert(new Element('input', { type: 'hidden', name: name, value: value })); + } + + function handleMethod(element) { + var method = element.readAttribute('data-method'), + url = element.readAttribute('href'), + csrf_param = $$('meta[name=csrf-param]')[0], + csrf_token = $$('meta[name=csrf-token]')[0]; + + var form = new Element('form', { method: "POST", action: url, style: "display: none;" }); + $(element.parentNode).insert(form); + + if (method !== 'post') { + insertHiddenField(form, '_method', method); + } + + if (csrf_param) { + insertHiddenField(form, csrf_param.readAttribute('content'), csrf_token.readAttribute('content')); + } + + form.submit(); + } + + function disableFormElements(form) { + form.select('input[type=submit][data-disable-with]').each(function(input) { + input.store('rails:original-value', input.getValue()); + input.setValue(input.readAttribute('data-disable-with')).disable(); + }); + } + + function enableFormElements(form) { + form.select('input[type=submit][data-disable-with]').each(function(input) { + input.setValue(input.retrieve('rails:original-value')).enable(); + }); + } + + function allowAction(element) { + var message = element.readAttribute('data-confirm'); + return !message || confirm(message); + } + + document.on('click', 'a[data-confirm], a[data-remote], a[data-method]', function(event, link) { + if (!allowAction(link)) { + event.stop(); + return false; + } + + if (link.readAttribute('data-remote')) { + handleRemote(link); + event.stop(); + } else if (link.readAttribute('data-method')) { + handleMethod(link); + event.stop(); + } + }); + + document.on("click", "form input[type=submit], form button[type=submit], form button:not([type])", function(event, button) { + // register the pressed submit button + event.findElement('form').store('rails:submit-button', button.name || false); + }); + + document.on("submit", function(event) { + var form = event.findElement(); + + if (!allowAction(form)) { + event.stop(); + return false; + } + + if (form.readAttribute('data-remote')) { + handleRemote(form); + event.stop(); + } else { + disableFormElements(form); + } + }); + + document.on('ajax:create', 'form', function(event, form) { + if (form == event.findElement()) disableFormElements(form); + }); + + document.on('ajax:complete', 'form', function(event, form) { + if (form == event.findElement()) enableFormElements(form); + }); + + Ajax.Responders.register({ + onCreate: function(request) { + var csrf_meta_tag = $$('meta[name=csrf-token]')[0]; + + if (csrf_meta_tag) { + var header = 'X-CSRF-Token', + token = csrf_meta_tag.readAttribute('content'); + + if (!request.options.requestHeaders) { + request.options.requestHeaders = {}; + } + request.options.requestHeaders[header] = token; + } + } + }); +})(); diff --git a/railties/lib/rails/generators/rails/app/templates/public/javascripts/rails.js b/railties/lib/rails/generators/rails/app/templates/public/javascripts/rails.js deleted file mode 100644 index 4283ed8982..0000000000 --- a/railties/lib/rails/generators/rails/app/templates/public/javascripts/rails.js +++ /dev/null @@ -1,175 +0,0 @@ -(function() { - // Technique from Juriy Zaytsev - // http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/ - function isEventSupported(eventName) { - var el = document.createElement('div'); - eventName = 'on' + eventName; - var isSupported = (eventName in el); - if (!isSupported) { - el.setAttribute(eventName, 'return;'); - isSupported = typeof el[eventName] == 'function'; - } - el = null; - return isSupported; - } - - function isForm(element) { - return Object.isElement(element) && element.nodeName.toUpperCase() == 'FORM' - } - - function isInput(element) { - if (Object.isElement(element)) { - var name = element.nodeName.toUpperCase() - return name == 'INPUT' || name == 'SELECT' || name == 'TEXTAREA' - } - else return false - } - - var submitBubbles = isEventSupported('submit'), - changeBubbles = isEventSupported('change') - - if (!submitBubbles || !changeBubbles) { - // augment the Event.Handler class to observe custom events when needed - Event.Handler.prototype.initialize = Event.Handler.prototype.initialize.wrap( - function(init, element, eventName, selector, callback) { - init(element, eventName, selector, callback) - // is the handler being attached to an element that doesn't support this event? - if ( (!submitBubbles && this.eventName == 'submit' && !isForm(this.element)) || - (!changeBubbles && this.eventName == 'change' && !isInput(this.element)) ) { - // "submit" => "emulated:submit" - this.eventName = 'emulated:' + this.eventName - } - } - ) - } - - if (!submitBubbles) { - // discover forms on the page by observing focus events which always bubble - document.on('focusin', 'form', function(focusEvent, form) { - // special handler for the real "submit" event (one-time operation) - if (!form.retrieve('emulated:submit')) { - form.on('submit', function(submitEvent) { - var emulated = form.fire('emulated:submit', submitEvent, true) - // if custom event received preventDefault, cancel the real one too - if (emulated.returnValue === false) submitEvent.preventDefault() - }) - form.store('emulated:submit', true) - } - }) - } - - if (!changeBubbles) { - // discover form inputs on the page - document.on('focusin', 'input, select, texarea', function(focusEvent, input) { - // special handler for real "change" events - if (!input.retrieve('emulated:change')) { - input.on('change', function(changeEvent) { - input.fire('emulated:change', changeEvent, true) - }) - input.store('emulated:change', true) - } - }) - } - - function handleRemote(element) { - var method, url, params; - - var event = element.fire("ajax:before"); - if (event.stopped) return false; - - if (element.tagName.toLowerCase() === 'form') { - method = element.readAttribute('method') || 'post'; - url = element.readAttribute('action'); - params = element.serialize(); - } else { - method = element.readAttribute('data-method') || 'get'; - url = element.readAttribute('href'); - params = {}; - } - - new Ajax.Request(url, { - method: method, - parameters: params, - evalScripts: true, - - onComplete: function(request) { element.fire("ajax:complete", request); }, - onSuccess: function(request) { element.fire("ajax:success", request); }, - onFailure: function(request) { element.fire("ajax:failure", request); } - }); - - element.fire("ajax:after"); - } - - function handleMethod(element) { - var method = element.readAttribute('data-method'), - url = element.readAttribute('href'), - csrf_param = $$('meta[name=csrf-param]')[0], - csrf_token = $$('meta[name=csrf-token]')[0]; - - var form = new Element('form', { method: "POST", action: url, style: "display: none;" }); - element.parentNode.insert(form); - - if (method !== 'post') { - var field = new Element('input', { type: 'hidden', name: '_method', value: method }); - form.insert(field); - } - - if (csrf_param) { - var param = csrf_param.readAttribute('content'), - token = csrf_token.readAttribute('content'), - field = new Element('input', { type: 'hidden', name: param, value: token }); - form.insert(field); - } - - form.submit(); - } - - - document.on("click", "*[data-confirm]", function(event, element) { - var message = element.readAttribute('data-confirm'); - if (!confirm(message)) event.stop(); - }); - - document.on("click", "a[data-remote]", function(event, element) { - if (event.stopped) return; - handleRemote(element); - event.stop(); - }); - - document.on("click", "a[data-method]", function(event, element) { - if (event.stopped) return; - handleMethod(element); - event.stop(); - }); - - document.on("submit", function(event) { - var element = event.findElement(), - message = element.readAttribute('data-confirm'); - if (message && !confirm(message)) { - event.stop(); - return false; - } - - var inputs = element.select("input[type=submit][data-disable-with]"); - inputs.each(function(input) { - input.disabled = true; - input.writeAttribute('data-original-value', input.value); - input.value = input.readAttribute('data-disable-with'); - }); - - var element = event.findElement("form[data-remote]"); - if (element) { - handleRemote(element); - event.stop(); - } - }); - - document.on("ajax:after", "form", function(event, element) { - var inputs = element.select("input[type=submit][disabled=true][data-disable-with]"); - inputs.each(function(input) { - input.value = input.readAttribute('data-original-value'); - input.removeAttribute('data-original-value'); - input.disabled = false; - }); - }); -})(); diff --git a/railties/lib/rails/generators/rails/controller/templates/controller.rb b/railties/lib/rails/generators/rails/controller/templates/controller.rb index cda2659e69..c61ea4b510 100644 --- a/railties/lib/rails/generators/rails/controller/templates/controller.rb +++ b/railties/lib/rails/generators/rails/controller/templates/controller.rb @@ -1,3 +1,4 @@ +<% module_namespacing do -%> class <%= class_name %>Controller < ApplicationController <% for action in actions -%> def <%= action %> @@ -5,3 +6,4 @@ class <%= class_name %>Controller < ApplicationController <% end -%> end +<% end -%> diff --git a/railties/lib/rails/generators/rails/generator/USAGE b/railties/lib/rails/generators/rails/generator/USAGE index d8c3f7f634..d28eb3d7d8 100644 --- a/railties/lib/rails/generators/rails/generator/USAGE +++ b/railties/lib/rails/generators/rails/generator/USAGE @@ -1,6 +1,6 @@ Description: - Stubs out a new generator at lib/generators. Pass the generator name, either - CamelCased or under_scored, as an argument. + Stubs out a new generator at lib/generators. Pass the generator name as an argument, + either CamelCased or snake_cased. Example: `rails generate generator Awesome` @@ -8,4 +8,5 @@ Example: creates a standard awesome generator: lib/generators/awesome/ lib/generators/awesome/awesome_generator.rb + lib/generators/awesome/USAGE lib/generators/awesome/templates/ diff --git a/railties/lib/rails/generators/rails/generator/generator_generator.rb b/railties/lib/rails/generators/rails/generator/generator_generator.rb index 5b5d1884bc..3e0a442bda 100644 --- a/railties/lib/rails/generators/rails/generator/generator_generator.rb +++ b/railties/lib/rails/generators/rails/generator/generator_generator.rb @@ -14,9 +14,9 @@ module Rails def generator_dir if options[:namespace] - File.join("lib", "generators", file_name) + File.join("lib", "generators", regular_class_path, file_name) else - File.join("lib", "generators") + File.join("lib", "generators", regular_class_path) end end diff --git a/railties/lib/rails/generators/rails/helper/templates/helper.rb b/railties/lib/rails/generators/rails/helper/templates/helper.rb index 3fe2ecdc74..b4173151b4 100644 --- a/railties/lib/rails/generators/rails/helper/templates/helper.rb +++ b/railties/lib/rails/generators/rails/helper/templates/helper.rb @@ -1,2 +1,4 @@ +<% module_namespacing do -%> module <%= class_name %>Helper end +<% end -%> diff --git a/railties/lib/rails/generators/rails/migration/USAGE b/railties/lib/rails/generators/rails/migration/USAGE index d21c81b760..af74963b01 100644 --- a/railties/lib/rails/generators/rails/migration/USAGE +++ b/railties/lib/rails/generators/rails/migration/USAGE @@ -18,12 +18,12 @@ Example: This will create the AddTitleBodyToPost in db/migrate/20080514090912_add_title_body_to_post.rb with this in the Up migration: - add_column :posts, :title, :string - add_column :posts, :body, :text + add_column :posts, :title, :string + add_column :posts, :body, :text add_column :posts, :published, :boolean And this in the Down migration: - remove_column :posts, :published - remove_column :posts, :body + remove_column :posts, :published + remove_column :posts, :body remove_column :posts, :title diff --git a/railties/lib/rails/generators/rails/plugin/USAGE b/railties/lib/rails/generators/rails/plugin/USAGE index 00a429c585..1bcfcf190d 100644 --- a/railties/lib/rails/generators/rails/plugin/USAGE +++ b/railties/lib/rails/generators/rails/plugin/USAGE @@ -1,6 +1,6 @@ Description: Stubs out a new plugin at vendor/plugins. Pass the plugin name, either - CamelCased or under_scored, as an argument. + CamelCased or under_scored, as an argument. Example: `rails generate plugin BrowserFilters` diff --git a/railties/lib/rails/generators/rails/plugin/plugin_generator.rb b/railties/lib/rails/generators/rails/plugin/plugin_generator.rb index 40ed2062d3..97f681d826 100644 --- a/railties/lib/rails/generators/rails/plugin/plugin_generator.rb +++ b/railties/lib/rails/generators/rails/plugin/plugin_generator.rb @@ -1,3 +1,4 @@ + require 'rails/generators/rails/generator/generator_generator' module Rails @@ -5,6 +6,12 @@ module Rails class PluginGenerator < NamedBase class_option :tasks, :desc => "When supplied creates tasks base files." + def show_deprecation + return unless behavior == :invoke + message = "Plugin generator is deprecated, please use 'rails plugin new' command to generate plugin structure." + ActiveSupport::Deprecation.warn message + end + check_class_collision def create_root_files diff --git a/railties/lib/rails/generators/rails/plugin/templates/Rakefile.tt b/railties/lib/rails/generators/rails/plugin/templates/Rakefile.tt index 733e321c94..77149ae351 100644 --- a/railties/lib/rails/generators/rails/plugin/templates/Rakefile.tt +++ b/railties/lib/rails/generators/rails/plugin/templates/Rakefile.tt @@ -1,4 +1,4 @@ -require 'rake' +#!/usr/bin/env rake require 'rake/testtask' require 'rake/rdoctask' diff --git a/railties/lib/rails/generators/rails/plugin_new/USAGE b/railties/lib/rails/generators/rails/plugin_new/USAGE new file mode 100644 index 0000000000..9a7bf9f396 --- /dev/null +++ b/railties/lib/rails/generators/rails/plugin_new/USAGE @@ -0,0 +1,10 @@ +Description: + The 'rails plugin new' command creates a skeleton for developing any + kind of Rails extension with ability to run tests using dummy Rails + application. + +Example: + rails plugin new ~/Code/Ruby/blog + + This generates a skeletal Rails plugin in ~/Code/Ruby/blog. + See the README in the newly created plugin to get going. diff --git a/railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb b/railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb new file mode 100644 index 0000000000..3cf8410d1e --- /dev/null +++ b/railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb @@ -0,0 +1,290 @@ +require 'active_support/core_ext/hash/slice' +require "rails/generators/rails/app/app_generator" +require 'date' + +module Rails + class PluginBuilder + def rakefile + template "Rakefile" + end + + def app + if options[:mountable] + directory "app" + template "#{app_templates_dir}/app/views/layouts/application.html.erb.tt", + "app/views/layouts/#{name}/application.html.erb" + end + end + + def readme + template "README.rdoc" + end + + def gemfile + template "Gemfile" + end + + def license + template "MIT-LICENSE" + end + + def gemspec + template "%name%.gemspec" + end + + def gitignore + copy_file "gitignore", ".gitignore" + end + + def lib + template "lib/%name%.rb" + template "lib/tasks/%name%_tasks.rake" + if full? + template "lib/%name%/engine.rb" + end + end + + def config + template "config/routes.rb" if full? + end + + def test + template "test/test_helper.rb" + template "test/%name%_test.rb" + append_file "Rakefile", <<-EOF +#{rakefile_test_tasks} + +task :default => :test + EOF + if full? + template "test/integration/navigation_test.rb" + end + end + + def generate_test_dummy(force = false) + opts = (options || {}).slice(:skip_active_record, :skip_javascript, :database, :javascript, :quiet, :pretend, :force, :skip) + opts[:force] = force + + invoke Rails::Generators::AppGenerator, + [ File.expand_path(dummy_path, destination_root) ], opts + end + + def test_dummy_config + template "rails/boot.rb", "#{dummy_path}/config/boot.rb", :force => true + template "rails/application.rb", "#{dummy_path}/config/application.rb", :force => true + if mountable? + template "rails/routes.rb", "#{dummy_path}/config/routes.rb", :force => true + end + end + + def test_dummy_clean + inside dummy_path do + remove_file ".gitignore" + remove_file "db/seeds.rb" + remove_file "doc" + remove_file "Gemfile" + remove_file "lib/tasks" + remove_file "public/images/rails.png" + remove_file "public/index.html" + remove_file "public/robots.txt" + remove_file "README" + remove_file "test" + remove_file "vendor" + end + end + + def stylesheets + empty_directory_with_gitkeep "public/stylesheets" if options[:mountable] + end + + def javascripts + return unless options[:mountable] + + empty_directory "#{app_templates_dir}/public/javascripts" + + unless options[:skip_javascript] + copy_file "#{app_templates_dir}/public/javascripts/#{options[:javascript]}.js", "public/javascripts/#{options[:javascript]}.js" + copy_file "#{app_templates_dir}/public/javascripts/#{options[:javascript]}_ujs.js", "public/javascripts/rails.js" + + if options[:javascript] == "prototype" + copy_file "#{app_templates_dir}/public/javascripts/controls.js", "public/javascripts/controls.js" + copy_file "#{app_templates_dir}/public/javascripts/dragdrop.js", "public/javascripts/dragdrop.js" + copy_file "#{app_templates_dir}/public/javascripts/effects.js", "public/javascripts/effects.js" + end + end + + copy_file "#{app_templates_dir}/public/javascripts/application.js", "public/javascripts/application.js" + end + + def script(force = false) + directory "script", :force => force do |content| + "#{shebang}\n" + content + end + chmod "script", 0755, :verbose => false + end + end + + module Generators + class PluginNewGenerator < AppBase + add_shared_options_for "plugin" + + alias_method :plugin_path, :app_path + + class_option :dummy_path, :type => :string, :default => "test/dummy", + :desc => "Create dummy application at given path" + + class_option :full, :type => :boolean, :default => false, + :desc => "Generate rails engine with integration tests" + + class_option :mountable, :type => :boolean, :default => false, + :desc => "Generate mountable isolated application" + + class_option :skip_gemspec, :type => :boolean, :default => false, + :desc => "Skip gemspec file" + + def initialize(*args) + raise Error, "Options should be given after the plugin name. For details run: rails plugin --help" if args[0].blank? + + @dummy_path = nil + super + end + + public_task :create_root + + def create_root_files + build(:readme) + build(:rakefile) + build(:gemspec) unless options[:skip_gemspec] + build(:license) + build(:gitignore) unless options[:skip_git] + build(:gemfile) unless options[:skip_gemfile] + end + + def create_app_files + build(:app) + end + + def create_config_files + build(:config) + end + + def create_lib_files + build(:lib) + end + + def create_public_stylesheets_files + build(:stylesheets) + end + + def create_javascript_files + build(:javascripts) + end + + def create_script_files + build(:script) + end + + def create_test_files + build(:test) unless options[:skip_test_unit] + end + + def create_test_dummy_files + return if options[:skip_test_unit] + create_dummy_app + end + + def finish_template + build(:leftovers) + end + + public_task :apply_rails_template, :bundle_if_dev_or_edge + + protected + def app_templates_dir + "../../app/templates" + end + + def create_dummy_app(path = nil) + dummy_path(path) if path + + say_status :vendor_app, dummy_path + mute do + build(:generate_test_dummy) + store_application_definition! + build(:test_dummy_config) + build(:test_dummy_clean) + # ensure that script/rails has proper dummy_path + build(:script, true) + end + end + + def full? + options[:full] || options[:mountable] + end + + def mountable? + options[:mountable] + end + + def self.banner + "rails plugin new #{self.arguments.map(&:usage).join(' ')} [options]" + end + + def name + @name ||= File.basename(destination_root) + end + + def camelized + @camelized ||= name.gsub(/\W/, '_').squeeze('_').camelize + end + + def valid_const? + if camelized =~ /^\d/ + raise Error, "Invalid plugin name #{name}. Please give a name which does not start with numbers." + elsif RESERVED_NAMES.include?(name) + raise Error, "Invalid plugin name #{name}. Please give a name which does not match one of the reserved rails words." + elsif Object.const_defined?(camelized) + raise Error, "Invalid plugin name #{name}, constant #{camelized} is already in use. Please choose another application name." + end + end + + def application_definition + @application_definition ||= begin + + dummy_application_path = File.expand_path("#{dummy_path}/config/application.rb", destination_root) + unless options[:pretend] || !File.exists?(dummy_application_path) + contents = File.read(dummy_application_path) + contents[(contents.index("module Dummy"))..-1] + end + end + end + alias :store_application_definition! :application_definition + + def get_builder_class + defined?(::PluginBuilder) ? ::PluginBuilder : Rails::PluginBuilder + end + + def rakefile_test_tasks + <<-RUBY +require 'rake/testtask' + +Rake::TestTask.new(:test) do |t| + t.libs << 'lib' + t.libs << 'test' + t.pattern = 'test/**/*_test.rb' + t.verbose = false +end + RUBY + end + + def dummy_path(path = nil) + @dummy_path = path if path + @dummy_path || options[:dummy_path] + end + + def mute(&block) + shell.mute(&block) + end + end + end +end diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/%name%.gemspec b/railties/lib/rails/generators/rails/plugin_new/templates/%name%.gemspec new file mode 100644 index 0000000000..3d9bfb22c7 --- /dev/null +++ b/railties/lib/rails/generators/rails/plugin_new/templates/%name%.gemspec @@ -0,0 +1,9 @@ +# Provide a simple gemspec so you can easily use your +# project in your rails apps through git. +Gem::Specification.new do |s| + s.name = "<%= name %>" + s.summary = "Insert <%= camelized %> summary." + s.description = "Insert <%= camelized %> description." + s.files = Dir["lib/**/*"] + ["MIT-LICENSE", "Rakefile", "README.rdoc"] + s.version = "0.0.1" +end diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/Gemfile b/railties/lib/rails/generators/rails/plugin_new/templates/Gemfile new file mode 100644 index 0000000000..29900c93dc --- /dev/null +++ b/railties/lib/rails/generators/rails/plugin_new/templates/Gemfile @@ -0,0 +1,11 @@ +source "http://rubygems.org" + +<%= rails_gemfile_entry -%> + +<% if full? -%> +<%= database_gemfile_entry -%> +<% end -%> + +if RUBY_VERSION < '1.9' + gem "ruby-debug", ">= 0.10.3" +end diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/MIT-LICENSE b/railties/lib/rails/generators/rails/plugin_new/templates/MIT-LICENSE new file mode 100644 index 0000000000..d7a9109894 --- /dev/null +++ b/railties/lib/rails/generators/rails/plugin_new/templates/MIT-LICENSE @@ -0,0 +1,20 @@ +Copyright <%= Date.today.year %> YOURNAME + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/README.rdoc b/railties/lib/rails/generators/rails/plugin_new/templates/README.rdoc new file mode 100644 index 0000000000..301d647731 --- /dev/null +++ b/railties/lib/rails/generators/rails/plugin_new/templates/README.rdoc @@ -0,0 +1,3 @@ += <%= camelized %> + +This project rocks and uses MIT-LICENSE.
\ No newline at end of file diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/Rakefile b/railties/lib/rails/generators/rails/plugin_new/templates/Rakefile new file mode 100755 index 0000000000..5704e75a29 --- /dev/null +++ b/railties/lib/rails/generators/rails/plugin_new/templates/Rakefile @@ -0,0 +1,21 @@ +#!/usr/bin/env rake +begin + require 'bundler/setup' +rescue LoadError + puts 'You must `gem install bundler` and `bundle install` to run rake tasks' +end + +require 'rake/rdoctask' + +Rake::RDocTask.new(:rdoc) do |rdoc| + rdoc.rdoc_dir = 'rdoc' + rdoc.title = '<%= camelized %>' + rdoc.options << '--line-numbers' << '--inline-source' + rdoc.rdoc_files.include('README.rdoc') + rdoc.rdoc_files.include('lib/**/*.rb') +end + +<% if full? && !options[:skip_active_record] -%> +APP_RAKEFILE = File.expand_path("../<%= dummy_path -%>/Rakefile", __FILE__) +load 'rails/tasks/engine.rake' +<% end %> diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/app/controllers/%name%/application_controller.rb.tt b/railties/lib/rails/generators/rails/plugin_new/templates/app/controllers/%name%/application_controller.rb.tt new file mode 100644 index 0000000000..448ad7f989 --- /dev/null +++ b/railties/lib/rails/generators/rails/plugin_new/templates/app/controllers/%name%/application_controller.rb.tt @@ -0,0 +1,4 @@ +module <%= camelized %> + class ApplicationController < ActionController::Base + end +end diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/app/helpers/%name%/application_helper.rb.tt b/railties/lib/rails/generators/rails/plugin_new/templates/app/helpers/%name%/application_helper.rb.tt new file mode 100644 index 0000000000..40ae9f52c2 --- /dev/null +++ b/railties/lib/rails/generators/rails/plugin_new/templates/app/helpers/%name%/application_helper.rb.tt @@ -0,0 +1,4 @@ +module <%= camelized %> + module ApplicationHelper + end +end diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/config/routes.rb b/railties/lib/rails/generators/rails/plugin_new/templates/config/routes.rb new file mode 100644 index 0000000000..8e158d5831 --- /dev/null +++ b/railties/lib/rails/generators/rails/plugin_new/templates/config/routes.rb @@ -0,0 +1,6 @@ +<% if mountable? -%> +<%= camelized %>::Engine.routes.draw do +<% else -%> +Rails.application.routes.draw do +<% end -%> +end diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/gitignore b/railties/lib/rails/generators/rails/plugin_new/templates/gitignore new file mode 100644 index 0000000000..1463de6dfb --- /dev/null +++ b/railties/lib/rails/generators/rails/plugin_new/templates/gitignore @@ -0,0 +1,6 @@ +.bundle/ +log/*.log +pkg/ +test/dummy/db/*.sqlite3 +test/dummy/log/*.log +test/dummy/tmp/
\ No newline at end of file diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/lib/%name%.rb b/railties/lib/rails/generators/rails/plugin_new/templates/lib/%name%.rb new file mode 100644 index 0000000000..2d3bdc510c --- /dev/null +++ b/railties/lib/rails/generators/rails/plugin_new/templates/lib/%name%.rb @@ -0,0 +1,6 @@ +<% if full? -%> +require "<%= name %>/engine" + +<% end -%> +module <%= camelized %> +end diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/lib/%name%/engine.rb b/railties/lib/rails/generators/rails/plugin_new/templates/lib/%name%/engine.rb new file mode 100644 index 0000000000..aa8ea77bae --- /dev/null +++ b/railties/lib/rails/generators/rails/plugin_new/templates/lib/%name%/engine.rb @@ -0,0 +1,7 @@ +module <%= camelized %> + class Engine < Rails::Engine +<% if mountable? -%> + isolate_namespace <%= camelized %> +<% end -%> + end +end diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/lib/tasks/%name%_tasks.rake b/railties/lib/rails/generators/rails/plugin_new/templates/lib/tasks/%name%_tasks.rake new file mode 100644 index 0000000000..7121f5ae23 --- /dev/null +++ b/railties/lib/rails/generators/rails/plugin_new/templates/lib/tasks/%name%_tasks.rake @@ -0,0 +1,4 @@ +# desc "Explaining what the task does" +# task :<%= name %> do +# # Task goes here +# end diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/rails/application.rb b/railties/lib/rails/generators/rails/plugin_new/templates/rails/application.rb new file mode 100644 index 0000000000..8b68280a5e --- /dev/null +++ b/railties/lib/rails/generators/rails/plugin_new/templates/rails/application.rb @@ -0,0 +1,16 @@ +require File.expand_path('../boot', __FILE__) + +<% unless options[:skip_active_record] -%> +require 'rails/all' +<% else -%> +# require "active_record/railtie" +require "action_controller/railtie" +require "action_mailer/railtie" +require "active_resource/railtie" +require "rails/test_unit/railtie" +<% end -%> + +Bundler.require +require "<%= name %>" + +<%= application_definition %> diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/rails/boot.rb b/railties/lib/rails/generators/rails/plugin_new/templates/rails/boot.rb new file mode 100644 index 0000000000..eba0681370 --- /dev/null +++ b/railties/lib/rails/generators/rails/plugin_new/templates/rails/boot.rb @@ -0,0 +1,10 @@ +require 'rubygems' +gemfile = File.expand_path('../../../../Gemfile', __FILE__) + +if File.exist?(gemfile) + ENV['BUNDLE_GEMFILE'] = gemfile + require 'bundler' + Bundler.setup +end + +$:.unshift File.expand_path('../../../../lib', __FILE__)
\ No newline at end of file diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/rails/routes.rb b/railties/lib/rails/generators/rails/plugin_new/templates/rails/routes.rb new file mode 100644 index 0000000000..730ee31c3d --- /dev/null +++ b/railties/lib/rails/generators/rails/plugin_new/templates/rails/routes.rb @@ -0,0 +1,4 @@ +Rails.application.routes.draw do + + mount <%= camelized %>::Engine => "/<%= name %>" +end diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/script/rails.tt b/railties/lib/rails/generators/rails/plugin_new/templates/script/rails.tt new file mode 100644 index 0000000000..ebd5a77dd5 --- /dev/null +++ b/railties/lib/rails/generators/rails/plugin_new/templates/script/rails.tt @@ -0,0 +1,5 @@ +#!/usr/bin/env ruby +# This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application. + +ENGINE_PATH = File.expand_path('../..', __FILE__) +load File.expand_path('../../<%= dummy_path %>/script/rails', __FILE__) diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/test/%name%_test.rb b/railties/lib/rails/generators/rails/plugin_new/templates/test/%name%_test.rb new file mode 100644 index 0000000000..0a8bbd4aaf --- /dev/null +++ b/railties/lib/rails/generators/rails/plugin_new/templates/test/%name%_test.rb @@ -0,0 +1,7 @@ +require 'test_helper' + +class <%= camelized %>Test < ActiveSupport::TestCase + test "truth" do + assert_kind_of Module, <%= camelized %> + end +end diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/test/integration/navigation_test.rb b/railties/lib/rails/generators/rails/plugin_new/templates/test/integration/navigation_test.rb new file mode 100644 index 0000000000..dd4d2da4eb --- /dev/null +++ b/railties/lib/rails/generators/rails/plugin_new/templates/test/integration/navigation_test.rb @@ -0,0 +1,13 @@ +require 'test_helper' + +class NavigationTest < ActionDispatch::IntegrationTest +<% unless options[:skip_active_record] -%> + fixtures :all +<% end -%> + + # Replace this with your real tests. + test "the truth" do + assert true + end +end + diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/test/test_helper.rb b/railties/lib/rails/generators/rails/plugin_new/templates/test/test_helper.rb new file mode 100644 index 0000000000..dcd3b276e3 --- /dev/null +++ b/railties/lib/rails/generators/rails/plugin_new/templates/test/test_helper.rb @@ -0,0 +1,10 @@ +# Configure Rails Environment +ENV["RAILS_ENV"] = "test" + +require File.expand_path("../dummy/config/environment.rb", __FILE__) +require "rails/test_help" + +Rails.backtrace_cleaner.remove_silencers! + +# Load support files +Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f } diff --git a/railties/lib/rails/generators/rails/resource/resource_generator.rb b/railties/lib/rails/generators/rails/resource/resource_generator.rb index fc070026d6..c7345f3cfb 100644 --- a/railties/lib/rails/generators/rails/resource/resource_generator.rb +++ b/railties/lib/rails/generators/rails/resource/resource_generator.rb @@ -16,9 +16,9 @@ module Rails def add_resource_route return if options[:actions].present? - route_config = class_path.collect{|namespace| "namespace :#{namespace} do " }.join(" ") + route_config = regular_class_path.collect{|namespace| "namespace :#{namespace} do " }.join(" ") route_config << "resources :#{file_name.pluralize}" - route_config << " end" * class_path.size + route_config << " end" * regular_class_path.size route route_config end end diff --git a/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb b/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb index b21340f755..b5317a055b 100644 --- a/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb +++ b/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb @@ -1,3 +1,4 @@ +<% module_namespacing do -%> class <%= controller_class_name %>Controller < ApplicationController # GET <%= route_url %> # GET <%= route_url %>.xml @@ -81,3 +82,4 @@ class <%= controller_class_name %>Controller < ApplicationController end end end +<% end -%> diff --git a/railties/lib/rails/generators/resource_helpers.rb b/railties/lib/rails/generators/resource_helpers.rb index 829f4b200a..de01c858dd 100644 --- a/railties/lib/rails/generators/resource_helpers.rb +++ b/railties/lib/rails/generators/resource_helpers.rb @@ -17,7 +17,7 @@ module Rails def initialize(*args) #:nodoc: super - if name == name.pluralize && !options[:force_plural] + if name == name.pluralize && name.singularize != name.pluralize && !options[:force_plural] unless ResourceHelpers.skip_warn say "Plural version of the model detected, using singularized version. Override with --force-plural." ResourceHelpers.skip_warn = true @@ -34,7 +34,7 @@ module Rails attr_reader :controller_name def controller_class_path - @class_path + class_path end def controller_file_name @@ -46,14 +46,14 @@ module Rails end def controller_class_name - @controller_class_name ||= (controller_class_path + [controller_file_name]).map!{ |m| m.camelize }.join('::') + (controller_class_path + [controller_file_name]).map!{ |m| m.camelize }.join('::') end def controller_i18n_scope @controller_i18n_scope ||= controller_file_path.gsub('/', '.') end - # Loads the ORM::Generators::ActiveModel class. This class is responsable + # Loads the ORM::Generators::ActiveModel class. This class is responsible # to tell scaffold entities how to generate an specific method for the # ORM. Check Rails::Generators::ActiveModel for more information. def orm_class diff --git a/railties/lib/rails/generators/test_case.rb b/railties/lib/rails/generators/test_case.rb index 3376b422cb..ee85b70bb5 100644 --- a/railties/lib/rails/generators/test_case.rb +++ b/railties/lib/rails/generators/test_case.rb @@ -1,6 +1,7 @@ require 'active_support/core_ext/class/attribute' require 'active_support/core_ext/module/delegation' require 'active_support/core_ext/hash/reverse_merge' +require 'active_support/core_ext/kernel/reporting' require 'rails/generators' require 'fileutils' @@ -65,25 +66,6 @@ module Rails self.destination_root = path end - # Captures the given stream and returns it: - # - # stream = capture(:stdout){ puts "Cool" } - # stream # => "Cool\n" - # - def capture(stream) - begin - stream = stream.to_s - eval "$#{stream} = StringIO.new" - yield - result = eval("$#{stream}").string - ensure - eval("$#{stream} = #{stream.upcase}") - end - - result - end - alias :silence :capture - # Asserts a given file exists. You need to supply an absolute path or a path relative # to the configured destination: # @@ -132,7 +114,7 @@ module Rails end alias :assert_no_directory :assert_no_file - # Asserts a given file does not exist. You need to supply an absolute path or a + # Asserts a given migration exists. You need to supply an absolute path or a # path relative to the configured destination: # # assert_migration "db/migrate/create_products.rb" diff --git a/railties/lib/rails/generators/test_unit/controller/templates/functional_test.rb b/railties/lib/rails/generators/test_unit/controller/templates/functional_test.rb index 0d4185846d..11a73ebad7 100644 --- a/railties/lib/rails/generators/test_unit/controller/templates/functional_test.rb +++ b/railties/lib/rails/generators/test_unit/controller/templates/functional_test.rb @@ -1,5 +1,6 @@ require 'test_helper' +<% module_namespacing do -%> class <%= class_name %>ControllerTest < ActionController::TestCase <% if actions.empty? -%> # Replace this with your real tests. @@ -16,3 +17,4 @@ class <%= class_name %>ControllerTest < ActionController::TestCase <% end -%> <% end -%> end +<% end -%> diff --git a/railties/lib/rails/generators/test_unit/helper/templates/helper_test.rb b/railties/lib/rails/generators/test_unit/helper/templates/helper_test.rb index 591e40900e..7d37bda0f9 100644 --- a/railties/lib/rails/generators/test_unit/helper/templates/helper_test.rb +++ b/railties/lib/rails/generators/test_unit/helper/templates/helper_test.rb @@ -1,4 +1,6 @@ require 'test_helper' +<% module_namespacing do -%> class <%= class_name %>HelperTest < ActionView::TestCase end +<% end -%> diff --git a/railties/lib/rails/generators/test_unit/mailer/templates/functional_test.rb b/railties/lib/rails/generators/test_unit/mailer/templates/functional_test.rb index 80ac7f0feb..b62c7fd279 100644 --- a/railties/lib/rails/generators/test_unit/mailer/templates/functional_test.rb +++ b/railties/lib/rails/generators/test_unit/mailer/templates/functional_test.rb @@ -1,5 +1,6 @@ require 'test_helper' +<% module_namespacing do -%> class <%= class_name %>Test < ActionMailer::TestCase <% for action in actions -%> test "<%= action %>" do @@ -18,3 +19,4 @@ class <%= class_name %>Test < ActionMailer::TestCase end <% end -%> end +<% end -%> diff --git a/railties/lib/rails/generators/test_unit/model/templates/fixtures.yml b/railties/lib/rails/generators/test_unit/model/templates/fixtures.yml index a30132bc99..6465a6a6e2 100644 --- a/railties/lib/rails/generators/test_unit/model/templates/fixtures.yml +++ b/railties/lib/rails/generators/test_unit/model/templates/fixtures.yml @@ -1,4 +1,4 @@ -# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html +# Read about fixtures at http://api.rubyonrails.org/classes/Fixtures.html <% unless attributes.empty? -%> one: diff --git a/railties/lib/rails/generators/test_unit/model/templates/unit_test.rb b/railties/lib/rails/generators/test_unit/model/templates/unit_test.rb index 3e0bc29d3a..6f79879838 100644 --- a/railties/lib/rails/generators/test_unit/model/templates/unit_test.rb +++ b/railties/lib/rails/generators/test_unit/model/templates/unit_test.rb @@ -1,8 +1,10 @@ require 'test_helper' +<% module_namespacing do -%> class <%= class_name %>Test < ActiveSupport::TestCase # Replace this with your real tests. test "the truth" do assert true end end +<% end -%> diff --git a/railties/lib/rails/generators/test_unit/observer/templates/unit_test.rb b/railties/lib/rails/generators/test_unit/observer/templates/unit_test.rb index 03f6d5666e..cd116f5ce9 100644 --- a/railties/lib/rails/generators/test_unit/observer/templates/unit_test.rb +++ b/railties/lib/rails/generators/test_unit/observer/templates/unit_test.rb @@ -1,8 +1,10 @@ require 'test_helper' +<% module_namespacing do -%> class <%= class_name %>ObserverTest < ActiveSupport::TestCase # Replace this with your real tests. test "the truth" do assert true end end +<% end -%> diff --git a/railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb b/railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb index f23e495450..964d59d84c 100644 --- a/railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb +++ b/railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb @@ -1,5 +1,6 @@ require 'test_helper' +<% module_namespacing do -%> class <%= controller_class_name %>ControllerTest < ActionController::TestCase setup do @<%= singular_table_name %> = <%= table_name %>(:one) @@ -47,3 +48,4 @@ class <%= controller_class_name %>ControllerTest < ActionController::TestCase assert_redirected_to <%= index_helper %>_path end end +<% end -%> diff --git a/railties/lib/rails/info.rb b/railties/lib/rails/info.rb index 6cbd1f21c0..d05e031f56 100644 --- a/railties/lib/rails/info.rb +++ b/railties/lib/rails/info.rb @@ -1,5 +1,4 @@ require "cgi" -require "active_support/core_ext/cgi" module Rails module Info diff --git a/railties/lib/rails/info_controller.rb b/railties/lib/rails/info_controller.rb index 196eeb4a6c..6b4bdb2921 100644 --- a/railties/lib/rails/info_controller.rb +++ b/railties/lib/rails/info_controller.rb @@ -1,6 +1,6 @@ class Rails::InfoController < ActionController::Base def properties - if consider_all_requests_local? || local_request? + if consider_all_requests_local? || request.local? render :inline => Rails::Info.to_html else render :text => '<p>For security purposes, this information is only available to local requests.</p>', :status => :forbidden diff --git a/railties/lib/rails/info_routes.rb b/railties/lib/rails/info_routes.rb deleted file mode 100644 index b5c4e4c1e0..0000000000 --- a/railties/lib/rails/info_routes.rb +++ /dev/null @@ -1,3 +0,0 @@ -Rails.application.routes.draw do - match '/rails/info/properties' => "rails/info#properties" -end diff --git a/railties/lib/rails/paths.rb b/railties/lib/rails/paths.rb index d303212f52..d15887f561 100644 --- a/railties/lib/rails/paths.rb +++ b/railties/lib/rails/paths.rb @@ -2,15 +2,17 @@ require 'set' module Rails module Paths - module PathParent - attr_reader :children - + module PathParent #:nodoc: def method_missing(id, *args) - name = id.to_s + match = id.to_s.match(/^(.*)=$/) + full = [@current, $1 || id].compact.join("/") + + ActiveSupport::Deprecation.warn 'config.paths.app.controller API is deprecated in ' << + 'favor of config.paths["app/controller"] API.' - if name =~ /^(.*)=$/ || args.any? - @children[$1 || name] = Path.new(@root, *args) - elsif path = @children[name] + if match || args.any? + @root[full] = Path.new(@root, full, *args) + elsif path = @root[full] path else super @@ -18,22 +20,72 @@ module Rails end end - class Root + # This object is an extended hash that behaves as root of the Rails::Paths system. + # It allows you to collect information about how you want to structure your application + # paths by a Hash like API. It requires you to give a physical path on initialization. + # + # root = Root.new + # root.add "app/controllers", :eager_load => true + # + # The command above creates a new root object and add "app/controllers" as a path. + # This means we can get a Path object back like below: + # + # path = root["app/controllers"] + # path.eager_load? #=> true + # path.is_a?(Rails::Paths::Path) #=> true + # + # The Path object is simply an array and allows you to easily add extra paths: + # + # path.is_a?(Array) #=> true + # path.inspect #=> ["app/controllers"] + # + # path << "lib/controllers" + # path.inspect #=> ["app/controllers", "lib/controllers"] + # + # Notice that when you add a path using #add, the path object created already + # contains the path with the same path value given to #add. In some situations, + # you may not want this behavior, so you can give :with as option. + # + # root.add "config/routes", :with => "config/routes.rb" + # root["config/routes"].inspect #=> ["config/routes.rb"] + # + # #add also accepts the following options as argument: eager_load, autoload, + # autoload_once and glob. + # + # Finally, the Path object also provides a few helpers: + # + # root = Root.new + # root.path = "/rails" + # root.add "app/controllers" + # + # root["app/controllers"].expanded #=> ["/rails/app/controllers"] + # root["app/controllers"].existent #=> ["/rails/app/controllers"] + # + # Check the Path documentation for more information. + class Root < ::Hash include PathParent - attr_accessor :path def initialize(path) raise if path.is_a?(Array) - @children = {} + @current = nil @path = path @root = self - @all_paths = [] + super() + end + + def []=(path, value) + value = Path.new(self, path, value) unless value.is_a?(Path) + super(path, value) + end + + def add(path, options={}) + with = options[:with] || path + self[path] = Path.new(self, path, with, options) end def all_paths - @all_paths.uniq! - @all_paths + values.tap { |v| v.uniq! } end def autoload_once @@ -52,68 +104,54 @@ module Rails filter_by(:load_path?) end - def push(*) - raise "Application root can only have one physical path" - end - - alias unshift push - alias << push - alias concat push - protected def filter_by(constraint) all = [] all_paths.each do |path| if path.send(constraint) - paths = path.paths - paths -= path.children.values.map { |p| p.send(constraint) ? [] : p.paths }.flatten + paths = path.existent + paths -= path.children.map { |p| p.send(constraint) ? [] : p.existent }.flatten all.concat(paths) end end all.uniq! - all.reject! { |p| !File.exists?(p) } all end end - class Path - include PathParent, Enumerable + class Path < Array + include PathParent attr_reader :path attr_accessor :glob - def initialize(root, *paths) - options = paths.last.is_a?(::Hash) ? paths.pop : {} - @children = {} + def initialize(root, current, *paths) + options = paths.last.is_a?(::Hash) ? paths.pop : {} + super(paths.flatten) + + @current = current @root = root - @paths = paths.flatten @glob = options[:glob] - autoload_once! if options[:autoload_once] - eager_load! if options[:eager_load] - autoload! if options[:autoload] - load_path! if options[:load_path] - - @root.all_paths << self - end - - def each - to_a.each { |p| yield p } + options[:autoload_once] ? autoload_once! : skip_autoload_once! + options[:eager_load] ? eager_load! : skip_eager_load! + options[:autoload] ? autoload! : skip_autoload! + options[:load_path] ? load_path! : skip_load_path! end - def push(path) - @paths.push path + def children + keys = @root.keys.select { |k| k.include?(@current) } + keys.delete(@current) + @root.values_at(*keys.sort) end - alias << push - - def unshift(path) - @paths.unshift path + def first + expanded.first end - def concat(paths) - @paths.concat paths + def last + expanded.last end %w(autoload_once eager_load autoload load_path).each do |m| @@ -132,20 +170,36 @@ module Rails RUBY end - def paths + # Expands all paths against the root and return all unique values. + def expanded raise "You need to set a path root" unless @root.path + result = [] - result = @paths.map do |p| + each do |p| path = File.expand_path(p, @root.path) - @glob ? Dir[File.join(path, @glob)] : path + + if @glob + result.concat Dir[File.join(path, @glob)] + else + result << path + end end - result.flatten! result.uniq! result end - alias to_a paths + # Returns all expanded paths but only if they exist in the filesystem. + def existent + expanded.select { |f| File.exists?(f) } + end + + def paths + ActiveSupport::Deprecation.warn "paths is deprecated. Please call expand instead." + expanded + end + + alias to_a expanded end end -end
\ No newline at end of file +end diff --git a/railties/lib/rails/plugin.rb b/railties/lib/rails/plugin.rb index be229cc9a2..ceddd25eaa 100644 --- a/railties/lib/rails/plugin.rb +++ b/railties/lib/rails/plugin.rb @@ -16,8 +16,12 @@ module Rails # Besides this conceptual difference, the only difference between Rails::Engine and # Rails::Plugin is that plugins automatically load the file "init.rb" at the plugin # root during the boot process. - # + # class Plugin < Engine + def self.global_plugins + @global_plugins ||= [] + end + def self.inherited(base) raise "You cannot inherit from Rails::Plugin" end @@ -28,6 +32,11 @@ module Rails Dir["#{path}/*"].each do |plugin_path| plugin = new(plugin_path) next unless list.include?(plugin.name) || list.include?(:all) + if global_plugins.include?(plugin.name) + warn "WARNING: plugin #{plugin.name} from #{path} was not loaded. Plugin with the same name has been already loaded." + next + end + global_plugins << plugin.name plugins << plugin end end @@ -39,17 +48,8 @@ module Rails attr_reader :name, :path - def load_tasks - super - load_deprecated_tasks - end - - def load_deprecated_tasks - tasks = Dir["#{root}/{tasks,rails/tasks}/**/*.rake"].sort - if tasks.any? - ActiveSupport::Deprecation.warn "Rake tasks in #{tasks.to_sentence} are deprecated. Use lib/tasks instead" - tasks.each { |ext| load(ext) } - end + def railtie_name + name.to_s end def initialize(root) @@ -62,29 +62,28 @@ module Rails end initializer :handle_lib_autoload, :before => :set_load_path do |app| - paths = if app.config.reload_plugins + autoload = if app.config.reload_plugins config.autoload_paths else config.autoload_once_paths end - paths.concat config.paths.lib.to_a + autoload.concat paths["lib"].existent end initializer :load_init_rb, :before => :load_config_initializers do |app| - files = %w(rails/init.rb init.rb).map { |path| File.expand_path path, root } - if initrb = files.find { |path| File.file? path } - if initrb == files.first - ActiveSupport::Deprecation.warn "Use toplevel init.rb; rails/init.rb is deprecated: #{initrb}" - end + init_rb = File.expand_path("init.rb", root) + if File.file?(init_rb) config = app.config - eval(File.read(initrb), binding, initrb) + # TODO: think about evaling initrb in context of Engine (currently it's + # always evaled in context of Rails::Application) + eval(File.read(init_rb), binding, init_rb) end end initializer :sanity_check_railties_collision do if Engine.subclasses.map { |k| k.root.to_s }.include?(root.to_s) - raise "\"#{name}\" is a Railtie/Engine and cannot be installed as plugin" + raise "\"#{name}\" is a Railtie/Engine and cannot be installed as a plugin" end end end diff --git a/railties/lib/rails/rack/log_tailer.rb b/railties/lib/rails/rack/log_tailer.rb index 011ac6cecc..830d840894 100644 --- a/railties/lib/rails/rack/log_tailer.rb +++ b/railties/lib/rails/rack/log_tailer.rb @@ -19,7 +19,7 @@ module Rails def tail! @file.seek @cursor - if !@file.eof? + unless @file.eof? contents = @file.read @cursor = @file.tell $stdout.print contents diff --git a/railties/lib/rails/rack/logger.rb b/railties/lib/rails/rack/logger.rb index b3dc1f894c..3be262de08 100644 --- a/railties/lib/rails/rack/logger.rb +++ b/railties/lib/rails/rack/logger.rb @@ -19,9 +19,9 @@ module Rails def before_dispatch(env) request = ActionDispatch::Request.new(env) - path = request.fullpath + path = request.filtered_path - info "\n\nStarted #{env["REQUEST_METHOD"]} \"#{path}\" " \ + info "\n\nStarted #{request.request_method} \"#{path}\" " \ "for #{request.ip} at #{Time.now.to_default_s}" end diff --git a/railties/lib/rails/railtie.rb b/railties/lib/rails/railtie.rb index 8a6e2716dc..7fca565124 100644 --- a/railties/lib/rails/railtie.rb +++ b/railties/lib/rails/railtie.rb @@ -1,58 +1,45 @@ require 'rails/initializable' require 'rails/configuration' require 'active_support/inflector' -require 'active_support/deprecation' module Rails - # Railtie is the core of the Rails Framework and provides several hooks to extend + # Railtie is the core of the Rails framework and provides several hooks to extend # Rails and/or modify the initialization process. # # Every major component of Rails (Action Mailer, Action Controller, - # Action View, Active Record and Active Resource) are all Railties, so each of - # them is responsible to set their own initialization. This makes, for example, - # Rails absent of any Active Record hook, allowing any other ORM framework to hook in. + # Action View, Active Record and Active Resource) is a Railtie. Each of + # them is responsible for their own initialization. This makes Rails itself + # absent of any component hooks, allowing other components to be used in + # place of any of the Rails defaults. # # Developing a Rails extension does _not_ require any implementation of # Railtie, but if you need to interact with the Rails framework during - # or after boot, then Railtie is what you need to do that interaction. + # or after boot, then Railtie is needed. # - # For example, the following would need you to implement Railtie in your - # plugin: + # For example, an extension doing any of the following would require Railtie: # # * creating initializers - # * configuring a Rails framework or the Application, like setting a generator - # * adding Rails config.* keys to the environment - # * setting up a subscriber to the Rails +ActiveSupport::Notifications+ - # * adding rake tasks into rails + # * configuring a Rails framework for the application, like setting a generator + # * adding config.* keys to the environment + # * setting up a subscriber with ActiveSupport::Notifications + # * adding rake tasks # # == Creating your Railtie # - # Implementing Railtie in your Rails extension is done by creating a class - # Railtie that has your extension name and making sure that this gets loaded - # during boot time of the Rails stack. + # To extend Rails using Railtie, create a Railtie class which inherits + # from Rails::Railtie within your extension's namespace. This class must be + # loaded during the Rails boot process. # - # You can do this however you wish, but here is an example if you want to provide - # it for a gem that can be used with or without Rails: + # The following example demonstrates an extension which can be used with or without Rails. # - # * Create a file (say, lib/my_gem/railtie.rb) which contains class Railtie inheriting from - # Rails::Railtie and is namespaced to your gem: - # - # # lib/my_gem/railtie.rb - # module MyGem - # class Railtie < Rails::Railtie - # end + # # lib/my_gem/railtie.rb + # module MyGem + # class Railtie < Rails::Railtie # end + # end # - # * Require your own gem as well as rails in this file: - # - # # lib/my_gem/railtie.rb - # require 'my_gem' - # require 'rails' - # - # module MyGem - # class Railtie < Rails::Railtie - # end - # end + # # lib/my_gem.rb + # require 'my_gem/railtie' if defined?(Rails) # # == Initializers # @@ -84,10 +71,10 @@ module Rails # # class MyRailtie < Rails::Railtie # # Customize the ORM - # config.generators.orm :my_railtie_orm + # config.app_generators.orm :my_railtie_orm # # # Add a to_prepare block which is executed once in production - # # and before which request in development + # # and before each request in development # config.to_prepare do # MyRailtie.setup! # end @@ -98,7 +85,7 @@ module Rails # If your railtie has rake tasks, you can tell Rails to load them through the method # rake tasks: # - # class MyRailtie < Railtie + # class MyRailtie < Rails::Railtie # rake_tasks do # load "path/to/my_railtie.tasks" # end @@ -108,7 +95,7 @@ module Rails # your generators at a different location, you can specify in your Railtie a block which # will load them during normal generators lookup: # - # class MyRailtie < Railtie + # class MyRailtie < Rails::Railtie # generators do # require "path/to/my_railtie_generator" # end @@ -121,7 +108,7 @@ module Rails # described here can be used in all three. # # Be sure to look at the documentation of those specific classes for more information. - # + # class Railtie autoload :Configurable, "rails/railtie/configurable" autoload :Configuration, "rails/railtie/configuration" @@ -131,25 +118,19 @@ module Rails ABSTRACT_RAILTIES = %w(Rails::Railtie Rails::Plugin Rails::Engine Rails::Application) class << self + private :new + def subclasses @subclasses ||= [] end def inherited(base) unless base.abstract_railtie? - base.send(:include, self::Configurable) + base.send(:include, Railtie::Configurable) subclasses << base end end - def railtie_name(*) - ActiveSupport::Deprecation.warn "railtie_name is deprecated and has no effect", caller - end - - def log_subscriber(*) - ActiveSupport::Deprecation.warn "log_subscriber is deprecated and has no effect", caller - end - def rake_tasks(&blk) @rake_tasks ||= [] @rake_tasks << blk if blk @@ -171,6 +152,22 @@ module Rails def abstract_railtie? ABSTRACT_RAILTIES.include?(name) end + + def railtie_name(name = nil) + @railtie_name = name.to_s if name + @railtie_name ||= generate_railtie_name(self.name) + end + + protected + def generate_railtie_name(class_or_module) + ActiveSupport::Inflector.underscore(class_or_module).gsub("/", "_") + end + end + + delegate :railtie_name, :to => "self.class" + + def config + @config ||= Railtie::Configuration.new end def eager_load! @@ -182,6 +179,13 @@ module Rails def load_tasks self.class.rake_tasks.each(&:call) + + # load also tasks from all superclasses + klass = self.class.superclass + while klass.respond_to?(:rake_tasks) + klass.rake_tasks.each { |t| self.instance_exec(&t) } + klass = klass.superclass + end end def load_generators diff --git a/railties/lib/rails/railtie/configurable.rb b/railties/lib/rails/railtie/configurable.rb index a2eb938c5a..920ab67ff1 100644 --- a/railties/lib/rails/railtie/configurable.rb +++ b/railties/lib/rails/railtie/configurable.rb @@ -1,22 +1,32 @@ module Rails class Railtie module Configurable - def self.included(base) - base.extend ClassMethods - end + extend ActiveSupport::Concern module ClassMethods - def config - @config ||= Railtie::Configuration.new - end + delegate :config, :to => :instance def inherited(base) - raise "You cannot inherit from a Rails::Railtie child" + raise "You cannot inherit from a #{self.superclass.name} child" end - end - def config - self.class.config + def instance + @instance ||= new + end + + def respond_to?(*args) + super || instance.respond_to?(*args) + end + + def configure(&block) + class_eval(&block) + end + + protected + + def method_missing(*args, &block) + instance.send(*args, &block) + end end end end diff --git a/railties/lib/rails/railtie/configuration.rb b/railties/lib/rails/railtie/configuration.rb index 4e6f94c534..2c7b5bc048 100644 --- a/railties/lib/rails/railtie/configuration.rb +++ b/railties/lib/rails/railtie/configuration.rb @@ -16,47 +16,49 @@ module Rails @@app_middleware ||= Rails::Configuration::MiddlewareStackProxy.new end - # Holds generators configuration: + # This allows you to modify application's generators from Railties. # - # config.generators do |g| - # g.orm :datamapper, :migration => true - # g.template_engine :haml - # g.test_framework :rspec - # end - # - # If you want to disable color in console, do: - # - # config.generators.colorize_logging = false - # - def generators - @@generators ||= Rails::Configuration::Generators.new - if block_given? - yield @@generators - else - @@generators - end + # Values set on app_generators will become defaults for application, unless + # application overwrites them. + def app_generators + @@app_generators ||= Rails::Configuration::Generators.new + yield(@@app_generators) if block_given? + @@app_generators end + def generators(&block) #:nodoc + ActiveSupport::Deprecation.warn "config.generators in Rails::Railtie is deprecated. Please use config.app_generators instead." + app_generators(&block) + end + + # First configurable block to run. Called before any initializers are run. def before_configuration(&block) ActiveSupport.on_load(:before_configuration, :yield => true, &block) end + # Third configurable block to run. Does not run if config.cache_classes + # set to false. def before_eager_load(&block) ActiveSupport.on_load(:before_eager_load, :yield => true, &block) end + # Second configurable block to run. Called before frameworks initialize. def before_initialize(&block) ActiveSupport.on_load(:before_initialize, :yield => true, &block) end + # Last configurable block to run. Called after frameworks initialize. def after_initialize(&block) ActiveSupport.on_load(:after_initialize, :yield => true, &block) end + # Array of callbacks defined by #to_prepare. def to_prepare_blocks @@to_prepare_blocks ||= [] end + # Defines generic callbacks to run before #after_initialize. Useful for + # Rails::Railtie subclasses. def to_prepare(&blk) to_prepare_blocks << blk if blk end @@ -65,6 +67,13 @@ module Rails super || @@options.key?(name.to_sym) end + # static_asset_paths is a Hash containing asset_paths + # with associated public folders, like: + # { "/" => "/app/public", "/my_engine" => "app/engines/my_engine/public" } + def static_asset_paths + @@static_asset_paths ||= ActiveSupport::OrderedHash.new + end + private def method_missing(name, *args, &blk) @@ -78,4 +87,4 @@ module Rails end end end -end
\ No newline at end of file +end diff --git a/railties/lib/rails/ruby_version_check.rb b/railties/lib/rails/ruby_version_check.rb index e8d1d1e039..4d57c5973c 100644 --- a/railties/lib/rails/ruby_version_check.rb +++ b/railties/lib/rails/ruby_version_check.rb @@ -14,8 +14,7 @@ elsif RUBY_VERSION > '1.9' and RUBY_VERSION < '1.9.2' $stderr.puts <<-end_message Rails 3 doesn't officially support Ruby 1.9.1 since recent stable - releases have segfaulted the test suite. Please upgrade to Ruby 1.9.2 - before Rails 3 is released! + releases have segfaulted the test suite. Please upgrade to Ruby 1.9.2. You're running #{RUBY_DESCRIPTION} diff --git a/railties/lib/rails/script_rails_loader.rb b/railties/lib/rails/script_rails_loader.rb index 91672e5d81..7054089614 100644 --- a/railties/lib/rails/script_rails_loader.rb +++ b/railties/lib/rails/script_rails_loader.rb @@ -17,11 +17,11 @@ module Rails rescue SystemCallError # could not chdir, no problem just return end - + def self.in_rails_application? File.exists?(SCRIPT_RAILS) end - + def self.in_rails_application_subdirectory?(path = Pathname.new(Dir.pwd)) File.exists?(File.join(path, SCRIPT_RAILS)) || !path.root? && in_rails_application_subdirectory?(path.parent) end diff --git a/railties/lib/rails/tasks.rb b/railties/lib/rails/tasks.rb index 9807000578..af52014728 100644 --- a/railties/lib/rails/tasks.rb +++ b/railties/lib/rails/tasks.rb @@ -11,6 +11,7 @@ $VERBOSE = nil routes statistics tmp + railties ).each do |task| load "rails/tasks/#{task}.rake" end diff --git a/railties/lib/rails/tasks/documentation.rake b/railties/lib/rails/tasks/documentation.rake index c1b1a41d48..edd716d7d0 100644 --- a/railties/lib/rails/tasks/documentation.rake +++ b/railties/lib/rails/tasks/documentation.rake @@ -4,15 +4,15 @@ require 'rake/rdoctask' class RDocTaskWithoutDescriptions < Rake::RDocTask def define task rdoc_task_name - + task rerdoc_task_name => [clobber_task_name, rdoc_task_name] - + task clobber_task_name do rm_r rdoc_dir rescue nil end - + task :clobber => [clobber_task_name] - + directory @rdoc_dir task rdoc_task_name => [rdoc_target] file rdoc_target => @rdoc_files + [Rake.application.rakefile] do @@ -47,7 +47,7 @@ namespace :doc do rdoc.rdoc_files.include('app/**/*.rb') rdoc.rdoc_files.include('lib/**/*.rb') } - Rake::Task['doc:app'].comment = "Generate docs for the app -- also availble doc:rails, doc:guides, doc:plugins (options: TEMPLATE=/rdoc-template.rb, TITLE=\"Custom Title\")" + Rake::Task['doc:app'].comment = "Generate docs for the app -- also available doc:rails, doc:guides, doc:plugins (options: TEMPLATE=/rdoc-template.rb, TITLE=\"Custom Title\")" # desc 'Generate documentation for the Rails framework.' RDocTaskWithoutDescriptions.new("rails") { |rdoc| diff --git a/railties/lib/rails/tasks/engine.rake b/railties/lib/rails/tasks/engine.rake new file mode 100644 index 0000000000..2f0e7be896 --- /dev/null +++ b/railties/lib/rails/tasks/engine.rake @@ -0,0 +1,69 @@ +task "load_app" do + namespace :app do + load APP_RAKEFILE + end + + if !defined?(ENGINE_PATH) || !ENGINE_PATH + ENGINE_PATH = find_engine_path(APP_RAKEFILE) + end +end + +def app_task(name) + task name => [:load_app, "app:db:#{name}"] +end + +namespace :db do + app_task "reset" + + desc "Migrate the database (options: VERSION=x, VERBOSE=false)." + app_task "migrate" + app_task "migrate:up" + app_task "migrate:down" + app_task "migrate:redo" + app_task "migrate:reset" + + desc "Display status of migrations" + app_task "migrate:status" + + desc 'Create the database from config/database.yml for the current Rails.env (use db:create:all to create all dbs in the config)' + app_task "create" + app_task "create:all" + + desc 'Drops the database for the current Rails.env (use db:drop:all to drop all databases)' + app_task "drop" + app_task "drop:all" + + desc "Load fixtures into the current environment's database." + app_task "fixtures:load" + + desc "Rolls the schema back to the previous version (specify steps w/ STEP=n)." + app_task "rollback" + + desc "Create a db/schema.rb file that can be portably used against any DB supported by AR" + app_task "schema:dump" + + desc "Load a schema.rb file into the database" + app_task "schema:load" + + desc "Load the seed data from db/seeds.rb" + app_task "seed" + + desc "Create the database, load the schema, and initialize with the seed data (use db:reset to also drop the db first)" + app_task "setup" + + desc "Dump the database structure to an SQL file" + app_task "structure:dump" + + desc "Retrieves the current schema version number" + app_task "version" +end + +def find_engine_path(path) + return if path == "/" + + if Rails::Engine.find(path) + path + else + find_engine_path(File.expand_path('..', path)) + end +end diff --git a/railties/lib/rails/tasks/framework.rake b/railties/lib/rails/tasks/framework.rake index 443dacd739..5222b7bf50 100644 --- a/railties/lib/rails/tasks/framework.rake +++ b/railties/lib/rails/tasks/framework.rake @@ -1,21 +1,4 @@ namespace :rails do - namespace :freeze do - # desc "The rails:freeze:gems is deprecated, please use bundle install instead" - task :gems do - abort "The rails:freeze:gems is deprecated, please use bundle install instead" - end - - # desc 'The freeze:edge command has been deprecated, specify the path setting in your app Gemfile instead and bundle install' - task :edge do - abort 'The freeze:edge command has been deprecated, specify the path setting in your app Gemfile instead and bundle install' - end - end - - # desc 'The unfreeze command has been deprecated, please use bundler commands instead' - task :unfreeze do - abort 'The unfreeze command has been deprecated, please use bundler commands instead' - end - desc "Update both configs and public/javascripts from Rails (or use just update:javascripts or update:configs)" task :update => [ "update:configs", "update:javascripts", "update:scripts", "update:application_controller" ] @@ -77,7 +60,7 @@ namespace :rails do # desc "Update Prototype javascripts from your current rails install" task :javascripts do - invoke_from_app_generator :create_prototype_files + invoke_from_app_generator :create_javascript_files end # desc "Adds new scripts to the application script/ directory" diff --git a/railties/lib/rails/tasks/misc.rake b/railties/lib/rails/tasks/misc.rake index c6c22d83bf..e505b8c338 100644 --- a/railties/lib/rails/tasks/misc.rake +++ b/railties/lib/rails/tasks/misc.rake @@ -7,7 +7,7 @@ task :rails_env do end end -desc 'Generate a crytographically secure secret key (this is typically used to generate a secret for cookie sessions).' +desc 'Generate a cryptographically secure secret key (this is typically used to generate a secret for cookie sessions).' task :secret do require 'active_support/secure_random' puts ActiveSupport::SecureRandom.hex(64) diff --git a/railties/lib/rails/tasks/railties.rake b/railties/lib/rails/tasks/railties.rake new file mode 100644 index 0000000000..16703879cf --- /dev/null +++ b/railties/lib/rails/tasks/railties.rake @@ -0,0 +1,29 @@ +namespace :railties do + namespace :install do + # desc "Copies missing assets from Railties (e.g. plugins, engines). You can specify Railties to use with FROM=railtie1,railtie2" + task :assets => :rails_env do + require 'rails/generators/base' + Rails.application.initialize! + + to_load = ENV["FROM"].blank? ? :all : ENV["FROM"].split(",").map {|n| n.strip } + app_public_path = Rails.application.paths["public"].first + + Rails.application.railties.all do |railtie| + next unless to_load == :all || to_load.include?(railtie.railtie_name) + + if railtie.respond_to?(:paths) && (path = railtie.paths["public"].first) && + (assets_dir = railtie.config.compiled_asset_path) && File.exist?(path) + + Rails::Generators::Base.source_root(path) + copier = Rails::Generators::Base.new + Dir[File.join(path, "**/*")].each do |file| + relative = file.gsub(/^#{path}\//, '') + if File.file?(file) + copier.copy_file relative, File.join(app_public_path, assets_dir, relative) + end + end + end + end + end + end +end diff --git a/railties/lib/rails/tasks/routes.rake b/railties/lib/rails/tasks/routes.rake index a99232c4be..02e22361e0 100644 --- a/railties/lib/rails/tasks/routes.rake +++ b/railties/lib/rails/tasks/routes.rake @@ -1,20 +1,27 @@ desc 'Print out all defined routes in match order, with names. Target specific controller with CONTROLLER=x.' task :routes => :environment do Rails.application.reload_routes! - all_routes = ENV['CONTROLLER'] ? Rails.application.routes.routes.select { |route| route.defaults[:controller] == ENV['CONTROLLER'] } : Rails.application.routes.routes + all_routes = Rails.application.routes.routes + + if ENV['CONTROLLER'] + all_routes = all_routes.select{ |route| route.defaults[:controller] == ENV['CONTROLLER'] } + end + routes = all_routes.collect do |route| - # TODO: The :index method is deprecated in 1.9 in favor of :key - # but we don't have :key in 1.8.7. We can remove this check when - # stop supporting 1.8.x - key_method = Hash.method_defined?('key') ? 'key' : 'index' - name = Rails.application.routes.named_routes.routes.send(key_method, route).to_s - reqs = route.requirements.empty? ? "" : route.requirements.inspect - {:name => name, :verb => route.verb.to_s, :path => route.path, :reqs => reqs} + + reqs = route.requirements.dup + reqs[:to] = route.app unless route.app.class.name.to_s =~ /^ActionDispatch::Routing/ + reqs = reqs.empty? ? "" : reqs.inspect + + {:name => route.name.to_s, :verb => route.verb.to_s, :path => route.path, :reqs => reqs} end - routes.reject!{ |r| r[:path] == "/rails/info/properties" } # skip the route if it's internal info route - name_width = routes.collect {|r| r[:name]}.collect {|n| n.length}.max - verb_width = routes.collect {|r| r[:verb]}.collect {|v| v.length}.max - path_width = routes.collect {|r| r[:path]}.collect {|s| s.length}.max + + routes.reject! { |r| r[:path] =~ %r{/rails/info/properties} } # Skip the route if it's internal info route + + name_width = routes.map{ |r| r[:name].length }.max + verb_width = routes.map{ |r| r[:verb].length }.max + path_width = routes.map{ |r| r[:path].length }.max + routes.each do |r| puts "#{r[:name].rjust(name_width)} #{r[:verb].ljust(verb_width)} #{r[:path].ljust(path_width)} #{r[:reqs]}" end diff --git a/railties/lib/rails/test_help.rb b/railties/lib/rails/test_help.rb index ec5e4a357c..00029e627e 100644 --- a/railties/lib/rails/test_help.rb +++ b/railties/lib/rails/test_help.rb @@ -1,6 +1,6 @@ -# Make double-sure the RAILS_ENV is set to test, -# so fixtures are loaded to the right database -abort("Abort testing: Your Rails environment is not running in test mode!") unless Rails.env.test? +# Make double-sure the RAILS_ENV is not set to production, +# so fixtures aren't loaded into that environment +abort("Abort testing: Your Rails environment is running in production mode!") if Rails.env.production? require 'test/unit' require 'active_support/core_ext/kernel/requires' @@ -19,9 +19,13 @@ if defined?(ActiveRecord) class ActiveSupport::TestCase include ActiveRecord::TestFixtures self.fixture_path = "#{Rails.root}/test/fixtures/" + + setup do + ActiveRecord::IdentityMap.clear + end end - ActionController::IntegrationTest.fixture_path = ActiveSupport::TestCase.fixture_path + ActionDispatch::IntegrationTest.fixture_path = ActiveSupport::TestCase.fixture_path def create_fixtures(*table_names, &block) Fixtures.create_fixtures(ActiveSupport::TestCase.fixture_path, table_names, {}, &block) @@ -39,14 +43,3 @@ class ActionDispatch::IntegrationTest @routes = Rails.application.routes end end - -begin - require_library_or_gem 'ruby-debug' - Debugger.start - if Debugger.respond_to?(:settings) - Debugger.settings[:autoeval] = true - Debugger.settings[:autolist] = 1 - end -rescue LoadError - # ruby-debug wasn't available so neither can the debugging be -end diff --git a/railties/lib/rails/test_unit/railtie.rb b/railties/lib/rails/test_unit/railtie.rb index e3fafc4b9d..2b6170ebfb 100644 --- a/railties/lib/rails/test_unit/railtie.rb +++ b/railties/lib/rails/test_unit/railtie.rb @@ -1,6 +1,6 @@ module Rails class TestUnitRailtie < Rails::Railtie - config.generators do |c| + config.app_generators do |c| c.test_framework :test_unit, :fixture => true, :fixture_replacement => nil diff --git a/railties/lib/rails/test_unit/testing.rake b/railties/lib/rails/test_unit/testing.rake index 38c14fcd6b..28dc40379b 100644 --- a/railties/lib/rails/test_unit/testing.rake +++ b/railties/lib/rails/test_unit/testing.rake @@ -1,3 +1,4 @@ +require 'rbconfig' require 'rake/testtask' # Monkey-patch to silence the description from Rake::TestTask to cut down on rake -T noise @@ -62,7 +63,7 @@ end module Kernel def silence_stderr old_stderr = STDERR.dup - STDERR.reopen(Config::CONFIG['host_os'] =~ /mswin|mingw/ ? 'NUL:' : '/dev/null') + STDERR.reopen(RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ ? 'NUL:' : '/dev/null') STDERR.sync = true yield ensure @@ -72,7 +73,8 @@ end desc 'Runs test:units, test:functionals, test:integration together (also available: test:benchmark, test:profile, test:plugins)' task :test do - errors = %w(test:units test:functionals test:integration).collect do |task| + tests_to_run = ENV['TEST'] ? ["test:single"] : %w(test:units test:functionals test:integration) + errors = tests_to_run.collect do |task| begin Rake::Task[task].invoke nil @@ -122,6 +124,10 @@ namespace :test do end Rake::Task['test:uncommitted'].comment = "Test changes since last checkin (only Subversion and Git)" + Rake::TestTask.new(:single => "test:prepare") do |t| + t.libs << "test" + end + TestTaskWithoutDescription.new(:units => "test:prepare") do |t| t.libs << "test" t.pattern = 'test/unit/**/*_test.rb' diff --git a/railties/lib/rails/version.rb b/railties/lib/rails/version.rb index c5d1d02bc1..b076881c21 100644 --- a/railties/lib/rails/version.rb +++ b/railties/lib/rails/version.rb @@ -1,10 +1,10 @@ module Rails module VERSION #:nodoc: MAJOR = 3 - MINOR = 0 + MINOR = 1 TINY = 0 - BUILD = "rc" + PRE = "beta" - STRING = [MAJOR, MINOR, TINY, BUILD].join('.') + STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.') end end diff --git a/railties/railties.gemspec b/railties/railties.gemspec index d76b74190b..c3793d3ac3 100644 --- a/railties/railties.gemspec +++ b/railties/railties.gemspec @@ -19,8 +19,8 @@ Gem::Specification.new do |s| s.rdoc_options << '--exclude' << '.' s.has_rdoc = false - s.add_dependency('rake', '>= 0.8.3') - s.add_dependency('thor', '~> 0.14.0') + s.add_dependency('rake', '>= 0.8.7') + s.add_dependency('thor', '~> 0.14.4') s.add_dependency('activesupport', version) s.add_dependency('actionpack', version) end diff --git a/railties/test/abstract_unit.rb b/railties/test/abstract_unit.rb index a05bae5dcc..8b38081667 100644 --- a/railties/test/abstract_unit.rb +++ b/railties/test/abstract_unit.rb @@ -11,7 +11,8 @@ require 'action_controller' require 'rails/all' # TODO: Remove these hacks -class TestApp < Rails::Application - config.root = File.dirname(__FILE__) +module TestApp + class Application < Rails::Application + config.root = File.dirname(__FILE__) + end end -Rails.application = TestApp diff --git a/railties/test/application/configuration_test.rb b/railties/test/application/configuration_test.rb index 9928ee2c52..044fd2a278 100644 --- a/railties/test/application/configuration_test.rb +++ b/railties/test/application/configuration_test.rb @@ -26,24 +26,23 @@ module ApplicationTests FileUtils.rm_rf(new_app) if File.directory?(new_app) end - test "Rails::Application.instance is nil until app is initialized" do + test "Rails.application is nil until app is initialized" do require 'rails' - assert_nil Rails::Application.instance + assert_nil Rails.application require "#{app_path}/config/environment" - assert_equal AppTemplate::Application.instance, Rails::Application.instance + assert_equal AppTemplate::Application.instance, Rails.application end - test "Rails::Application responds to all instance methods" do + test "Rails.application responds to all instance methods" do require "#{app_path}/config/environment" - assert_respond_to Rails::Application, :routes_reloader - assert_equal Rails::Application.routes_reloader, Rails.application.routes_reloader - assert_equal Rails::Application.routes_reloader, AppTemplate::Application.routes_reloader + assert_respond_to Rails.application, :routes_reloader + assert_equal Rails.application.routes_reloader, AppTemplate::Application.routes_reloader end test "Rails::Application responds to paths" do require "#{app_path}/config/environment" assert_respond_to AppTemplate::Application, :paths - assert_equal AppTemplate::Application.paths.app.views.to_a, ["#{app_path}/app/views"] + assert_equal AppTemplate::Application.paths["app/views"].expanded, ["#{app_path}/app/views"] end test "the application root is set correctly" do @@ -96,6 +95,11 @@ module ApplicationTests assert AppTemplate::Application.config.allow_concurrency end + test "asset_path defaults to nil for application" do + require "#{app_path}/config/environment" + assert_equal nil, AppTemplate::Application.config.asset_path + end + test "the application can be marked as threadsafe when there are no frameworks" do FileUtils.rm_rf("#{app_path}/config/environments") add_to_config <<-RUBY @@ -125,22 +129,6 @@ module ApplicationTests assert !ActionController.autoload?(:RecordIdentifier) end - test "runtime error is raised if config.frameworks= is used" do - add_to_config "config.frameworks = []" - - assert_raises RuntimeError do - require "#{app_path}/config/environment" - end - end - - test "runtime error is raised if config.frameworks is used" do - add_to_config "config.frameworks -= []" - - assert_raises RuntimeError do - require "#{app_path}/config/environment" - end - end - test "filter_parameters should be able to set via config.filter_parameters" do add_to_config <<-RUBY config.filter_parameters += [ :foo, 'bar', lambda { |key, value| @@ -172,22 +160,32 @@ module ApplicationTests assert $prepared end + def assert_utf8 + if RUBY_VERSION < '1.9' + assert_equal "UTF8", $KCODE + else + assert_equal Encoding::UTF_8, Encoding.default_external + assert_equal Encoding::UTF_8, Encoding.default_internal + end + end + + test "skipping config.encoding still results in 'utf-8' as the default" do + require "#{app_path}/config/application" + assert_utf8 + end + test "config.encoding sets the default encoding" do add_to_config <<-RUBY config.encoding = "utf-8" RUBY require "#{app_path}/config/application" - - unless RUBY_VERSION < '1.9' - assert_equal Encoding::UTF_8, Encoding.default_external - assert_equal Encoding::UTF_8, Encoding.default_internal - end + assert_utf8 end test "config.paths.public sets Rails.public_path" do add_to_config <<-RUBY - config.paths.public = "somewhere" + config.paths["public"] = "somewhere" RUBY require "#{app_path}/config/application" @@ -218,7 +216,7 @@ module ApplicationTests protect_from_forgery def index - render :inline => "<%= csrf_meta_tag %>" + render :inline => "<%= csrf_meta_tags %>" end end @@ -267,5 +265,73 @@ module ApplicationTests get "/" assert_not_equal res, last_response.body end + + test "config.asset_path is not passed through env" do + make_basic_app do |app| + app.config.asset_path = "/omg%s" + end + + class ::OmgController < ActionController::Base + def index + render :inline => "<%= image_path('foo.jpg') %>" + end + end + + get "/" + assert_equal "/omg/images/foo.jpg", last_response.body + end + + test "config.action_view.cache_template_loading with cache_classes default" do + add_to_config "config.cache_classes = true" + require "#{app_path}/config/environment" + require 'action_view/base' + + assert ActionView::Resolver.caching? + end + + test "config.action_view.cache_template_loading without cache_classes default" do + add_to_config "config.cache_classes = false" + require "#{app_path}/config/environment" + require 'action_view/base' + + assert !ActionView::Resolver.caching? + end + + test "config.action_view.cache_template_loading = false" do + add_to_config <<-RUBY + config.cache_classes = true + config.action_view.cache_template_loading = false + RUBY + require "#{app_path}/config/environment" + require 'action_view/base' + + assert !ActionView::Resolver.caching? + end + + test "config.action_view.cache_template_loading = true" do + add_to_config <<-RUBY + config.cache_classes = false + config.action_view.cache_template_loading = true + RUBY + require "#{app_path}/config/environment" + require 'action_view/base' + + assert ActionView::Resolver.caching? + end + + test "config.action_dispatch.show_exceptions is sent in env" do + make_basic_app do |app| + app.config.action_dispatch.show_exceptions = true + end + + class ::OmgController < ActionController::Base + def index + render :text => env["action_dispatch.show_exceptions"] + end + end + + get "/" + assert_equal 'true', last_response.body + end end end diff --git a/railties/test/application/console_test.rb b/railties/test/application/console_test.rb index a72e6916dd..793e73556c 100644 --- a/railties/test/application/console_test.rb +++ b/railties/test/application/console_test.rb @@ -1,7 +1,7 @@ require 'isolation/abstract_unit' class ConsoleTest < Test::Unit::TestCase - include ActiveSupport::Testing::Isolation + include ActiveSupport::Testing::Isolation def setup build_app @@ -14,27 +14,26 @@ class ConsoleTest < Test::Unit::TestCase end def test_app_method_should_return_integration_session + TestHelpers::Rack.send :remove_method, :app load_environment console_session = app - assert_not_nil console_session - assert_instance_of ActionController::Integration::Session, console_session + assert_instance_of ActionDispatch::Integration::Session, console_session end def test_new_session_should_return_integration_session load_environment session = new_session - assert_not_nil session - assert_instance_of ActionController::Integration::Session, session + assert_instance_of ActionDispatch::Integration::Session, session end - def test_reload_should_fire_preparation_callbacks + def test_reload_should_fire_preparation_and_cleanup_callbacks load_environment a = b = c = nil # TODO: These should be defined on the initializer - ActionDispatch::Callbacks.to_prepare { a = b = c = 1 } - ActionDispatch::Callbacks.to_prepare { b = c = 2 } - ActionDispatch::Callbacks.to_prepare { c = 3 } + ActionDispatch::Reloader.to_cleanup { a = b = c = 1 } + ActionDispatch::Reloader.to_cleanup { b = c = 2 } + ActionDispatch::Reloader.to_prepare { c = 3 } # Hide Reloading... output silence_stream(STDOUT) { reload! } diff --git a/railties/test/application/generators_test.rb b/railties/test/application/generators_test.rb index d258625f42..8b840fffd0 100644 --- a/railties/test/application/generators_test.rb +++ b/railties/test/application/generators_test.rb @@ -25,6 +25,11 @@ module ApplicationTests yield app_const.config end + test "allow running plugin new generator inside Rails app directory" do + FileUtils.cd(rails_root){ `ruby script/rails plugin new vendor/plugins/bukkits` } + assert File.exist?(File.join(rails_root, "vendor/plugins/bukkits/test/dummy/config/application.rb")) + end + test "generators default values" do with_bare_config do |c| assert_equal(true, c.generators.colorize_logging) @@ -69,7 +74,7 @@ module ApplicationTests assert_equal :rspec, Rails::Generators.options[:rails][:test_framework] assert_equal "-w", Rails::Generators.aliases[:rails][:test_framework] assert_equal Hash[:shoulda => :test_unit], Rails::Generators.fallbacks - assert_equal ["#{app_path}/lib/templates", "some/where"], Rails::Generators.templates_path + assert_equal ["some/where"], Rails::Generators.templates_path end test "generators no color on initialization" do diff --git a/railties/test/application/initializers/frameworks_test.rb b/railties/test/application/initializers/frameworks_test.rb index d8e916f45f..19311a7fa0 100644 --- a/railties/test/application/initializers/frameworks_test.rb +++ b/railties/test/application/initializers/frameworks_test.rb @@ -1,7 +1,7 @@ require "isolation/abstract_unit" module ApplicationTests - class FrameworlsTest < Test::Unit::TestCase + class FrameworksTest < Test::Unit::TestCase include ActiveSupport::Testing::Isolation def setup @@ -61,9 +61,77 @@ module ApplicationTests require "#{app_path}/config/environment" assert Foo.method_defined?(:foo_path) + assert Foo.method_defined?(:main_app) assert_equal ["notify"], Foo.action_methods end + test "allows to not load all helpers for controllers" do + add_to_config "config.action_controller.include_all_helpers = false" + + app_file "app/controllers/application_controller.rb", <<-RUBY + class ApplicationController < ActionController::Base + end + RUBY + + app_file "app/controllers/foo_controller.rb", <<-RUBY + class FooController < ApplicationController + def included_helpers + render :inline => "<%= from_app_helper -%> <%= from_foo_helper %>" + end + + def not_included_helper + render :inline => "<%= respond_to?(:from_bar_helper) -%>" + end + end + RUBY + + app_file "app/helpers/application_helper.rb", <<-RUBY + module ApplicationHelper + def from_app_helper + "from_app_helper" + end + end + RUBY + + app_file "app/helpers/foo_helper.rb", <<-RUBY + module FooHelper + def from_foo_helper + "from_foo_helper" + end + end + RUBY + + app_file "app/helpers/bar_helper.rb", <<-RUBY + module BarHelper + def from_bar_helper + "from_bar_helper" + end + end + RUBY + + app_file "config/routes.rb", <<-RUBY + AppTemplate::Application.routes.draw do + match "/:controller(/:action)" + end + RUBY + + require 'rack/test' + extend Rack::Test::Methods + + get "/foo/included_helpers" + assert_equal "from_app_helper from_foo_helper", last_response.body + + get "/foo/not_included_helper" + assert_equal "false", last_response.body + end + + # AD + test "action_dispatch extensions are applied to ActionDispatch" do + add_to_config "config.action_dispatch.tld_length = 2" + require "#{app_path}/config/environment" + assert_equal 2, ActionDispatch::Http::URL.tld_length + end + # AS test "if there's no config.active_support.bare, all of ActiveSupport is required" do use_frameworks [] @@ -98,17 +166,7 @@ module ApplicationTests require "#{app_path}/config/environment" - expects = [ActiveRecord::QueryCache, ActiveRecord::SessionStore] - middleware = Rails.application.config.middleware.map { |m| m.klass } - assert_equal expects, middleware & expects - end - - test "database middleware initializes when allow concurrency is true" do - add_to_config "config.threadsafe!" - - require "#{app_path}/config/environment" - - expects = [ActiveRecord::ConnectionAdapters::ConnectionManagement, ActiveRecord::QueryCache] + expects = [ActiveRecord::IdentityMap::Middleware, ActiveRecord::ConnectionAdapters::ConnectionManagement, ActiveRecord::QueryCache, ActiveRecord::SessionStore] middleware = Rails.application.config.middleware.map { |m| m.klass } assert_equal expects, middleware & expects end diff --git a/railties/test/application/initializers/i18n_test.rb b/railties/test/application/initializers/i18n_test.rb index 4baa8a8170..390f65ab5c 100644 --- a/railties/test/application/initializers/i18n_test.rb +++ b/railties/test/application/initializers/i18n_test.rb @@ -63,6 +63,36 @@ module ApplicationTests assert I18n.load_path.include?("#{app_path}/config/another_locale.yml") end + test "load_path is populated before eager loaded models" do + add_to_config <<-RUBY + config.cache_classes = true + RUBY + + app_file "config/locales/en.yml", <<-YAML +en: + foo: "1" + YAML + + app_file 'app/models/foo.rb', <<-RUBY + class Foo < ActiveRecord::Base + @foo = I18n.t(:foo) + end + RUBY + + app_file 'config/routes.rb', <<-RUBY + AppTemplate::Application.routes.draw do + match '/i18n', :to => lambda { |env| [200, {}, [Foo.instance_variable_get('@foo')]] } + end + RUBY + + require 'rack/test' + extend Rack::Test::Methods + load_app + + get "/i18n" + assert_equal "1", last_response.body + end + test "locales are reloaded if they change between requests" do add_to_config <<-RUBY config.cache_classes = false @@ -74,7 +104,7 @@ en: YAML app_file 'config/routes.rb', <<-RUBY - AppTemplate::Application.routes.draw do |map| + AppTemplate::Application.routes.draw do match '/i18n', :to => lambda { |env| [200, {}, [I18n.t(:foo)]] } end RUBY @@ -147,4 +177,4 @@ en: assert_fallbacks :ca => [:ca, :"es-ES", :es, :'en-US', :en] end end -end
\ No newline at end of file +end diff --git a/railties/test/application/loading_test.rb b/railties/test/application/loading_test.rb index 340ce67511..c340465e87 100644 --- a/railties/test/application/loading_test.rb +++ b/railties/test/application/loading_test.rb @@ -18,10 +18,10 @@ class LoadingTest < Test::Unit::TestCase validates_acceptance_of :title, :accept => "omg" end MODEL - + require "#{rails_root}/config/environment" setup_ar! - + p = Post.create(:title => 'omg') assert_equal 1, Post.count assert_equal 'omg', p.title @@ -42,6 +42,23 @@ class LoadingTest < Test::Unit::TestCase User end + test "load config/environments/environment before Bootstrap initializers" do + app_file "config/environments/development.rb", <<-RUBY + AppTemplate::Application.configure do + config.development_environment_loaded = true + end + RUBY + + add_to_config <<-RUBY + config.before_initialize do + config.loaded = config.development_environment_loaded + end + RUBY + + require "#{app_path}/config/environment" + assert ::AppTemplate::Application.config.loaded + end + def test_descendants_are_cleaned_on_each_request_without_cache_classes add_to_config <<-RUBY config.cache_classes = false @@ -53,7 +70,7 @@ class LoadingTest < Test::Unit::TestCase MODEL app_file 'config/routes.rb', <<-RUBY - AppTemplate::Application.routes.draw do |map| + AppTemplate::Application.routes.draw do match '/load', :to => lambda { |env| [200, {}, Post.all] } match '/unload', :to => lambda { |env| [200, {}, []] } end @@ -72,8 +89,13 @@ class LoadingTest < Test::Unit::TestCase assert_equal [], ActiveRecord::Base.descendants end + test "initialize_cant_be_called_twice" do + require "#{app_path}/config/environment" + assert_raise(RuntimeError) { ::AppTemplate::Application.initialize! } + end + protected - + def setup_ar! ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :database => ":memory:") ActiveRecord::Migration.verbose = false diff --git a/railties/test/application/middleware/best_practices_test.rb b/railties/test/application/middleware/best_practices_test.rb new file mode 100644 index 0000000000..5b722e7510 --- /dev/null +++ b/railties/test/application/middleware/best_practices_test.rb @@ -0,0 +1,26 @@ +require 'isolation/abstract_unit' + +module ApplicationTests + class BestPracticesTest < Test::Unit::TestCase + include ActiveSupport::Testing::Isolation + + def setup + build_app + boot_rails + require 'rack/test' + extend Rack::Test::Methods + simple_controller + end + + test "simple controller in production mode returns best standards" do + get '/foo' + assert_equal "IE=Edge,chrome=1", last_response.headers["X-UA-Compatible"] + end + + test "simple controller in development mode leaves out Chrome" do + app("development") + get "/foo" + assert_equal "IE=Edge", last_response.headers["X-UA-Compatible"] + end + end +end diff --git a/railties/test/application/middleware/cache_test.rb b/railties/test/application/middleware/cache_test.rb new file mode 100644 index 0000000000..f582ed0e42 --- /dev/null +++ b/railties/test/application/middleware/cache_test.rb @@ -0,0 +1,150 @@ +require 'isolation/abstract_unit' + +module ApplicationTests + class RoutingTest < Test::Unit::TestCase + include ActiveSupport::Testing::Isolation + + def setup + build_app + boot_rails + require 'rack/test' + extend Rack::Test::Methods + end + + def simple_controller + controller :expires, <<-RUBY + class ExpiresController < ApplicationController + def expires_header + expires_in 10, :public => !params[:private] + render :text => ActiveSupport::SecureRandom.hex(16) + end + + def expires_etag + render_conditionally(:etag => "1") + end + + def expires_last_modified + $last_modified ||= Time.now.utc + render_conditionally(:last_modified => $last_modified) + end + private + def render_conditionally(headers) + if stale?(headers.merge(:public => !params[:private])) + render :text => ActiveSupport::SecureRandom.hex(16) + end + end + end + RUBY + + app_file 'config/routes.rb', <<-RUBY + AppTemplate::Application.routes.draw do + match ':controller(/:action)' + end + RUBY + end + + def test_cache_is_disabled_in_dev_mode + simple_controller + app("development") + + get "/expires/expires_header" + assert_nil last_response.headers['X-Rack-Cache'] + + body = last_response.body + + get "/expires/expires_header" + assert_nil last_response.headers['X-Rack-Cache'] + assert_not_equal body, last_response.body + end + + def test_cache_works_with_expires + simple_controller + + get "/expires/expires_header" + assert_equal "miss, store", last_response.headers["X-Rack-Cache"] + assert_equal "max-age=10, public", last_response.headers["Cache-Control"] + + body = last_response.body + + get "/expires/expires_header" + + assert_equal "fresh", last_response.headers["X-Rack-Cache"] + + assert_equal body, last_response.body + end + + def test_cache_works_with_expires_private + simple_controller + + get "/expires/expires_header", :private => true + assert_equal "miss", last_response.headers["X-Rack-Cache"] + assert_equal "private, max-age=10", last_response.headers["Cache-Control"] + + body = last_response.body + + get "/expires/expires_header", :private => true + assert_equal "miss", last_response.headers["X-Rack-Cache"] + assert_not_equal body, last_response.body + end + + def test_cache_works_with_etags + simple_controller + + get "/expires/expires_etag" + assert_equal "miss, store", last_response.headers["X-Rack-Cache"] + assert_equal "public", last_response.headers["Cache-Control"] + + body = last_response.body + etag = last_response.headers["ETag"] + + get "/expires/expires_etag", {}, "If-None-Match" => etag + assert_equal "stale, valid, store", last_response.headers["X-Rack-Cache"] + assert_equal body, last_response.body + end + + def test_cache_works_with_etags_private + simple_controller + + get "/expires/expires_etag", :private => true + assert_equal "miss", last_response.headers["X-Rack-Cache"] + assert_equal "must-revalidate, private, max-age=0", last_response.headers["Cache-Control"] + + body = last_response.body + etag = last_response.headers["ETag"] + + get "/expires/expires_etag", {:private => true}, "If-None-Match" => etag + assert_equal "miss", last_response.headers["X-Rack-Cache"] + assert_not_equal body, last_response.body + end + + def test_cache_works_with_last_modified + simple_controller + + get "/expires/expires_last_modified" + assert_equal "miss, store", last_response.headers["X-Rack-Cache"] + assert_equal "public", last_response.headers["Cache-Control"] + + body = last_response.body + last = last_response.headers["Last-Modified"] + + get "/expires/expires_last_modified", {}, "If-Modified-Since" => last + assert_equal "stale, valid, store", last_response.headers["X-Rack-Cache"] + assert_equal body, last_response.body + end + + def test_cache_works_with_last_modified_private + simple_controller + + get "/expires/expires_last_modified", :private => true + assert_equal "miss", last_response.headers["X-Rack-Cache"] + assert_equal "must-revalidate, private, max-age=0", last_response.headers["Cache-Control"] + + body = last_response.body + last = last_response.headers["Last-Modified"] + + get "/expires/expires_last_modified", {:private => true}, "If-Modified-Since" => last + assert_equal "miss", last_response.headers["X-Rack-Cache"] + assert_not_equal body, last_response.body + end + end +end diff --git a/railties/test/application/middleware/remote_ip_test.rb b/railties/test/application/middleware/remote_ip_test.rb new file mode 100644 index 0000000000..f28302d70a --- /dev/null +++ b/railties/test/application/middleware/remote_ip_test.rb @@ -0,0 +1,63 @@ +require 'isolation/abstract_unit' + +module ApplicationTests + class RemoteIpTest < Test::Unit::TestCase + include ActiveSupport::Testing::Isolation + + def setup + build_app + boot_rails + FileUtils.rm_rf "#{app_path}/config/environments" + end + + def app + @app ||= Rails.application + end + + def remote_ip(env = {}) + remote_ip = nil + env = Rack::MockRequest.env_for("/").merge(env).merge!( + 'action_dispatch.show_exceptions' => false, + 'action_dispatch.secret_token' => 'b3c631c314c0bbca50c1b2843150fe33' + ) + + endpoint = Proc.new do |e| + remote_ip = ActionDispatch::Request.new(e).remote_ip + [200, {}, ["Hello"]] + end + + Rails.application.middleware.build(endpoint).call(env) + remote_ip + end + + test "remote_ip works" do + make_basic_app + assert_equal "1.1.1.1", remote_ip("REMOTE_ADDR" => "1.1.1.1") + end + + test "checks IP spoofing by default" do + make_basic_app + assert_raises(ActionDispatch::RemoteIp::IpSpoofAttackError) do + remote_ip("HTTP_X_FORWARDED_FOR" => "1.1.1.1", "HTTP_CLIENT_IP" => "1.1.1.2") + end + end + + test "can disable IP spoofing check" do + make_basic_app do |app| + app.config.action_dispatch.ip_spoofing_check = false + end + + assert_nothing_raised(ActionDispatch::RemoteIp::IpSpoofAttackError) do + assert_equal "1.1.1.2", remote_ip("HTTP_X_FORWARDED_FOR" => "1.1.1.1", "HTTP_CLIENT_IP" => "1.1.1.2") + end + end + + test "the user can set trusted proxies" do + make_basic_app do |app| + app.config.action_dispatch.trusted_proxies = /^4\.2\.42\.42$/ + end + + assert_equal "1.1.1.1", remote_ip("REMOTE_ADDR" => "4.2.42.42,1.1.1.1") + end + end +end diff --git a/railties/test/application/middleware/sendfile_test.rb b/railties/test/application/middleware/sendfile_test.rb new file mode 100644 index 0000000000..0128261cd4 --- /dev/null +++ b/railties/test/application/middleware/sendfile_test.rb @@ -0,0 +1,56 @@ +require 'isolation/abstract_unit' + +module ApplicationTests + class SendfileTest < Test::Unit::TestCase + include ActiveSupport::Testing::Isolation + + def setup + build_app + boot_rails + FileUtils.rm_rf "#{app_path}/config/environments" + end + + def app + @app ||= Rails.application + end + + define_method :simple_controller do + class ::OmgController < ActionController::Base + def index + send_file __FILE__ + end + end + end + + # x_sendfile_header middleware + test "config.action_dispatch.x_sendfile_header defaults to ''" do + make_basic_app + simple_controller + + get "/" + assert_equal File.read(__FILE__), last_response.body + end + + test "config.action_dispatch.x_sendfile_header can be set" do + make_basic_app do |app| + app.config.action_dispatch.x_sendfile_header = "X-Sendfile" + end + + simple_controller + + get "/" + assert_equal File.expand_path(__FILE__), last_response.headers["X-Sendfile"] + end + + test "config.action_dispatch.x_sendfile_header is sent to Rack::Sendfile" do + make_basic_app do |app| + app.config.action_dispatch.x_sendfile_header = 'X-Lighttpd-Send-File' + end + + simple_controller + + get "/" + assert_equal File.expand_path(__FILE__), last_response.headers["X-Lighttpd-Send-File"] + end + end +end diff --git a/railties/test/application/middleware/show_exceptions_test.rb b/railties/test/application/middleware/show_exceptions_test.rb new file mode 100644 index 0000000000..5487e41e0a --- /dev/null +++ b/railties/test/application/middleware/show_exceptions_test.rb @@ -0,0 +1,37 @@ +require 'isolation/abstract_unit' + +module ApplicationTests + class ShowExceptionsTest < Test::Unit::TestCase + include ActiveSupport::Testing::Isolation + + def setup + build_app + boot_rails + FileUtils.rm_rf "#{app_path}/config/environments" + end + + def app + @app ||= Rails.application + end + + test "unspecified route when set action_dispatch.show_exceptions to false" do + make_basic_app do |app| + app.config.action_dispatch.show_exceptions = false + end + + assert_raise(ActionController::RoutingError) do + get '/foo' + end + end + + test "unspecified route when set action_dispatch.show_exceptions to true" do + make_basic_app do |app| + app.config.action_dispatch.show_exceptions = true + end + + assert_nothing_raised(ActionController::RoutingError) do + get '/foo' + end + end + end +end diff --git a/railties/test/application/middleware_test.rb b/railties/test/application/middleware_test.rb index 1f127cee78..b314832685 100644 --- a/railties/test/application/middleware_test.rb +++ b/railties/test/application/middleware_test.rb @@ -27,7 +27,10 @@ module ApplicationTests "ActionDispatch::ShowExceptions", "ActionDispatch::RemoteIp", "Rack::Sendfile", + "ActionDispatch::Reloader", "ActionDispatch::Callbacks", + "ActiveRecord::IdentityMap::Middleware", + "ActiveRecord::ConnectionAdapters::ConnectionManagement", "ActiveRecord::QueryCache", "ActionDispatch::Cookies", "ActionDispatch::Session::CookieStore", @@ -35,15 +38,26 @@ module ApplicationTests "ActionDispatch::ParamsParser", "Rack::MethodOverride", "ActionDispatch::Head", + "Rack::ConditionalGet", + "Rack::ETag", "ActionDispatch::BestStandardsSupport" ], middleware end + test "Rack::Cache is present when action_controller.perform_caching is set" do + add_to_config "config.action_controller.perform_caching = true" + + boot! + + assert_equal "Rack::Cache", middleware.first + end + test "removing Active Record omits its middleware" do use_frameworks [] boot! assert !middleware.include?("ActiveRecord::ConnectionAdapters::ConnectionManagement") assert !middleware.include?("ActiveRecord::QueryCache") + assert !middleware.include?("ActiveRecord::IdentityMap::Middleware") end test "removes lock if allow concurrency is set" do @@ -64,10 +78,16 @@ module ApplicationTests assert !middleware.include?("ActionDispatch::Static") end - test "removes show exceptions if action_dispatch.show_exceptions is disabled" do + test "includes show exceptions even action_dispatch.show_exceptions is disabled" do add_to_config "config.action_dispatch.show_exceptions = false" boot! - assert !middleware.include?("ActionDispatch::ShowExceptions") + assert middleware.include?("ActionDispatch::ShowExceptions") + end + + test "removes ActionDispatch::Reloader if cache_classes is true" do + add_to_config "config.cache_classes = true" + boot! + assert !middleware.include?("ActionDispatch::Reloader") end test "use middleware" do @@ -94,87 +114,57 @@ module ApplicationTests assert_equal "Rack::Runtime", middleware.fourth end + test "identity map is inserted" do + boot! + assert middleware.include?("ActiveRecord::IdentityMap::Middleware") + end + test "insert middleware before" do add_to_config "config.middleware.insert_before ActionDispatch::Static, Rack::Config" boot! assert_equal "Rack::Config", middleware.first end - # x_sendfile_header middleware - test "config.action_dispatch.x_sendfile_header defaults to ''" do + # ConditionalGet + Etag + test "conditional get + etag middlewares handle http caching based on body" do make_basic_app class ::OmgController < ActionController::Base def index - send_file __FILE__ + if params[:nothing] + render :text => "" + else + render :text => "OMG" + end end end - get "/" - assert_equal File.read(__FILE__), last_response.body - end - - test "config.action_dispatch.x_sendfile_header can be set" do - make_basic_app do |app| - app.config.action_dispatch.x_sendfile_header = "X-Sendfile" - end - - class ::OmgController < ActionController::Base - def index - send_file __FILE__ - end - end + etag = "5af83e3196bf99f440f31f2e1a6c9afe".inspect get "/" - assert_equal File.expand_path(__FILE__), last_response.headers["X-Sendfile"] - end - - test "config.action_dispatch.x_sendfile_header is sent to Rack::Sendfile" do - make_basic_app do |app| - app.config.action_dispatch.x_sendfile_header = 'X-Lighttpd-Send-File' - end - - class ::OmgController < ActionController::Base - def index - send_file __FILE__ - end - end - - get "/" - assert_equal File.expand_path(__FILE__), last_response.headers["X-Lighttpd-Send-File"] - end - - # remote_ip tests - test "remote_ip works" do - make_basic_app - assert_equal "1.1.1.1", remote_ip("REMOTE_ADDR" => "1.1.1.1") - end - - test "checks IP spoofing by default" do - make_basic_app - assert_raises(ActionDispatch::RemoteIp::IpSpoofAttackError) do - remote_ip("HTTP_X_FORWARDED_FOR" => "1.1.1.1", "HTTP_CLIENT_IP" => "1.1.1.2") - end - end - - test "can disable IP spoofing check" do - make_basic_app do |app| - app.config.action_dispatch.ip_spoofing_check = false - end - - assert_nothing_raised(ActionDispatch::RemoteIp::IpSpoofAttackError) do - assert_equal "1.1.1.2", remote_ip("HTTP_X_FORWARDED_FOR" => "1.1.1.1", "HTTP_CLIENT_IP" => "1.1.1.2") - end - end - - test "the user can set trusted proxies" do - make_basic_app do |app| - app.config.action_dispatch.trusted_proxies = /^4\.2\.42\.42$/ - end - - assert_equal "1.1.1.1", remote_ip("REMOTE_ADDR" => "4.2.42.42,1.1.1.1") - end - + assert_equal 200, last_response.status + assert_equal "OMG", last_response.body + assert_equal "text/html; charset=utf-8", last_response.headers["Content-Type"] + assert_equal "max-age=0, private, must-revalidate", last_response.headers["Cache-Control"] + assert_equal etag, last_response.headers["Etag"] + + get "/", {}, "HTTP_IF_NONE_MATCH" => etag + assert_equal 304, last_response.status + assert_equal "", last_response.body + assert_equal nil, last_response.headers["Content-Type"] + assert_equal "max-age=0, private, must-revalidate", last_response.headers["Cache-Control"] + assert_equal etag, last_response.headers["Etag"] + + get "/?nothing=true" + puts last_response.body + assert_equal 200, last_response.status + assert_equal "", last_response.body + assert_equal "text/html; charset=utf-8", last_response.headers["Content-Type"] + assert_equal "no-cache", last_response.headers["Cache-Control"] + assert_equal nil, last_response.headers["Etag"] + end + + # Show exceptions middleware test "show exceptions middleware filter backtrace before logging" do my_middleware = Struct.new(:app) do def call(env) @@ -203,21 +193,5 @@ module ApplicationTests def middleware AppTemplate::Application.middleware.map(&:klass).map(&:name) end - - def remote_ip(env = {}) - remote_ip = nil - env = Rack::MockRequest.env_for("/").merge(env).merge!( - 'action_dispatch.show_exceptions' => false, - 'action_dispatch.secret_token' => 'b3c631c314c0bbca50c1b2843150fe33' - ) - - endpoint = Proc.new do |e| - remote_ip = ActionDispatch::Request.new(e).remote_ip - [200, {}, ["Hello"]] - end - - Rails.application.middleware.build(endpoint).call(env) - remote_ip - end end end diff --git a/railties/test/application/paths_test.rb b/railties/test/application/paths_test.rb index c98b11556b..b1ff6e9cb1 100644 --- a/railties/test/application/paths_test.rb +++ b/railties/test/application/paths_test.rb @@ -25,7 +25,7 @@ module ApplicationTests end def assert_path(paths, *dir) - assert_equal [root(*dir)], paths.paths + assert_equal [root(*dir)], paths.expanded end def assert_in_load_path(*path) @@ -37,20 +37,20 @@ module ApplicationTests end test "booting up Rails yields a valid paths object" do - assert_path @paths.app.models, "app", "models" - assert_path @paths.app.helpers, "app", "helpers" - assert_path @paths.app.views, "app", "views" - assert_path @paths.lib, "lib" - assert_path @paths.vendor, "vendor" - assert_path @paths.vendor.plugins, "vendor", "plugins" - assert_path @paths.tmp, "tmp" - assert_path @paths.tmp.cache, "tmp", "cache" - assert_path @paths.config, "config" - assert_path @paths.config.locales, "config", "locales", "en.yml" - assert_path @paths.config.environment, "config", "environment.rb" - assert_path @paths.config.environments, "config", "environments", "development.rb" + assert_path @paths["app/models"], "app/models" + assert_path @paths["app/helpers"], "app/helpers" + assert_path @paths["app/views"], "app/views" + assert_path @paths["lib"], "lib" + assert_path @paths["vendor"], "vendor" + assert_path @paths["vendor/plugins"], "vendor/plugins" + assert_path @paths["tmp"], "tmp" + assert_path @paths["tmp/cache"], "tmp/cache" + assert_path @paths["config"], "config" + assert_path @paths["config/locales"], "config/locales/en.yml" + assert_path @paths["config/environment"], "config/environment.rb" + assert_path @paths["config/environments"], "config/environments/development.rb" - assert_equal root("app", "controllers"), @paths.app.controllers.to_a.first + assert_equal root("app", "controllers"), @paths["app/controllers"].expanded.first end test "booting up Rails yields a list of paths that are eager" do diff --git a/railties/test/application/rackup_test.rb b/railties/test/application/rackup_test.rb index 863950c04f..b0a9925890 100644 --- a/railties/test/application/rackup_test.rb +++ b/railties/test/application/rackup_test.rb @@ -31,13 +31,6 @@ module ApplicationTests assert_kind_of Rails::Application, Rails.application end - # Passenger still uses AC::Dispatcher, so we need to - # keep it working for now - test "deprecated ActionController::Dispatcher still works" do - rackup - assert_kind_of Rails::Application, ActionController::Dispatcher.new - end - test "the config object is available on the application object" do rackup assert_equal 'UTC', Rails.application.config.time_zone diff --git a/railties/test/application/rake_test.rb b/railties/test/application/rake_test.rb index d6e100ffe3..59e5ef4dee 100644 --- a/railties/test/application/rake_test.rb +++ b/railties/test/application/rake_test.rb @@ -14,7 +14,7 @@ module ApplicationTests app_file "lib/tasks/app.rake", <<-RUBY $task_loaded = Rake::Task.task_defined?("db:create:all") RUBY - + require "#{app_path}/config/environment" ::Rails.application.load_tasks assert $task_loaded @@ -33,5 +33,71 @@ module ApplicationTests assert_match "SuperMiddleware", Dir.chdir(app_path){ `rake middleware` } end + + def test_initializers_are_executed_in_rake_tasks + add_to_config <<-RUBY + initializer "do_something" do + puts "Doing something..." + end + + rake_tasks do + task :do_nothing => :environment do + end + end + RUBY + + output = Dir.chdir(app_path){ `rake do_nothing` } + assert_match "Doing something...", output + end + + def test_code_statistics_sanity + assert_match "Code LOC: 5 Test LOC: 0 Code to Test Ratio: 1:0.0", + Dir.chdir(app_path){ `rake stats` } + end + + def test_rake_routes_output_strips_anchors_from_http_verbs + app_file "config/routes.rb", <<-RUBY + AppTemplate::Application.routes.draw do + get '/cart', :to => 'cart#show' + end + RUBY + assert_match 'cart GET /cart(.:format)', Dir.chdir(app_path){ `rake routes` } + end + + def test_model_and_migration_generator_with_change_syntax + Dir.chdir(app_path) do + `rails generate model user username:string password:string` + `rails generate migration add_email_to_users email:string` + end + + output = Dir.chdir(app_path){ `rake db:migrate` } + assert_match /create_table\(:users\)/, output + assert_match /CreateUsers: migrated/, output + assert_match /add_column\(:users, :email, :string\)/, output + assert_match /AddEmailToUsers: migrated/, output + + output = Dir.chdir(app_path){ `rake db:rollback STEP=2` } + assert_match /drop_table\("users"\)/, output + assert_match /CreateUsers: reverted/, output + assert_match /remove_column\("users", :email\)/, output + assert_match /AddEmailToUsers: reverted/, output + end + + def test_loading_specific_fixtures + Dir.chdir(app_path) do + `rails generate model user username:string password:string` + `rails generate model product name:string` + `rake db:migrate` + end + + require "#{rails_root}/config/environment" + + # loading a specific fixture + errormsg = Dir.chdir(app_path) { `rake db:fixtures:load FIXTURES=products` } + assert $?.success?, errormsg + + assert_equal 2, ::AppTemplate::Application::Product.count + assert_equal 0, ::AppTemplate::Application::User.count + end end -end
\ No newline at end of file +end diff --git a/railties/test/application/routing_test.rb b/railties/test/application/routing_test.rb index febc53bac9..62589c998d 100644 --- a/railties/test/application/routing_test.rb +++ b/railties/test/application/routing_test.rb @@ -11,34 +11,6 @@ module ApplicationTests extend Rack::Test::Methods end - def app(env = "production") - old_env = ENV["RAILS_ENV"] - - @app ||= begin - ENV["RAILS_ENV"] = env - require "#{app_path}/config/environment" - Rails.application - end - ensure - ENV["RAILS_ENV"] = old_env - end - - def simple_controller - controller :foo, <<-RUBY - class FooController < ApplicationController - def index - render :text => "foo" - end - end - RUBY - - app_file 'config/routes.rb', <<-RUBY - AppTemplate::Application.routes.draw do |map| - match ':controller(/:action)' - end - RUBY - end - test "rails/info/properties in development" do app("development") get "/rails/info/properties" @@ -58,21 +30,6 @@ module ApplicationTests assert_equal 'foo', last_response.body end - test "simple controller in production mode returns best standards" do - simple_controller - - get '/foo' - assert_equal "IE=Edge,chrome=1", last_response.headers["X-UA-Compatible"] - end - - test "simple controller in development mode leaves out Chrome" do - simple_controller - app("development") - - get "/foo" - assert_equal "IE=Edge", last_response.headers["X-UA-Compatible"] - end - test "simple controller with helper" do controller :foo, <<-RUBY class FooController < ApplicationController @@ -91,7 +48,7 @@ module ApplicationTests RUBY app_file 'config/routes.rb', <<-RUBY - AppTemplate::Application.routes.draw do |map| + AppTemplate::Application.routes.draw do match ':controller(/:action)' end RUBY @@ -102,7 +59,7 @@ module ApplicationTests test "mount rack app" do app_file 'config/routes.rb', <<-RUBY - AppTemplate::Application.routes.draw do |map| + AppTemplate::Application.routes.draw do mount lambda { |env| [200, {}, [env["PATH_INFO"]]] }, :at => "/blog" # The line below is required because mount sometimes # fails when a resource route is added. @@ -132,7 +89,7 @@ module ApplicationTests RUBY app_file 'config/routes.rb', <<-RUBY - AppTemplate::Application.routes.draw do |map| + AppTemplate::Application.routes.draw do match ':controller(/:action)' end RUBY @@ -164,7 +121,7 @@ module ApplicationTests RUBY app_file 'config/routes.rb', <<-RUBY - AppTemplate::Application.routes.draw do |map| + AppTemplate::Application.routes.draw do match 'admin/foo', :to => 'admin/foo#index' match 'foo', :to => 'foo#index' end @@ -177,6 +134,34 @@ module ApplicationTests assert_equal 'admin::foo', last_response.body end + test "routes appending blocks" do + app_file 'config/routes.rb', <<-RUBY + AppTemplate::Application.routes.draw do + match ':controller#:action' + end + RUBY + + add_to_config <<-R + routes.append do + match '/win' => lambda { |e| [200, {'Content-Type'=>'text/plain'}, ['WIN']] } + end + R + + app 'development' + + get '/win' + assert_equal 'WIN', last_response.body + + app_file 'config/routes.rb', <<-R + AppTemplate::Application.routes.draw do + match 'lol' => 'hello#index' + end + R + + get '/win' + assert_equal 'WIN', last_response.body + end + {"development" => "baz", "production" => "bar"}.each do |mode, expected| test "reloads routes when configuration is changed in #{mode}" do controller :foo, <<-RUBY @@ -192,7 +177,7 @@ module ApplicationTests RUBY app_file 'config/routes.rb', <<-RUBY - AppTemplate::Application.routes.draw do |map| + AppTemplate::Application.routes.draw do match 'foo', :to => 'foo#bar' end RUBY @@ -203,7 +188,7 @@ module ApplicationTests assert_equal 'bar', last_response.body app_file 'config/routes.rb', <<-RUBY - AppTemplate::Application.routes.draw do |map| + AppTemplate::Application.routes.draw do match 'foo', :to => 'foo#baz' end RUBY @@ -215,7 +200,32 @@ module ApplicationTests end end - test 'resource routing with irrigular inflection' do + test 'routes are loaded just after initialization' do + require "#{app_path}/config/application" + + # Create the rack app just inside after initialize callback + ActiveSupport.on_load(:after_initialize) do + ::InitializeRackApp = lambda { |env| [200, {}, ["InitializeRackApp"]] } + end + + app_file 'config/routes.rb', <<-RUBY + AppTemplate::Application.routes.draw do + match 'foo', :to => ::InitializeRackApp + end + RUBY + + get '/foo' + assert_equal "InitializeRackApp", last_response.body + end + + test 'reload_routes! is part of Rails.application API' do + app("development") + assert_nothing_raised do + Rails.application.reload_routes! + end + end + + test 'resource routing with irregular inflection' do app_file 'config/initializers/inflection.rb', <<-RUBY ActiveSupport::Inflector.inflections do |inflect| inflect.irregular 'yazi', 'yazilar' @@ -223,7 +233,7 @@ module ApplicationTests RUBY app_file 'config/routes.rb', <<-RUBY - AppTemplate::Application.routes.draw do |map| + AppTemplate::Application.routes.draw do resources :yazilar end RUBY diff --git a/railties/test/application/runner_test.rb b/railties/test/application/runner_test.rb index 07a3d94120..292d1e247f 100644 --- a/railties/test/application/runner_test.rb +++ b/railties/test/application/runner_test.rb @@ -18,6 +18,10 @@ module ApplicationTests MODEL end + def test_should_include_runner_in_shebang_line_in_help + assert_match "/rails runner", Dir.chdir(app_path) { `bundle exec rails runner --help` } + end + def test_should_run_ruby_statement assert_match "42", Dir.chdir(app_path) { `bundle exec rails runner "puts User.count"` } end diff --git a/railties/test/application/test_test.rb b/railties/test/application/test_test.rb index de316a6fd0..1fbbb40132 100644 --- a/railties/test/application/test_test.rb +++ b/railties/test/application/test_test.rb @@ -53,7 +53,7 @@ module ApplicationTests app_file 'test/integration/posts_test.rb', <<-RUBY require 'test_helper' - class PostsTest < ActionController::IntegrationTest + class PostsTest < ActionDispatch::IntegrationTest def test_index get '/posts' assert_response :success diff --git a/railties/test/fixtures/lib/empty_builder.rb b/railties/test/fixtures/lib/app_builders/empty_builder.rb index babd9c2461..babd9c2461 100644 --- a/railties/test/fixtures/lib/empty_builder.rb +++ b/railties/test/fixtures/lib/app_builders/empty_builder.rb diff --git a/railties/test/fixtures/lib/app_builders/simple_builder.rb b/railties/test/fixtures/lib/app_builders/simple_builder.rb new file mode 100644 index 0000000000..993d3a2aa2 --- /dev/null +++ b/railties/test/fixtures/lib/app_builders/simple_builder.rb @@ -0,0 +1,7 @@ +class AppBuilder + def gitignore + create_file ".gitignore", <<-R.strip +foobar + R + end +end diff --git a/railties/test/fixtures/lib/app_builders/tweak_builder.rb b/railties/test/fixtures/lib/app_builders/tweak_builder.rb new file mode 100644 index 0000000000..cb50be01cb --- /dev/null +++ b/railties/test/fixtures/lib/app_builders/tweak_builder.rb @@ -0,0 +1,7 @@ +class AppBuilder < Rails::AppBuilder + def gitignore + create_file ".gitignore", <<-R.strip +foobar + R + end +end diff --git a/railties/test/fixtures/lib/create_test_dummy_template.rb b/railties/test/fixtures/lib/create_test_dummy_template.rb new file mode 100644 index 0000000000..e4378bbd1a --- /dev/null +++ b/railties/test/fixtures/lib/create_test_dummy_template.rb @@ -0,0 +1 @@ +create_dummy_app("spec/dummy") diff --git a/railties/test/fixtures/lib/plugin_builders/empty_builder.rb b/railties/test/fixtures/lib/plugin_builders/empty_builder.rb new file mode 100644 index 0000000000..5c5607621c --- /dev/null +++ b/railties/test/fixtures/lib/plugin_builders/empty_builder.rb @@ -0,0 +1,2 @@ +class PluginBuilder +end diff --git a/railties/test/fixtures/lib/plugin_builders/simple_builder.rb b/railties/test/fixtures/lib/plugin_builders/simple_builder.rb new file mode 100644 index 0000000000..08f6c5535d --- /dev/null +++ b/railties/test/fixtures/lib/plugin_builders/simple_builder.rb @@ -0,0 +1,7 @@ +class PluginBuilder + def gitignore + create_file ".gitignore", <<-R.strip +foobar + R + end +end diff --git a/railties/test/fixtures/lib/plugin_builders/spec_builder.rb b/railties/test/fixtures/lib/plugin_builders/spec_builder.rb new file mode 100644 index 0000000000..aa18c7ddaa --- /dev/null +++ b/railties/test/fixtures/lib/plugin_builders/spec_builder.rb @@ -0,0 +1,19 @@ +class PluginBuilder < Rails::PluginBuilder + def test + create_file "spec/spec_helper.rb" + append_file "Rakefile", <<-EOF +# spec tasks in rakefile + +task :default => :spec + EOF + end + + def generate_test_dummy + dummy_path("spec/dummy") + super + end + + def skip_test_unit? + true + end +end diff --git a/railties/test/fixtures/lib/plugin_builders/tweak_builder.rb b/railties/test/fixtures/lib/plugin_builders/tweak_builder.rb new file mode 100644 index 0000000000..1e801409a4 --- /dev/null +++ b/railties/test/fixtures/lib/plugin_builders/tweak_builder.rb @@ -0,0 +1,7 @@ +class PluginBuilder < Rails::PluginBuilder + def gitignore + create_file ".gitignore", <<-R.strip +foobar + R + end +end diff --git a/railties/test/fixtures/lib/simple_builder.rb b/railties/test/fixtures/lib/simple_builder.rb deleted file mode 100644 index 47dcdc0d96..0000000000 --- a/railties/test/fixtures/lib/simple_builder.rb +++ /dev/null @@ -1,7 +0,0 @@ -class AppBuilder - def configru - create_file "config.ru", <<-R.strip -run proc { |env| [200, { "Content-Type" => "text/html" }, ["Hello World"]] } - R - end -end
\ No newline at end of file diff --git a/railties/test/fixtures/lib/tweak_builder.rb b/railties/test/fixtures/lib/tweak_builder.rb deleted file mode 100644 index eed20ecc9b..0000000000 --- a/railties/test/fixtures/lib/tweak_builder.rb +++ /dev/null @@ -1,7 +0,0 @@ -class AppBuilder < Rails::AppBuilder - def configru - create_file "config.ru", <<-R.strip -run proc { |env| [200, { "Content-Type" => "text/html" }, ["Hello World"]] } - R - end -end
\ No newline at end of file diff --git a/railties/test/generators/actions_test.rb b/railties/test/generators/actions_test.rb index 0472ca73a8..68d4c17623 100644 --- a/railties/test/generators/actions_test.rb +++ b/railties/test/generators/actions_test.rb @@ -7,11 +7,16 @@ class ActionsTest < Rails::Generators::TestCase arguments [destination_root] def setup + Rails.application = TestApp::Application super @git_plugin_uri = 'git://github.com/technoweenie/restful-authentication.git' @svn_plugin_uri = 'svn://svnhub.com/technoweenie/restful-authentication/trunk' end + def teardown + Rails.application = TestApp::Application.instance + end + def test_invoke_other_generator_with_shortcut action :invoke, 'model', ['my_model'] assert_file 'app/models/my_model.rb', /MyModel/ @@ -79,37 +84,6 @@ class ActionsTest < Rails::Generators::TestCase assert_file 'Gemfile', /gem "will\-paginate"/ end - def test_gem_with_options_should_include_all_options_in_gemfile - run_generator - - assert_deprecated do - action :gem, 'mislav-will-paginate', :lib => 'will-paginate', :source => 'http://gems.github.com' - end - - assert_deprecated do - action :gem, 'thoughtbot-factory_girl', :require_as => 'factory_girl', :source => 'http://gems.github.com' - end - - assert_file 'Gemfile', /gem "mislav\-will\-paginate", :require => "will\-paginate"/ - assert_file 'Gemfile', /source "http:\/\/gems\.github\.com"/ - assert_file 'Gemfile', /gem "thoughtbot-factory_girl", :require => "factory_girl"/ - end - - def test_gem_with_env_should_include_all_dependencies_in_gemfile - run_generator - - assert_deprecated do - action :gem, 'rspec', :env => %w(development test) - end - - assert_deprecated do - action :gem, 'rspec-rails', :only => %w(development test) - end - - assert_file 'Gemfile', /gem "rspec", :group => \["development", "test"\]/ - assert_file 'Gemfile', /gem "rspec-rails", :group => \["development", "test"\]/ - end - def test_gem_with_version_should_include_version_in_gemfile run_generator @@ -204,12 +178,6 @@ class ActionsTest < Rails::Generators::TestCase action :capify! end - def test_freeze_is_deprecated - assert_deprecated do - action :freeze! - end - end - def test_route_should_add_data_to_the_routes_block_in_config_routes run_generator route_command = "route '/login', :controller => 'sessions', :action => 'new'" @@ -223,6 +191,31 @@ class ActionsTest < Rails::Generators::TestCase assert_match(/Welcome to Rails/, action(:readme, "README")) end + def test_readme_with_quiet + generator(default_arguments, :quiet => true) + run_generator + Rails::Generators::AppGenerator.expects(:source_root).times(2).returns(destination_root) + assert_no_match(/Welcome to Rails/, action(:readme, "README")) + end + + def test_log + assert_equal("YES\n", action(:log, "YES")) + end + + def test_log_with_status + assert_equal(" yes YES\n", action(:log, :yes, "YES")) + end + + def test_log_with_quiet + generator(default_arguments, :quiet => true) + assert_equal("", action(:log, "YES")) + end + + def test_log_with_status_with_quiet + generator(default_arguments, :quiet => true) + assert_equal("", action(:log, :yes, "YES")) + end + protected def action(*args, &block) diff --git a/railties/test/generators/app_generator_test.rb b/railties/test/generators/app_generator_test.rb index 08cfb585f9..018c2fa6bf 100644 --- a/railties/test/generators/app_generator_test.rb +++ b/railties/test/generators/app_generator_test.rb @@ -1,6 +1,7 @@ require 'abstract_unit' require 'generators/generators_test_helper' require 'rails/generators/rails/app/app_generator' +require 'generators/shared_generator_tests.rb' DEFAULT_APP_FILES = %w( .gitignore @@ -40,28 +41,10 @@ DEFAULT_APP_FILES = %w( class AppGeneratorTest < Rails::Generators::TestCase include GeneratorsTestHelper arguments [destination_root] + include SharedGeneratorTests - def setup - super - Rails::Generators::AppGenerator.instance_variable_set('@desc', nil) - @bundle_command = File.basename(Thor::Util.ruby_command).sub(/ruby/, 'bundle') - end - - def teardown - super - Rails::Generators::AppGenerator.instance_variable_set('@desc', nil) - end - - def test_application_skeleton_is_created - run_generator - - DEFAULT_APP_FILES.each{ |path| assert_file path } - end - - def test_application_generate_pretend - run_generator ["testapp", "--pretend"] - - DEFAULT_APP_FILES.each{ |path| assert_no_file path } + def default_files + ::DEFAULT_APP_FILES end def test_application_controller_and_layout_files @@ -70,42 +53,34 @@ class AppGeneratorTest < Rails::Generators::TestCase assert_no_file "public/stylesheets/application.css" end - def test_options_before_application_name_raises_an_error - content = capture(:stderr){ run_generator(["--skip-active-record", destination_root]) } - assert_equal "Options should be given after the application name. For details run: rails --help\n", content - end - - def test_name_collision_raises_an_error - reserved_words = %w[application destroy plugin runner test] - reserved_words.each do |reserved| - content = capture(:stderr){ run_generator [File.join(destination_root, reserved)] } - assert_equal "Invalid application name #{reserved}. Please give a name which does not match one of the reserved rails words.\n", content - end - end - - def test_invalid_database_option_raises_an_error - content = capture(:stderr){ run_generator([destination_root, "-d", "unknown"]) } - assert_match /Invalid value for \-\-database option/, content - end - def test_invalid_application_name_raises_an_error content = capture(:stderr){ run_generator [File.join(destination_root, "43-things")] } assert_equal "Invalid application name 43-things. Please give a name which does not start with numbers.\n", content end - def test_application_name_raises_an_error_if_name_already_used_constant - %w{ String Hash Class Module Set Symbol }.each do |ruby_class| - content = capture(:stderr){ run_generator [File.join(destination_root, ruby_class)] } - assert_equal "Invalid application name #{ruby_class}, constant #{ruby_class} is already in use. Please choose another application name.\n", content - end - end - def test_invalid_application_name_is_fixed run_generator [File.join(destination_root, "things-43")] assert_file "things-43/config/environment.rb", /Things43::Application\.initialize!/ assert_file "things-43/config/application.rb", /^module Things43$/ end + def test_application_new_exits_with_non_zero_code_on_invalid_application_name + # TODO: Suppress the output of this (it's because of a Thor::Error) + `rails new test` + assert_equal false, $?.success? + end + + def test_application_new_exits_with_message_and_non_zero_code_when_generating_inside_existing_rails_directory + app_root = File.join(destination_root, 'myfirstapp') + run_generator [app_root] + output = nil + Dir.chdir(app_root) do + output = `rails new mysecondapp` + end + assert_equal "Can't initialize a new Rails application within the directory of another, please change to a non-Rails directory first.\nType 'rails' for help.\n", output + assert_equal false, $?.success? + end + def test_application_name_is_detected_if_it_exists_and_app_folder_renamed app_root = File.join(destination_root, "myapp") app_moved_root = File.join(destination_root, "myapp_moved") @@ -118,16 +93,26 @@ class AppGeneratorTest < Rails::Generators::TestCase FileUtils.mv(app_root, app_moved_root) - # forces the shell to automatically overwrite all files - Thor::Base.shell.send(:attr_accessor, :always_force) - shell = Thor::Base.shell.new - shell.send(:always_force=, true) - generator = Rails::Generators::AppGenerator.new ["rails"], { :with_dispatchers => true }, - :destination_root => app_moved_root, :shell => shell + :destination_root => app_moved_root, :shell => @shell generator.send(:app_const) silence(:stdout){ generator.send(:create_config_files) } assert_file "myapp_moved/config/environment.rb", /Myapp::Application\.initialize!/ + assert_file "myapp_moved/config/initializers/session_store.rb", /_myapp_session/ + end + + def test_rails_update_generates_correct_session_key + app_root = File.join(destination_root, 'myapp') + run_generator [app_root] + + Rails.application.config.root = app_root + Rails.application.class.stubs(:name).returns("Myapp") + Rails.application.stubs(:is_a?).returns(Rails::Application) + + generator = Rails::Generators::AppGenerator.new ["rails"], { :with_dispatchers => true }, :destination_root => app_root, :shell => @shell + generator.send(:app_const) + silence(:stdout){ generator.send(:create_config_files) } + assert_file "myapp/config/initializers/session_store.rb", /_myapp_session/ end def test_application_names_are_not_singularized @@ -138,18 +123,22 @@ class AppGeneratorTest < Rails::Generators::TestCase def test_config_database_is_added_by_default run_generator assert_file "config/database.yml", /sqlite3/ - assert_file "Gemfile", /^gem\s+["']sqlite3-ruby["'],\s+:require\s+=>\s+["']sqlite3["']$/ + assert_file "Gemfile", /^gem\s+["']sqlite3["']$/ end def test_config_another_database run_generator([destination_root, "-d", "mysql"]) assert_file "config/database.yml", /mysql/ - assert_file "Gemfile", /^gem\s+["']mysql["']$/ + assert_file "Gemfile", /^gem\s+["']mysql2["']$/ end - def test_config_database_is_not_added_if_skip_active_record_is_given + def test_generator_if_skip_active_record_is_given run_generator [destination_root, "--skip-active-record"] assert_no_file "config/database.yml" + assert_file "test/test_helper.rb" do |helper_content| + assert_no_match /fixtures :all/, helper_content + end + assert_file "test/performance/browsing_test.rb" end def test_active_record_is_removed_from_frameworks_if_skip_active_record_is_given @@ -163,26 +152,37 @@ class AppGeneratorTest < Rails::Generators::TestCase assert_file "public/javascripts/application.js" assert_file "public/javascripts/prototype.js" assert_file "public/javascripts/rails.js" + assert_file "public/javascripts/controls.js" + assert_file "public/javascripts/dragdrop.js" + assert_file "public/javascripts/effects.js" assert_file "test" end - def test_prototype_and_test_unit_are_skipped_if_required - run_generator [destination_root, "--skip-prototype", "--skip-test-unit"] + def test_javascript_is_skipped_if_required + run_generator [destination_root, "--skip-javascript"] assert_file "config/application.rb", /^\s+config\.action_view\.javascript_expansions\[:defaults\]\s+=\s+%w\(\)/ assert_file "public/javascripts/application.js" assert_no_file "public/javascripts/prototype.js" assert_no_file "public/javascripts/rails.js" - assert_no_file "test" end - def test_shebang_is_added_to_rails_file - run_generator [destination_root, "--ruby", "foo/bar/baz"] - assert_file "script/rails", /#!foo\/bar\/baz/ + def test_config_prototype_javascript_library + run_generator [destination_root, "-j", "prototype"] + assert_file "config/application.rb", /#\s+config\.action_view\.javascript_expansions\[:defaults\]\s+=\s+%w\(jquery rails\)/ + assert_file "public/javascripts/application.js" + assert_file "public/javascripts/prototype.js" + assert_file "public/javascripts/controls.js" + assert_file "public/javascripts/dragdrop.js" + assert_file "public/javascripts/effects.js" + assert_file "public/javascripts/rails.js", /prototype/ end - def test_shebang_when_is_the_same_as_default_use_env - run_generator [destination_root, "--ruby", Thor::Util.ruby_command] - assert_file "script/rails", /#!\/usr\/bin\/env/ + def test_config_jquery_javascript_library + run_generator [destination_root, "-j", "jquery"] + assert_file "config/application.rb", /^\s+config\.action_view\.javascript_expansions\[:defaults\]\s+=\s+%w\(jquery rails\)/ + assert_file "public/javascripts/application.js" + assert_file "public/javascripts/jquery.js" + assert_file "public/javascripts/rails.js", /jQuery/ end def test_template_from_dir_pwd @@ -190,21 +190,6 @@ class AppGeneratorTest < Rails::Generators::TestCase assert_match /It works from file!/, run_generator([destination_root, "-m", "lib/template.rb"]) end - def test_template_raises_an_error_with_invalid_path - content = capture(:stderr){ run_generator([destination_root, "-m", "non/existant/path"]) } - assert_match /The template \[.*\] could not be loaded/, content - assert_match /non\/existant\/path/, content - end - - def test_template_is_executed_when_supplied - path = "http://gist.github.com/103208.txt" - template = %{ say "It works!" } - template.instance_eval "def read; self; end" # Make the string respond to read - - generator([destination_root], :template => path).expects(:open).with(path, 'Accept' => 'application/x-thor-template').returns(template) - assert_match /It works!/, silence(:stdout){ generator.invoke_all } - end - def test_usage_read_from_file File.expects(:read).returns("USAGE FROM FILE") assert_equal "USAGE FROM FILE", Rails::Generators::AppGenerator.desc @@ -224,17 +209,11 @@ class AppGeneratorTest < Rails::Generators::TestCase assert_file 'lib/test_file.rb', 'heres test data' end - def test_dev_option - generator([destination_root], :dev => true).expects(:run).with("#{@bundle_command} install") - silence(:stdout){ generator.invoke_all } - rails_path = File.expand_path('../../..', Rails.root) - assert_file 'Gemfile', /^gem\s+["']rails["'],\s+:path\s+=>\s+["']#{Regexp.escape(rails_path)}["']$/ - end - - def test_edge_option - generator([destination_root], :edge => true).expects(:run).with("#{@bundle_command} install") - silence(:stdout){ generator.invoke_all } - assert_file 'Gemfile', /^gem\s+["']rails["'],\s+:git\s+=>\s+["']#{Regexp.escape("git://github.com/rails/rails.git")}["']$/ + def test_test_unit_is_removed_from_frameworks_if_skip_test_unit_is_given + run_generator [destination_root, "--skip-test-unit"] + assert_file "config/application.rb" do |file| + assert_match /config.generators.test_framework = false/, file + end end protected @@ -250,60 +229,21 @@ class CustomAppGeneratorTest < Rails::Generators::TestCase tests Rails::Generators::AppGenerator arguments [destination_root] + include SharedCustomGeneratorTests - def setup - super - Rails::Generators::AppGenerator.instance_variable_set('@desc', nil) - @bundle_command = File.basename(Thor::Util.ruby_command).sub(/ruby/, 'bundle') - end - - def teardown - super - Rails::Generators::AppGenerator.instance_variable_set('@desc', nil) - Object.class_eval { remove_const :AppBuilder if const_defined?(:AppBuilder) } - end - - def test_builder_option_with_empty_app_builder - FileUtils.cd(Rails.root) - run_generator([destination_root, "-b", "#{Rails.root}/lib/empty_builder.rb"]) - DEFAULT_APP_FILES.each{ |path| assert_no_file path } - end - - def test_builder_option_with_simple_app_builder - FileUtils.cd(Rails.root) - run_generator([destination_root, "-b", "#{Rails.root}/lib/simple_builder.rb"]) - (DEFAULT_APP_FILES - ['config.ru']).each{ |path| assert_no_file path } - assert_file "config.ru", %[run proc { |env| [200, { "Content-Type" => "text/html" }, ["Hello World"]] }] - end - - def test_builder_option_with_relative_path - here = File.expand_path(File.dirname(__FILE__)) - FileUtils.cd(here) - run_generator([destination_root, "-b", "../fixtures/lib/simple_builder.rb"]) - (DEFAULT_APP_FILES - ['config.ru']).each{ |path| assert_no_file path } - assert_file "config.ru", %[run proc { |env| [200, { "Content-Type" => "text/html" }, ["Hello World"]] }] +protected + def default_files + ::DEFAULT_APP_FILES end - def test_builder_option_with_tweak_app_builder - FileUtils.cd(Rails.root) - run_generator([destination_root, "-b", "#{Rails.root}/lib/tweak_builder.rb"]) - DEFAULT_APP_FILES.each{ |path| assert_file path } - assert_file "config.ru", %[run proc { |env| [200, { "Content-Type" => "text/html" }, ["Hello World"]] }] + def builders_dir + "app_builders" end - def test_builder_option_with_http - path = "http://gist.github.com/103208.txt" - template = "class AppBuilder; end" - template.instance_eval "def read; self; end" # Make the string respond to read - - generator([destination_root], :builder => path).expects(:open).with(path, 'Accept' => 'application/x-thor-template').returns(template) - capture(:stdout) { generator.invoke_all } - - DEFAULT_APP_FILES.each{ |path| assert_no_file path } + def builder_class + :AppBuilder end -protected - def action(*args, &block) silence(:stdout){ generator.send(*args, &block) } end diff --git a/railties/test/generators/generated_attribute_test.rb b/railties/test/generators/generated_attribute_test.rb index de7e4de2a6..064546a3f3 100644 --- a/railties/test/generators/generated_attribute_test.rb +++ b/railties/test/generators/generated_attribute_test.rb @@ -108,4 +108,16 @@ class GeneratedAttributeTest < Rails::Generators::TestCase ) end end + + def test_nil_type_raises_exception + assert_raise Thor::Error do + create_generated_attribute(nil, 'title') + end + end + + def test_missing_type_raises_exception + assert_raise Thor::Error do + create_generated_attribute('', 'title') + end + end end diff --git a/railties/test/generators/generator_generator_test.rb b/railties/test/generators/generator_generator_test.rb index 26f975a191..f4c975fc18 100644 --- a/railties/test/generators/generator_generator_test.rb +++ b/railties/test/generators/generator_generator_test.rb @@ -17,4 +17,43 @@ class GeneratorGeneratorTest < Rails::Generators::TestCase assert_file "lib/generators/awesome/awesome_generator.rb", /class AwesomeGenerator < Rails::Generators::NamedBase/ end + + def test_namespaced_generator_skeleton + run_generator ["rails/awesome"] + + %w( + lib/generators/rails/awesome + lib/generators/rails/awesome/USAGE + lib/generators/rails/awesome/templates + ).each{ |path| assert_file path } + + assert_file "lib/generators/rails/awesome/awesome_generator.rb", + /class Rails::AwesomeGenerator < Rails::Generators::NamedBase/ + end + + def test_generator_skeleton_is_created_without_file_name_namespace + run_generator ["awesome", "--namespace", "false"] + + %w( + lib/generators/ + lib/generators/USAGE + lib/generators/templates + ).each{ |path| assert_file path } + + assert_file "lib/generators/awesome_generator.rb", + /class AwesomeGenerator < Rails::Generators::NamedBase/ + end + + def test_namespaced_generator_skeleton_without_file_name_namespace + run_generator ["rails/awesome", "--namespace", "false"] + + %w( + lib/generators/rails + lib/generators/rails/USAGE + lib/generators/rails/templates + ).each{ |path| assert_file path } + + assert_file "lib/generators/rails/awesome_generator.rb", + /class Rails::AwesomeGenerator < Rails::Generators::NamedBase/ + end end diff --git a/railties/test/generators/generators_test_helper.rb b/railties/test/generators/generators_test_helper.rb index 4a5a9b2932..1b9a8fd8a7 100644 --- a/railties/test/generators/generators_test_helper.rb +++ b/railties/test/generators/generators_test_helper.rb @@ -34,6 +34,6 @@ module GeneratorsTestHelper routes = File.expand_path("../../../lib/rails/generators/rails/app/templates/config/routes.rb", __FILE__) destination = File.join(destination_root, "config") FileUtils.mkdir_p(destination) - FileUtils.cp File.expand_path(routes), destination + FileUtils.cp routes, destination end -end
\ No newline at end of file +end diff --git a/railties/test/generators/mailer_generator_test.rb b/railties/test/generators/mailer_generator_test.rb index 450dec7716..f4fdc46328 100644 --- a/railties/test/generators/mailer_generator_test.rb +++ b/railties/test/generators/mailer_generator_test.rb @@ -59,6 +59,15 @@ class MailerGeneratorTest < Rails::Generators::TestCase assert_match /haml \[not found\]/, content end + def test_mailer_with_namedspaced_mailer + run_generator ["Farm::Animal", "moos"] + assert_file "app/mailers/farm/animal.rb" do |mailer| + assert_match /class Farm::Animal < ActionMailer::Base/, mailer + assert_match /en\.farm\.animal\.moos\.subject/, mailer + end + assert_file "app/views/farm/animal/moos.text.erb" + end + def test_actions_are_turned_into_methods run_generator diff --git a/railties/test/generators/migration_generator_test.rb b/railties/test/generators/migration_generator_test.rb index f9d1e42d24..6eecfc8e2e 100644 --- a/railties/test/generators/migration_generator_test.rb +++ b/railties/test/generators/migration_generator_test.rb @@ -34,15 +34,10 @@ class MigrationGeneratorTest < Rails::Generators::TestCase run_generator [migration, "title:string", "body:text"] assert_migration "db/migrate/#{migration}.rb" do |content| - assert_class_method :up, content do |up| + assert_method :change, content do |up| assert_match /add_column :posts, :title, :string/, up assert_match /add_column :posts, :body, :text/, up end - - assert_class_method :down, content do |down| - assert_match /remove_column :posts, :title/, down - assert_match /remove_column :posts, :body/, down - end end end @@ -51,12 +46,12 @@ class MigrationGeneratorTest < Rails::Generators::TestCase run_generator [migration, "title:string", "body:text"] assert_migration "db/migrate/#{migration}.rb" do |content| - assert_class_method :up, content do |up| + assert_method :up, content do |up| assert_match /remove_column :posts, :title/, up assert_match /remove_column :posts, :body/, up end - assert_class_method :down, content do |down| + assert_method :down, content do |down| assert_match /add_column :posts, :title, :string/, down assert_match /add_column :posts, :body, :text/, down end @@ -68,11 +63,11 @@ class MigrationGeneratorTest < Rails::Generators::TestCase run_generator [migration, "title:string", "content:text"] assert_migration "db/migrate/#{migration}.rb" do |content| - assert_class_method :up, content do |up| + assert_method :up, content do |up| assert_match /^\s*$/, up end - assert_class_method :down, content do |down| + assert_method :down, content do |down| assert_match /^\s*$/, down end end diff --git a/railties/test/generators/model_generator_test.rb b/railties/test/generators/model_generator_test.rb index ef415a4fed..3d773b4134 100644 --- a/railties/test/generators/model_generator_test.rb +++ b/railties/test/generators/model_generator_test.rb @@ -11,6 +11,12 @@ class ModelGeneratorTest < Rails::Generators::TestCase assert_match /TestUnit options:/, content end + def test_model_with_missing_attribute_type + content = capture(:stderr) { run_generator ["post", "title:string", "body"] } + assert_match /Missing type for attribute 'body'/, content + assert_match /Example: 'body:string' where string is the type/, content + end + def test_invokes_default_orm run_generator assert_file "app/models/account.rb", /class Account < ActiveRecord::Base/ @@ -93,15 +99,11 @@ class ModelGeneratorTest < Rails::Generators::TestCase run_generator ["product", "name:string", "supplier_id:integer"] assert_migration "db/migrate/create_products.rb" do |m| - assert_class_method :up, m do |up| + assert_method :change, m do |up| assert_match /create_table :products/, up assert_match /t\.string :name/, up assert_match /t\.integer :supplier_id/, up end - - assert_class_method :down, m do |down| - assert_match /drop_table :products/, down - end end end @@ -135,16 +137,28 @@ class ModelGeneratorTest < Rails::Generators::TestCase run_generator ["account", "--no-timestamps"] assert_migration "db/migrate/create_accounts.rb" do |m| - assert_class_method :up, m do |up| + assert_method :change, m do |up| assert_no_match /t.timestamps/, up end end end - def test_migration_already_exists_error_message + def test_migration_is_skipped_with_skip_option + run_generator + output = run_generator ["Account", "--skip"] + assert_match %r{skip\s+db/migrate/\d+_create_accounts.rb}, output + end + + def test_migration_is_ignored_as_identical_with_skip_option + run_generator ["Account"] + output = run_generator ["Account", "--skip"] + assert_match %r{identical\s+db/migrate/\d+_create_accounts.rb}, output + end + + def test_migration_is_skipped_on_skip_behavior run_generator - error = capture(:stderr){ run_generator ["Account"], :behavior => :skip } - assert_match /Another migration is already named create_accounts/, error + output = run_generator ["Account"], :behavior => :skip + assert_match %r{skip\s+db/migrate/\d+_create_accounts.rb}, output end def test_migration_error_is_not_shown_on_revoke @@ -159,6 +173,15 @@ class ModelGeneratorTest < Rails::Generators::TestCase assert_no_migration "db/migrate/create_accounts.rb" end + def test_existing_migration_is_removed_on_force + run_generator + old_migration = Dir["#{destination_root}/db/migrate/*_create_accounts.rb"].first + error = capture(:stderr) { run_generator ["Account", "--force"] } + assert_no_match /Another migration is already named create_accounts/, error + assert_no_file old_migration + assert_migration 'db/migrate/create_accounts.rb' + end + def test_invokes_default_test_framework run_generator assert_file "test/unit/account_test.rb", /class AccountTest < ActiveSupport::TestCase/ @@ -180,4 +203,45 @@ class ModelGeneratorTest < Rails::Generators::TestCase content = capture(:stderr){ run_generator ["object"] } assert_match /The name 'Object' is either already used in your application or reserved/, content end + + def test_index_is_added_for_belongs_to_association + run_generator ["account", "supplier:belongs_to"] + + assert_migration "db/migrate/create_accounts.rb" do |m| + assert_method :change, m do |up| + assert_match /add_index/, up + end + end + end + + def test_index_is_added_for_references_association + run_generator ["account", "supplier:references"] + + assert_migration "db/migrate/create_accounts.rb" do |m| + assert_method :change, m do |up| + assert_match /add_index/, up + end + end + end + + def test_index_is_skipped_for_belongs_to_association + run_generator ["account", "supplier:belongs_to", "--no-indexes"] + + assert_migration "db/migrate/create_accounts.rb" do |m| + assert_method :change, m do |up| + assert_no_match /add_index/, up + end + end + end + + def test_index_is_skipped_for_references_association + run_generator ["account", "supplier:references", "--no-indexes"] + + assert_migration "db/migrate/create_accounts.rb" do |m| + assert_method :change, m do |up| + assert_no_match /add_index/, up + end + end + end + end diff --git a/railties/test/generators/named_base_test.rb b/railties/test/generators/named_base_test.rb index 1badae0713..f23701e99e 100644 --- a/railties/test/generators/named_base_test.rb +++ b/railties/test/generators/named_base_test.rb @@ -98,6 +98,11 @@ class NamedBaseTest < Rails::Generators::TestCase assert_name g, 'posts', :index_helper end + def test_index_helper_to_pluralize_once + g = generator ['Stadium'] + assert_name g, 'stadia', :index_helper + end + def test_index_helper_with_uncountable g = generator ['Sheep'] assert_name g, 'sheep_index', :index_helper diff --git a/railties/test/generators/namespaced_generators_test.rb b/railties/test/generators/namespaced_generators_test.rb new file mode 100644 index 0000000000..d61a02d32f --- /dev/null +++ b/railties/test/generators/namespaced_generators_test.rb @@ -0,0 +1,357 @@ +require 'generators/generators_test_helper' +require 'rails/generators/rails/controller/controller_generator' +require 'rails/generators/rails/model/model_generator' +require 'rails/generators/rails/observer/observer_generator' +require 'rails/generators/mailer/mailer_generator' +require 'rails/generators/rails/scaffold/scaffold_generator' + +class NamespacedGeneratorTestCase < Rails::Generators::TestCase + def setup + TestApp::Application.isolate_namespace(TestApp) + end + + def teardown + if TestApp.respond_to?(:_railtie) + TestApp.singleton_class.send(:undef_method, :_railtie) + TestApp.singleton_class.send(:undef_method, :table_name_prefix) + TestApp::Application.isolated = false + end + end +end + +class NamespacedControllerGeneratorTest < NamespacedGeneratorTestCase + include GeneratorsTestHelper + arguments %w(Account foo bar) + tests Rails::Generators::ControllerGenerator + + setup :copy_routes + + def test_namespaced_controller_skeleton_is_created + run_generator + assert_file "app/controllers/test_app/account_controller.rb", /module TestApp/, / class AccountController < ApplicationController/ + assert_file "test/functional/test_app/account_controller_test.rb", /module TestApp/, / class AccountControllerTest/ + end + + def test_skipping_namespace + run_generator ["Account", "--skip-namespace"] + assert_file "app/controllers/account_controller.rb", /class AccountController < ApplicationController/ + assert_file "app/helpers/account_helper.rb", /module AccountHelper/ + end + + def test_namespaced_controller_with_additional_namespace + run_generator ["admin/account"] + assert_file "app/controllers/test_app/admin/account_controller.rb", /module TestApp/, / class Admin::AccountController < ApplicationController/ + end + + def test_helpr_is_also_namespaced + run_generator + assert_file "app/helpers/test_app/account_helper.rb", /module TestApp/, / module AccountHelper/ + assert_file "test/unit/helpers/test_app/account_helper_test.rb", /module TestApp/, / class AccountHelperTest/ + end + + def test_invokes_default_test_framework + run_generator + assert_file "test/functional/test_app/account_controller_test.rb" + end + + def test_invokes_default_template_engine + run_generator + assert_file "app/views/test_app/account/foo.html.erb", %r(app/views/test_app/account/foo\.html\.erb) + assert_file "app/views/test_app/account/bar.html.erb", %r(app/views/test_app/account/bar\.html\.erb) + end + + def test_routes_should_not_be_namespaced + run_generator + assert_file "config/routes.rb", /get "account\/foo"/, /get "account\/bar"/ + end +# + def test_invokes_default_template_engine_even_with_no_action + run_generator ["account"] + assert_file "app/views/test_app/account" + end +end + +class NamespacedModelGeneratorTest < NamespacedGeneratorTestCase + include GeneratorsTestHelper + arguments %w(Account name:string age:integer) + tests Rails::Generators::ModelGenerator + + def test_module_file_is_not_created + run_generator + assert_no_file "app/models/test_app.rb" + end + + def test_adds_namespace_to_model + run_generator + assert_file "app/models/test_app/account.rb", /module TestApp/, / class Account < ActiveRecord::Base/ + end + + def test_model_with_namespace + run_generator ["admin/account"] + assert_file "app/models/test_app/admin.rb", /module TestApp/, /module Admin/ + assert_file "app/models/test_app/admin.rb", /def self\.table_name_prefix/ + assert_file "app/models/test_app/admin.rb", /'admin_'/ + assert_file "app/models/test_app/admin/account.rb", /module TestApp/, /class Admin::Account < ActiveRecord::Base/ + end + + def test_migration + run_generator + assert_migration "db/migrate/create_test_app_accounts.rb", /create_table :test_app_accounts/, /class CreateTestAppAccounts < ActiveRecord::Migration/ + end + + def test_migration_with_namespace + run_generator ["Gallery::Image"] + assert_migration "db/migrate/create_test_app_gallery_images", /class CreateTestAppGalleryImages < ActiveRecord::Migration/ + assert_no_migration "db/migrate/create_test_app_images" + end + + def test_migration_with_nested_namespace + run_generator ["Admin::Gallery::Image"] + assert_no_migration "db/migrate/create_images" + assert_no_migration "db/migrate/create_gallery_images" + assert_migration "db/migrate/create_test_app_admin_gallery_images", /class CreateTestAppAdminGalleryImages < ActiveRecord::Migration/ + assert_migration "db/migrate/create_test_app_admin_gallery_images", /create_table :test_app_admin_gallery_images/ + end + + def test_migration_with_nested_namespace_without_pluralization + ActiveRecord::Base.pluralize_table_names = false + run_generator ["Admin::Gallery::Image"] + assert_no_migration "db/migrate/create_images" + assert_no_migration "db/migrate/create_gallery_images" + assert_no_migration "db/migrate/create_test_app_admin_gallery_images" + assert_migration "db/migrate/create_test_app_admin_gallery_image", /class CreateTestAppAdminGalleryImage < ActiveRecord::Migration/ + assert_migration "db/migrate/create_test_app_admin_gallery_image", /create_table :test_app_admin_gallery_image/ + ensure + ActiveRecord::Base.pluralize_table_names = true + end + + def test_invokes_default_test_framework + run_generator + assert_file "test/unit/test_app/account_test.rb", /module TestApp/, /class AccountTest < ActiveSupport::TestCase/ + assert_file "test/fixtures/test_app/accounts.yml", /name: MyString/, /age: 1/ + end +end + +class NamespacedObserverGeneratorTest < NamespacedGeneratorTestCase + include GeneratorsTestHelper + arguments %w(account) + tests Rails::Generators::ObserverGenerator + + def test_invokes_default_orm + run_generator + assert_file "app/models/test_app/account_observer.rb", /module TestApp/, / class AccountObserver < ActiveRecord::Observer/ + end + + def test_invokes_default_orm_with_class_path + run_generator ["admin/account"] + assert_file "app/models/test_app/admin/account_observer.rb", /module TestApp/, / class Admin::AccountObserver < ActiveRecord::Observer/ + end + + def test_invokes_default_test_framework + run_generator + assert_file "test/unit/test_app/account_observer_test.rb", /module TestApp/, / class AccountObserverTest < ActiveSupport::TestCase/ + end +end + +class NamespacedMailerGeneratorTest < NamespacedGeneratorTestCase + include GeneratorsTestHelper + arguments %w(notifier foo bar) + tests Rails::Generators::MailerGenerator + + def test_mailer_skeleton_is_created + run_generator + assert_file "app/mailers/test_app/notifier.rb" do |mailer| + assert_match /module TestApp/, mailer + assert_match /class Notifier < ActionMailer::Base/, mailer + assert_match /default :from => "from@example.com"/, mailer + end + end + + def test_mailer_with_i18n_helper + run_generator + assert_file "app/mailers/test_app/notifier.rb" do |mailer| + assert_match /en\.notifier\.foo\.subject/, mailer + assert_match /en\.notifier\.bar\.subject/, mailer + end + end + + def test_invokes_default_test_framework + run_generator + assert_file "test/functional/test_app/notifier_test.rb" do |test| + assert_match /module TestApp/, test + assert_match /class NotifierTest < ActionMailer::TestCase/, test + assert_match /test "foo"/, test + assert_match /test "bar"/, test + end + end + + def test_invokes_default_template_engine + run_generator + assert_file "app/views/test_app/notifier/foo.text.erb" do |view| + assert_match %r(app/views/test_app/notifier/foo\.text\.erb), view + assert_match /<%= @greeting %>/, view + end + + assert_file "app/views/test_app/notifier/bar.text.erb" do |view| + assert_match %r(app/views/test_app/notifier/bar\.text\.erb), view + assert_match /<%= @greeting %>/, view + end + end + + def test_invokes_default_template_engine_even_with_no_action + run_generator ["notifier"] + assert_file "app/views/test_app/notifier" + end +end + +class NamespacedScaffoldGeneratorTest < NamespacedGeneratorTestCase + include GeneratorsTestHelper + arguments %w(product_line title:string price:integer) + tests Rails::Generators::ScaffoldGenerator + + setup :copy_routes + + def test_scaffold_on_invoke + run_generator + + # Model + assert_file "app/models/test_app/product_line.rb", /module TestApp\n class ProductLine < ActiveRecord::Base/ + assert_file "test/unit/test_app/product_line_test.rb", /module TestApp\n class ProductLineTest < ActiveSupport::TestCase/ + assert_file "test/fixtures/test_app/product_lines.yml" + assert_migration "db/migrate/create_test_app_product_lines.rb" + + # Route + assert_file "config/routes.rb" do |route| + assert_match(/resources :product_lines$/, route) + end + + # Controller + assert_file "app/controllers/test_app/product_lines_controller.rb" do |content| + assert_match(/module TestApp\n class ProductLinesController < ApplicationController/, content) + end + + assert_file "test/functional/test_app/product_lines_controller_test.rb", + /module TestApp\n class ProductLinesControllerTest < ActionController::TestCase/ + + # Views + %w( + index + edit + new + show + _form + ).each { |view| assert_file "app/views/test_app/product_lines/#{view}.html.erb" } + assert_no_file "app/views/layouts/test_app/product_lines.html.erb" + + # Helpers + assert_file "app/helpers/test_app/product_lines_helper.rb" + assert_file "test/unit/helpers/test_app/product_lines_helper_test.rb" + + # Stylesheets + assert_file "public/stylesheets/scaffold.css" + end + + def test_scaffold_on_revoke + run_generator + run_generator ["product_line"], :behavior => :revoke + + # Model + assert_no_file "app/models/test_app/product_line.rb" + assert_no_file "test/unit/test_app/product_line_test.rb" + assert_no_file "test/fixtures/test_app/product_lines.yml" + assert_no_migration "db/migrate/create_test_app_product_lines.rb" + + # Route + assert_file "config/routes.rb" do |route| + assert_no_match(/resources :product_lines$/, route) + end + + # Controller + assert_no_file "app/controllers/test_app/product_lines_controller.rb" + assert_no_file "test/functional/test_app/product_lines_controller_test.rb" + + # Views + assert_no_file "app/views/test_app/product_lines" + assert_no_file "app/views/test_app/layouts/product_lines.html.erb" + + # Helpers + assert_no_file "app/helpers/test_app/product_lines_helper.rb" + assert_no_file "test/unit/helpers/test_app/product_lines_helper_test.rb" + + # Stylesheets (should not be removed) + assert_file "public/stylesheets/scaffold.css" + end + + def test_scaffold_with_namespace_on_invoke + run_generator [ "admin/role", "name:string", "description:string" ] + + # Model + assert_file "app/models/test_app/admin.rb", /module TestApp\n module Admin/ + assert_file "app/models/test_app/admin/role.rb", /module TestApp\n class Admin::Role < ActiveRecord::Base/ + assert_file "test/unit/test_app/admin/role_test.rb", /module TestApp\n class Admin::RoleTest < ActiveSupport::TestCase/ + assert_file "test/fixtures/test_app/admin/roles.yml" + assert_migration "db/migrate/create_test_app_admin_roles.rb" + + # Route + assert_file "config/routes.rb" do |route| + assert_match(/namespace :admin do resources :roles end$/, route) + end + + # Controller + assert_file "app/controllers/test_app/admin/roles_controller.rb" do |content| + assert_match(/module TestApp\n class Admin::RolesController < ApplicationController/, content) + end + + assert_file "test/functional/test_app/admin/roles_controller_test.rb", + /module TestApp\n class Admin::RolesControllerTest < ActionController::TestCase/ + + # Views + %w( + index + edit + new + show + _form + ).each { |view| assert_file "app/views/test_app/admin/roles/#{view}.html.erb" } + assert_no_file "app/views/layouts/admin/roles.html.erb" + + # Helpers + assert_file "app/helpers/test_app/admin/roles_helper.rb" + assert_file "test/unit/helpers/test_app/admin/roles_helper_test.rb" + + # Stylesheets + assert_file "public/stylesheets/scaffold.css" + end + + def test_scaffold_with_namespace_on_revoke + run_generator [ "admin/role", "name:string", "description:string" ] + run_generator [ "admin/role" ], :behavior => :revoke + + # Model + assert_file "app/models/test_app/admin.rb" # ( should not be remove ) + assert_no_file "app/models/test_app/admin/role.rb" + assert_no_file "test/unit/test_app/admin/role_test.rb" + assert_no_file "test/fixtures/test_app/admin/roles.yml" + assert_no_migration "db/migrate/create_test_app_admin_roles.rb" + + # Route + assert_file "config/routes.rb" do |route| + assert_no_match(/namespace :admin do resources :roles end$/, route) + end + + # Controller + assert_no_file "app/controllers/test_app/admin/roles_controller.rb" + assert_no_file "test/functional/test_app/admin/roles_controller_test.rb" + + # Views + assert_no_file "app/views/test_app/admin/roles" + assert_no_file "app/views/layouts/test_app/admin/roles.html.erb" + + # Helpers + assert_no_file "app/helpers/test_app/admin/roles_helper.rb" + assert_no_file "test/unit/helpers/test_app/admin/roles_helper_test.rb" + + # Stylesheets (should not be removed) + assert_file "public/stylesheets/scaffold.css" + end +end diff --git a/railties/test/generators/plugin_generator_test.rb b/railties/test/generators/plugin_generator_test.rb index c1f646f7c1..e6686a6af4 100644 --- a/railties/test/generators/plugin_generator_test.rb +++ b/railties/test/generators/plugin_generator_test.rb @@ -6,7 +6,7 @@ class PluginGeneratorTest < Rails::Generators::TestCase arguments %w(plugin_fu) def test_plugin_skeleton_is_created - run_generator + silence(:stderr) { run_generator } year = Date.today.year %w( @@ -36,30 +36,36 @@ class PluginGeneratorTest < Rails::Generators::TestCase end def test_invokes_default_test_framework - run_generator + silence(:stderr) { run_generator } assert_file "vendor/plugins/plugin_fu/test/plugin_fu_test.rb", /class PluginFuTest < ActiveSupport::TestCase/ assert_file "vendor/plugins/plugin_fu/test/test_helper.rb" end def test_logs_if_the_test_framework_cannot_be_found - content = run_generator ["plugin_fu", "--test-framework=rspec"] + content = nil + silence(:stderr) { content = run_generator ["plugin_fu", "--test-framework=rspec"] } assert_match /rspec \[not found\]/, content end def test_creates_tasks_if_required - run_generator ["plugin_fu", "--tasks"] + silence(:stderr) { run_generator ["plugin_fu", "--tasks"] } assert_file "vendor/plugins/plugin_fu/lib/tasks/plugin_fu_tasks.rake" end def test_creates_generator_if_required - run_generator ["plugin_fu", "--generator"] + silence(:stderr) { run_generator ["plugin_fu", "--generator"] } assert_file "vendor/plugins/plugin_fu/lib/generators/templates" assert_file "vendor/plugins/plugin_fu/lib/generators/plugin_fu_generator.rb", /class PluginFuGenerator < Rails::Generators::NamedBase/ end def test_plugin_generator_on_revoke - run_generator + silence(:stderr) { run_generator } run_generator ["plugin_fu"], :behavior => :revoke end + + def test_deprecation + output = capture(:stderr) { run_generator } + assert_match /Plugin generator is deprecated, please use 'rails plugin new' command to generate plugin structure./, output + end end diff --git a/railties/test/generators/plugin_new_generator_test.rb b/railties/test/generators/plugin_new_generator_test.rb new file mode 100644 index 0000000000..3c11c8dbaf --- /dev/null +++ b/railties/test/generators/plugin_new_generator_test.rb @@ -0,0 +1,229 @@ +require 'abstract_unit' +require 'generators/generators_test_helper' +require 'rails/generators/rails/plugin_new/plugin_new_generator' +require 'generators/shared_generator_tests.rb' + +DEFAULT_PLUGIN_FILES = %w( + .gitignore + Gemfile + Rakefile + bukkits.gemspec + MIT-LICENSE + lib + lib/bukkits.rb + lib/tasks/bukkits_tasks.rake + script/rails + test/bukkits_test.rb + test/test_helper.rb + test/dummy +) + +class PluginNewGeneratorTest < Rails::Generators::TestCase + include GeneratorsTestHelper + destination File.join(Rails.root, "tmp/bukkits") + arguments [destination_root] + include SharedGeneratorTests + + def default_files + ::DEFAULT_PLUGIN_FILES + end + + def test_invalid_plugin_name_raises_an_error + content = capture(:stderr){ run_generator [File.join(destination_root, "43-things")] } + assert_equal "Invalid plugin name 43-things. Please give a name which does not start with numbers.\n", content + end + + def test_invalid_plugin_name_is_fixed + run_generator [File.join(destination_root, "things-43")] + assert_file "things-43/lib/things-43.rb", /module Things43/ + end + + def test_generating_without_options + run_generator + assert_file "README.rdoc", /Bukkits/ + assert_no_file "config/routes.rb" + assert_file "test/test_helper.rb" + assert_file "test/bukkits_test.rb", /assert_kind_of Module, Bukkits/ + end + + def test_generating_test_files_in_full_mode + run_generator [destination_root, "--full"] + assert_directory "test/integration/" + + assert_file "test/integration/navigation_test.rb", /ActionDispatch::IntegrationTest/ + end + + def test_ensure_that_plugin_options_are_not_passed_to_app_generator + FileUtils.cd(Rails.root) + assert_no_match(/It works from file!.*It works_from_file/, run_generator([destination_root, "-m", "lib/template.rb"])) + end + + def test_ensure_that_test_dummy_can_be_generated_from_a_template + FileUtils.cd(Rails.root) + run_generator([destination_root, "-m", "lib/create_test_dummy_template.rb", "--skip-test-unit"]) + assert_file "spec/dummy" + assert_no_file "test" + end + + def test_database_entry_is_assed_by_default_in_full_mode + run_generator([destination_root, "--full"]) + assert_file "test/dummy/config/database.yml", /sqlite/ + assert_file "Gemfile", /^gem\s+["']sqlite3["']$/ + end + + def test_config_another_database + run_generator([destination_root, "-d", "mysql", "--full"]) + assert_file "test/dummy/config/database.yml", /mysql/ + assert_file "Gemfile", /^gem\s+["']mysql2["']$/ + end + + def test_active_record_is_removed_from_frameworks_if_skip_active_record_is_given + run_generator [destination_root, "--skip-active-record"] + assert_file "test/dummy/config/application.rb", /#\s+require\s+["']active_record\/railtie["']/ + end + + def test_ensure_that_skip_active_record_option_is_passed_to_app_generator + run_generator [destination_root, "--skip_active_record"] + assert_no_file "test/dummy/config/database.yml" + assert_no_match(/ActiveRecord/, File.read(File.join(destination_root, "test/test_helper.rb"))) + end + + def test_ensure_that_database_option_is_passed_to_app_generator + run_generator [destination_root, "--database", "postgresql"] + assert_file "test/dummy/config/database.yml", /postgres/ + end + + def test_skipping_javascripts_without_mountable_option + run_generator + assert_no_file "public/javascripts/prototype.js" + assert_no_file "public/javascripts/rails.js" + assert_no_file "public/javascripts/controls.js" + assert_no_file "public/javascripts/dragdrop.js" + assert_no_file "public/javascripts/dragdrop.js" + assert_no_file "public/javascripts/application.js" + end + + def test_javascripts_generation + run_generator [destination_root, "--mountable"] + assert_file "public/javascripts/rails.js" + assert_file "public/javascripts/prototype.js" + assert_file "public/javascripts/controls.js" + assert_file "public/javascripts/dragdrop.js" + assert_file "public/javascripts/dragdrop.js" + assert_file "public/javascripts/application.js" + end + + def test_skip_javascripts + run_generator [destination_root, "--skip-javascript", "--mountable"] + assert_no_file "public/javascripts/prototype.js" + assert_no_file "public/javascripts/rails.js" + assert_no_file "public/javascripts/controls.js" + assert_no_file "public/javascripts/dragdrop.js" + assert_no_file "public/javascripts/dragdrop.js" + end + + def test_ensure_that_javascript_option_is_passed_to_app_generator + run_generator [destination_root, "--javascript", "jquery"] + assert_file "test/dummy/public/javascripts/jquery.js" + end + + def test_ensure_that_skip_javascript_option_is_passed_to_app_generator + run_generator [destination_root, "--skip_javascript"] + assert_no_file "test/dummy/public/javascripts/prototype.js" + end + + def test_template_from_dir_pwd + FileUtils.cd(Rails.root) + assert_match(/It works from file!/, run_generator([destination_root, "-m", "lib/template.rb"])) + end + + def test_ensure_that_tests_works + run_generator + FileUtils.cd destination_root + `bundle install` + assert_match(/1 tests, 1 assertions, 0 failures, 0 errors/, `bundle exec rake test`) + end + + def test_ensure_that_tests_works_in_full_mode + run_generator [destination_root, "--full", "--skip_active_record"] + FileUtils.cd destination_root + `bundle install` + assert_match(/2 tests, 2 assertions, 0 failures, 0 errors/, `bundle exec rake test`) + end + + def test_creating_engine_in_full_mode + run_generator [destination_root, "--full"] + assert_file "config/routes.rb", /Rails.application.routes.draw do/ + assert_file "lib/bukkits/engine.rb", /module Bukkits\n class Engine < Rails::Engine\n end\nend/ + assert_file "lib/bukkits.rb", /require "bukkits\/engine"/ + end + + def test_being_quiet_while_creating_dummy_application + assert_no_match(/create\s+config\/application.rb/, run_generator) + end + + def test_create_mountable_application_with_mountable_option + run_generator [destination_root, "--mountable"] + assert_file "config/routes.rb", /Bukkits::Engine.routes.draw do/ + assert_file "lib/bukkits/engine.rb", /isolate_namespace Bukkits/ + assert_file "test/dummy/config/routes.rb", /mount Bukkits::Engine => "\/bukkits"/ + assert_file "app/controllers/bukkits/application_controller.rb", /module Bukkits\n class ApplicationController < ActionController::Base/ + assert_file "app/helpers/bukkits/application_helper.rb", /module Bukkits\n module ApplicationHelper/ + assert_file "app/views/layouts/bukkits/application.html.erb", /<title>Bukkits<\/title>/ + end + + def test_passing_dummy_path_as_a_parameter + run_generator [destination_root, "--dummy_path", "spec/dummy"] + assert_file "spec/dummy" + assert_file "spec/dummy/config/application.rb" + assert_no_file "test/dummy" + end + + def test_skipping_gemspec + run_generator [destination_root, "--skip-gemspec"] + assert_no_file "bukkits.gemspec" + end + +protected + + def action(*args, &block) + silence(:stdout){ generator.send(*args, &block) } + end + +end + +class CustomPluginGeneratorTest < Rails::Generators::TestCase + include GeneratorsTestHelper + tests Rails::Generators::PluginNewGenerator + + destination File.join(Rails.root, "tmp/bukkits") + arguments [destination_root] + include SharedCustomGeneratorTests + + def test_overriding_test_framework + FileUtils.cd(destination_root) + run_generator([destination_root, "-b", "#{Rails.root}/lib/plugin_builders/spec_builder.rb"]) + assert_file 'spec/spec_helper.rb' + assert_file 'spec/dummy' + assert_file 'Rakefile', /task :default => :spec/ + assert_file 'Rakefile', /# spec tasks in rakefile/ + assert_file 'script/rails', %r{spec/dummy} + end + +protected + def default_files + ::DEFAULT_PLUGIN_FILES + end + + def builder_class + :PluginBuilder + end + + def builders_dir + "plugin_builders" + end + + def action(*args, &block) + silence(:stdout){ generator.send(*args, &block) } + end +end diff --git a/railties/test/generators/resource_generator_test.rb b/railties/test/generators/resource_generator_test.rb index 55d5bd6f83..71b3619351 100644 --- a/railties/test/generators/resource_generator_test.rb +++ b/railties/test/generators/resource_generator_test.rb @@ -73,6 +73,11 @@ class ResourceGeneratorTest < Rails::Generators::TestCase assert_no_match /Plural version of the model detected/, content end + def test_mass_nouns_do_not_throw_warnings + content = run_generator ["sheep".freeze] + assert_no_match /Plural version of the model detected/, content + end + def test_route_is_removed_on_revoke run_generator run_generator ["account"], :behavior => :revoke diff --git a/railties/test/generators/scaffold_generator_test.rb b/railties/test/generators/scaffold_generator_test.rb index f12445ae35..df787f61ba 100644 --- a/railties/test/generators/scaffold_generator_test.rb +++ b/railties/test/generators/scaffold_generator_test.rb @@ -3,7 +3,7 @@ require 'rails/generators/rails/scaffold/scaffold_generator' class ScaffoldGeneratorTest < Rails::Generators::TestCase include GeneratorsTestHelper - arguments %w(product_line title:string price:integer) + arguments %w(product_line title:string product:belongs_to user:references) setup :copy_routes @@ -14,48 +14,51 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase assert_file "app/models/product_line.rb", /class ProductLine < ActiveRecord::Base/ assert_file "test/unit/product_line_test.rb", /class ProductLineTest < ActiveSupport::TestCase/ assert_file "test/fixtures/product_lines.yml" - assert_migration "db/migrate/create_product_lines.rb" + assert_migration "db/migrate/create_product_lines.rb", /belongs_to :product/ + assert_migration "db/migrate/create_product_lines.rb", /add_index :product_lines, :product_id/ + assert_migration "db/migrate/create_product_lines.rb", /references :user/ + assert_migration "db/migrate/create_product_lines.rb", /add_index :product_lines, :user_id/ # Route assert_file "config/routes.rb" do |route| - assert_match /resources :product_lines$/, route + assert_match(/resources :product_lines$/, route) end # Controller assert_file "app/controllers/product_lines_controller.rb" do |content| - assert_match /class ProductLinesController < ApplicationController/, content + assert_match(/class ProductLinesController < ApplicationController/, content) assert_instance_method :index, content do |m| - assert_match /@product_lines = ProductLine\.all/, m + assert_match(/@product_lines = ProductLine\.all/, m) end assert_instance_method :show, content do |m| - assert_match /@product_line = ProductLine\.find\(params\[:id\]\)/, m + assert_match(/@product_line = ProductLine\.find\(params\[:id\]\)/, m) end assert_instance_method :new, content do |m| - assert_match /@product_line = ProductLine\.new/, m + assert_match(/@product_line = ProductLine\.new/, m) end assert_instance_method :edit, content do |m| - assert_match /@product_line = ProductLine\.find\(params\[:id\]\)/, m + assert_match(/@product_line = ProductLine\.find\(params\[:id\]\)/, m) end assert_instance_method :create, content do |m| - assert_match /@product_line = ProductLine\.new\(params\[:product_line\]\)/, m - assert_match /@product_line\.save/, m - assert_match /@product_line\.errors/, m + assert_match(/@product_line = ProductLine\.new\(params\[:product_line\]\)/, m) + assert_match(/@product_line\.save/, m) + assert_match(/@product_line\.errors/, m) end assert_instance_method :update, content do |m| - assert_match /@product_line = ProductLine\.find\(params\[:id\]\)/, m - assert_match /@product_line\.update_attributes\(params\[:product_line\]\)/, m - assert_match /@product_line\.errors/, m + assert_match(/@product_line = ProductLine\.find\(params\[:id\]\)/, m) + assert_match(/@product_line\.update_attributes\(params\[:product_line\]\)/, m) + assert_match(/@product_line\.errors/, m) end assert_instance_method :destroy, content do |m| - assert_match /@product_line = ProductLine\.find\(params\[:id\]\)/, m - assert_match /@product_line\.destroy/, m + assert_match(/@product_line = ProductLine\.find\(params\[:id\]\)/, m) + assert_match(/@product_line\.destroy/, m) end end @@ -92,7 +95,7 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase # Route assert_file "config/routes.rb" do |route| - assert_no_match /resources :product_lines$/, route + assert_no_match(/resources :product_lines$/, route) end # Controller @@ -123,44 +126,44 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase # Route assert_file "config/routes.rb" do |route| - assert_match /namespace :admin do resources :roles end$/, route + assert_match(/namespace :admin do resources :roles end$/, route) end # Controller assert_file "app/controllers/admin/roles_controller.rb" do |content| - assert_match /class Admin::RolesController < ApplicationController/, content + assert_match(/class Admin::RolesController < ApplicationController/, content) assert_instance_method :index, content do |m| - assert_match /@admin_roles = Admin::Role\.all/, m + assert_match(/@admin_roles = Admin::Role\.all/, m) end assert_instance_method :show, content do |m| - assert_match /@admin_role = Admin::Role\.find\(params\[:id\]\)/, m + assert_match(/@admin_role = Admin::Role\.find\(params\[:id\]\)/, m) end assert_instance_method :new, content do |m| - assert_match /@admin_role = Admin::Role\.new/, m + assert_match(/@admin_role = Admin::Role\.new/, m) end assert_instance_method :edit, content do |m| - assert_match /@admin_role = Admin::Role\.find\(params\[:id\]\)/, m + assert_match(/@admin_role = Admin::Role\.find\(params\[:id\]\)/, m) end assert_instance_method :create, content do |m| - assert_match /@admin_role = Admin::Role\.new\(params\[:admin_role\]\)/, m - assert_match /@admin_role\.save/, m - assert_match /@admin_role\.errors/, m + assert_match(/@admin_role = Admin::Role\.new\(params\[:admin_role\]\)/, m) + assert_match(/@admin_role\.save/, m) + assert_match(/@admin_role\.errors/, m) end assert_instance_method :update, content do |m| - assert_match /@admin_role = Admin::Role\.find\(params\[:id\]\)/, m - assert_match /@admin_role\.update_attributes\(params\[:admin_role\]\)/, m - assert_match /@admin_role\.errors/, m + assert_match(/@admin_role = Admin::Role\.find\(params\[:id\]\)/, m) + assert_match(/@admin_role\.update_attributes\(params\[:admin_role\]\)/, m) + assert_match(/@admin_role\.errors/, m) end assert_instance_method :destroy, content do |m| - assert_match /@admin_role = Admin::Role\.find\(params\[:id\]\)/, m - assert_match /@admin_role\.destroy/, m + assert_match(/@admin_role = Admin::Role\.find\(params\[:id\]\)/, m) + assert_match(/@admin_role\.destroy/, m) end end @@ -198,7 +201,7 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase # Route assert_file "config/routes.rb" do |route| - assert_no_match /namespace :admin do resources :roles end$/, route + assert_no_match(/namespace :admin do resources :roles end$/, route) end # Controller @@ -231,4 +234,10 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase assert_file "config/routes.rb", /\.routes\.draw do\s*\|map\|\s*$/ end + + def test_scaffold_generator_outputs_error_message_on_missing_attribute_type + content = capture(:stderr) { run_generator ["post", "title:string", "body"]} + assert_match(/Missing type for attribute 'body'/, content) + assert_match(/Example: 'body:string' where string is the type/, content) + end end diff --git a/railties/test/generators/shared_generator_tests.rb b/railties/test/generators/shared_generator_tests.rb new file mode 100644 index 0000000000..c9c5d2fad2 --- /dev/null +++ b/railties/test/generators/shared_generator_tests.rb @@ -0,0 +1,195 @@ +module SharedGeneratorTests + def setup + Rails.application = TestApp::Application + super + Rails::Generators::AppGenerator.instance_variable_set('@desc', nil) + @bundle_command = File.basename(Thor::Util.ruby_command).sub(/ruby/, 'bundle') + + Kernel::silence_warnings do + Thor::Base.shell.send(:attr_accessor, :always_force) + @shell = Thor::Base.shell.new + @shell.send(:always_force=, true) + end + end + + def teardown + super + Rails::Generators::AppGenerator.instance_variable_set('@desc', nil) + Rails.application = TestApp::Application.instance + end + + def test_skeleton_is_created + run_generator + + default_files.each{ |path| assert_file path } + end + + def test_plugin_new_generate_pretend + run_generator ["testapp", "--pretend"] + default_files.each{ |path| assert_no_file File.join("testapp",path) } + end + + def test_invalid_database_option_raises_an_error + content = capture(:stderr){ run_generator([destination_root, "-d", "unknown"]) } + assert_match(/Invalid value for \-\-database option/, content) + end + + def test_test_unit_is_skipped_if_required + run_generator [destination_root, "--skip-test-unit"] + assert_no_file "test" + end + + def test_options_before_application_name_raises_an_error + content = capture(:stderr){ run_generator(["--pretend", destination_root]) } + assert_match(/Options should be given after the \w+ name. For details run: rails( plugin)? --help\n/, content) + end + + def test_name_collision_raises_an_error + reserved_words = %w[application destroy plugin runner test] + reserved_words.each do |reserved| + content = capture(:stderr){ run_generator [File.join(destination_root, reserved)] } + assert_match(/Invalid \w+ name #{reserved}. Please give a name which does not match one of the reserved rails words.\n/, content) + end + end + + def test_name_raises_an_error_if_name_already_used_constant + %w{ String Hash Class Module Set Symbol }.each do |ruby_class| + content = capture(:stderr){ run_generator [File.join(destination_root, ruby_class)] } + assert_match(/Invalid \w+ name #{ruby_class}, constant #{ruby_class} is already in use. Please choose another \w+ name.\n/, content) + end + end + + def test_shebang_is_added_to_rails_file + run_generator [destination_root, "--ruby", "foo/bar/baz"] + assert_file "script/rails", /#!foo\/bar\/baz/ + end + + def test_shebang_when_is_the_same_as_default_use_env + run_generator [destination_root, "--ruby", Thor::Util.ruby_command] + assert_file "script/rails", /#!\/usr\/bin\/env/ + end + + def test_template_raises_an_error_with_invalid_path + content = capture(:stderr){ run_generator([destination_root, "-m", "non/existant/path"]) } + assert_match(/The template \[.*\] could not be loaded/, content) + assert_match(/non\/existant\/path/, content) + end + + def test_template_is_executed_when_supplied + path = "http://gist.github.com/103208.txt" + template = %{ say "It works!" } + template.instance_eval "def read; self; end" # Make the string respond to read + + generator([destination_root], :template => path).expects(:open).with(path, 'Accept' => 'application/x-thor-template').returns(template) + assert_match(/It works!/, silence(:stdout){ generator.invoke_all }) + end + + def test_dev_option + generator([destination_root], :dev => true).expects(:run).with("#{@bundle_command} install") + silence(:stdout){ generator.invoke_all } + rails_path = File.expand_path('../../..', Rails.root) + assert_file 'Gemfile', /^gem\s+["']rails["'],\s+:path\s+=>\s+["']#{Regexp.escape(rails_path)}["']$/ + end + + def test_edge_option + generator([destination_root], :edge => true).expects(:run).with("#{@bundle_command} install") + silence(:stdout){ generator.invoke_all } + assert_file 'Gemfile', %r{^gem\s+["']rails["'],\s+:git\s+=>\s+["']#{Regexp.escape("git://github.com/rails/rails.git")}["']$} + end + + def test_template_raises_an_error_with_invalid_path + content = capture(:stderr){ run_generator([destination_root, "-m", "non/existant/path"]) } + assert_match(/The template \[.*\] could not be loaded/, content) + assert_match(/non\/existant\/path/, content) + end + + def test_template_is_executed_when_supplied + path = "http://gist.github.com/103208.txt" + template = %{ say "It works!" } + template.instance_eval "def read; self; end" # Make the string respond to read + + generator([destination_root], :template => path).expects(:open).with(path, 'Accept' => 'application/x-thor-template').returns(template) + assert_match(/It works!/, silence(:stdout){ generator.invoke_all }) + end + + def test_template_is_executed_when_supplied_an_https_path + path = "https://gist.github.com/103208.txt" + template = %{ say "It works!" } + template.instance_eval "def read; self; end" # Make the string respond to read + + generator([destination_root], :template => path).expects(:open).with(path, 'Accept' => 'application/x-thor-template').returns(template) + assert_match(/It works!/, silence(:stdout){ generator.invoke_all }) + end + + def test_dev_option + generator([destination_root], :dev => true).expects(:run).with("#{@bundle_command} install") + silence(:stdout){ generator.invoke_all } + rails_path = File.expand_path('../../..', Rails.root) + assert_file 'Gemfile', /^gem\s+["']rails["'],\s+:path\s+=>\s+["']#{Regexp.escape(rails_path)}["']$/ + end + + def test_edge_option + generator([destination_root], :edge => true).expects(:run).with("#{@bundle_command} install") + silence(:stdout){ generator.invoke_all } + assert_file 'Gemfile', %r{^gem\s+["']rails["'],\s+:git\s+=>\s+["']#{Regexp.escape("git://github.com/rails/rails.git")}["']$} + end +end + +module SharedCustomGeneratorTests + def setup + Rails.application = TestApp::Application + super + Rails::Generators::AppGenerator.instance_variable_set('@desc', nil) + @bundle_command = File.basename(Thor::Util.ruby_command).sub(/ruby/, 'bundle') + end + + def teardown + super + Rails::Generators::AppGenerator.instance_variable_set('@desc', nil) + Object.class_eval do + remove_const :AppBuilder if const_defined?(:AppBuilder) + remove_const :PluginBuilder if const_defined?(:PluginBuilder) + end + Rails.application = TestApp::Application.instance + end + + def test_builder_option_with_empty_app_builder + FileUtils.cd(destination_root) + run_generator([destination_root, "-b", "#{Rails.root}/lib/#{builders_dir}/empty_builder.rb"]) + default_files.each{ |path| assert_no_file path } + end + + def test_builder_option_with_simple_plugin_builder + FileUtils.cd(destination_root) + run_generator([destination_root, "-b", "#{Rails.root}/lib/#{builders_dir}/simple_builder.rb"]) + (default_files - ['.gitignore']).each{ |path| assert_no_file path } + assert_file ".gitignore", "foobar" + end + + def test_builder_option_with_relative_path + here = File.expand_path(File.dirname(__FILE__)) + FileUtils.cd(here) + run_generator([destination_root, "-b", "../fixtures/lib/#{builders_dir}/simple_builder.rb"]) + FileUtils.cd(destination_root) + (default_files - ['.gitignore']).each{ |path| assert_no_file path } + assert_file ".gitignore", "foobar" + end + + def test_builder_option_with_tweak_plugin_builder + FileUtils.cd(destination_root) + run_generator([destination_root, "-b", "#{Rails.root}/lib/#{builders_dir}/tweak_builder.rb"]) + default_files.each{ |path| assert_file path } + assert_file ".gitignore", "foobar" + end + + def test_builder_option_with_http + path = "http://gist.github.com/103208.txt" + template = "class #{builder_class}; end" + template.instance_eval "def read; self; end" # Make the string respond to read + + generator([destination_root], :builder => path).expects(:open).with(path, 'Accept' => 'application/x-thor-template').returns(template) + capture(:stdout) { generator.invoke_all } + + default_files.each{ |path| assert_no_file(path) } + end +end diff --git a/railties/test/generators_test.rb b/railties/test/generators_test.rb index f93800a5ae..99c9d790eb 100644 --- a/railties/test/generators_test.rb +++ b/railties/test/generators_test.rb @@ -94,6 +94,14 @@ class GeneratorsTest < Rails::Generators::TestCase assert_match /Rails 2\.x generator/, output end + def test_invoke_with_nested_namespaces + model_generator = mock('ModelGenerator') do + expects(:start).with(["Account"], {}) + end + Rails::Generators.expects(:find_by_namespace).with('namespace', 'my:awesome').returns(model_generator) + Rails::Generators.invoke 'my:awesome:namespace', ["Account"] + end + def test_rails_generators_help_with_builtin_information output = capture(:stdout){ Rails::Generators.help } assert_match /Rails:/, output @@ -102,6 +110,12 @@ class GeneratorsTest < Rails::Generators::TestCase assert_no_match /^ app$/, output end + def test_rails_generators_help_does_not_include_app_nor_plugin_new + output = capture(:stdout){ Rails::Generators.help } + assert_no_match /app/, output + assert_no_match /plugin_new/, output + end + def test_rails_generators_with_others_information output = capture(:stdout){ Rails::Generators.help } assert_match /Fixjour:/, output @@ -114,6 +128,16 @@ class GeneratorsTest < Rails::Generators::TestCase assert_match /^ active_record:fixjour$/, output end + def test_default_banner_should_show_generator_namespace + klass = Rails::Generators.find_by_namespace(:foobar) + assert_match /^rails generate foobar:foobar/, klass.banner + end + + def test_default_banner_should_not_show_rails_generator_namespace + klass = Rails::Generators.find_by_namespace(:model) + assert_match /^rails generate model/, klass.banner + end + def test_no_color_sets_proper_shell Rails::Generators.no_color! assert_equal Thor::Shell::Basic, Thor::Base.shell diff --git a/railties/test/isolation/abstract_unit.rb b/railties/test/isolation/abstract_unit.rb index 390c0ab543..c5b1cb9a80 100644 --- a/railties/test/isolation/abstract_unit.rb +++ b/railties/test/isolation/abstract_unit.rb @@ -19,6 +19,7 @@ RAILS_FRAMEWORK_ROOT = File.expand_path("#{File.dirname(__FILE__)}/../../..") # to run the tests require "#{RAILS_FRAMEWORK_ROOT}/activesupport/lib/active_support/testing/isolation" require "#{RAILS_FRAMEWORK_ROOT}/activesupport/lib/active_support/testing/declarative" +require "#{RAILS_FRAMEWORK_ROOT}/activesupport/lib/active_support/core_ext/kernel/reporting" module TestHelpers module Paths @@ -44,6 +45,17 @@ module TestHelpers end module Rack + def app(env = "production") + old_env = ENV["RAILS_ENV"] + @app ||= begin + ENV["RAILS_ENV"] = env + require "#{app_path}/config/environment" + Rails.application + end + ensure + ENV["RAILS_ENV"] = old_env + end + def extract_body(response) "".tap do |body| response[2].each {|chunk| body << chunk } @@ -123,6 +135,22 @@ module TestHelpers extend ::Rack::Test::Methods end + def simple_controller + controller :foo, <<-RUBY + class FooController < ApplicationController + def index + render :text => "foo" + end + end + RUBY + + app_file 'config/routes.rb', <<-RUBY + AppTemplate::Application.routes.draw do + match ':controller(/:action)' + end + RUBY + end + class Bukkit attr_reader :path @@ -187,6 +215,13 @@ module TestHelpers end end + def remove_from_config(str) + file = "#{app_path}/config/application.rb" + contents = File.read(file) + contents.sub!(/#{str}/, "") + File.open(file, "w+") { |f| f.puts contents } + end + def app_file(path, contents) FileUtils.mkdir_p File.dirname("#{app_path}/#{path}") File.open("#{app_path}/#{path}", 'w') do |f| @@ -203,6 +238,7 @@ module TestHelpers :activemodel, :activerecord, :activeresource] - arr + remove_from_config "config.active_record.identity_map = true" if to_remove.include? :activerecord $:.reject! {|path| path =~ %r'/(#{to_remove.join('|')})/' } end diff --git a/railties/test/paths_test.rb b/railties/test/paths_test.rb index 80fae8c543..6e4e3446b3 100644 --- a/railties/test/paths_test.rb +++ b/railties/test/paths_test.rb @@ -20,234 +20,264 @@ class PathsTest < ActiveSupport::TestCase test "a paths object initialized with nil can be updated" do root = Rails::Paths::Root.new(nil) - root.app = "app" + root.add "app" root.path = "/root" - assert_equal ["/root/app"], root.app.to_a + assert_equal ["app"], root["app"] + assert_equal ["/root/app"], root["app"].to_a end test "creating a root level path" do - @root.app = "/foo/bar" - assert_equal ["/foo/bar"], @root.app.to_a + @root.add "app" + assert_equal ["/foo/bar/app"], @root["app"].to_a + end + + test "creating a root level path with options" do + @root.add "app", :with => "/foo/bar" + assert_equal ["/foo/bar"], @root["app"].to_a end test "raises exception if root path never set" do root = Rails::Paths::Root.new(nil) - root.app = "app" + root.add "app" assert_raises RuntimeError do - root.app.to_a + root["app"].to_a end end - test "creating a root level path without assignment" do - @root.app "/foo/bar" - assert_equal ["/foo/bar"], @root.app.to_a - end - - test "trying to access a path that does not exist raises NoMethodError" do - assert_raises(NoMethodError) { @root.app } - end - - test "relative paths are relative to the paths root" do - @root.app = "app" - assert_equal ["/foo/bar/app"], @root.app.to_a - end - - test "relative paths are relative to the paths root without assignment" do - @root.app "app" - assert_equal ["/foo/bar/app"], @root.app.to_a - end - test "creating a child level path" do - @root.app = "/foo/bar" - @root.app.models = "/foo/bar/baz" - assert_equal ["/foo/bar/baz"], @root.app.models.to_a + @root.add "app" + @root.add "app/models" + assert_equal ["/foo/bar/app/models"], @root["app/models"].to_a end - test "creating a child level path without assignment" do - @root.app = "/foo/bar" - @root.app.models "/foo/bar/baz" - assert_equal ["/foo/bar/baz"], @root.app.models.to_a + test "creating a child level path with option" do + @root.add "app" + @root.add "app/models", :with => "/foo/bar/baz" + assert_equal ["/foo/bar/baz"], @root["app/models"].to_a end test "child level paths are relative from the root" do - @root.app = "/app" - @root.app.models = "baz" - - assert_equal ["/foo/bar/baz"], @root.app.models.to_a + @root.add "app" + @root.add "app/models", :with => "baz" + assert_equal ["/foo/bar/baz"], @root["app/models"].to_a end test "adding multiple physical paths as an array" do - @root.app = ["/app", "/app2"] - assert_equal ["/app", "/app2"], @root.app.to_a - end - - test "adding multiple physical paths as an array without assignment" do - @root.app "/app", "/app2" - assert_equal ["/app", "/app2"], @root.app.to_a + @root.add "app", :with => ["/app", "/app2"] + assert_equal ["/app", "/app2"], @root["app"].to_a end test "adding multiple physical paths using #push" do - @root.app = "/app" - @root.app.push "/app2" - assert_equal ["/app", "/app2"], @root.app.to_a + @root.add "app" + @root["app"].push "app2" + assert_equal ["/foo/bar/app", "/foo/bar/app2"], @root["app"].to_a end test "adding multiple physical paths using <<" do - @root.app = "/app" - @root.app << "/app2" - assert_equal ["/app", "/app2"], @root.app.to_a + @root.add "app" + @root["app"] << "app2" + assert_equal ["/foo/bar/app", "/foo/bar/app2"], @root["app"].to_a end test "adding multiple physical paths using concat" do - @root.app = "/app" - @root.app.concat ["/app2", "/app3"] - assert_equal ["/app", "/app2", "/app3"], @root.app.to_a + @root.add "app" + @root["app"].concat ["app2", "/app3"] + assert_equal ["/foo/bar/app", "/foo/bar/app2", "/app3"], @root["app"].to_a end test "adding multiple physical paths using #unshift" do - @root.app = "/app" - @root.app.unshift "/app2" - assert_equal ["/app2", "/app"], @root.app.to_a + @root.add "app" + @root["app"].unshift "app2" + assert_equal ["/foo/bar/app2", "/foo/bar/app"], @root["app"].to_a end test "the root can only have one physical path" do assert_raise(RuntimeError) { Rails::Paths::Root.new(["/fiz", "/biz"]) } - assert_raise(RuntimeError) { @root.push "/biz" } - assert_raise(RuntimeError) { @root.unshift "/biz" } - assert_raise(RuntimeError) { @root.concat ["/biz"]} - assert_raise(RuntimeError) { @root << "/biz" } end test "it is possible to add a path that should be autoloaded only once" do - @root.app = "/app" - @root.app.autoload_once! - assert @root.app.autoload_once? - assert @root.autoload_once.include?(@root.app.paths.first) + @root.add "app", :with => "/app" + @root["app"].autoload_once! + assert @root["app"].autoload_once? + assert @root.autoload_once.include?(@root["app"].expanded.first) end test "it is possible to remove a path that should be autoloaded only once" do - @root.app = "/app" - @root.app.autoload_once! - assert @root.app.autoload_once? + @root["app"] = "/app" + @root["app"].autoload_once! + assert @root["app"].autoload_once? - @root.app.skip_autoload_once! - assert !@root.app.autoload_once? - assert !@root.autoload_once.include?(@root.app.paths.first) + @root["app"].skip_autoload_once! + assert !@root["app"].autoload_once? + assert !@root.autoload_once.include?(@root["app"].expanded.first) end test "it is possible to add a path without assignment and specify it should be loaded only once" do - @root.app "/app", :autoload_once => true - assert @root.app.autoload_once? + @root.add "app", :with => "/app", :autoload_once => true + assert @root["app"].autoload_once? assert @root.autoload_once.include?("/app") end test "it is possible to add multiple paths without assignment and specify it should be loaded only once" do - @root.app "/app", "/app2", :autoload_once => true - assert @root.app.autoload_once? + @root.add "app", :with => ["/app", "/app2"], :autoload_once => true + assert @root["app"].autoload_once? assert @root.autoload_once.include?("/app") assert @root.autoload_once.include?("/app2") end test "making a path autoload_once more than once only includes it once in @root.load_once" do - @root.app = "/app" - @root.app.autoload_once! - @root.app.autoload_once! - assert_equal 1, @root.autoload_once.select {|p| p == @root.app.paths.first }.size + @root["app"] = "/app" + @root["app"].autoload_once! + @root["app"].autoload_once! + assert_equal 1, @root.autoload_once.select {|p| p == @root["app"].expanded.first }.size end test "paths added to a load_once path should be added to the autoload_once collection" do - @root.app = "/app" - @root.app.autoload_once! - @root.app << "/app2" + @root["app"] = "/app" + @root["app"].autoload_once! + @root["app"] << "/app2" assert_equal 2, @root.autoload_once.size end test "it is possible to mark a path as eager loaded" do - @root.app = "/app" - @root.app.eager_load! - assert @root.app.eager_load? - assert @root.eager_load.include?(@root.app.paths.first) + @root["app"] = "/app" + @root["app"].eager_load! + assert @root["app"].eager_load? + assert @root.eager_load.include?(@root["app"].to_a.first) end test "it is possible to skip a path from eager loading" do - @root.app = "/app" - @root.app.eager_load! - assert @root.app.eager_load? + @root["app"] = "/app" + @root["app"].eager_load! + assert @root["app"].eager_load? - @root.app.skip_eager_load! - assert !@root.app.eager_load? - assert !@root.eager_load.include?(@root.app.paths.first) + @root["app"].skip_eager_load! + assert !@root["app"].eager_load? + assert !@root.eager_load.include?(@root["app"].to_a.first) end test "it is possible to add a path without assignment and mark it as eager" do - @root.app "/app", :eager_load => true - assert @root.app.eager_load? + @root.add "app", :with => "/app", :eager_load => true + assert @root["app"].eager_load? assert @root.eager_load.include?("/app") end test "it is possible to add multiple paths without assignment and mark them as eager" do - @root.app "/app", "/app2", :eager_load => true - assert @root.app.eager_load? + @root.add "app", :with => ["/app", "/app2"], :eager_load => true + assert @root["app"].eager_load? assert @root.eager_load.include?("/app") assert @root.eager_load.include?("/app2") end test "it is possible to create a path without assignment and mark it both as eager and load once" do - @root.app "/app", :eager_load => true, :autoload_once => true - assert @root.app.eager_load? - assert @root.app.autoload_once? + @root.add "app", :with => "/app", :eager_load => true, :autoload_once => true + assert @root["app"].eager_load? + assert @root["app"].autoload_once? assert @root.eager_load.include?("/app") assert @root.autoload_once.include?("/app") end test "making a path eager more than once only includes it once in @root.eager_paths" do - @root.app = "/app" - @root.app.eager_load! - @root.app.eager_load! - assert_equal 1, @root.eager_load.select {|p| p == @root.app.paths.first }.size + @root["app"] = "/app" + @root["app"].eager_load! + @root["app"].eager_load! + assert_equal 1, @root.eager_load.select {|p| p == @root["app"].expanded.first }.size end test "paths added to a eager_load path should be added to the eager_load collection" do - @root.app = "/app" - @root.app.eager_load! - @root.app << "/app2" + @root["app"] = "/app" + @root["app"].eager_load! + @root["app"] << "/app2" assert_equal 2, @root.eager_load.size end test "it should be possible to add a path's default glob" do - @root.app = "/app" - @root.app.glob = "*.rb" - assert_equal "*.rb", @root.app.glob + @root["app"] = "/app" + @root["app"].glob = "*.rb" + assert_equal "*.rb", @root["app"].glob end test "it should be possible to override a path's default glob without assignment" do - @root.app "/app", :glob => "*.rb" - assert_equal "*.rb", @root.app.glob + @root.add "app", :with => "/app", :glob => "*.rb" + assert_equal "*.rb", @root["app"].glob end test "a path can be added to the load path" do - @root.app = "app" - @root.app.load_path! - @root.app.models = "app/models" + @root["app"] = "app" + @root["app"].load_path! + @root["app/models"] = "app/models" assert_equal ["/foo/bar/app"], @root.load_paths end test "a path can be added to the load path on creation" do - @root.app "/app", :load_path => true - assert @root.app.load_path? + @root.add "app", :with => "/app", :load_path => true + assert @root["app"].load_path? assert_equal ["/app"], @root.load_paths end test "a path can be marked as autoload path" do - @root.app = "app" - @root.app.autoload! - @root.app.models = "app/models" + @root["app"] = "app" + @root["app"].autoload! + @root["app/models"] = "app/models" assert_equal ["/foo/bar/app"], @root.autoload_paths end test "a path can be marked as autoload on creation" do - @root.app "/app", :autoload => true - assert @root.app.autoload? + @root.add "app", :with => "/app", :autoload => true + assert @root["app"].autoload? assert_equal ["/app"], @root.autoload_paths end + + # Deprecated API tests + + test "reading a root level path with assignment" do + @root.add "app" + assert_deprecated do + assert_equal ["/foo/bar/app"], @root.app.to_a + end + end + + test "creating a root level path with assignment" do + assert_deprecated do + @root.app = "/foo/bar" + end + assert_equal ["/foo/bar"], @root["app"].to_a + end + + test "creating a root level path without assignment" do + assert_deprecated do + @root.app "/foo/bar" + end + assert_equal ["/foo/bar"], @root["app"].to_a + end + + test "reading a nested level path with assignment" do + @root.add "app" + @root.add "app/model" + assert_deprecated do + assert_equal ["/foo/bar/app/model"], @root.app.model.to_a + end + end + + test "creating a nested level path with assignment" do + @root.add "app" + assert_deprecated do + @root.app.model = "/foo/bar" + end + assert_equal ["/foo/bar"], @root["app/model"].to_a + end + + test "creating a nested level path without assignment" do + @root.add "app" + assert_deprecated do + @root.app.model "/foo/bar" + end + assert_equal ["/foo/bar"], @root["app/model"].to_a + end + + test "trying to access a path that does not exist raises NoMethodError" do + assert_deprecated do + assert_raises(NoMethodError) { @root.app } + end + end end diff --git a/railties/test/rails_info_controller_test.rb b/railties/test/rails_info_controller_test.rb index 687c2d1568..9d194f41a6 100644 --- a/railties/test/rails_info_controller_test.rb +++ b/railties/test/rails_info_controller_test.rb @@ -14,26 +14,28 @@ class InfoControllerTest < ActionController::TestCase Rails.application.routes.draw do match '/rails/info/properties' => "rails/info#properties" end - @controller.stubs(:consider_all_requests_local? => false, :local_request? => true) + @request.stubs(:local? => true) + @controller.stubs(:consider_all_requests_local? => false) @routes = Rails.application.routes Rails::InfoController.send(:include, @routes.url_helpers) end test "info controller does not allow remote requests" do - @controller.stubs(:consider_all_requests_local? => false, :local_request? => false) + @request.stubs(:local? => false) get :properties assert_response :forbidden end test "info controller renders an error message when request was forbidden" do - @controller.stubs(:consider_all_requests_local? => false, :local_request? => false) + @request.stubs(:local? => false) get :properties assert_select 'p' end test "info controller allows requests when all requests are considered local" do - @controller.stubs(:consider_all_requests_local? => true, :local_request? => false) + @request.stubs(:local? => false) + @controller.stubs(:consider_all_requests_local? => true) get :properties assert_response :success end diff --git a/railties/test/railties/engine_test.rb b/railties/test/railties/engine_test.rb index 7410a10712..0ce00db3c4 100644 --- a/railties/test/railties/engine_test.rb +++ b/railties/test/railties/engine_test.rb @@ -1,10 +1,15 @@ require "isolation/abstract_unit" require "railties/shared_tests" +require 'stringio' +require 'rack/test' +require 'rack/file' module RailtiesTest class EngineTest < Test::Unit::TestCase + include ActiveSupport::Testing::Isolation include SharedTests + include Rack::Test::Methods def setup build_app @@ -13,6 +18,7 @@ module RailtiesTest plugin.write "lib/bukkits.rb", <<-RUBY class Bukkits class Engine < ::Rails::Engine + railtie_name "bukkits" end end RUBY @@ -50,5 +56,750 @@ module RailtiesTest assert index < initializers.index { |i| i.name == :build_middleware_stack } end + + + class Upcaser + def initialize(app) + @app = app + end + + def call(env) + response = @app.call(env) + response[2].each { |b| b.upcase! } + response + end + end + + test "engine is a rack app and can have his own middleware stack" do + add_to_config("config.action_dispatch.show_exceptions = false") + + @plugin.write "lib/bukkits.rb", <<-RUBY + class Bukkits + class Engine < ::Rails::Engine + endpoint lambda { |env| [200, {'Content-Type' => 'text/html'}, ['Hello World']] } + config.middleware.use ::RailtiesTest::EngineTest::Upcaser + end + end + RUBY + + app_file "config/routes.rb", <<-RUBY + AppTemplate::Application.routes.draw do + mount(Bukkits::Engine => "/bukkits") + end + RUBY + + boot_rails + + get("/bukkits") + assert_equal "HELLO WORLD", last_response.body + end + + test "it provides routes as default endpoint" do + @plugin.write "lib/bukkits.rb", <<-RUBY + class Bukkits + class Engine < ::Rails::Engine + end + end + RUBY + + @plugin.write "config/routes.rb", <<-RUBY + Bukkits::Engine.routes.draw do + match "/foo" => lambda { |env| [200, {'Content-Type' => 'text/html'}, ['foo']] } + end + RUBY + + app_file "config/routes.rb", <<-RUBY + Rails.application.routes.draw do + mount(Bukkits::Engine => "/bukkits") + end + RUBY + + boot_rails + + get("/bukkits/foo") + assert_equal "foo", last_response.body + end + + test "engine can load its own plugins" do + @plugin.write "lib/bukkits.rb", <<-RUBY + class Bukkits + class Engine < ::Rails::Engine + end + end + RUBY + + @plugin.write "vendor/plugins/yaffle/init.rb", <<-RUBY + config.yaffle_loaded = true + RUBY + + boot_rails + + assert Bukkits::Engine.config.yaffle_loaded + end + + test "engine does not load plugins that already exists in application" do + @plugin.write "lib/bukkits.rb", <<-RUBY + class Bukkits + class Engine < ::Rails::Engine + end + end + RUBY + + @plugin.write "vendor/plugins/yaffle/init.rb", <<-RUBY + config.engine_yaffle_loaded = true + RUBY + + app_file "vendor/plugins/yaffle/init.rb", <<-RUBY + config.app_yaffle_loaded = true + RUBY + + warnings = capture(:stderr) { boot_rails } + + assert !warnings.empty? + assert !Bukkits::Engine.config.respond_to?(:engine_yaffle_loaded) + assert Rails.application.config.app_yaffle_loaded + end + + test "it loads its environment file" do + @plugin.write "lib/bukkits.rb", <<-RUBY + class Bukkits + class Engine < ::Rails::Engine + end + end + RUBY + + @plugin.write "config/environments/development.rb", <<-RUBY + Bukkits::Engine.configure do + config.environment_loaded = true + end + RUBY + + boot_rails + + assert Bukkits::Engine.config.environment_loaded + end + + test "it passes router in env" do + @plugin.write "lib/bukkits.rb", <<-RUBY + class Bukkits + class Engine < ::Rails::Engine + endpoint lambda { |env| [200, {'Content-Type' => 'text/html'}, 'hello'] } + end + end + RUBY + + boot_rails + + env = Rack::MockRequest.env_for("/") + Bukkits::Engine.call(env) + assert_equal Bukkits::Engine.routes, env['action_dispatch.routes'] + + env = Rack::MockRequest.env_for("/") + Rails.application.call(env) + assert_equal Rails.application.routes, env['action_dispatch.routes'] + end + + test "it allows to set asset_path" do + @plugin.write "lib/bukkits.rb", <<-RUBY + class Bukkits + class Engine < ::Rails::Engine + end + end + RUBY + + + @plugin.write "config/routes.rb", <<-RUBY + Bukkits::Engine.routes.draw do + match "/foo" => "foo#index" + end + RUBY + + @plugin.write "app/controllers/foo_controller.rb", <<-RUBY + class FooController < ActionController::Base + def index + render :index + end + end + RUBY + + @plugin.write "app/views/foo/index.html.erb", <<-ERB + <%= image_path("foo.png") %> + <%= javascript_include_tag("foo") %> + <%= stylesheet_link_tag("foo") %> + ERB + + app_file "config/routes.rb", <<-RUBY + Rails.application.routes.draw do + mount Bukkits::Engine => "/bukkits" + end + RUBY + + add_to_config 'config.asset_path = "/omg%s"' + + boot_rails + + # should set asset_path with engine name by default + assert_equal "/bukkits_engine%s", ::Bukkits::Engine.config.asset_path + + ::Bukkits::Engine.config.asset_path = "/bukkits%s" + + get("/bukkits/foo") + stripped_body = last_response.body.split("\n").map(&:strip).join + + expected = "/omg/bukkits/images/foo.png" + + "<script src=\"/omg/bukkits/javascripts/foo.js\" type=\"text/javascript\"></script>" + + "<link href=\"/omg/bukkits/stylesheets/foo.css\" media=\"screen\" rel=\"stylesheet\" type=\"text/css\" />" + assert_equal expected, stripped_body + end + + test "default application's asset_path" do + @plugin.write "config/routes.rb", <<-RUBY + Bukkits::Engine.routes.draw do + match "/foo" => "foo#index" + end + RUBY + + @plugin.write "app/controllers/foo_controller.rb", <<-RUBY + class FooController < ActionController::Base + def index + render :inline => '<%= image_path("foo.png") %>' + end + end + RUBY + + app_file "config/routes.rb", <<-RUBY + AppTemplate::Application.routes.draw do + mount Bukkits::Engine => "/bukkits" + end + RUBY + + boot_rails + + get("/bukkits/foo") + assert_equal "/bukkits/images/foo.png", last_response.body.strip + end + + test "engine's files are served via ActionDispatch::Static" do + add_to_config "config.serve_static_assets = true" + + @plugin.write "lib/bukkits.rb", <<-RUBY + class Bukkits + class Engine < ::Rails::Engine + engine_name :bukkits + end + end + RUBY + + @plugin.write "public/bukkits.html", "/bukkits/bukkits.html" + app_file "public/app.html", "/app.html" + app_file "public/bukkits/file_from_app.html", "/bukkits/file_from_app.html" + + boot_rails + + get("/app.html") + assert_equal File.read(File.join(app_path, "public/app.html")), last_response.body + + get("/bukkits/bukkits.html") + assert_equal File.read(File.join(@plugin.path, "public/bukkits.html")), last_response.body + + get("/bukkits/file_from_app.html") + assert_equal File.read(File.join(app_path, "public/bukkits/file_from_app.html")), last_response.body + end + + test "an applications files are given priority over an engines files when served via ActionDispatch::Static" do + add_to_config "config.serve_static_assets = true" + + @plugin.write "lib/bukkits.rb", <<-RUBY + class Bukkits + class Engine < ::Rails::Engine + engine_name :bukkits + end + end + RUBY + + app_file "config/routes.rb", <<-RUBY + AppTemplate::Application.routes.draw do + mount Bukkits::Engine => "/bukkits" + end + RUBY + + @plugin.write "public/bukkits.html", "in engine" + + app_file "public/bukkits/bukkits.html", "in app" + + boot_rails + + get('/bukkits/bukkits.html') + + assert_equal 'in app', last_response.body.strip + end + + test "shared engine should include application's helpers and own helpers" do + app_file "config/routes.rb", <<-RUBY + AppTemplate::Application.routes.draw do + match "/foo" => "bukkits/foo#index", :as => "foo" + match "/foo/show" => "bukkits/foo#show" + match "/foo/bar" => "bukkits/foo#bar" + end + RUBY + + app_file "app/helpers/some_helper.rb", <<-RUBY + module SomeHelper + def something + "Something... Something... Something..." + end + end + RUBY + + @plugin.write "app/helpers/bar_helper.rb", <<-RUBY + module BarHelper + def bar + "It's a bar." + end + end + RUBY + + @plugin.write "app/controllers/bukkits/foo_controller.rb", <<-RUBY + class Bukkits::FooController < ActionController::Base + def index + render :inline => "<%= something %>" + end + + def show + render :text => foo_path + end + + def bar + render :inline => "<%= bar %>" + end + end + RUBY + + boot_rails + + get("/foo") + assert_equal "Something... Something... Something...", last_response.body + + get("/foo/show") + assert_equal "/foo", last_response.body + + get("/foo/bar") + assert_equal "It's a bar.", last_response.body + end + + test "isolated engine should include only its own routes and helpers" do + @plugin.write "lib/bukkits.rb", <<-RUBY + module Bukkits + class Engine < ::Rails::Engine + isolate_namespace Bukkits + end + end + RUBY + + @plugin.write "app/models/bukkits/post.rb", <<-RUBY + module Bukkits + class Post + extend ActiveModel::Naming + + def to_param + "1" + end + end + end + RUBY + + app_file "config/routes.rb", <<-RUBY + AppTemplate::Application.routes.draw do + match "/bar" => "bar#index", :as => "bar" + mount Bukkits::Engine => "/bukkits", :as => "bukkits" + end + RUBY + + @plugin.write "config/routes.rb", <<-RUBY + Bukkits::Engine.routes.draw do + match "/foo" => "foo#index", :as => "foo" + match "/foo/show" => "foo#show" + match "/from_app" => "foo#from_app" + match "/routes_helpers_in_view" => "foo#routes_helpers_in_view" + match "/polymorphic_path_without_namespace" => "foo#polymorphic_path_without_namespace" + resources :posts + end + RUBY + + app_file "app/helpers/some_helper.rb", <<-RUBY + module SomeHelper + def something + "Something... Something... Something..." + end + end + RUBY + + @plugin.write "app/helpers/engine_helper.rb", <<-RUBY + module EngineHelper + def help_the_engine + "Helped." + end + end + RUBY + + @plugin.write "app/controllers/bukkits/foo_controller.rb", <<-RUBY + class Bukkits::FooController < ActionController::Base + def index + render :inline => "<%= help_the_engine %>" + end + + def show + render :text => foo_path + end + + def from_app + render :inline => "<%= (self.respond_to?(:bar_path) || self.respond_to?(:something)) %>" + end + + def routes_helpers_in_view + render :inline => "<%= foo_path %>, <%= main_app.bar_path %>" + end + + def polymorphic_path_without_namespace + render :text => polymorphic_path(Post.new) + end + end + RUBY + + @plugin.write "app/mailers/bukkits/my_mailer.rb", <<-RUBY + module Bukkits + class MyMailer < ActionMailer::Base + end + end + RUBY + + add_to_config("config.action_dispatch.show_exceptions = false") + + boot_rails + + assert_equal "bukkits_", Bukkits.table_name_prefix + assert_equal "bukkits", Bukkits::Engine.engine_name + assert_equal Bukkits._railtie, Bukkits::Engine + assert ::Bukkits::MyMailer.method_defined?(:foo_path) + assert !::Bukkits::MyMailer.method_defined?(:bar_path) + + get("/bukkits/from_app") + assert_equal "false", last_response.body + + get("/bukkits/foo/show") + assert_equal "/bukkits/foo", last_response.body + + get("/bukkits/foo") + assert_equal "Helped.", last_response.body + + get("/bukkits/routes_helpers_in_view") + assert_equal "/bukkits/foo, /bar", last_response.body + + get("/bukkits/polymorphic_path_without_namespace") + assert_equal "/bukkits/posts/1", last_response.body + end + + test "isolated engine should avoid namespace in names if that's possible" do + @plugin.write "lib/bukkits.rb", <<-RUBY + module Bukkits + class Engine < ::Rails::Engine + isolate_namespace Bukkits + end + end + RUBY + + @plugin.write "app/models/bukkits/post.rb", <<-RUBY + module Bukkits + class Post + extend ActiveModel::Naming + include ActiveModel::Conversion + attr_accessor :title + + def to_param + "1" + end + + def persisted? + false + end + end + end + RUBY + + app_file "config/routes.rb", <<-RUBY + AppTemplate::Application.routes.draw do + mount Bukkits::Engine => "/bukkits", :as => "bukkits" + end + RUBY + + @plugin.write "config/routes.rb", <<-RUBY + Bukkits::Engine.routes.draw do + resources :posts + end + RUBY + + @plugin.write "app/controllers/bukkits/posts_controller.rb", <<-RUBY + class Bukkits::PostsController < ActionController::Base + def new + end + end + RUBY + + @plugin.write "app/views/bukkits/posts/new.html.erb", <<-ERB + <%= form_for(Bukkits::Post.new) do |f| %> + <%= f.text_field :title %> + <% end %> + ERB + + add_to_config("config.action_dispatch.show_exceptions = false") + + boot_rails + + get("/bukkits/posts/new") + assert_match /name="post\[title\]"/, last_response.body + end + + test "loading seed data" do + @plugin.write "db/seeds.rb", <<-RUBY + Bukkits::Engine.config.bukkits_seeds_loaded = true + RUBY + + app_file "db/seeds.rb", <<-RUBY + Rails.application.config.app_seeds_loaded = true + RUBY + + boot_rails + + Rails.application.load_seed + assert Rails.application.config.app_seeds_loaded + assert_raise(NoMethodError) do Bukkits::Engine.config.bukkits_seeds_loaded end + + Bukkits::Engine.load_seed + assert Bukkits::Engine.config.bukkits_seeds_loaded + end + + test "using namespace more than once on one module should not overwrite _railtie method" do + @plugin.write "lib/bukkits.rb", <<-RUBY + module AppTemplate + class Engine < ::Rails::Engine + isolate_namespace(AppTemplate) + end + end + RUBY + + add_to_config "isolate_namespace AppTemplate" + + app_file "config/routes.rb", <<-RUBY + AppTemplate::Application.routes.draw do end + RUBY + + boot_rails + + assert_equal AppTemplate._railtie, AppTemplate::Engine + end + + test "properly reload routes" do + # when routes are inside application class definition + # they should not be reloaded when engine's routes + # file has changed + add_to_config <<-RUBY + routes do + mount lambda{|env| [200, {}, ["foo"]]} => "/foo" + mount Bukkits::Engine => "/bukkits" + end + RUBY + + FileUtils.rm(File.join(app_path, "config/routes.rb")) + + @plugin.write "config/routes.rb", <<-RUBY + Bukkits::Engine.routes.draw do + mount lambda{|env| [200, {}, ["bar"]]} => "/bar" + end + RUBY + + @plugin.write "lib/bukkits.rb", <<-RUBY + module Bukkits + class Engine < ::Rails::Engine + isolate_namespace(Bukkits) + end + end + RUBY + + boot_rails + + require "#{rails_root}/config/environment" + + get("/foo") + assert_equal "foo", last_response.body + + get("/bukkits/bar") + assert_equal "bar", last_response.body + end + + test "setting generators for engine and overriding app generator's" do + @plugin.write "lib/bukkits.rb", <<-RUBY + module Bukkits + class Engine < ::Rails::Engine + config.generators do |g| + g.orm :datamapper + g.template_engine :haml + g.test_framework :rspec + end + + config.app_generators do |g| + g.orm :mongoid + g.template_engine :liquid + g.test_framework :shoulda + end + end + end + RUBY + + add_to_config <<-RUBY + config.generators do |g| + g.test_framework :test_unit + end + RUBY + + boot_rails + require "#{rails_root}/config/environment" + + app_generators = Rails.application.config.generators.options[:rails] + assert_equal :mongoid , app_generators[:orm] + assert_equal :liquid , app_generators[:template_engine] + assert_equal :test_unit, app_generators[:test_framework] + + generators = Bukkits::Engine.config.generators.options[:rails] + assert_equal :datamapper, generators[:orm] + assert_equal :haml , generators[:template_engine] + assert_equal :rspec , generators[:test_framework] + end + + test "engine should get default generators with ability to overwrite them" do + @plugin.write "lib/bukkits.rb", <<-RUBY + module Bukkits + class Engine < ::Rails::Engine + config.generators.test_framework :rspec + end + end + RUBY + + boot_rails + require "#{rails_root}/config/environment" + + generators = Bukkits::Engine.config.generators.options[:rails] + assert_equal :active_record, generators[:orm] + assert_equal :rspec , generators[:test_framework] + + app_generators = Rails.application.config.generators.options[:rails] + assert_equal :test_unit , app_generators[:test_framework] + end + + test "do not create table_name_prefix method if it already exists" do + @plugin.write "lib/bukkits.rb", <<-RUBY + module Bukkits + def self.table_name_prefix + "foo" + end + + class Engine < ::Rails::Engine + isolate_namespace(Bukkits) + end + end + RUBY + + boot_rails + require "#{rails_root}/config/environment" + + assert_equal "foo", Bukkits.table_name_prefix + end + + test "fetching engine by path" do + @plugin.write "lib/bukkits.rb", <<-RUBY + module Bukkits + class Engine < ::Rails::Engine + end + end + RUBY + + boot_rails + require "#{rails_root}/config/environment" + + assert_equal Bukkits::Engine.instance, Rails::Engine.find(@plugin.path) + + # check expanding paths + engine_dir = @plugin.path.chomp("/").split("/").last + engine_path = File.join(@plugin.path, '..', engine_dir) + assert_equal Bukkits::Engine.instance, Rails::Engine.find(engine_path) + end + + test "ensure that engine properly sets assets directories" do + add_to_config("config.action_dispatch.show_exceptions = false") + add_to_config("config.serve_static_assets = true") + + @plugin.write "lib/bukkits.rb", <<-RUBY + module Bukkits + class Engine < ::Rails::Engine + isolate_namespace Bukkits + end + end + RUBY + + @plugin.write "public/stylesheets/foo.css", "" + @plugin.write "public/javascripts/foo.js", "" + + @plugin.write "app/views/layouts/bukkits/application.html.erb", <<-RUBY + <%= stylesheet_link_tag :all %> + <%= javascript_include_tag :all %> + <%= yield %> + RUBY + + @plugin.write "app/controllers/bukkits/home_controller.rb", <<-RUBY + module Bukkits + class HomeController < ActionController::Base + def index + render :text => "Good morning!", :layout => "bukkits/application" + end + end + end + RUBY + + @plugin.write "config/routes.rb", <<-RUBY + Bukkits::Engine.routes.draw do + match "/home" => "home#index" + end + RUBY + + app_file "config/routes.rb", <<-RUBY + Rails.application.routes.draw do + mount Bukkits::Engine => "/bukkits" + end + RUBY + + require 'rack/test' + extend Rack::Test::Methods + + boot_rails + + require "#{rails_root}/config/environment" + + assert_equal File.join(@plugin.path, "public"), Bukkits::HomeController.assets_dir + assert_equal File.join(@plugin.path, "public/stylesheets"), Bukkits::HomeController.stylesheets_dir + assert_equal File.join(@plugin.path, "public/javascripts"), Bukkits::HomeController.javascripts_dir + + assert_equal File.join(app_path, "public"), ActionController::Base.assets_dir + assert_equal File.join(app_path, "public/stylesheets"), ActionController::Base.stylesheets_dir + assert_equal File.join(app_path, "public/javascripts"), ActionController::Base.javascripts_dir + + get "/bukkits/home" + + assert_match %r{bukkits/stylesheets/foo.css}, last_response.body + assert_match %r{bukkits/javascripts/foo.js}, last_response.body + end + + private + def app + Rails.application + end end end diff --git a/railties/test/railties/mounted_engine_test.rb b/railties/test/railties/mounted_engine_test.rb new file mode 100644 index 0000000000..47a4753e78 --- /dev/null +++ b/railties/test/railties/mounted_engine_test.rb @@ -0,0 +1,174 @@ +require 'isolation/abstract_unit' + +module ApplicationTests + class ApplicationRoutingTest < Test::Unit::TestCase + require 'rack/test' + include Rack::Test::Methods + include ActiveSupport::Testing::Isolation + + def setup + build_app + + add_to_config("config.action_dispatch.show_exceptions = false") + + @plugin = engine "blog" + + app_file 'config/routes.rb', <<-RUBY + AppTemplate::Application.routes.draw do + match "/engine_route" => "application_generating#engine_route" + match "/engine_route_in_view" => "application_generating#engine_route_in_view" + match "/url_for_engine_route" => "application_generating#url_for_engine_route" + match "/polymorphic_route" => "application_generating#polymorphic_route" + scope "/:user", :user => "anonymous" do + mount Blog::Engine => "/blog" + end + root :to => 'main#index' + end + RUBY + + @plugin.write "app/models/blog/post.rb", <<-RUBY + module Blog + class Post + extend ActiveModel::Naming + + def id + 44 + end + + def to_param + id.to_s + end + + def new_record? + false + end + end + end + RUBY + + @plugin.write "lib/blog.rb", <<-RUBY + module Blog + class Engine < ::Rails::Engine + isolate_namespace(Blog) + end + end + RUBY + + @plugin.write "config/routes.rb", <<-RUBY + Blog::Engine.routes.draw do + resources :posts + match '/generate_application_route', :to => 'posts#generate_application_route' + match '/application_route_in_view', :to => 'posts#application_route_in_view' + end + RUBY + + @plugin.write "app/controllers/blog/posts_controller.rb", <<-RUBY + module Blog + class PostsController < ActionController::Base + def index + render :text => blog.post_path(1) + end + + def generate_application_route + path = main_app.url_for(:controller => "/main", + :action => "index", + :only_path => true) + render :text => path + end + + def application_route_in_view + render :inline => "<%= main_app.root_path %>" + end + end + end + RUBY + + app_file "app/controllers/application_generating_controller.rb", <<-RUBY + class ApplicationGeneratingController < ActionController::Base + def engine_route + render :text => blog.posts_path + end + + def engine_route_in_view + render :inline => "<%= blog.posts_path %>" + end + + def url_for_engine_route + render :text => blog.url_for(:controller => "blog/posts", :action => "index", :user => "john", :only_path => true) + end + + def polymorphic_route + render :text => polymorphic_url([blog, Blog::Post.new]) + end + end + RUBY + + boot_rails + end + + def app + @app ||= begin + require "#{app_path}/config/environment" + Rails.application + end + end + + def reset_script_name! + Rails.application.routes.default_url_options = {} + end + + def script_name(script_name) + Rails.application.routes.default_url_options = {:script_name => script_name} + end + + test "routes generation in engine and application" do + # test generating engine's route from engine + get "/john/blog/posts" + assert_equal "/john/blog/posts/1", last_response.body + + # test generating engine's route from engine with default_url_options + script_name "/foo" + get "/john/blog/posts", {}, 'SCRIPT_NAME' => "/foo" + assert_equal "/foo/john/blog/posts/1", last_response.body + reset_script_name! + + # test generating engine's route from application + get "/engine_route" + assert_equal "/anonymous/blog/posts", last_response.body + + get "/engine_route_in_view" + assert_equal "/anonymous/blog/posts", last_response.body + + get "/url_for_engine_route" + assert_equal "/john/blog/posts", last_response.body + + # test generating engine's route from application with default_url_options + script_name "/foo" + get "/engine_route", {}, 'SCRIPT_NAME' => "/foo" + assert_equal "/foo/anonymous/blog/posts", last_response.body + + script_name "/foo" + get "/url_for_engine_route", {}, 'SCRIPT_NAME' => "/foo" + assert_equal "/foo/john/blog/posts", last_response.body + reset_script_name! + + # test generating application's route from engine + get "/someone/blog/generate_application_route" + assert_equal "/", last_response.body + + get "/somone/blog/application_route_in_view" + assert_equal "/", last_response.body + + # test generating application's route from engine with default_url_options + script_name "/foo" + get "/someone/blog/generate_application_route", {}, 'SCRIPT_NAME' => '/foo' + assert_equal "/foo/", last_response.body + reset_script_name! + + # test polymorphic routes + get "/polymorphic_route" + assert_equal "http://example.org/anonymous/blog/posts/44", last_response.body + end + end +end + diff --git a/railties/test/railties/plugin_test.rb b/railties/test/railties/plugin_test.rb index b143f56484..c15ac05103 100644 --- a/railties/test/railties/plugin_test.rb +++ b/railties/test/railties/plugin_test.rb @@ -110,37 +110,10 @@ module RailtiesTest boot_rails rescue Exception => e rescued = true - assert_equal '"bukkits" is a Railtie/Engine and cannot be installed as plugin', e.message + assert_equal '"bukkits" is a Railtie/Engine and cannot be installed as a plugin', e.message end assert rescued, "Expected boot rails to fail" end - - test "loads deprecated rails/init.rb" do - @plugin.write "rails/init.rb", <<-RUBY - $loaded = true - RUBY - - boot_rails - assert $loaded - end - - test "deprecated tasks are also loaded" do - $executed = false - @plugin.write "tasks/foo.rake", <<-RUBY - task :foo do - $executed = true - end - RUBY - - boot_rails - require 'rake' - require 'rake/rdoctask' - require 'rake/testtask' - Rails.application.load_tasks - Rake::Task[:foo].invoke - assert $executed - end - end end diff --git a/railties/test/railties/railtie_test.rb b/railties/test/railties/railtie_test.rb index db0fd87491..7ea8364ae9 100644 --- a/railties/test/railties/railtie_test.rb +++ b/railties/test/railties/railtie_test.rb @@ -19,6 +19,22 @@ module RailtiesTest assert !Rails::Railtie.respond_to?(:config) end + test "Railtie provides railtie_name" do + begin + class ::FooBarBaz < Rails::Railtie ; end + assert_equal "foo_bar_baz", ::FooBarBaz.railtie_name + ensure + Object.send(:remove_const, :"FooBarBaz") + end + end + + test "railtie_name can be set manualy" do + class Foo < Rails::Railtie + railtie_name "bar" + end + assert_equal "bar", Foo.railtie_name + end + test "cannot inherit from a railtie" do class Foo < Rails::Railtie ; end assert_raise RuntimeError do @@ -87,6 +103,30 @@ module RailtiesTest assert $ran_block end + test "rake_tasks block defined in superclass of railtie is also executed" do + $ran_block = [] + + class Rails::Railtie + rake_tasks do + $ran_block << railtie_name + end + end + + class MyTie < Rails::Railtie + railtie_name "my_tie" + end + + require "#{app_path}/config/environment" + + assert_equal [], $ran_block + require 'rake' + require 'rake/testtask' + require 'rake/rdoctask' + + AppTemplate::Application.load_tasks + assert $ran_block.include?("my_tie") + end + test "generators block is executed when MyApp.load_generators is called" do $ran_block = false @@ -132,7 +172,7 @@ module RailtiesTest require "#{app_path}/config/environment" assert $ran_block end - + test "we can change our environment if we want to" do begin original_env = Rails.env diff --git a/railties/test/railties/shared_tests.rb b/railties/test/railties/shared_tests.rb index ce7c55c11c..3eb79d57c8 100644 --- a/railties/test/railties/shared_tests.rb +++ b/railties/test/railties/shared_tests.rb @@ -10,6 +10,100 @@ module RailtiesTest @app ||= Rails.application end + def test_install_migrations_and_assets + @plugin.write "public/javascripts/foo.js", "doSomething()" + + @plugin.write "db/migrate/1_create_users.rb", <<-RUBY + class CreateUsers < ActiveRecord::Migration + end + RUBY + + app_file "db/migrate/1_create_sessions.rb", <<-RUBY + class CreateSessions < ActiveRecord::Migration + end + RUBY + + add_to_config "ActiveRecord::Base.timestamped_migrations = false" + + Dir.chdir(app_path) do + `rake bukkits:install` + assert File.exists?("#{app_path}/db/migrate/2_create_users.rb") + assert File.exists?(app_path("public/bukkits/javascripts/foo.js")) + end + end + + def test_copying_assets + @plugin.write "public/javascripts/foo.js", "doSomething()" + @plugin.write "public/stylesheets/foo.css", "h1 { font-size: 10000px }" + @plugin.write "public/images/img.png", "" + + Dir.chdir(app_path) do + `rake bukkits:install:assets --trace` + + assert File.exists?(app_path("public/bukkits/javascripts/foo.js")) + assert_equal "doSomething()\n", File.read(app_path("public/bukkits/javascripts/foo.js")) + assert File.exists?(app_path("public/bukkits/stylesheets/foo.css")) + assert_equal "h1 { font-size: 10000px }\n", File.read(app_path("public/bukkits/stylesheets/foo.css")) + assert File.exists?(app_path("public/bukkits/images/img.png")) + end + end + + def test_copying_migrations + @plugin.write "db/migrate/1_create_users.rb", <<-RUBY + class CreateUsers < ActiveRecord::Migration + end + RUBY + + @plugin.write "db/migrate/2_add_last_name_to_users.rb", <<-RUBY + class AddLastNameToUsers < ActiveRecord::Migration + end + RUBY + + @plugin.write "db/migrate/3_create_sessions.rb", <<-RUBY + class CreateSessions < ActiveRecord::Migration + end + RUBY + + app_file "db/migrate/1_create_sessions.rb", <<-RUBY + class CreateSessions < ActiveRecord::Migration + end + RUBY + + yaffle = plugin "acts_as_yaffle", "::LEVEL = config.log_level" do |plugin| + plugin.write "lib/acts_as_yaffle.rb", "class ActsAsYaffle; end" + end + + yaffle.write "db/migrate/1_create_yaffles.rb", <<-RUBY + class CreateYaffles < ActiveRecord::Migration + end + RUBY + + add_to_config "ActiveRecord::Base.timestamped_migrations = false" + + Dir.chdir(app_path) do + output = `rake bukkits:install:migrations` + + assert File.exists?("#{app_path}/db/migrate/2_create_users.rb") + assert File.exists?("#{app_path}/db/migrate/3_add_last_name_to_users.rb") + assert_match /Copied migration 2_create_users.rb from bukkits/, output + assert_match /Copied migration 3_add_last_name_to_users.rb from bukkits/, output + assert_match /NOTE: Migration 3_create_sessions.rb from bukkits has been skipped/, output + assert_equal 3, Dir["#{app_path}/db/migrate/*.rb"].length + + output = `rake railties:install:migrations` + + assert File.exists?("#{app_path}/db/migrate/4_create_yaffles.rb") + assert_match /NOTE: Migration 3_create_sessions.rb from bukkits has been skipped/, output + assert_match /Copied migration 4_create_yaffles.rb from acts_as_yaffle/, output + assert_no_match /2_create_users/, output + + migrations_count = Dir["#{app_path}/db/migrate/*.rb"].length + output = `rake railties:install:migrations` + + assert_equal migrations_count, Dir["#{app_path}/db/migrate/*.rb"].length + end + end + def test_puts_its_lib_directory_on_load_path boot_rails require "another" @@ -129,7 +223,7 @@ module RailtiesTest RUBY app_file "config/routes.rb", <<-RUBY - AppTemplate::Application.routes.draw do |map| + AppTemplate::Application.routes.draw do match 'foo', :to => 'foo#index' end RUBY @@ -143,7 +237,7 @@ module RailtiesTest RUBY @plugin.write "config/routes.rb", <<-RUBY - Rails.application.routes.draw do |map| + Rails.application.routes.draw do match 'foo', :to => 'bar#index' match 'bar', :to => 'bar#index' end @@ -200,7 +294,7 @@ YAML boot_rails - assert_equal %W( + expected_locales = %W( #{RAILS_FRAMEWORK_ROOT}/activesupport/lib/active_support/locale/en.yml #{RAILS_FRAMEWORK_ROOT}/activemodel/lib/active_model/locale/en.yml #{RAILS_FRAMEWORK_ROOT}/activerecord/lib/active_record/locale/en.yml @@ -208,7 +302,13 @@ YAML #{@plugin.path}/config/locales/en.yml #{app_path}/config/locales/en.yml #{app_path}/app/locales/en.yml - ).map { |path| File.expand_path(path) }, I18n.load_path.map { |path| File.expand_path(path) } + ).map { |path| File.expand_path(path) } + + actual_locales = I18n.load_path.map { |path| + File.expand_path(path) + } & expected_locales # remove locales external to Rails + + assert_equal expected_locales, actual_locales assert_equal "2", I18n.t(:foo) assert_equal "1", I18n.t(:bar) diff --git a/railties/test/script_rails_loader_test.rb b/railties/test/script_rails_loader_test.rb index 2a87e5cb58..3ccc147749 100644 --- a/railties/test/script_rails_loader_test.rb +++ b/railties/test/script_rails_loader_test.rb @@ -2,21 +2,21 @@ require 'abstract_unit' require 'rails/script_rails_loader' class ScriptRailsLoaderTest < ActiveSupport::TestCase - + test "is in a rails application if script/rails exists" do File.stubs(:exists?).returns(true) assert Rails::ScriptRailsLoader.in_rails_application? end - + test "is in a rails application if parent directory has script/rails" do File.stubs(:exists?).with("/foo/bar/script/rails").returns(false) File.stubs(:exists?).with("/foo/script/rails").returns(true) assert Rails::ScriptRailsLoader.in_rails_application_subdirectory?(Pathname.new("/foo/bar")) end - + test "is not in a rails application if at the root directory and doesn't have script/rails" do Pathname.any_instance.stubs(:root?).returns true assert !Rails::ScriptRailsLoader.in_rails_application? end - + end
\ No newline at end of file |