diff options
Diffstat (limited to 'railties')
101 files changed, 4262 insertions, 228 deletions
diff --git a/railties/CHANGELOG b/railties/CHANGELOG index b5c5aba460..3a276d5aad 100644 --- a/railties/CHANGELOG +++ b/railties/CHANGELOG @@ -1,5 +1,13 @@ *Edge* +* Added config.threadsafe! to toggle allow concurrency settings and disable the dependency loader [Josh Peek] + +* Turn cache_classes on by default [Josh Peek] + +* Added configurable eager load paths. Defaults to app/models, app/controllers, and app/helpers [Josh Peek] + +* Introduce simple internationalization support. [Ruby i18n team] + * Make script/plugin install <plugin> -r <revision> option work with git based plugins. #257. [Tim Pope Jakub Kuźma]. Example: script/plugin install git://github.com/mislav/will_paginate.git -r agnostic # Installs 'agnostic' branch diff --git a/railties/Rakefile b/railties/Rakefile index f64b60b0dd..174c85b59a 100644 --- a/railties/Rakefile +++ b/railties/Rakefile @@ -272,6 +272,21 @@ Rake::RDocTask.new { |rdoc| rdoc.rdoc_files.include('lib/commands/**/*.rb') } +guides = ['securing_rails_applications', 'testing_rails_applications', 'creating_plugins'] +guides_html_files = [] +guides.each do |guide_name| + input = "doc/guides/#{guide_name}/#{guide_name}.txt" + output = "doc/guides/#{guide_name}/#{guide_name}.html" + guides_html_files << output + file output => Dir["doc/guides/#{guide_name}/*.txt"] do + sh "mizuho", input, "--template", "manualsonrails", "--multi-page", + "--icons-dir", "../icons" + end +end + +desc "Generate HTML output for the guides" +task :generate_guides => guides_html_files + # Generate GEM ---------------------------------------------------------------------------- task :copy_gem_environment do diff --git a/railties/bin/about b/railties/bin/about index ed8deb0dfc..ed8deb0dfc 100644..100755 --- a/railties/bin/about +++ b/railties/bin/about diff --git a/railties/bin/console b/railties/bin/console index 498077ab33..498077ab33 100644..100755 --- a/railties/bin/console +++ b/railties/bin/console diff --git a/railties/bin/destroy b/railties/bin/destroy index a4df765a39..a4df765a39 100644..100755 --- a/railties/bin/destroy +++ b/railties/bin/destroy diff --git a/railties/bin/generate b/railties/bin/generate index 173a9f147d..173a9f147d 100644..100755 --- a/railties/bin/generate +++ b/railties/bin/generate diff --git a/railties/bin/performance/benchmarker b/railties/bin/performance/benchmarker index c842d35d33..c842d35d33 100644..100755 --- a/railties/bin/performance/benchmarker +++ b/railties/bin/performance/benchmarker diff --git a/railties/bin/performance/profiler b/railties/bin/performance/profiler index d855ac8b13..d855ac8b13 100644..100755 --- a/railties/bin/performance/profiler +++ b/railties/bin/performance/profiler diff --git a/railties/bin/performance/request b/railties/bin/performance/request index ae3f38c74b..ae3f38c74b 100644..100755 --- a/railties/bin/performance/request +++ b/railties/bin/performance/request diff --git a/railties/bin/plugin b/railties/bin/plugin index 87cd2070fe..87cd2070fe 100644..100755 --- a/railties/bin/plugin +++ b/railties/bin/plugin diff --git a/railties/bin/process/inspector b/railties/bin/process/inspector index bf25ad86d1..bf25ad86d1 100644..100755 --- a/railties/bin/process/inspector +++ b/railties/bin/process/inspector diff --git a/railties/bin/process/reaper b/railties/bin/process/reaper index c77f04535f..c77f04535f 100644..100755 --- a/railties/bin/process/reaper +++ b/railties/bin/process/reaper diff --git a/railties/bin/process/spawner b/railties/bin/process/spawner index 7118f3983c..7118f3983c 100644..100755 --- a/railties/bin/process/spawner +++ b/railties/bin/process/spawner diff --git a/railties/bin/runner b/railties/bin/runner index a4a7cb25ba..a4a7cb25ba 100644..100755 --- a/railties/bin/runner +++ b/railties/bin/runner diff --git a/railties/bin/server b/railties/bin/server index 3c67f39b69..3c67f39b69 100644..100755 --- a/railties/bin/server +++ b/railties/bin/server diff --git a/railties/config.ru b/railties/config.ru new file mode 100644 index 0000000000..43492a2dcc --- /dev/null +++ b/railties/config.ru @@ -0,0 +1,17 @@ +# Rackup Configuration +# +# Start Rails mongrel server with rackup +# $ rackup -p 3000 config.ru +# +# Start server with webrick (or any compatible Rack server) instead +# $ rackup -p 3000 -s webrick config.ru + +# Require your environment file to bootstrap Rails +require File.dirname(__FILE__) + '/config/environment' + +# Static server middleware +# You can remove this extra check if you use an asset server +use Rails::Rack::Static + +# Dispatch the request +run ActionController::Dispatcher.new diff --git a/railties/configs/apache.conf b/railties/configs/apache.conf index d9d211c058..d9d211c058 100755..100644 --- a/railties/configs/apache.conf +++ b/railties/configs/apache.conf diff --git a/railties/dispatches/dispatch.fcgi b/railties/dispatches/dispatch.fcgi index 65188f380b..664dbbbee8 100755 --- a/railties/dispatches/dispatch.fcgi +++ b/railties/dispatches/dispatch.fcgi @@ -1,4 +1,4 @@ -#!/usr/local/bin/ruby +#!/usr/bin/env ruby # # You may specify the path to the FastCGI crash log (a log of unhandled # exceptions which forced the FastCGI instance to exit, great for debugging) diff --git a/railties/dispatches/dispatch.rb b/railties/dispatches/dispatch.rb index 9b5ae760ff..32fa3b2665 100755 --- a/railties/dispatches/dispatch.rb +++ b/railties/dispatches/dispatch.rb @@ -1,4 +1,4 @@ -#!/usr/local/bin/ruby +#!/usr/bin/env ruby require File.dirname(__FILE__) + "/../config/environment" unless defined?(RAILS_ROOT) @@ -7,4 +7,4 @@ require File.dirname(__FILE__) + "/../config/environment" unless defined?(RAILS_ require "dispatcher" ADDITIONAL_LOAD_PATHS.reverse.each { |dir| $:.unshift(dir) if File.directory?(dir) } if defined?(Apache::RubyRun) -Dispatcher.dispatch
\ No newline at end of file +Dispatcher.dispatch diff --git a/railties/dispatches/gateway.cgi b/railties/dispatches/gateway.cgi index fb1fa22f04..0305b7f810 100644..100755 --- a/railties/dispatches/gateway.cgi +++ b/railties/dispatches/gateway.cgi @@ -1,4 +1,4 @@ -#!/usr/local/bin/ruby +#!/usr/bin/env ruby require 'drb' @@ -94,4 +94,4 @@ end $stdout.write output $stdout.flush -$stdout.close
\ No newline at end of file +$stdout.close diff --git a/railties/doc/guides/actionview/helpers.markdown b/railties/doc/guides/actionview/helpers.markdown new file mode 100644 index 0000000000..c702e83ff9 --- /dev/null +++ b/railties/doc/guides/actionview/helpers.markdown @@ -0,0 +1,91 @@ +Helpers +==================== + +Helper Basics +------------------------ + +Helpers allow you to encapsulate rendering tasks as reusable functions. Helpers are modules, not classes, so their methods execute in the context in which they are called. They get included in a controller (typically the ApplicationController) using the helper function, like so + + Class ApplicationController < ActionController::Base + … + helper :menu + + def … + end + end + +In this way, methods in the menu helper are made available to any view or partial in your application. These methods can accept parameters, for example controller instance variables (eg; records or record collections gathered by you current controller), items from the view or partial’s locals[] hash or items from the params[] hash. You may wish to pass your controller instance variables and items from the params[] hash to the locals hash before rendering (See the section on partials). Helper methods can also accept an executable block of code. + +It is important to remember, though, that helpers are for rendering, and that they become available once a controller method has returned, while Rails is engaged in rendering the contents generated by a controller method. This means that helper methods are not available from within the methods of your controllers. + +Helpers can accomplish a variety of tasks, from formatting a complex tag for embedding content for a browser plugin (eg; Flash), to assembling a menu of options appropriate for the current context of your application, to generating sections of forms that get assembled on-the-fly. + +Helpers are organized around rendering tasks, so it is not necessary (nor necessarily desirable) to organize them around your application’s controllers or models. In fact, one of the benefits of helpers is that they are not connected via a rendering pipeline to specific controllers, like views and partials are. They can and should handle more generalized tasks. + +Here is a very simple, pseudo-example: + + module MenuHelper + def menu(records, menu_options={}) + item_options = menu_options.merge({<some stuff>}) + items = records.collect |record| do + menu_item(record, options) + end + content_tag(“ul”, items, options) + end + + def menu_item(record, item_options={})) + action = item_options[:action] + action ||= “show” + content_tag(“li”, link_to(record.title, :action => action, item_options) + end + end + + +This helper will require that records passed into it have certain fields (notably :title). The helper could be written to use this as a default, allowing the field to be overwritten by an element of item_options. + +Look at the Rails API for examples of helpers included in Rails, eg; [`ActionView::Helpers::ActiveRecordHelper`](http://api.rubyonrails.org/classes/ActionView/Helpers/ActiveRecordHelper.html). + +Passing Blocks to Helper Methods +------------------------ + +We mentioned before that blocks can be passed to helper methods. This allows for an interesting wrinkle: a block passed to a helper method can cause it to render a partial, which can then be wrapped by the helper method’s output. This can make your helper method much more reusable. It doesn’t need to know anything about the internals about what it is rendering, it just contextualizes it for the page. You can also use the helper to modify the locals hash for the partial, based on some configuration information unique to the current controller. You could implement a flexible themes system in this way. + + +Partials vs. Helpers? +------------------------ + +In general, the choice between using a partial vs. using a helper depends on the amount of flexibility you need. If the task is more about reacting to conditions than performing actual rendering, you may likely want a helper method. If you want to be able to call it from a variety of views, again, you may want to use a helper method. You can expect to extract helper methods out of code in views and partials during refactoring. + + +Tutorial -- Calling a Helper [UNFINISHED] +------------------------ + +1. Create a Rails application using `rails helper_test` +Notice the code: + + class ApplicationController < ActionController::Base + helper :all # include all helpers, all the time +For this tutorial, we'll keep this code, but you will likely want to exert more control over loading your helpers. + +2. Configure a database of your choice for the app. + +3. Inside of the `/app/helpers/` directory, create a new file called, `menu_helper.rb`. Write this in the file: + + module MenuHelpers + def menu(records, item_proc=nil) + items = records.collect{ |record| + menu_item(record, item_proc) + } + content_tag("ul", items) + end + + def menu_item(record, item_proc=nil) + item_url = item_proc.call(record) + item_url ||= { :action => :show } + content_tag("li", link_to(record.name, item_url)) + end + end + +4. Create a scaffold for some object in your app, using `./script/generate scaffold widgets`. +5. Create a database table for your widgets, with at least the fields `name` and `id`. Create a few widgets. +6. Call the menu command twice from `index.html.erb`, once using the default action, and once supplying a Proc to generate urls.
\ No newline at end of file diff --git a/railties/doc/guides/actionview/partials.markdown b/railties/doc/guides/actionview/partials.markdown new file mode 100644 index 0000000000..2988b933bc --- /dev/null +++ b/railties/doc/guides/actionview/partials.markdown @@ -0,0 +1,90 @@ +A Guide to Using Partials +=============================== + +This guide elaborates on the use and function of partials in Ruby on Rails. As your Rails application grows, your view templates can start to contain a lot of duplicate view code. To manage and reduce this complexity, you can by abstract view template code into partials. Partials are reusable snippets of eRB template code stored in separate files with an underscore ('_') prefix. + +Partials can be located anywhere in the `app/views` directory. File extensions for partials work just like other template files, they bear an extension that denotes what kind of code they generate. For example, `_animal.html.erb` and `_animal.xml.erb` are valid filenames for partials. + +Partials can be inserted in eRB template code by calling the `render` method with the `:partial` option. For example: + + <%= render :partial => 'foo' %> + +This inserts the result of evaluating the template `_foo.html.erb` into the parent template file at this location. Note that `render` assumes that the partial will be in the same directory as the calling parent template and have the same file extension. Partials can be located anywhere within the `app/views` directory. To use a partial located in a different directory then it the parent, add a '/' before it: + + <%= render :partial => '/common/foo' %> + +Loads the partial file from the `app/views/common/_foo.html.erb` directory. + +Abstracting views into partials can be approached in a number of different ways, depending on the situation. Sometimes, the code that you are abstracting is a specialized view of an object or a collection of objects. Other times, you can look at partials as a reusable subroutine. We'll explore each of these approaches and when to use them as well as the syntax for calling them. + +Partials as a View Subroutine +----------------------------- + +Using the `:locals` option, you can pass a hash of values which will be treated as local variables within the partial template. + + <%= render :partial => "person", :locals => { :name => "david" } %> + +The variable `name` contains the value `"david"` within the `_person.html.erb` template. Passing variables in this way allows you to create modular, reusable template files. Note that if you want to make local variables that are optional in some use cases, you will have to set them to a sentinel value such as `nil` when they have not been passed. So, in the example above, if the `name` variable is optional in some use cases, you must set: + + <% name ||= nil -%> + +So that you can later check: + + <% if name -%> + <p>Hello, <%= name %>!</p> + <% end -%> + +Otherwise, the if statement will throw an error at runtime. + +Another thing to be aware of is that instance variables that are visible to the parent view template are visible to the partial. So you might be tempted to do this: + + <%= render :partial => "person" %> + +And then within the partial: + + <% if @name -%> + <p>Hello, <%= @name %>!</p> + <% end -%> + +The potential snag here is that if multiple templates start to rely on this partial, you will need to maintain an instance variable with the same name across all of these templates and controllers. This approach can quickly become brittle if overused. + +Partials as a View of an Object +-------------------------------- + +Another way to look at partials is to view them as mini-views of a particular object or instance variable. Use the `:object` option to pass an object assigns that object to an instance variable named after the partial itself. For example: + + # Renders the partial, making @new_person available through + # the local variable 'person' + render :partial => "person", :object => @new_person + +If the instance variable `name` in the parent template matches the name of the partial, you can use a shortcut: + + render :partial => "person" + +Now the value that was in `@person` in the parent template is accessible as `person` in the partial. + +Partials as a View of a Collection +----------------------------------- + +Often it is the case that you need to display not just a single object, but a collection of objects. Rather than having to constantly nest the same partial within the same iterator code, Rails provides a syntactical shortcut using the `:collection` option: + + # Renders a collection of the same partial by making each element + # of @winners available through the local variable "person" as it + # builds the complete response. + render :partial => "person", :collection => @winners + +This calls the `_person.html.erb` partial for each person in the `@winners` collection. This also creates a local variable within the partial called `partial_counter` which contains the index of the current value. So for example: + + <%= partial_counter %>) <%= person -%> + +Where `@winners` contains three people, produces the following output: + + 1) Bill + 2) Jeff + 3) Nick + +One last detail, you can place an arbitrary snippet of code in between the objects using the `:spacer_template` option. + + # Renders the same collection of partials, but also renders the + # person_divider partial between each person partial. + render :partial => "person", :collection => @winners, :spacer_template => "person_divider" diff --git a/railties/doc/guides/activerecord/basics.markdown b/railties/doc/guides/activerecord/basics.markdown new file mode 100644 index 0000000000..0d030fabf9 --- /dev/null +++ b/railties/doc/guides/activerecord/basics.markdown @@ -0,0 +1,56 @@ +Active Record Basics +==================== + + + +The ActiveRecord Pattern +------------------------ + +Active Record (the library) conforms to the active record design pattern. The active record pattern is a design pattern often found in applications that use relational database. The name comes from by Martin Fowler's book *Patterns of Enterprise Application Architecture*, in which he describes an active record object as: + +> An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data. + +So, an object that follows the active record pattern encapsulates both data and behavior; in other words, they are responsible for saving and loading to the database and also for any domain logic that acts on the data. The data structure of the Active Record should exactly match that of the database: one field in the class for each column in the table. + +The Active Record class typically has methods that do the following: + +* Construct an instances of an Active Record class from a SQL result +* Construct a new class instance for insertion into the table +* Get and set column values +* Wrap business logic where appropriate +* Update existing objects and update the related rows in the database + +Mapping Your Database +--------------------- + +### Plural tables, singular classes ### + +### Schema lives in the database ### + +Creating Records +---------------- + +### Using save ### + +### Using create ### + +Retrieving Existing Rows +------------------------ + +### Using find ### + +### Using find_by_* ### + +Editing and Updating Rows +------------------------- + +### Editing an instance + +### Using update_all/update_attributes ### + +Deleting Data +------------- + +### Destroying a record ### + +### Deleting a record ###
\ No newline at end of file diff --git a/railties/doc/guides/creating_plugins/acts_as_yaffle.txt b/railties/doc/guides/creating_plugins/acts_as_yaffle.txt new file mode 100644 index 0000000000..12d40deb18 --- /dev/null +++ b/railties/doc/guides/creating_plugins/acts_as_yaffle.txt @@ -0,0 +1,193 @@ +== Add an `acts_as_yaffle` method to ActiveRecord == + +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. + +To keep things clean, create a new test file called 'acts_as_yaffle_test.rb' in your plugin's test directory and require your test helper. + +[source, ruby] +------------------------------------------------------ +# File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb + +require File.dirname(__FILE__) + '/test_helper.rb' + +class Hickwall < ActiveRecord::Base + acts_as_yaffle +end + +class ActsAsYaffleTest < Test::Unit::TestCase +end +------------------------------------------------------ + +[source, ruby] +------------------------------------------------------ +# File: vendor/plugins/lib/acts_as_yaffle.rb + +module Yaffle +end +------------------------------------------------------ + +One of the most common plugin patterns for `acts_as_yaffle` plugins is to structure your file like so: + +[source, 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 + + module InstanceMethods + # any method placed here will apply to instaces, like @hickwall + end +end +------------------------------------------------------ + +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`). + +Let's add class method named `acts_as_yaffle` - testing it out first. You already defined the ActiveRecord models in your test helper, so if you run tests now they will fail. + +Back in your `acts_as_yaffle` file, update ClassMethods like so: + +[source, ruby] +------------------------------------------------------ +module ClassMethods + def acts_as_yaffle(options = {}) + send :include, InstanceMethods + end +end +------------------------------------------------------ + +Now that test should pass. Since your plugin is going to work with field names, you need to allow people to define the field names, in case there is a naming conflict. You can write a few simple tests for this: + +[source, ruby] +------------------------------------------------------ +# File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb + +require File.dirname(__FILE__) + '/test_helper.rb' + +class ActsAsYaffleTest < Test::Unit::TestCase + def test_a_hickwalls_yaffle_text_field_should_be_last_squawk + assert_equal "last_squawk", Hickwall.yaffle_text_field + end + + def test_a_hickwalls_yaffle_date_field_should_be_last_squawked_at + assert_equal "last_squawked_at", Hickwall.yaffle_date_field + end + + def test_a_wickwalls_yaffle_text_field_should_be_last_tweet + assert_equal "last_tweet", Wickwall.yaffle_text_field + end + + def test_a_wickwalls_yaffle_date_field_should_be_last_tweeted_at + assert_equal "last_tweeted_at", Wickwall.yaffle_date_field + end +end +------------------------------------------------------ + +To make these tests pass, you could modify your `acts_as_yaffle` file like so: + +[source, ruby] +------------------------------------------------------ +# File: vendor/plugins/yaffle/lib/acts_as_yaffle.rb + +module Yaffle + def self.included(base) + base.send :extend, ClassMethods + end + + module ClassMethods + def acts_as_yaffle(options = {}) + cattr_accessor :yaffle_text_field, :yaffle_date_field + self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s + self.yaffle_date_field = (options[:yaffle_date_field] || :last_squawked_at).to_s + send :include, InstanceMethods + end + end + + module InstanceMethods + end +end +------------------------------------------------------ + +Now you can add tests for the instance methods, and the instance method itself: + +[source, ruby] +------------------------------------------------------ +# File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb + +require File.dirname(__FILE__) + '/test_helper.rb' + +class ActsAsYaffleTest < Test::Unit::TestCase + + def test_a_hickwalls_yaffle_text_field_should_be_last_squawk + assert_equal "last_squawk", Hickwall.yaffle_text_field + end + def test_a_hickwalls_yaffle_date_field_should_be_last_squawked_at + assert_equal "last_squawked_at", Hickwall.yaffle_date_field + end + + def test_a_wickwalls_yaffle_text_field_should_be_last_squawk + assert_equal "last_tweet", Wickwall.yaffle_text_field + end + def test_a_wickwalls_yaffle_date_field_should_be_last_squawked_at + assert_equal "last_tweeted_at", Wickwall.yaffle_date_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_hickwalls_squawk_should_populate_last_squawked_at + hickwall = Hickwall.new + hickwall.squawk("Hello World") + assert_equal Date.today, hickwall.last_squawked_at + end + + def test_wickwalls_squawk_should_populate_last_tweet + wickwall = Wickwall.new + wickwall.squawk("Hello World") + assert_equal "squawk! Hello World", wickwall.last_tweet + end + def test_wickwalls_squawk_should_populate_last_tweeted_at + wickwall = Wickwall.new + wickwall.squawk("Hello World") + assert_equal Date.today, wickwall.last_tweeted_at + end +end +------------------------------------------------------ + +[source, ruby] +------------------------------------------------------ +# File: vendor/plugins/yaffle/lib/acts_as_yaffle.rb + +module Yaffle + def self.included(base) + base.send :extend, ClassMethods + end + + module ClassMethods + def acts_as_yaffle(options = {}) + cattr_accessor :yaffle_text_field, :yaffle_date_field + self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s + self.yaffle_date_field = (options[:yaffle_date_field] || :last_squawked_at).to_s + send :include, InstanceMethods + end + end + + module InstanceMethods + def squawk(string) + write_attribute(self.class.yaffle_text_field, string.to_squawk) + write_attribute(self.class.yaffle_date_field, Date.today) + end + end +end +------------------------------------------------------ + +Note the use of `write_attribute` to write to the field in model. diff --git a/railties/doc/guides/creating_plugins/appendix.txt b/railties/doc/guides/creating_plugins/appendix.txt new file mode 100644 index 0000000000..a78890ccd5 --- /dev/null +++ b/railties/doc/guides/creating_plugins/appendix.txt @@ -0,0 +1,46 @@ +== Appendix == + +=== References === + + * http://nubyonrails.com/articles/the-complete-guide-to-rails-plugins-part-i + * http://nubyonrails.com/articles/2006/05/09/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 + +=== Final plugin directory structure === + +The final plugin should have a directory structure that looks something like this: + +------------------------------------------------ + |-- MIT-LICENSE + |-- README + |-- Rakefile + |-- generators + | `-- yaffle + | |-- USAGE + | |-- templates + | | `-- definition.txt + | `-- yaffle_generator.rb + |-- init.rb + |-- install.rb + |-- lib + | |-- acts_as_yaffle.rb + | |-- commands.rb + | |-- core_ext.rb + | |-- routing.rb + | `-- view_helpers.rb + |-- tasks + | `-- yaffle_tasks.rake + |-- test + | |-- acts_as_yaffle_test.rb + | |-- core_ext_test.rb + | |-- database.yml + | |-- debug.log + | |-- routing_test.rb + | |-- schema.rb + | |-- test_helper.rb + | `-- view_helpers_test.rb + |-- uninstall.rb + `-- yaffle_plugin.sqlite3.db +------------------------------------------------ + diff --git a/railties/doc/guides/creating_plugins/basics.markdown b/railties/doc/guides/creating_plugins/basics.markdown new file mode 100644 index 0000000000..f59e8728d7 --- /dev/null +++ b/railties/doc/guides/creating_plugins/basics.markdown @@ -0,0 +1,861 @@ +Creating Plugin Basics +==================== + +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. + +In this tutorial you will learn how to create a plugin that includes: + +Core Extensions - extending String: + + # Anywhere + "hello".squawk # => "squawk! hello! squawk!" + +An `acts_as_yaffle` method for Active Record models that adds a "squawk" method: + + class Hickwall < ActiveRecord::Base + acts_as_yaffle :yaffle_text_field => :last_sang_at + end + + Hickwall.new.squawk("Hello World") + +A view helper that will print out squawking info: + + squawk_info_for(@hickwall) + +A generator that creates a migration to add squawk columns to a model: + + script/generate yaffle hickwall + +A custom generator command: + + class YaffleGenerator < Rails::Generator::NamedBase + def manifest + m.yaffle_definition + end + end + end + +A custom route method: + + ActionController::Routing::Routes.draw do |map| + map.yaffles + end + +In addition you'll learn how to: + +* test your plugins +* work with init.rb, how to store model, views, controllers, helpers and even other plugins in your plugins +* create documentation for your plugin. +* write custom rake tasks in your plugin + +Create the basic app +--------------------- + +In this tutorial we will create a basic rails application with 1 resource: bird. Start out by building the basic rails app: + +> The following instructions will work for sqlite3. For more detailed instructions on how to create a rails app for other databases see the API docs. + + rails plugin_demo + cd plugin_demo + script/generate scaffold bird name:string + rake db:migrate + script/server + +Then navigate to [http://localhost:3000/birds](http://localhost:3000/birds). Make sure you have a functioning rails app before continuing. + +Create the plugin +----------------------- + +The built-in Rails plugin generator stubs out a new plugin. 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: + + ./script/generate plugin BrowserFilters + ./script/generate plugin BrowserFilters --with-generator + +Later in the plugin we will create a generator, so go ahead and add the --with-generator option now: + + script/generate plugin yaffle --with-generator + +You should see the following output: + + 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 + +For this plugin you won't need the file vendor/plugins/yaffle/lib/yaffle.rb so you can delete that. + + rm vendor/plugins/yaffle/lib/yaffle.rb + +> Editor's note: many plugin authors prefer to keep this file, and add all of the require statements in it. That way, they only line in init.rb would be `require "yaffle"` +> If you are developing a plugin that has a lot of files in the lib directory, you may want to create a subdirectory like lib/yaffle and store your files in there. That way your init.rb file stays clean + +Setup the plugin for testing +------------------------ + +Testing plugins that use the entire Rails stack can be complex, and the generator doesn't offer any help. In this tutorial you will learn how to test your plugin against multiple different adapters using ActiveRecord. This tutorial will not cover how to use fixtures in plugin tests. + +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 that sets up the database before your tests + +For this plugin you'll need 2 tables/models, Hickwalls and Wickwalls, so add the following files: + + # File: vendor/plugins/yaffle/test/database.yml + + sqlite: + :adapter: sqlite + :dbfile: yaffle_plugin.sqlite.db + sqlite3: + :adapter: sqlite3 + :dbfile: yaffle_plugin.sqlite3.db + postgresql: + :adapter: postgresql + :username: postgres + :password: postgres + :database: yaffle_plugin_test + :min_messages: ERROR + mysql: + :adapter: mysql + :host: localhost + :username: rails + :password: + :database: yaffle_plugin_test + + # File: vendor/plugins/yaffle/test/test_helper.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 + end + + # File: 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')) + + 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__) + '/../init.rb' + + class Hickwall < ActiveRecord::Base + acts_as_yaffle + end + + class Wickwall < ActiveRecord::Base + acts_as_yaffle :yaffle_text_field => :last_tweet, :yaffle_date_field => :last_tweeted_at + end + +Add a `to_squawk` method to String +----------------------- + +To update a core class you will have to: + +* Write tests for the desired functionality +* Create a file for the code you wish to use +* Require that file from your init.rb + +Most plugins store their code classes in the plugin's lib directory. When you add a file to the lib directory, you must also require that file from init.rb. The file you are going to add for this tutorial is `lib/core_ext.rb` + +First, you need to write the tests. Testing plugins is very similar to testing rails apps. The generated test file should look something like this: + + # File: vendor/plugins/yaffle/test/core_ext_test.rb + + require 'test/unit' + + class CoreExtTest < Test::Unit::TestCase + # Replace this with your real tests. + def test_this_plugin + flunk + end + end + +Start off by removing the default test, and adding a require statement for your test helper. + + # File: vendor/plugins/yaffle/test/core_ext_test.rb + + require 'test/unit' + require File.dirname(__FILE__) + '/test_helper.rb' + + class CoreExtTest < Test::Unit::TestCase + end + +Navigate to your plugin directory and run `rake test` + + cd vendor/plugins/yaffle + rake test + +Your test should fail with `no such file to load -- ./test/../lib/core_ext.rb (LoadError)` because we haven't created any file yet. Create the file `lib/core_ext.rb` and re-run the tests. You should see a different error message: + + 1.) Failure ... + No tests were specified + +Great - now you are ready to start development. The first thing we'll do is to add a method to String called `to_squawk` which will prefix the string with the word "squawk! ". The test will look something like this: + + # File: vendor/plugins/yaffle/init.rb + + class CoreExtTest < Test::Unit::TestCase + def test_string_should_respond_to_squawk + assert_equal true, "".respond_to?(:to_squawk) + end + def test_string_prepend_empty_strings_with_the_word_squawk + assert_equal "squawk!", "".to_squawk + end + def test_string_prepend_non_empty_strings_with_the_word_squawk + assert_equal "squawk! Hello World", "Hello World".to_squawk + end + end + + # File: vendor/plugins/yaffle/init.rb + + require "core_ext" + + # File: vendor/plugins/yaffle/lib/core_ext.rb + + String.class_eval do + def to_squawk + "squawk! #{self}".strip + end + end + +When monkey-patching existing classes it's often better to use `class_eval` instead of opening the class directly. + +To test that your method does what it says it does, run the unit tests. To test this manually, fire up a console and start squawking: + + script/console + >> "Hello World".to_squawk + => "squawk! Hello World" + +If that worked, congratulations! You just created your first test-driven plugin that extends a core ruby class. + +Add an `acts_as_yaffle` method to ActiveRecord +----------------------- + +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. + +To keep things clean, create a new test file called `acts_as_yaffle_test.rb` in your plugin's test directory and require your test helper. + + # File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb + + require File.dirname(__FILE__) + '/test_helper.rb' + + class Hickwall < ActiveRecord::Base + acts_as_yaffle + end + + class ActsAsYaffleTest < Test::Unit::TestCase + end + + # File: vendor/plugins/lib/acts_as_yaffle.rb + + module Yaffle + end + +One of the most common plugin patterns for `acts_as_yaffle` plugins is to structure your file like so: + + 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 + + module InstanceMethods + # any method placed here will apply to instaces, like @hickwall + end + end + +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`). + +Let's add class method named `acts_as_yaffle` - testing it out first. You already defined the ActiveRecord models in your test helper, so if you run tests now they will fail. + +Back in your `acts_as_yaffle` file, update ClassMethods like so: + + module ClassMethods + def acts_as_yaffle(options = {}) + send :include, InstanceMethods + end + end + +Now that test should pass. Since your plugin is going to work with field names, you need to allow people to define the field names, in case there is a naming conflict. You can write a few simple tests for this: + + # File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb + + require File.dirname(__FILE__) + '/test_helper.rb' + + class ActsAsYaffleTest < Test::Unit::TestCase + def test_a_hickwalls_yaffle_text_field_should_be_last_squawk + assert_equal "last_squawk", Hickwall.yaffle_text_field + end + def test_a_hickwalls_yaffle_date_field_should_be_last_squawked_at + assert_equal "last_squawked_at", Hickwall.yaffle_date_field + end + def test_a_wickwalls_yaffle_text_field_should_be_last_tweet + assert_equal "last_tweet", Wickwall.yaffle_text_field + end + def test_a_wickwalls_yaffle_date_field_should_be_last_tweeted_at + assert_equal "last_tweeted_at", Wickwall.yaffle_date_field + end + end + +To make these tests pass, you could modify your `acts_as_yaffle` file like so: + + # File: vendor/plugins/yaffle/lib/acts_as_yaffle.rb + + module Yaffle + def self.included(base) + base.send :extend, ClassMethods + end + + module ClassMethods + def acts_as_yaffle(options = {}) + cattr_accessor :yaffle_text_field, :yaffle_date_field + self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s + self.yaffle_date_field = (options[:yaffle_date_field] || :last_squawked_at).to_s + send :include, InstanceMethods + end + end + + module InstanceMethods + end + end + +Now you can add tests for the instance methods, and the instance method itself: + + # File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb + + require File.dirname(__FILE__) + '/test_helper.rb' + + class ActsAsYaffleTest < Test::Unit::TestCase + + def test_a_hickwalls_yaffle_text_field_should_be_last_squawk + assert_equal "last_squawk", Hickwall.yaffle_text_field + end + def test_a_hickwalls_yaffle_date_field_should_be_last_squawked_at + assert_equal "last_squawked_at", Hickwall.yaffle_date_field + end + + def test_a_wickwalls_yaffle_text_field_should_be_last_squawk + assert_equal "last_tweet", Wickwall.yaffle_text_field + end + def test_a_wickwalls_yaffle_date_field_should_be_last_squawked_at + assert_equal "last_tweeted_at", Wickwall.yaffle_date_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_hickwalls_squawk_should_populate_last_squawked_at + hickwall = Hickwall.new + hickwall.squawk("Hello World") + assert_equal Date.today, hickwall.last_squawked_at + end + + def test_wickwalls_squawk_should_populate_last_tweet + wickwall = Wickwall.new + wickwall.squawk("Hello World") + assert_equal "squawk! Hello World", wickwall.last_tweet + end + def test_wickwalls_squawk_should_populate_last_tweeted_at + wickwall = Wickwall.new + wickwall.squawk("Hello World") + assert_equal Date.today, wickwall.last_tweeted_at + end + end + + # File: vendor/plugins/yaffle/lib/acts_as_yaffle.rb + + module Yaffle + def self.included(base) + base.send :extend, ClassMethods + end + + module ClassMethods + def acts_as_yaffle(options = {}) + cattr_accessor :yaffle_text_field, :yaffle_date_field + self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s + self.yaffle_date_field = (options[:yaffle_date_field] || :last_squawked_at).to_s + send :include, InstanceMethods + end + end + + module InstanceMethods + def squawk(string) + write_attribute(self.class.yaffle_text_field, string.to_squawk) + write_attribute(self.class.yaffle_date_field, Date.today) + end + end + end + +Note the use of write_attribute to write to the field in model. + +Create a view helper +----------------------- + +Creating a view helper is a 3-step process: + +* Add an appropriately named file to the lib directory +* Require the file and hooks in init.rb +* Write the tests + +First, create the test to define the functionality you want: + + # File: vendor/plugins/yaffle/test/view_helpers_test.rb + + require File.dirname(__FILE__) + '/test_helper.rb' + include YaffleViewHelper + + class ViewHelpersTest < Test::Unit::TestCase + def test_squawk_info_for_should_return_the_text_and_date + time = Time.now + hickwall = Hickwall.new + hickwall.last_squawk = "Hello World" + hickwall.last_squawked_at = time + assert_equal "Hello World, #{time.to_s}", squawk_info_for(hickwall) + end + end + +Then add the following statements to init.rb: + + # File: vendor/plugins/yaffle/init.rb + + require "view_helpers" + ActionView::Base.send :include, YaffleViewHelper + +Then add the view helpers file and + + # File: vendor/plugins/yaffle/lib/view_helpers.rb + + module YaffleViewHelper + def squawk_info_for(yaffle) + returning "" do |result| + result << yaffle.read_attribute(yaffle.class.yaffle_text_field) + result << ", " + result << yaffle.read_attribute(yaffle.class.yaffle_date_field).to_s + end + end + end + +You can also test this in script/console by using the "helper" method: + + script/console + >> helper.squawk_info_for(@some_yaffle_instance) + +Create a migration generator +----------------------- + +When you created the plugin above, you specified the --with-generator option, so you already have the generator stubs in your plugin. + +We'll be relying on the built-in rails generate template for this tutorial. Going into the details of generators is beyond the scope of this tutorial. + +Type: + + script/generate + +You should see the line: + + Plugins (vendor/plugins): yaffle + +When you run `script/generate yaffle` you should see the contents of your USAGE file. For this plugin, the USAGE file looks like this: + + Description: + Creates a migration that adds yaffle squawk fields to the given model + + Example: + ./script/generate yaffle hickwall + + This will create: + db/migrate/TIMESTAMP_add_yaffle_fields_to_hickwall + +Now you can add code to your generator: + + # File: vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb + + class YaffleGenerator < 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 + end + + def yaffle_local_assigns + returning(assigns = {}) do + 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")] + assigns[:attributes] << Rails::Generator::GeneratedAttribute.new("last_squawked_at", "datetime") + end + end + end + +Note that you need to be aware of whether or not table names are pluralized. + +This does a few things: + +* Reuses the built in rails migration_template method +* Reuses the built-in rails migration template + +When you run the generator like + + script/generate yaffle bird + +You will see a new file: + + # File: db/migrate/20080529225649_add_yaffle_fields_to_birds.rb + + class AddYaffleFieldsToBirds < ActiveRecord::Migration + def self.up + add_column :birds, :last_squawk, :string + add_column :birds, :last_squawked_at, :datetime + end + + def self.down + remove_column :birds, :last_squawked_at + remove_column :birds, :last_squawk + end + end + +Add a custom generator command +------------------------ + +You may have noticed above that you can used one of the built-in rails migration commands `m.migration_template`. You can create your own commands for these, using the following steps: + +1. Add the require and hook statements to init.rb +2. Create the commands - creating 3 sets, Create, Destroy, List +3. Add the method to your generator + +Working with the internals of generators is beyond the scope of this tutorial, but here is a basic example: + + # File: vendor/plugins/yaffle/init.rb + + require "commands" + 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 + + # File: vendor/plugins/yaffle/lib/commands.rb + + 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 + end + end + end + + # File: vendor/plugins/yaffle/generators/yaffle/templates/definition.txt + + Yaffle is a bird + + # File: vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb + + class YaffleGenerator < Rails::Generator::NamedBase + def manifest + m.yaffle_definition + end + end + end + +This example just uses the built-in "file" method, but you could do anything that ruby allows. + +Add a Custom Route +------------------------ + +Testing routes in plugins can be complex, especially if the controllers are also in the plugin itself. Jamis Buck showed a great example of this in [http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2](http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2) + + # File: vendor/plugins/yaffle/test/routing_test.rb + + 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 + + private + + # yes, I know about assert_recognizes, but it has proven problematic to + # use in these tests, since it uses RouteSet#recognize (which actually + # tries to instantiate the controller) and because it uses an awkward + # parameter order. + def assert_recognition(method, path, options) + result = ActionController::Routing::Routes.recognize_path(path, :method => method) + assert_equal options, result + end + end + + # File: vendor/plugins/yaffle/init.rb + + require "routing" + ActionController::Routing::RouteSet::Mapper.send :include, Yaffle::Routing::MapperExtensions + + # File: vendor/plugins/yaffle/lib/routing.rb + + module Yaffle #:nodoc: + module Routing #:nodoc: + module MapperExtensions + def yaffles + @set.add_route("/yaffles", {:controller => "yaffles_controller", :action => "index"}) + end + end + end + end + + # File: config/routes.rb + + ActionController::Routing::Routes.draw do |map| + ... + map.yaffles + end + +You can also see if your routes work by running `rake routes` from your app directory. + +Generate RDoc Documentation +----------------------- + +Once your plugin is stable, the tests pass on all database 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: + +* 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. + +Before you generate your documentation, be sure to go through and add nodoc comments to those modules and methods that are not important to your users. + +Once your comments are good to go, navigate to your plugin directory and run + + rake rdoc + +Work with init.rb +------------------------ + +The plugin initializer script init.rb is invoked via `eval` (not require) so it has slightly different behavior. + +If you reopen any classes in init.rb itself your changes will potentially be made to the wrong module. There are 2 ways around this: + +The first way is to explicitly define the top-level module space for all modules and classes, like ::Hash + + # File: vendor/plugins/yaffle/init.rb + + class ::Hash + def is_a_special_hash? + true + end + end + +OR you can use `module_eval` or `class_eval` + + # File: vendor/plugins/yaffle/init.rb + + Hash.class_eval do + def is_a_special_hash? + true + end + end + +Store models, views, helpers, and controllers in your plugins +------------------------ + +You can easily store models, views, helpers and controllers in plugins. Just create a folder for each in the lib folder, add them to the load path and remove them from the load once path: + + # File: vendor/plugins/yaffle/init.rb + + %w{ models controllers helpers }.each do |dir| + path = File.join(directory, 'lib', dir) + $LOAD_PATH << path + Dependencies.load_paths << path + Dependencies.load_once_paths.delete(path) + end + +Adding directories to the load path makes them appear just like files in the 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. + +Adding directories to the load once paths allow those changes to picked up as soon as you save the file - without having to restart the web server. + +Write custom rake tasks in your plugin +------------------------- + +When you created the plugin with the built-in rails generator, it generated a rake file for you in `vendor/plugins/yaffle/tasks/yaffle.rake`. Any rake task you add here will be available to the app. + +Many plugin authors put all of their rake tasks into a common namespace that is the same as the plugin, like so: + + # File: vendor/plugins/yaffle/tasks/yaffle.rake + + namespace :yaffle do + desc "Prints out the word 'Yaffle'" + task :squawk => :environment do + puts "squawk!" + end + end + +When you run `rake -T` from your plugin you will see + + yaffle:squawk "Prints out..." + +You can add as many files as you want in the tasks directory, and if they end in .rake Rails will pick them up. + +Store plugins in alternate locations +------------------------- + +You can store plugins wherever you want - you just have to add those plugins to the plugins path in environment.rb + +Since the plugin is only loaded after the plugin paths are defined, you can't redefine this in your plugins - but it may be good to now. + +You can even store plugins inside of other plugins for complete plugin madness! + + config.plugin_paths << File.join(RAILS_ROOT,"vendor","plugins","yaffle","lib","plugins") + +Create your own Plugin Loaders and Plugin Locators +------------------------ + +If the built-in plugin behavior is inadequate, you can change almost every aspect of the location and loading process. You can write your own plugin locators and plugin loaders, but that's beyond the scope of this tutorial. + +Use Custom Plugin Generators +------------------------ + +If you are an RSpec fan, you can install the `rspec_plugin_generator`, which will generate the spec folder and database for you. + +[http://github.com/pat-maddox/rspec-plugin-generator/tree/master](http://github.com/pat-maddox/rspec-plugin-generator/tree/master) + +References +------------------------ + +* [http://nubyonrails.com/articles/the-complete-guide-to-rails-plugins-part-i](http://nubyonrails.com/articles/the-complete-guide-to-rails-plugins-part-i) +* [http://nubyonrails.com/articles/2006/05/09/the-complete-guide-to-rails-plugins-part-ii](http://nubyonrails.com/articles/2006/05/09/the-complete-guide-to-rails-plugins-part-ii) +* [http://github.com/technoweenie/attachment_fu/tree/master](http://github.com/technoweenie/attachment_fu/tree/master) +* [http://daddy.platte.name/2007/05/rails-plugins-keep-initrb-thin.html](http://daddy.platte.name/2007/05/rails-plugins-keep-initrb-thin.html) + +Appendices +------------------------ + +The final plugin should have a directory structure that looks something like this: + + |-- MIT-LICENSE + |-- README + |-- Rakefile + |-- generators + | `-- yaffle + | |-- USAGE + | |-- templates + | | `-- definition.txt + | `-- yaffle_generator.rb + |-- init.rb + |-- install.rb + |-- lib + | |-- acts_as_yaffle.rb + | |-- commands.rb + | |-- core_ext.rb + | |-- routing.rb + | `-- view_helpers.rb + |-- tasks + | `-- yaffle_tasks.rake + |-- test + | |-- acts_as_yaffle_test.rb + | |-- core_ext_test.rb + | |-- database.yml + | |-- debug.log + | |-- routing_test.rb + | |-- schema.rb + | |-- test_helper.rb + | `-- view_helpers_test.rb + |-- uninstall.rb + `-- yaffle_plugin.sqlite3.db diff --git a/railties/doc/guides/creating_plugins/creating_plugins.txt b/railties/doc/guides/creating_plugins/creating_plugins.txt new file mode 100644 index 0000000000..f2ed6ed8bb --- /dev/null +++ b/railties/doc/guides/creating_plugins/creating_plugins.txt @@ -0,0 +1,84 @@ +The Basics of Creating Rails Plugins +==================================== + +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. + +In this tutorial you will learn how to create a plugin that includes: + + * Core Extensions - extending String with a `to_squawk` method: ++ +[source, ruby] +------------------------------------------- +# Anywhere +"hello!".to_squawk # => "squawk! hello!" +------------------------------------------- + +* An `acts_as_yaffle` method for ActiveRecord models that adds a `squawk` method: ++ +[source, ruby] +------------------------------------------- +class Hickwall < ActiveRecord::Base + acts_as_yaffle :yaffle_text_field => :last_sang_at +end + +Hickwall.new.squawk("Hello World") +------------------------------------------- + +* A view helper that will print out squawking info: ++ +[source, ruby] +------------------------------------------- +squawk_info_for(@hickwall) +------------------------------------------- + +* A generator that creates a migration to add squawk columns to a model: ++ +------------------------------------------- +script/generate yaffle hickwall +------------------------------------------- + +* A custom generator command: ++ +[source, ruby] +------------------------------------------- +class YaffleGenerator < Rails::Generator::NamedBase + def manifest + m.yaffle_definition + end +end +------------------------------------------- + +* A custom route method: ++ +[source, ruby] +------------------------------------------- +ActionController::Routing::Routes.draw do |map| + map.yaffles +end +------------------------------------------- + +In addition you'll learn how to: + + * test your plugins. + * work with 'init.rb', how to store model, views, controllers, helpers and even other plugins in your plugins. + * create documentation for your plugin. + * write custom Rake tasks in your plugin. + + +include::preparation.txt[] + +include::string_to_squawk.txt[] + +include::acts_as_yaffle.txt[] + +include::view_helper.txt[] + +include::migration_generator.txt[] + +include::custom_generator.txt[] + +include::custom_route.txt[] + +include::odds_and_ends.txt[] + +include::appendix.txt[] diff --git a/railties/doc/guides/creating_plugins/custom_generator.txt b/railties/doc/guides/creating_plugins/custom_generator.txt new file mode 100644 index 0000000000..6d9613ea01 --- /dev/null +++ b/railties/doc/guides/creating_plugins/custom_generator.txt @@ -0,0 +1,69 @@ +== Add a custom generator command == + +You may have noticed above that you can used one of the built-in rails migration commands `m.migration_template`. You can create your own commands for these, using the following steps: + + 1. Add the require and hook statements to init.rb. + 2. Create the commands - creating 3 sets, Create, Destroy, List. + 3. Add the method to your generator. + +Working with the internals of generators is beyond the scope of this tutorial, but here is a basic example: + +[source, ruby] +----------------------------------------------------------- +# File: vendor/plugins/yaffle/init.rb +require "commands" +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 +----------------------------------------------------------- + +[source, ruby] +----------------------------------------------------------- +# File: vendor/plugins/yaffle/lib/commands.rb + +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 + end + end +end +----------------------------------------------------------- + +----------------------------------------------------------- +# File: vendor/plugins/yaffle/generators/yaffle/templates/definition.txt + +Yaffle is a bird +----------------------------------------------------------- + +[source, ruby] +----------------------------------------------------------- +# File: vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb + +class YaffleGenerator < Rails::Generator::NamedBase + def manifest + m.yaffle_definition + end +end +----------------------------------------------------------- + +This example just uses the built-in "file" method, but you could do anything that Ruby allows. diff --git a/railties/doc/guides/creating_plugins/custom_route.txt b/railties/doc/guides/creating_plugins/custom_route.txt new file mode 100644 index 0000000000..7e399247ee --- /dev/null +++ b/railties/doc/guides/creating_plugins/custom_route.txt @@ -0,0 +1,69 @@ +== Add a Custom Route == + +Testing routes in plugins can be complex, especially if the controllers are also in the plugin itself. Jamis Buck showed a great example of this in http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2. + +[source, ruby] +-------------------------------------------------------- +# File: vendor/plugins/yaffle/test/routing_test.rb + +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 + + private + + # yes, I know about assert_recognizes, but it has proven problematic to + # use in these tests, since it uses RouteSet#recognize (which actually + # tries to instantiate the controller) and because it uses an awkward + # parameter order. + def assert_recognition(method, path, options) + result = ActionController::Routing::Routes.recognize_path(path, :method => method) + assert_equal options, result + end +end +-------------------------------------------------------- + +[source, ruby] +-------------------------------------------------------- +# File: vendor/plugins/yaffle/init.rb + +require "routing" +ActionController::Routing::RouteSet::Mapper.send :include, Yaffle::Routing::MapperExtensions +-------------------------------------------------------- + +[source, ruby] +-------------------------------------------------------- +# File: vendor/plugins/yaffle/lib/routing.rb + +module Yaffle #:nodoc: + module Routing #:nodoc: + module MapperExtensions + def yaffles + @set.add_route("/yaffles", {:controller => "yaffles_controller", :action => "index"}) + end + end + end +end +-------------------------------------------------------- + +[source, ruby] +-------------------------------------------------------- +# File: config/routes.rb + +ActionController::Routing::Routes.draw do |map| + ... + map.yaffles +end +-------------------------------------------------------- + +You can also see if your routes work by running `rake routes` from your app directory. diff --git a/railties/doc/guides/creating_plugins/migration_generator.txt b/railties/doc/guides/creating_plugins/migration_generator.txt new file mode 100644 index 0000000000..598a0c8437 --- /dev/null +++ b/railties/doc/guides/creating_plugins/migration_generator.txt @@ -0,0 +1,89 @@ +== Create a migration generator == + +When you created the plugin above, you specified the --with-generator option, so you already have the generator stubs in your plugin. + +We'll be relying on the built-in rails generate template for this tutorial. Going into the details of generators is beyond the scope of this tutorial. + +Type: + + script/generate + +You should see the line: + + Plugins (vendor/plugins): yaffle + +When you run `script/generate yaffle` you should see the contents of your USAGE file. For this plugin, the USAGE file looks like this: + +------------------------------------------------------------------ +Description: + Creates a migration that adds yaffle squawk fields to the given model + +Example: + ./script/generate yaffle hickwall + + This will create: + db/migrate/TIMESTAMP_add_yaffle_fields_to_hickwall +------------------------------------------------------------------ + +Now you can add code to your generator: + +[source, ruby] +------------------------------------------------------------------ +# File: vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb + +class YaffleGenerator < 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 + end + + def yaffle_local_assigns + returning(assigns = {}) do + 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")] + assigns[:attributes] << Rails::Generator::GeneratedAttribute.new("last_squawked_at", "datetime") + end + end +end +------------------------------------------------------------------ + +Note that you need to be aware of whether or not table names are pluralized. + +This does a few things: + + * Reuses the built in rails `migration_template` method. + * Reuses the built-in rails migration template. + +When you run the generator like + + script/generate yaffle bird + +You will see a new file: + +[source, ruby] +------------------------------------------------------------------ +# File: db/migrate/20080529225649_add_yaffle_fields_to_birds.rb + +class AddYaffleFieldsToBirds < ActiveRecord::Migration + def self.up + add_column :birds, :last_squawk, :string + add_column :birds, :last_squawked_at, :datetime + end + + def self.down + remove_column :birds, :last_squawked_at + remove_column :birds, :last_squawk + end +end +------------------------------------------------------------------ diff --git a/railties/doc/guides/creating_plugins/odds_and_ends.txt b/railties/doc/guides/creating_plugins/odds_and_ends.txt new file mode 100644 index 0000000000..eb127f73ca --- /dev/null +++ b/railties/doc/guides/creating_plugins/odds_and_ends.txt @@ -0,0 +1,122 @@ +== Odds and ends == + +=== Work with init.rb === + +The plugin initializer script 'init.rb' is invoked via `eval` (not `require`) so it has slightly different behavior. + +If you reopen any classes in init.rb itself your changes will potentially be made to the wrong module. There are 2 ways around this: + +The first way is to explicitly define the top-level module space for all modules and classes, like `::Hash`: + +[source, ruby] +--------------------------------------------------- +# File: vendor/plugins/yaffle/init.rb + +class ::Hash + def is_a_special_hash? + true + end +end +--------------------------------------------------- + +OR you can use `module_eval` or `class_eval`: + +--------------------------------------------------- +# File: vendor/plugins/yaffle/init.rb + +Hash.class_eval do + def is_a_special_hash? + true + end +end +--------------------------------------------------- + +=== Generate RDoc Documentation === + +Once your plugin is stable, the tests pass on all database 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: + + * 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. + +Before you generate your documentation, be sure to go through and add nodoc comments to those modules and methods that are not important to your users. + +Once your comments are good to go, navigate to your plugin directory and run: + + rake rdoc + + +=== Store models, views, helpers, and controllers in your plugins === + +You can easily store models, views, helpers and controllers in plugins. Just create a folder for each in the lib folder, add them to the load path and remove them from the load once path: + +[source, ruby] +--------------------------------------------------------- +# File: vendor/plugins/yaffle/init.rb + +%w{ models controllers helpers }.each do |dir| + path = File.join(directory, 'lib', dir) + $LOAD_PATH << path + Dependencies.load_paths << path + Dependencies.load_once_paths.delete(path) +end +--------------------------------------------------------- + +Adding directories to the load path makes them appear just like files in the 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. + +Adding directories to the load once paths allow those changes to picked up as soon as you save the file - without having to restart the web server. + + +=== Write custom Rake tasks in your plugin === + +When you created the plugin with the built-in rails generator, it generated a rake file for you in 'vendor/plugins/yaffle/tasks/yaffle.rake'. Any rake task you add here will be available to the app. + +Many plugin authors put all of their rake tasks into a common namespace that is the same as the plugin, like so: + +[source, ruby] +--------------------------------------------------------- +# File: vendor/plugins/yaffle/tasks/yaffle.rake + +namespace :yaffle do + desc "Prints out the word 'Yaffle'" + task :squawk => :environment do + puts "squawk!" + end +end +--------------------------------------------------------- + +When you run `rake -T` from your plugin you will see: + +--------------------------------------------------------- +yaffle:squawk # Prints out the word 'Yaffle' +--------------------------------------------------------- + +You can add as many files as you want in the tasks directory, and if they end in .rake Rails will pick them up. + +=== Store plugins in alternate locations === + +You can store plugins wherever you want - you just have to add those plugins to the plugins path in 'environment.rb'. + +Since the plugin is only loaded after the plugin paths are defined, you can't redefine this in your plugins - but it may be good to now. + +You can even store plugins inside of other plugins for complete plugin madness! + +[source, ruby] +--------------------------------------------------------- +config.plugin_paths << File.join(RAILS_ROOT,"vendor","plugins","yaffle","lib","plugins") +--------------------------------------------------------- + +=== Create your own Plugin Loaders and Plugin Locators === + +If the built-in plugin behavior is inadequate, you can change almost every aspect of the location and loading process. You can write your own plugin locators and plugin loaders, but that's beyond the scope of this tutorial. + + +=== Use Custom Plugin Generators === + +If you are an RSpec fan, you can install the `rspec_plugin_generator` gem, which will generate the spec folder and database for you. See http://github.com/pat-maddox/rspec-plugin-generator/tree/master. + diff --git a/railties/doc/guides/creating_plugins/preparation.txt b/railties/doc/guides/creating_plugins/preparation.txt new file mode 100644 index 0000000000..77e3a3561f --- /dev/null +++ b/railties/doc/guides/creating_plugins/preparation.txt @@ -0,0 +1,169 @@ +== Preparation == + +=== Create the basic app === + +In this tutorial we will create a basic rails application with 1 resource: bird. Start out by building the basic rails app: + +------------------------------------------------ +rails plugin_demo +cd plugin_demo +script/generate scaffold bird name:string +rake db:migrate +script/server +------------------------------------------------ + +Then navigate to http://localhost:3000/birds. Make sure you have a functioning rails app before continuing. + +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. + + +=== Create the plugin === + +The built-in Rails plugin generator stubs out a new plugin. 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: +---------------------------------------------- +./script/generate plugin BrowserFilters +./script/generate plugin BrowserFilters --with-generator +---------------------------------------------- + +Later in the plugin we will create a generator, so go ahead and add the `\--with-generator` option now: + +---------------------------------------------- +script/generate plugin yaffle --with-generator +---------------------------------------------- + +You should see the following output: + +---------------------------------------------- +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 +---------------------------------------------- + +For this plugin you won't need the file 'vendor/plugins/yaffle/lib/yaffle.rb' so you can delete that. + +---------------------------------------------- +rm vendor/plugins/yaffle/lib/yaffle.rb +---------------------------------------------- + +.Editor's note: +NOTE: Many plugin authors prefer to keep this file, and add all of the require statements in it. That way, they only line in init.rb would be `require "yaffle"`. If you are developing a plugin that has a lot of files in the lib directory, you may want to create a subdirectory like lib/yaffle and store your files in there. That way your init.rb file stays clean + + +=== Setup the plugin for testing === + +Testing plugins that use the entire Rails stack can be complex, and the generator doesn't offer any help. In this tutorial you will learn how to test your plugin against multiple different adapters using ActiveRecord. This tutorial will not cover how to use fixtures in plugin tests. + +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 that sets up the database before your tests. + +For this plugin you'll need 2 tables/models, Hickwalls and Wickwalls, so add the following files: + +*vendor/plugins/yaffle/test/database.yml:* + +---------------------------------------------- +sqlite: + :adapter: sqlite + :dbfile: yaffle_plugin.sqlite.db + +sqlite3: + :adapter: sqlite3 + :dbfile: yaffle_plugin.sqlite3.db + +postgresql: + :adapter: postgresql + :username: postgres + :password: postgres + :database: yaffle_plugin_test + :min_messages: ERROR + +mysql: + :adapter: mysql + :host: localhost + :username: rails + :password: + :database: yaffle_plugin_test +---------------------------------------------- + +*vendor/plugins/yaffle/test/test_helper.rb:* + +[source, ruby] +---------------------------------------------- +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 +end + +# File: 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')) + +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__) + '/../init.rb' + +class Hickwall < ActiveRecord::Base + acts_as_yaffle +end + +class Wickwall < ActiveRecord::Base + acts_as_yaffle :yaffle_text_field => :last_tweet, :yaffle_date_field => :last_tweeted_at +end +---------------------------------------------- diff --git a/railties/doc/guides/creating_plugins/string_to_squawk.txt b/railties/doc/guides/creating_plugins/string_to_squawk.txt new file mode 100644 index 0000000000..50516cef69 --- /dev/null +++ b/railties/doc/guides/creating_plugins/string_to_squawk.txt @@ -0,0 +1,103 @@ +== Add a `to_squawk` method to String == + +To update a core class you will have to: + + * Write tests for the desired functionality. + * Create a file for the code you wish to use. + * Require that file from your 'init.rb'. + +Most plugins store their code classes in the plugin's lib directory. When you add a file to the lib directory, you must also require that file from 'init.rb'. The file you are going to add for this tutorial is 'lib/core_ext.rb'. + +First, you need to write the tests. Testing plugins is very similar to testing rails apps. The generated test file should look something like this: + +[source, ruby] +-------------------------------------------------------- +# File: vendor/plugins/yaffle/test/core_ext_test.rb + +require 'test/unit' + +class CoreExtTest < Test::Unit::TestCase + # Replace this with your real tests. + def test_this_plugin + flunk + end +end +-------------------------------------------------------- + +Start off by removing the default test, and adding a require statement for your test helper. + +[source, ruby] +-------------------------------------------------------- +# File: vendor/plugins/yaffle/test/core_ext_test.rb + +require 'test/unit' +require File.dirname(__FILE__) + '/test_helper.rb' + +class CoreExtTest < Test::Unit::TestCase +end +-------------------------------------------------------- + +Navigate to your plugin directory and run `rake test`: + +-------------------------------------------------------- +cd vendor/plugins/yaffle +rake test +-------------------------------------------------------- + +Your test should fail with `no such file to load -- ./test/../lib/core_ext.rb (LoadError)` because we haven't created any file yet. Create the file 'lib/core_ext.rb' and re-run the tests. You should see a different error message: + +-------------------------------------------------------- +1.) Failure ... +No tests were specified +-------------------------------------------------------- + +Great - now you are ready to start development. The first thing we'll do is to add a method to String called `to_squawk` which will prefix the string with the word ``squawk!''. The test will look something like this: + +[source, ruby] +-------------------------------------------------------- +# File: vendor/plugins/yaffle/init.rb + +class CoreExtTest < Test::Unit::TestCase + def test_string_should_respond_to_squawk + assert_equal true, "".respond_to?(:to_squawk) + end + + def test_string_prepend_empty_strings_with_the_word_squawk + assert_equal "squawk!", "".to_squawk + end + + def test_string_prepend_non_empty_strings_with_the_word_squawk + assert_equal "squawk! Hello World", "Hello World".to_squawk + end +end +-------------------------------------------------------- + +[source, ruby] +-------------------------------------------------------- +# File: vendor/plugins/yaffle/init.rb + +require "core_ext" +-------------------------------------------------------- + +[source, ruby] +-------------------------------------------------------- +# File: vendor/plugins/yaffle/lib/core_ext.rb + +String.class_eval do + def to_squawk + "squawk! #{self}".strip + end +end +-------------------------------------------------------- + +When monkey-patching existing classes it's often better to use `class_eval` instead of opening the class directly. + +To test that your method does what it says it does, run the unit tests. To test this manually, fire up a console and start squawking: + +-------------------------------------------------------- +$ ./script/console +>> "Hello World".to_squawk +=> "squawk! Hello World" +-------------------------------------------------------- + +If that worked, congratulations! You just created your first test-driven plugin that extends a core ruby class. diff --git a/railties/doc/guides/creating_plugins/view_helper.txt b/railties/doc/guides/creating_plugins/view_helper.txt new file mode 100644 index 0000000000..b03a190e1a --- /dev/null +++ b/railties/doc/guides/creating_plugins/view_helper.txt @@ -0,0 +1,61 @@ +== Create a `squawk_info_for` view helper == + +Creating a view helper is a 3-step process: + + * Add an appropriately named file to the 'lib' directory. + * Require the file and hooks in 'init.rb'. + * Write the tests. + +First, create the test to define the functionality you want: + +[source, ruby] +--------------------------------------------------------------- +# File: vendor/plugins/yaffle/test/view_helpers_test.rb + +require File.dirname(__FILE__) + '/test_helper.rb' +include YaffleViewHelper + +class ViewHelpersTest < Test::Unit::TestCase + def test_squawk_info_for_should_return_the_text_and_date + time = Time.now + hickwall = Hickwall.new + hickwall.last_squawk = "Hello World" + hickwall.last_squawked_at = time + assert_equal "Hello World, #{time.to_s}", squawk_info_for(hickwall) + end +end +--------------------------------------------------------------- + +Then add the following statements to init.rb: + +[source, ruby] +--------------------------------------------------------------- +# File: vendor/plugins/yaffle/init.rb + +require "view_helpers" +ActionView::Base.send :include, YaffleViewHelper +--------------------------------------------------------------- + +Then add the view helpers file and + +[source, ruby] +--------------------------------------------------------------- +# File: vendor/plugins/yaffle/lib/view_helpers.rb + +module YaffleViewHelper + def squawk_info_for(yaffle) + returning "" do |result| + result << yaffle.read_attribute(yaffle.class.yaffle_text_field) + result << ", " + result << yaffle.read_attribute(yaffle.class.yaffle_date_field).to_s + end + end +end +--------------------------------------------------------------- + +You can also test this in script/console by using the `helper` method: + +--------------------------------------------------------------- +$ ./script/console +>> helper.squawk_info_for(@some_yaffle_instance) +--------------------------------------------------------------- diff --git a/railties/doc/guides/icons/README b/railties/doc/guides/icons/README new file mode 100644 index 0000000000..f12b2a730c --- /dev/null +++ b/railties/doc/guides/icons/README @@ -0,0 +1,5 @@ +Replaced the plain DocBook XSL admonition icons with Jimmac's DocBook +icons (http://jimmac.musichall.cz/ikony.php3). I dropped transparency +from the Jimmac icons to get round MS IE and FOP PNG incompatibilies. + +Stuart Rackham diff --git a/railties/doc/guides/icons/callouts/1.png b/railties/doc/guides/icons/callouts/1.png Binary files differnew file mode 100644 index 0000000000..7d473430b7 --- /dev/null +++ b/railties/doc/guides/icons/callouts/1.png diff --git a/railties/doc/guides/icons/callouts/10.png b/railties/doc/guides/icons/callouts/10.png Binary files differnew file mode 100644 index 0000000000..997bbc8246 --- /dev/null +++ b/railties/doc/guides/icons/callouts/10.png diff --git a/railties/doc/guides/icons/callouts/11.png b/railties/doc/guides/icons/callouts/11.png Binary files differnew file mode 100644 index 0000000000..ce47dac3f5 --- /dev/null +++ b/railties/doc/guides/icons/callouts/11.png diff --git a/railties/doc/guides/icons/callouts/12.png b/railties/doc/guides/icons/callouts/12.png Binary files differnew file mode 100644 index 0000000000..31daf4e2f2 --- /dev/null +++ b/railties/doc/guides/icons/callouts/12.png diff --git a/railties/doc/guides/icons/callouts/13.png b/railties/doc/guides/icons/callouts/13.png Binary files differnew file mode 100644 index 0000000000..14021a89c2 --- /dev/null +++ b/railties/doc/guides/icons/callouts/13.png diff --git a/railties/doc/guides/icons/callouts/14.png b/railties/doc/guides/icons/callouts/14.png Binary files differnew file mode 100644 index 0000000000..64014b75fe --- /dev/null +++ b/railties/doc/guides/icons/callouts/14.png diff --git a/railties/doc/guides/icons/callouts/15.png b/railties/doc/guides/icons/callouts/15.png Binary files differnew file mode 100644 index 0000000000..0d65765fcf --- /dev/null +++ b/railties/doc/guides/icons/callouts/15.png diff --git a/railties/doc/guides/icons/callouts/2.png b/railties/doc/guides/icons/callouts/2.png Binary files differnew file mode 100644 index 0000000000..5d09341b2f --- /dev/null +++ b/railties/doc/guides/icons/callouts/2.png diff --git a/railties/doc/guides/icons/callouts/3.png b/railties/doc/guides/icons/callouts/3.png Binary files differnew file mode 100644 index 0000000000..ef7b700471 --- /dev/null +++ b/railties/doc/guides/icons/callouts/3.png diff --git a/railties/doc/guides/icons/callouts/4.png b/railties/doc/guides/icons/callouts/4.png Binary files differnew file mode 100644 index 0000000000..adb8364eb5 --- /dev/null +++ b/railties/doc/guides/icons/callouts/4.png diff --git a/railties/doc/guides/icons/callouts/5.png b/railties/doc/guides/icons/callouts/5.png Binary files differnew file mode 100644 index 0000000000..4d7eb46002 --- /dev/null +++ b/railties/doc/guides/icons/callouts/5.png diff --git a/railties/doc/guides/icons/callouts/6.png b/railties/doc/guides/icons/callouts/6.png Binary files differnew file mode 100644 index 0000000000..0ba694af6c --- /dev/null +++ b/railties/doc/guides/icons/callouts/6.png diff --git a/railties/doc/guides/icons/callouts/7.png b/railties/doc/guides/icons/callouts/7.png Binary files differnew file mode 100644 index 0000000000..472e96f8ac --- /dev/null +++ b/railties/doc/guides/icons/callouts/7.png diff --git a/railties/doc/guides/icons/callouts/8.png b/railties/doc/guides/icons/callouts/8.png Binary files differnew file mode 100644 index 0000000000..5e60973c21 --- /dev/null +++ b/railties/doc/guides/icons/callouts/8.png diff --git a/railties/doc/guides/icons/callouts/9.png b/railties/doc/guides/icons/callouts/9.png Binary files differnew file mode 100644 index 0000000000..a0676d26cc --- /dev/null +++ b/railties/doc/guides/icons/callouts/9.png diff --git a/railties/doc/guides/icons/caution.png b/railties/doc/guides/icons/caution.png Binary files differnew file mode 100644 index 0000000000..cb9d5ea0df --- /dev/null +++ b/railties/doc/guides/icons/caution.png diff --git a/railties/doc/guides/icons/example.png b/railties/doc/guides/icons/example.png Binary files differnew file mode 100644 index 0000000000..bba1c0010d --- /dev/null +++ b/railties/doc/guides/icons/example.png diff --git a/railties/doc/guides/icons/home.png b/railties/doc/guides/icons/home.png Binary files differnew file mode 100644 index 0000000000..37a5231bac --- /dev/null +++ b/railties/doc/guides/icons/home.png diff --git a/railties/doc/guides/icons/important.png b/railties/doc/guides/icons/important.png Binary files differnew file mode 100644 index 0000000000..1096c23295 --- /dev/null +++ b/railties/doc/guides/icons/important.png diff --git a/railties/doc/guides/icons/next.png b/railties/doc/guides/icons/next.png Binary files differnew file mode 100644 index 0000000000..64e126bdda --- /dev/null +++ b/railties/doc/guides/icons/next.png diff --git a/railties/doc/guides/icons/note.png b/railties/doc/guides/icons/note.png Binary files differnew file mode 100644 index 0000000000..841820f7c4 --- /dev/null +++ b/railties/doc/guides/icons/note.png diff --git a/railties/doc/guides/icons/prev.png b/railties/doc/guides/icons/prev.png Binary files differnew file mode 100644 index 0000000000..3e8f12fe24 --- /dev/null +++ b/railties/doc/guides/icons/prev.png diff --git a/railties/doc/guides/icons/tip.png b/railties/doc/guides/icons/tip.png Binary files differnew file mode 100644 index 0000000000..a3a029d898 --- /dev/null +++ b/railties/doc/guides/icons/tip.png diff --git a/railties/doc/guides/icons/up.png b/railties/doc/guides/icons/up.png Binary files differnew file mode 100644 index 0000000000..2db1ce62fa --- /dev/null +++ b/railties/doc/guides/icons/up.png diff --git a/railties/doc/guides/icons/warning.png b/railties/doc/guides/icons/warning.png Binary files differnew file mode 100644 index 0000000000..0b0c419df2 --- /dev/null +++ b/railties/doc/guides/icons/warning.png diff --git a/railties/doc/guides/securing_rails_applications/creating_records_directly_from_form_parameters.txt b/railties/doc/guides/securing_rails_applications/creating_records_directly_from_form_parameters.txt new file mode 100644 index 0000000000..b237c4a17f --- /dev/null +++ b/railties/doc/guides/securing_rails_applications/creating_records_directly_from_form_parameters.txt @@ -0,0 +1,86 @@ +== Creating records directly from form parameters == + +=== The problem === + +Let's say you want to make a user registration system. Your users table looks like this: + +------------------------------------------------------- +CREATE TABLE users ( + id INTEGER PRIMARY KEY, + name VARCHAR(20) NOT NULL, -- the login name + password VARCHAR(20) NOT NULL, + role VARCHAR(20) NOT NULL DEFAULT "User", -- e.g. "Admin", "Moderator, "User" + approved INTEGER NOT NULL DEFAULT 0 -- is the registered accound approved by the administrator? +); + +CREATE UNIQUE INDEX users_name_unique ON users(name); +------------------------------------------------------- + +The registration form: + +[source, xhtml] +------------------------------------------------------- +<form method="post" action="http://website.domain/user/register"> + <input type="text" name="user[name]" /> + <input type="text" name="user[password]" /> +</form> +------------------------------------------------------- + +The easiest way to create a user object from the form data in the controller is: + +[source, ruby] +------------------------------------------------------- +User.create(params[:user]) +------------------------------------------------------- + +But what happens if someone decides to save the registration form to his disk and play around with adding a few fields? + +[source, xhtml] +------------------------------------------------------- +<form method="post" action="http://website.domain/user/register"> + <input type="text" name="user[name]" /> + <input type="text" name="user[password]" /> + <input type="text" name="user[role]" value="Admin" /> + <input type="text" name="user[approved]" value="1" /> +</form> +------------------------------------------------------- + +He can create an account, make himself admin and approve his own account with one click. + +=== The solution === + +Active Record provides two ways of securing sensitive attributes from being overwritten by malicious users that change the form. The first is `attr_protected` that denies mass-assignment the right to change the named parameters. + +Using `attr_protected`, we can secure the User models like this: + +[source, ruby] +------------------------------------------------------- +class User < ActiveRecord::Base + attr_protected :approved, :role +end +------------------------------------------------------- + +This will ensure that on doing `User.create(params[:user])` both `params[:user][:approved]` and `params[:user][:role]` will be ignored. You'll have to manually set them like this: + +[source, ruby] +------------------------------------------------------- +user = User.new(params[:user]) +user.approved = sanitize_properly(params[:user][:approved]) +user.role = sanitize_properly(params[:user][:role]) +------------------------------------------------------- + +=== Allowing instead of protecting === + +If you're afraid you might forget to apply `attr_protected` to the right attributes before making your model available to the cruel world, you can also specify the protection in reverse. You simply allow access instead of deny it, so only the attributes named in `attr_accessible` are available for mass-assignment. + +Using `attr_accessible`, we can secure the User models like this: + +[source, ruby] +------------------------------------------------------- +class User < ActiveRecord::Base + attr_accessible :name, :password +end +------------------------------------------------------- + +This description has exactly the same affect as doing `attr_protected :approved, :role`, but when you add new attrbutes to the User model, they'll be protected by default. + diff --git a/railties/doc/guides/securing_rails_applications/cross_site_scripting.txt b/railties/doc/guides/securing_rails_applications/cross_site_scripting.txt new file mode 100644 index 0000000000..56b3940511 --- /dev/null +++ b/railties/doc/guides/securing_rails_applications/cross_site_scripting.txt @@ -0,0 +1,64 @@ +== Cross Site Scripting (CSS/XSS) == + +=== The problem === + +Many web applications use session cookies to track the requests of a user. The cookie is used to identify the request and connect it to the session data (the `session` method in Rails). Usually the session contains a reference to the user that is currently logged in, e.g. the id of a User object. + +Cross Site Scripting is a technique for ``stealing'' the cookie from another visitor of the website, and thus stealing the login. Cookies are only available from the domain where the were originally created. The easiest way to get access to the cookie is to place a specially crafted piece of JavaScript code on the website; the script can read the cookie of a visitor and send it to the attacker, e.g. by transmitting the data as an URL parameter to another website. +2.2 Example of an attack + +A site with the following Eruby template is vulnerable to XSS: + +------------------------------------ +<%= params[:text] %> +------------------------------------ + +The 'text' parameter is directly included in the page, so it is possible to insert JavaScript code by setting the parameter to something like + +[source, xhtml] +------------------------------------ +<script>alert(document.cookie)</script> +------------------------------------ + +After url-encoding the script (e.g. with `CGI.encode`) the attacker can put it into an URL and make his victim open the URL in the browser. + +If you open the URL + +------------------------------------ +http://website.domain/controller/action?text=%3Cscript%3Ealert%28document.cookie%29%3C%2Fscript%3E +------------------------------------ + +you will get a popup window with your session cookie. Instead of opening the popup the script could as well send the session id to another server. + +=== How to protect your application === + +Obviously the key to a successful attack is the possibility to place JavaScript on a website that can receive the session cookie. This can be a blog with user comments, a web forum or a Wiki. How can you protect against it? Strictly convert HTML meta characters (`<` and `>`) to the equivalent HTML entities (`<` and `>`) in every string that is rendered in the website. This will ensure that, no matter what kind of text an attacker enters in a form or attaches to an URL, the browser will always render it as plain text and never interpret any HTML tags. This is a good idea anyway, as a user can easily mess up your layout by leaving tags open. If you want the user to be able to format his texts, it is usually better to use a markup language like Textile, Markdown or RDoc. + +Rails provides the helper method `h` for HTML meta character conversion in Views. + +Example: + +------------------------------------ +<%=h post.subject %> +<%=h post.text %> +------------------------------------ + +You should accustom to using `h` for any variable that is rendered in the view, even if you think you can trust it to be from a reliable source. + +=== XSS attacks using an echo service === + +The echo service is a service running on TCP port 7 that returns back everything you send to it. On Debian it is active by default. Now how can this be a security problem for a web application? + +If the server of the target website 'target.domain' is running an echo service, the attacker could create a form like the following on his own website: + +[source, xhtml] +------------------------------------ +<form action="http://target.domain:7/" method="post"> + <input type="hidden" name="code" value="some_javascript_code_here" /> + <input type="submit" /> +</form> +------------------------------------ + +If he makes someone who has a session cookie on the target website submit this form, the content of the hidden field is sent to the echo server at port 7 – and returned. If the browser decides to display the returned data as HTML (some versions of IE do), it will execute the JavaScript code; and because the domain is 'target.domain' the session cookie is available for the script. + +This is rather a client-side issue, but to reduce the probability of a successful attack you should deactivate any echo services on the web server. However this does not provide full security, because there are also some other services (e.g. FTP, POP3) that can be used instead of the echo server. diff --git a/railties/doc/guides/securing_rails_applications/securing_rails_applications.txt b/railties/doc/guides/securing_rails_applications/securing_rails_applications.txt new file mode 100644 index 0000000000..b2cebbd311 --- /dev/null +++ b/railties/doc/guides/securing_rails_applications/securing_rails_applications.txt @@ -0,0 +1,14 @@ +Securing Rails applications +=========================== + +This manual describes common security problems in web applications and how +to avoid them with Rails. If you have any questions or suggestions, please +mail me at ror(at)andreas-s.net. + + +include::sql_injection.txt[] + +include::cross_site_scripting.txt[] + +include::creating_records_directly_from_form_parameters.txt[] + diff --git a/railties/doc/guides/securing_rails_applications/sql_injection.txt b/railties/doc/guides/securing_rails_applications/sql_injection.txt new file mode 100644 index 0000000000..51a0520b39 --- /dev/null +++ b/railties/doc/guides/securing_rails_applications/sql_injection.txt @@ -0,0 +1,87 @@ +== SQL Injection == + +=== The problem === + +SQL injection is the #1 security problem in many web applications. How does it work? If the web application includes strings from unreliable sources (usually form parameters) in SQL statements and doesn't correctly quote any SQL meta characters like backslashes or single quotes, an attacker can change `WHERE` conditions in SQL statements, create records with invalid data or even execute arbitrary SQL statements. + +=== How to protect your application === + +If you only use the predefined ActiveRecord functions (attributes, save, find) without writing any conditions, limits or SQL queries yourself, ActiveRecord takes care of quoting any dangerous characters in the data for you. + +If you don't, you have to make sure that strings for arguments that are directly used to build SQL queries (like the condition, limit and sort arguments for `find :all`) do not contain any SQL meta characters. + +=== Using arbitrary strings in conditions and SQL statements === + +==== Wrong ==== + +Imagine a webmail system where a user can select a list of all the emails with a certain subject. A query could look like this: + +[source, ruby] +--------------------------------------------------------------------------- +Email.find(:all, "owner_id = 123 AND subject = '#{params[:subject]}'") +--------------------------------------------------------------------------- + +This is dangerous. Imagine a user sending the string `\' OR 1 \--` in the parameter 'subject'; the resulting statement will look like this: + +[source, ruby] +--------------------------------------------------------------------------- +Email.find(:all, "owner_id = 123 AND subject = '' OR 1 --'") +--------------------------------------------------------------------------- + +Because of ``OR 1'' the condition is always true. The part ``\--'' starts a SQL comment; everything after it will be ignored. The result: the user will get a list of all the emails in the database. + +(Of course the 'owner_id' would have to be inserted dynamically in a real application; this was omitted to keep the examples as simple as possible.) + +==== Correct ==== + +[source, ruby] +--------------------------------------------------------------------------- +Email.find(:all, ["owner_id = 123 AND subject = ?", params[:subject]]) +--------------------------------------------------------------------------- + +If the argument for find_all is an array instead of a string, ActiveRecord will insert the elements 2..n of the array for the `?` placeholders in the element 1, add quotation marks if the elements are strings, and quote all characters that have a special meaning for the database adapter used by the `Email` model. + +If you don't like the syntax of the array, you can take care of the quoting yourself by calling the `quote_value` method of the model class. You have to do this when you use `find_by_sql`, as the Array argument doesn't work there: + +[source, ruby] +--------------------------------------------------------------------------- +Email.find_by_sql("SELECT * FROM email WHERE owner_id = 123 AND subject = #{Email.quote_value(subject)}") +--------------------------------------------------------------------------- + +The quotation marks are added automatically by `Email.quote_value` if the argument is a string. + +=== Extracting queries into model methods === + +If you need to execute a query with the similar options in several places in your code, you should create a model method for that query. Instead of + +[source, ruby] +--------------------------------------------------------------------------- +emails = Email.find(:all, ["subject = ?", subject]) +--------------------------------------------------------------------------- + +you could define the following class method in the model: + +[source, ruby] +--------------------------------------------------------------------------- +class Email < ActiveRecord::Base + def self.find_with_subject(subject) + Email.find(:all, ["subject = ?", subject]) + end +end +--------------------------------------------------------------------------- + +and call it like this: + +[source, ruby] +--------------------------------------------------------------------------- +emails = Email.find_with_subject(subject) +--------------------------------------------------------------------------- + +This has the advantage that you don't have to care about meta characters when using the function `find_with_subject`. Generally you should always make sure that this kind of model method can not break anything, even if it is called with untrusted arguments. + +.ActiveRecord automatically generates finder methods +NOTE: The `find_with_subject` method given in the above example is actually redundant. +ActiveRecord automatically generates finder methods for columns. In this case, ActiveRecord +automatically generates the method `find_by_subject` (which works exactly like the `find_with_subject` +method given in the example). `find_with_subject` is only given here as an example. In general, +you should use ActiveRecord's auto-generated finder methods instead of writing your own. diff --git a/railties/doc/guides/testing_rails_applications/testing_rails_applications.txt b/railties/doc/guides/testing_rails_applications/testing_rails_applications.txt new file mode 100644 index 0000000000..a775ed2f09 --- /dev/null +++ b/railties/doc/guides/testing_rails_applications/testing_rails_applications.txt @@ -0,0 +1,1371 @@ +A Guide to Testing Rails Applications +===================================== + +This article is for fellow Rubyists looking for more information on test writing and how that fits into Ruby On Rails. If you're new to test writing or experienced with test writing, but not in Rails, hopefully you'll gain some practical tips and insight on successful testing. +Assumptions + +Just so we're all on the same page here, I'm making a few assumptions about you. + + * You've got Ruby installed and know how to run a Ruby script. + * You've got Rails installed + * You've created a basic Rails application with 1 controller and 1 model. + +If you haven't accomplished all of the above, you might be jumping ahead of yourself. Check out www.rubyonrails.org for some great beginner's tutorials. + +Make sure you have Ruby 1.8.6 or greater and Rails 2.0 or greater. + +Also, hats off to xal (and others) for creating this site. + + +== Testing 1-2-3... is this thing on? + +=== What are These Strange Creatures? + +I have to say that tests are such a straight-forward concept that it's actually harder to describe what they are than it is to show you how to do them. + +So what are tests? + +The Official Answer:: + Tests are collections of questions and scenarios that provide us (developers) with consistent results which prove that our application is doing what we expect it to do. + +The Unofficial Answer:: + We write tests to interrogate, taunt, bully, punish, and otherwise kick the crap out of our application code until it consistently gives us the correct answer. Think of it as ``tough love''. ;) + +Need some examples? + + * ensure user names have at least 4 characters + * ensure that when we save this record, the administrator is e-mailed + * ensure all replies are deleted when we delete the parent message + * ensure that Canadians have GST of 7% applied to their purchases + +The idea of tests is that you write them at the same time as you write your application. In essence, you're writing two application. As your application grows and becomes more complex, you create many tests. Re-running these tests at any point will help you discover if you've ``broke'' anything along the way. + +Some developers actually take this a step further and create the tests before they create the application. This is called Test Driven Development (TDD), and although I personally don't subscribe to it, it's a totally legit way of coding. + +There's volumes written about Test Driven Development and testing in general. For more information, talk to Mr. Google. + +=== So Why Test? + +As mentioned before, tests offer proof that you've done a good job. Your tests become your own personal QA assistant. If you code your tests correctly, at any point in development, you will know: + + * what processes work + * what processes fail + * the effect of adding new pieces onto your application + +With your tests as your safety net, you can do wild refactoring of your code and be able to tell what needs to be addressed simply by seeing which tests fail. + +In addition to normal "did it pass?" testing, you can go the opposite route. You can explicitly try to break your application such as feeding it unexpected and crazy input, shutting down critical resources like a database to see what happens, and tampering with things such as session values just to see what happens. By testing your application where the weak points are, you can fix it *before* it ever becomes an issue. + +A strong suite of tests ensures your application has a high level of quality. It's worth the extra effort. + +Another positive side-effect of writing tests is that you have basic usage documentation of how things work. Simply by looking at your testing code, you can see how you need to work with an object to make it do it's thing. + +But enough about theory. + + +== Introducing Test/Unit + +=== The Small Picture + +==== Hello World + +As we all know, Ruby ships with a boat load of great libraries. If you're like me, you've only used a quarter of them or so. One little gem of a library is 'test/unit'. It comes packaged with Ruby 1.8.1, so there's nothing to download. + +By using one line of code `require \'test/unit'`, you arm your Ruby script with the capability to write tests. + +Let's show you a really basic test, and then we'll step through it and explain some details. + +[source,ruby] +------------------------------------------------------ +# hello_test.rb + +require 'test/unit' + +class HelloTestCase < Test::Unit::TestCase + def test_hello + assert true + end +end +------------------------------------------------------ + +Quite possibly the simplest and least useful test ever invented, but it shows you the bare bones of writing a test case. That script can be run from the command line the same way your run any other Ruby script. + +Simply run `ruby hello_test.rb` and you will see the following: + +------------------------------------------------------ +Started +. +Finished in 0.0 seconds. + +1 tests, 1 assertions, 0 failures, 0 errors +------------------------------------------------------ + +Congratulations, your first test. + + +==== What Does It All Mean? + +By looking at the output of a test, you will be able to tell if the tests pass or not. In our example, not surprisingly, we've passed. The summary shows *1 test, 1 assertion, 0 failures, and 0 errors*. + +So, let's break our test source code down. + +First, line 1. + +[source,ruby] +------------------------------------------------------ +require 'test/unit' +------------------------------------------------------ + +You'll always have this when writing unit tests. It contains the classes and functionality to write and run unit tests. + +Next, we have a class `HelloTestCase` which derives from `Test::Unit::TestCase`. + +[source,ruby] +------------------------------------------------------ +class HelloTestCase < Test::Unit::TestCase +------------------------------------------------------ + +All of the tests that you create will directly subclass `Test::Unit::TestCase`. The TestCase provides the ``housing'' of where your tests will live. More on this in a bit. + +Finally, we have a method called `test_hello`. + +[source,ruby] +------------------------------------------------------ +def test_hello +------------------------------------------------------ + +All tests must follow this naming convention: *their names start with the first 4 characters test*, as in `test_hello`, `testme`, and `testarosa`. If you create a method that doesn't start with test, the testing framework won't recognize it as a test, hence, won't run it automatically, hence it is a normal Ruby method. + +Inside our `test_hello` method, we have an assertion. + +[source,ruby] +------------------------------------------------------ +assert true +------------------------------------------------------ + +Assertions are where the real work gets done. There are a whole army of different types of assertions that you'll use to make sure your code is doing the right thing. + + +=== The Big Picture + +Grab a cup of coffee and dunk your head in some ice water, because here's some more theory. + +There are 4 major players in the testing game. + +==== A: The Assertion + +An 'Assertion' is 1 line of code that evaluates an object (or expression) for expected results. + +For example, is this value = that value? is this object nil? does this line of code throw an exception? is the user's password greater than 5 characters? + +==== B: The Test ==== + +A 'Test' is method that contains assertions which represent a particular testing scenario. + +For example, we may have a test method called `test_valid_password`. In order for this test to pass, we might need to check a few things: + + * password is 4 or more characters + * password isn't the word ‘password' + * password isn't all spaces + +If all of these assertions are successful, the test will pass. + +==== C: The Test Case ==== +A 'Test Case' is a class inherited from `Test::Unit::TestCase` containing a testing ``strategy'' comprised of contextually related tests. + +For example, I may have a test case called UserTestCase which has a bunch of tests that check that: + + * the password is valid (`test_password`) + * the username doesn't have any forbidden words (`test_username_cussin`) + * a user is under the age of 150 (`test_shriveled_raisin`) + +==== D: The Test Suite ==== +A 'Test Suite' is a collection of test cases. When you run a test suite, it will, in turn, execute each test that belongs to it. + +For example, instead of running each test unit individually, you can run them all by creating a suite and including them. This is good for stuff like continuous-build integration. + +We won't get into test suites in this article. + + +==== The Hierarchy ==== + +The relationship of these objects to one-another looks like this: + + * a test suite + * has many test cases + * which have many tests + * which have many assertions + + +== Hello World on Steroids == + +=== The Victim === + +In the last episode, we learned that we write tests to prove our code works properly. Let's create a really simple class for us to test. + +[source,ruby] +-------------------------------------------------- +# secret_agent.rb +class SecretAgent + + # simple public properties + attr_accessor :username + attr_accessor :password + + # our "constructor" + def initialize(username,password) + @username = username + @password = password + end + + # the logic to determine if the password is + # good enough for the user to use + def is_password_secure? + return false if @password.nil? + return false if @password.empty? + return false if @password.size < 4 + return false if @password 'stirred' + return false if @password ‘password' + return false if @password == @username + true + end +end +-------------------------------------------------- + +Ok. So, we've got a class which represents a secret agent. What we're about to do is test a user to make sure that their password is secure enough to use in our top-secret database. + +The `is_password_secure?` method will answer that for us. If the user's password passes our stringent set of rules, then the function will return a true value and the secret agent granted access. + + +=== The Assault === + +Let's build upon the last test we wrote and add in a few more things, specifically, let's test out this brand new SecretAgent. + +[source,ruby] +----------------------------------------------- +require 'test/unit' +require 'secret_agent' + +class HelloTestCase < Test::Unit::TestCase + + def test_hello + assert true + end + + # our new test will exercise the new SecretAgent class + def test_these_passwords + # first, let's try a few passwords that should fail + assert !SecretAgent.new("bond","abc").is_password_secure? + assert !SecretAgent.new("bond","007").is_password_secure? + assert !SecretAgent.new("bond","stirred").is_password_secure? + assert !SecretAgent.new("bond","password").is_password_secure? + assert !SecretAgent.new("bond","bond").is_password_secure? + assert !SecretAgent.new("bond","").is_password_secure? + assert !SecretAgent.new("bond",nil).is_password_secure? + + # now, let's try passwords that should succeed + assert SecretAgent.new("bond","goldfinger").is_password_secure? + assert SecretAgent.new("bond","1234").is_password_secure? + assert SecretAgent.new("bond","shaken").is_password_secure? + end +end +----------------------------------------------- + +In this example, we've expanded our test case by adding another test called `test_these_passwords` with 10 assertions. Let's run it, cross our fingers, and hope it passes. + +----------------------------------------------- +Started +.. +Finished in 0.01 seconds. + +2 tests, 11 assertions, 0 failures, 0 errors +----------------------------------------------- + +Sweet! It passed! + +A couple of new things to notice about the results. See the line right underneath the word Started? Notice it has 2 dots instead of only 1 before? Each . represents a test. You can have 1 of 3 values where the dots are. + + * *.* means successful test (pass) + * *F* means failed test + * *E* means an error has occurred + +=== Failure, Error and General Discomfort === + +Let's add another in 2 more tests. This time, we'll make one of them fail and the other throw an error. Yes, on purpose. Yes, I'm a trained professional. + +[source,ruby] +--------------------------------------------------------------- +... +# this will result in a failure because the assertion fails... plus everyone +# knows batman really exists +def test_bam_zap_sock_pow + batman = nil + assert_not_nil batman +end + +# this will result in an error because it contains an undefined symbol +def test_uh_oh_hotdog + assert_not_nil does_this_var_speak_korean +end +... +--------------------------------------------------------------- + +Ok... Let's run this puppy. + +--------------------------------------------------------------- +Started +F..E +Finished in 0.07 seconds. + +1) Failure: +test_bam_zap_sock_pow(HelloTestCase) [/example/test.rb:62]: +<nil> expected to not be nil. + +2) Error: +test_uh_oh_hotdog(HelloTestCase): +NameError: undefined local variable or method 'does_this_var_speak_korean' for +#<HelloTestCase:0x28c59a0> /example/test.rb:68:in 'test_uh_oh_hotdog' + +4 tests, 12 assertions, 1 failures, 1 errors +--------------------------------------------------------------- + +Wow. Nasty. + +Take a look at the 2nd line. This time we have 'F..E' which means failure, pass, pass, error. In the details underneath the total elapsed time, you see what exactly went wrong and where. + +The incredibly observant will notice that even though the two new methods were added as the 3rd and 4th tests, they showed up in the results as 1st and 4th. That's because the tests are sorted alphabetically. + +So, that's what errors and failures look like. The difference is, a failure represents an assertion attempt that gave us the wrong results whereas an error is a Ruby problem. + + +=== This Side Up ^ === + +Another thing about assertions. They're fragile. If the test finds an assertion that fails, it will stop execution of that method and move on to the next test. + +If I had a test with 4 assertions, of which numbers 2, 3, and 4 were all going to fail, you'd only see #2 as the cause of the failed test. If you were to correct that failure, then rerun the test, it would be #3 thats causes grief. + +Got it? Good, there will be a pop quiz on Monday. + + +== The Test Case Life Cycle == + +=== 4.1 A Quick Recap === + +You already saw a simple test case in action. It looked something like this: + +[source,ruby] +--------------------------------------------------------- +require 'test/unit' + +class MyTestCase < Test::Unit::TestCase + + def test_1 + assert true + end + + def test_2 + end + + def test_3 + end + +end +--------------------------------------------------------- + +You saw that: + + * we need to use `require ‘test/unit'` + * we need to inherit from `Test::Unit::TestCase` + * we need to define methods that start with `test` + * we need assertions to prove our code works + +Next, we're going to look at the flow of how test cases are run. + + +=== The Flow === + +When a test case is run, the testing framework creates a ‘fresh' object before running each test. That allows the test to not have to worry about what state the other test methods leave the object in. So for the above example, the testing flow looks like this when run: + + * an object of class `MyTestCase` is created + * method `test_1` is run + * the test case object is destroyed + +then... + + * a brand new object of class `MyTestCase` is created + * method `test_2` is run + * the test case object is destroyed + +then... + + * one last object of class `MyTestCase` is created + * method `test_3` is run + * the test case object is destroyed + + +=== Setup and Teardown Exposed === + +Now, there are 2 special methods that you can use to hook into this process. One is called setup and the other is called teardown. + +Let's rewrite our test. + +[source,ruby] +------------------------------------------ +require 'test/unit' + +class MyTestCase < Test::Unit::TestCase + + # called before every single test + def setup + @name = 'jimmy' + @age = 150 + end + + # called after every single test + def teardown + end + + # our tests + def test_1 + assert true + end + + def test_2 + end + + def test_3 + end +end +------------------------------------------ + +The `setup` method will always be called just before the test method. Comparatively, the `teardown` method will always be called always be called just after the test method. So now, the flow looks like this: + + * an object of class `MyTestCase` is created + * method `setup` is run + * method `test_1` is run + * method `teardown` is run + * the test case object is destroyed + +then... + + * a brand new object of class `MyTestCase` is created + * method `setup` is run + * method `test_2` is run + * method `teardown` is run + * the test case object is destroyed + +then... + + * one last object of class `MyTestCase` is created + * method `setup` is run + * method `test_3` is run + * method `teardown` is run + * the test case object is destroyed + +What can you do with this? Well, the `setup` method is good for stuff like creating objects that each method uses. For example, maybe we need to create a user and populate her with sample data before running each of the tests? + +As you'll see later, Rails uses the `setup` and `teardown` methods extensively. + + +== Hey Test/Unit. Assert This! == + +=== The Assertion Lineup === + +By now you've caught a glimpse of some of the assertions that are available. Assertions are the worker bees of testing. They are the ones that actually perform the checks to ensure things are going as planned. + +There are a bunch of different types of assertions you can use. Here's the complete list of assertions that ship with test/unit. The [msg] is an optional string message you can specify to make your test failure messages clearer. It's not required. + +`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_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. + +`assert_match( regexp, string, [msg] )`:: + Ensures that a string matches the regular expression. + +`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_raises( 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`. + +`assert_respond_to( obj, symbol, [msg] )`:: + Ensures that obj has a method called symbol. + +`assert_operator( obj1, operator, obj2, [msg] )`:: + Ensures that `obj1.operator(obj2)` is true. + +`assert_send( array, [msg] )`:: + Ensures that executing the method listed in `array[1]` on the object in `array[0]` with the parameters of `array[2 and up]` is true. This one is weird eh? + +`flunk( [msg] )`:: + Ensures failure... like me and high school chemistry exams. + +Because of the modular nature of the testing framework, it is possible to create your own assertions. In fact, that's exactly what Rails does. It has some specialized assertions to make your life easier. + +Creating your own assertions is more of an advanced topic we won't cover in this tutorial. + + +== The Rails Fly-By == + +=== It's About Frikkin' Time === + +Finally we get to testing in with Ruby on Rails! By this point, I'm going to assume a few things. + + * you're familiar with the basic building blocks of 'test/unit' + * you know that there are a bunch of assertions you can use + * you know what the special methods `setup` and `teardown` are + * you're conscious + +Rails promotes testing. The Ruby on Rails framework itself was built using these testing methodologies. + +In fact, the features built-in to Rails makes it exceptionally easy to do testing. For every model and controller you create using the `script/generate model` and `script/generate controller` scripts, corresponding test stubs are created. + +=== Where They Live === + +Your tests, quite surprisingly, go in your 'test' directory under your rails application. In the test directory, you'll see 4 sub-directories; one for controller tests ('functional'), one for model tests ('unit'), one for mock objects ('mocks') and one that only holds sample data ('fixtures'). + + * test + - /unit + - /functional + - /fixtures + - /mocks + +=== How to Turn Them On === + +To run these tests, you simply run the test script directly: + +--------------------------------------------- +ruby test/unit/my_good_old_test_unit.rb +--------------------------------------------- + +Another way to run your tests is to have the main rakefile run it for you. `rake test_functional` will run all your controller tests and `rake test_units` will run all your model tests. + +=== The 3 Environments === + +Testing support was woven into the Rails fabric from the beginning. It wasn't a ``oh! let's bolt on support for running tests because they're new and cool'' epiphany. + +Each Rails application you build has 3 sides. A side for production, a side for development and a side for testing. + +Let's take a closer look at the Rails 'config/database.yml' file. This YAML configuration file has 3 different sections defining 3 unique database setups: + + * production + * development + * test + +Why 3 different databases? Well, there's one for testing where you can use sample data, there's one for development where you'll be most of the time as you develop your application, and then production for the ``real deal'', or when it goes live. + +Every new Rails application should have these 3 sections filled out. They should point to different databases. You may end up not having a local database for your production environment, but development and test should both exist and be different. + +=== Why Make This Distinction? === + +If you stop and think about it for a second, it makes sense. + +By segregating your development database and your testing database, you're not in any danger of losing any data where it matters. + +For example, you need to test your new `delete_this_user_and_every_everything_associated_with_it` function. Wouldn't you want to run this in an environment which makes no difference if you destroy data or not? + +When you do end up destroying your testing database (and it will happen, trust me), simply run a task in your rakefile to rebuild it from scratch according to the specs defined in the development database. You can do this by running `rake db:test:prepare`. + + +== The Lo-Down on Fixtures == + +=== What They Are === + +The structure is one thing, but what about when I want to automatically create sample data? + +Enter fixtures. Fixtures is a fancy word for ‘sample data'. Fixtures allow you to populate your testing database with predefined data before your tests run. Fixtures are database independent and assume one of two formats: *YAML* or *CSV*. + +You'll find fixtures under your 'test/fixtures' directory. When you run `script/generate model` to create a new model, fixture stubs will be automatically created and placed in this directory. + +=== YAML the Camel is a Mammal with Enamel === + +YAML-formatted fixtures are a very human-friendly way to describe your sample data. These types of fixtures have the *.yml* file extension (as in 'users.yml'). + +On any given Sunday, a YAML fixture file may look like this: + +--------------------------------------------- +# low & behold! I am a YAML comment! +david: + id: 1 + name: David Heinemeier Hansson + birthday: 1979-10-15 + profession: Systems development + +steve: + id: 2 + name: Steve Ross Kellock + birthday: 1974-09-27 + profession: guy with keyboard +--------------------------------------------- + +Each fixture is given a 'name' followed by an indented list of colon-separated key/value pairs. Records are separated by a blank space. You can place comments by using the # character in the first column. + +=== Comma Seperated === + +Fixtures can also be described using the all-too-familiar comma-separated value file format. These files, just like YAML fixtures are placed in the 'test/fixtures directory', but these end with the *.csv* file extension (as in 'celebrity_holiday_figures.csv'). + +A CSV fixture looks like this: + +-------------------------------------------------------------- +id, username, password, stretchable, comments +1, sclaus, ihatekids, false, I like to say ""Ho! Ho! Ho!"" +2, ebunny, ihateeggs, true, Hoppity hop y'all +3, tfairy, ilovecavities, true, "Pull your teeth, I will" +-------------------------------------------------------------- + +The first line is the header. It is a comma-separated list of fields. The rest of the file is the payload: 1 record per line. A few notes about this format: + + * each cell is stripped of outward facing spaces + * if you use a comma as data, the cell must be encased in quotes + * if you use a quote as data, you must escape it with a 2nd quote + * don't use blank lines + * nulls can be achived by just placing a comma, for example, (1,sclaus,,false,) minus the parenthesis of course. + +Unlike the YAML format where you give each fixture a name, CSV fixture names are automatically generated. They follow a pattern of ``model-name''-''counter''. In the above example, you would have: + +-------------------------------------------------------------- +celebrity-holiday-figures-1 +celebrity-holiday-figures-2 +celebrity-holiday-figures-3 +-------------------------------------------------------------- + +The CSV format is great to use if you have existing data in a spreadsheet or database and you are able to save it (or export it) as a CSV. + +=== ERb'in It Up === + +ERb allows you embed ruby code within templates. Both the YAML and CSV fixture formats are pre-processed with ERb. This allows you to use Ruby to help you generate some sample data. + +I'll demonstrate with a YAML file: + +-------------------------------------------------------------- +<% earth_size = 20 -%> +mercury: + id: 1 + size: <%= earth_size / 50 %> + +venus: + id: 2 + size: <%= earth_size / 2 %> + +mars: + id: 3 + size: <%= earth_size - 69 %> +-------------------------------------------------------------- + +Anything encased within the + +------------- +<% -%> +------------- + +tag is considered Ruby code. To actually print something out, you must use the + +------------- +<%= %> +------------- + +tag. + +=== Fixtures in Action === + +Rails makes no assumptions when it comes to fixtures. You must explicitly load them yourself by using the fixtures method within your TestCase. For example, a users model unit test might look like this: + +[source, ruby] +-------------------------------------------------------------- +# Allow this test to hook into the Rails framework. +require File.dirname(__FILE__) + '/../test_helper' + +class UserTest < Test::Unit::TestCase + fixtures :users + + # Count the fixtures. + def test_count_my_fixtures + assert_equal 5, User.count + end +end +-------------------------------------------------------------- + +Using the fixtures method and placing the symbol name of the model, Rails will automatically load up the fixtures for you at the start of each test method. + +[source, ruby] +-------------------------------------------------------------- +fixtures :users +-------------------------------------------------------------- + +What exactly does this line of code do? It does 3 things: + + * it nukes any existing data living in the users table +* it loads the fixture data (if any) into the users table + * it dumps the data into a variable in case you want to access it directly + +So, in the above example, if we had another test method, we wouldn't have 10 users on the 2nd test because they would be wiped out before being created. + +You can load multiple fixtures by including them on the same line separated by commas. + +[source, ruby] +-------------------------------------------------------------- +fixtures :users, :losers, :bruisers, :cruisers +-------------------------------------------------------------- + +=== Hashes with Special Powers === + +Fixtures are basically Hash objects. As mentioned in point #3 above, you can access the hash object directly because it is automatically setup as a local variable of the test case. + +[source, ruby] +-------------------------------------------------------------- +... + fixtures :users + + def test_user + # this will return the Hash for the fixture named david + users(:david) + + # this will return the property for david called id + users(:david).id + end +... +-------------------------------------------------------------- + +But, by there's another side to fixtures... at night, if the moon is full and the wind completely still, fixtures can also transform themselves into the form of the original class! + +Now you can get at the methods only available to that class. + +[source, ruby] +-------------------------------------------------------------- +... + fixtures :users + + def test_user + # using the find method, we grab the "real" david as a User + david = users(:david).find + + # an now we have access to methods only available to a User class + email( david.girlfriend.email, david.illegitimate_children ) + end +... +-------------------------------------------------------------- + + +== Testing Your Models == + +=== A Unit Test === + +Unit tests are what we use to test our models. Generally, there is one test for each model. The test stubs are created automatically when you use `script/generate model SecretAgent` (for example). + +Let's take a look at what a unit test might look like. + +[source, ruby] +------------------------------------------------------- +# hook into the Rails environment +require File.dirname(__FILE__) + '/../test_helper' + +class SecretAgent < ActiveSupport::TestCase + fixtures :secret_agents + + # ensure the SecretAgent plays well with the database + def test_create_read_update_delete + # create a brand new secret agent + jimmy = SecretAgent.new("jagent", "unbelievablysecretpassword") + + # save him + assert jimmy.save + + # read him back + agent = SecretAgent.find(jimmy.id) + + # compare the usernames + assert_equal jimmy.username, agent.username + + # change the password by using hi-tech encryption + agent.username = agent.username.reverse + + # save the changes + assert agent.save + + # the agent gets killed + assert agent.destroy + end +end +------------------------------------------------------- + +In this basic unit test, we're exercising the 'SecretAgent' model. In our solitary test, we're proving a bunch of things about our 'SecretAgent' model. We try 4 different assertions to test that we can do the basics with the database such as create, read, update and delete (creatively known as CRUD). + +It is up to you to decide just how much you want to test of your model. Ideally you test anything that could possibly break, however, it is really trial and error. Only you know what's best to test. + +You most certainly want to test the validation code, and additionally, you probably want a least 1 test for every method in your model. + + +== Testing Your Controllers == + +=== What Is It? === + +The goal of functional testing is to test your controllers. When you get into the realm of testing controllers, we're operating at a higher level than the model. At this level, we test for things such as: + + * was the web request successful? + * were we redirected to the right page? + * were we successfully authenticated? + * was the correct object stored in the response template? + +Just as there is a one-to-one ratio between unit tests and models, so there is between functional tests and controllers. For a controller named `HomeController`, you would have a test case named `HomeControllerTest`. + +=== An Anatomy Lesson === + +So let's take a look at an example of a functional test. + +[source, ruby] +---------------------------------------------------- +require File.dirname(__FILE__) + '/../test_helper' + +class HomeControllerTest < ActionController::TestCase + # let's test our main index page + def test_index + get :index + assert_response :success + end +end +---------------------------------------------------- + +==== Making the moves ==== + +In the one test we have called `test_index`, we are simulating a request on the action called index and making sure the request was successful. + +The `get` method kicks off the web request and populates the results into the response. It accepts 4 arguments. + + * The action of the controller you are requesting. It can be in the form of a string or a symbol. Cool people use symbols. ;) + * An optional hash of request parameters to pass into the action (eg. query string parameters or post variables). + * An optional hash of session variables to pass along with the request. + * An optional hash of flash to stash your goulash. + +*Example:* Calling the `:show` action, passing an `id` of 12 as the params and setting `user_id` of 5 in the session. + +[source, ruby] +---------------------------------------------------- +get(:show, {'id' => "12"}, {'user_id' => 5}) +---------------------------------------------------- + +*Another example:* Calling the `:view` action, passing an `id` of 12 as the params, this time with no session, but with a flash message. + +[source, ruby] +---------------------------------------------------- +get(:view, {'id' => '12'}, nil, {'message' => 'booya!'}) +---------------------------------------------------- + +==== Available at your disposal ==== + +For those of you familiar with HTTP protocol, you'll know that get is a type of request. There are 5 request types supported in Rails: + + * get + * post + * put + * head + * delete + +All of request types are methods that you can use, however, you'll probably end up using the first two more ofter than the others. + +=== The 4 Hashes of the Apocolypse === + +After the request has been made by using one of the 5 methods (get, post, etc...), you will have 4 Hash objects ready for use. + +They are (starring in alphabetical order): + +`assigns`:: + Any objects that are stored as instance variables in actions for use in views. +`cookies`:: + Any objects cookies that are set. +`flash`:: + Any objects living in the flash. +`session`:: + Any object living in session variables. + +For example, let's say we have a `MoviesController` with an action called `movie`. The code for that action might look something like: + +[source, ruby] +---------------------------------------------------- +def movie + @movie = Movie.find(params[:id]) + if @movie.nil? + flash['message'] = "That movie has been burned." + redirect_to :controller => 'error', :action => 'missing' + end +end +---------------------------------------------------- + +Now, to test out if the proper movie is being set, we could have a series of tests that look like this: + +[source, ruby] +---------------------------------------------------- +# this test proves that fetching a movie works +def test_successfully_finding_a_movie + get :movie, "id" => "1" + assert_not_nil assigns["movie"] + assert_equal 1, assigns["movie"].id + assert flash.empty? +end + +# and when we can't find a movie... +def test_movie_not_found + get :movie, "id" => "666999" + assert_nil assigns["movie"] + assert flash.has_key?("message") + assert assigns.empty? +end +---------------------------------------------------- + +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 assigns. Check it out: + +[source, ruby] +---------------------------------------------------- +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) +---------------------------------------------------- + +Keep an eye out for that. mmmm kay? + +=== Response-Related Assertions === + +There are 3 assertions that deal with the overall response to a request. They are: + +`assert_template( expected_template, [msg] )`:: +Ensures the expected template was responsible for rendering. For example: ++ +[source, ruby] +-------------------------------------- +assert_template "user/profile" +-------------------------------------- ++ +This code will fail unless the template located at app/views/user/profile.rhtml was rendered. + +`assert_response( type_or_code, [msg] )`:: +Ensures the response type/status code is as expected. For example: ++ +[source, ruby] +-------------------------------------- +assert_response :success # page rendered ok +assert_response :redirect # we've been redirected +assert_response :missing # not found +assert_response 505 # status code was 505 +-------------------------------------- ++ +The possible options are: ++ + * `:success` (status code is 200) + * `:redirect` (status code is within 300..399) + * `:missing` (status code is 404) + * `:error` (status code is within 500..599) + * any number (to specifically reference a particular status code) + +`assert_redirected_to ( options={}, [msg] )`:: +Ensures we've been redirected to a specific place within our application. ++ +[source, ruby] +-------------------------- +assert_redirected_to :controller => 'widget', :action => 'view', :id => 555 +-------------------------- + +=== Tag-Related Assertions === + +The assert_tag and assert_no_tag assertions are for analysing the html returned from a request. + +==== assert_tag( options ) ==== +Ensures that a tag or text exists. There are a whole whack o' options you can use to discover what you are looking for. Some of the conditions are like XPATH in concept, but this is sexier. In fact, let's call it SEXPATH. + +The following description is lifted verbatim from the rails assertion docs. + +Asserts that there is a tag/node/element in the body of the response that meets all of the given conditions. The conditions parameter must be a hash of any of the following keys (all are optional): + + * `:tag` : the node type must match the corresponding value + * `:attributes` : a hash. The node's attributes must match the corresponding values in the hash. + * `:parent` : a hash. The node's parent must match the corresponding hash. + * `:child` : a hash. At least one of the node's immediate children must meet the criteria described by the hash. + * `:ancestor` : a hash. At least one of the node's ancestors must meet the criteria described by the hash. + * `:descendant` : a hash. At least one of the node's descendants must meet the criteria described by the hash. + * `:children` : a hash, for counting children of a node. Accepts the keys: + - `:count` : either a number or a range which must equal (or include) the number of children that match. + - `:less_than` : the number of matching children must be less than this number. + - `:greater_than` : the number of matching children must be greater than this number. + - `:only` : another hash consisting of the keys to use to match on the children, and only matching children will be counted. + - `:content` : (text nodes only). The content of the node must match the given value. + +Conditions are matched using the following algorithm: + + * if the condition is a *string*, it must be a substring of the value. + * if the condition is a *regexp*, it must match the value. + * if the condition is a *number*, the value must match `number.to_s`. + * if the condition is *true*, the value must not be `nil`. + * if the condition is *false* or *nil*, the value must be `nil`. + +These examples are taken from the same docs too: + +[source, ruby] +------------------------------------------------------------- + # assert that there is a "span" tag + assert_tag :tag => "span" + + # assert that there is a "span" inside of a "div" + assert_tag :tag => "span", :parent => { :tag => "div" } + + # assert that there is a "span" somewhere inside a table + assert_tag :tag => "span", :ancestor => { :tag => "table" } + + # assert that there is a "span" with at least one "em" child + assert_tag :tag => "span", :child => { :tag => "em" } + + # assert that there is a "span" containing a (possibly nested) + # "strong" tag. + assert_tag :tag => "span", :descendant => { :tag => "strong" } + + # assert that there is a "span" containing between 2 and 4 "em" tags + # as immediate children + assert_tag :tag => "span", + :children => { :count => 2..4, :only => { :tag => "em" } } + + # get funky: assert that there is a "div", with an "ul" ancestor + # and an "li" parent (with "class" = "enum"), and containing a + # "span" descendant that contains text matching /hello world/ + assert_tag :tag => "div", + :ancestor => { :tag => "ul" }, + :parent => { :tag => "li", + :attributes => { :class => "enum" } }, + :descendant => { :tag => "span", + :child => /hello world/ } +------------------------------------------------------------- + +==== assert_no_tag( options ) ==== +This is the exact opposite of assert_tag. It ensures that the tag does not exist. + +=== Routing-Related Assertions === + +==== assert_generates( expected_path, options, defaults={}, extras = {}, [msg] ) ==== +Ensures that the options map to the expected_path. + +[source, ruby] +------------------------------------------------------------- +opts = {:controller => "movies", :action => "movie", :id => "69"} +assert_generates "movies/movie/69", opts +------------------------------------------------------------- + +==== assert_recognizes( expected_options, path, extras={}, [msg] ) ==== +Ensures that when the path is chopped up into pieces, it is equal to expected_options. Essentially, the opposite of assert_generates. + +[source, ruby] +------------------------------------------------------------- +opts = {:controller => "movies", :action => "movie", :id => "69"} +assert_recognizes opts, "/movies/movie/69 + +# also, let's say i had a line in my config/routes.rb +# that looked like: +# +# map.connect ( +# 'calendar/:year/:month', +# :controller => 'content', +# :action => 'calendar', +# :year => nil, +# :month => nil, +# :requirements => {:year => /\d{4}/, :month => /\d{1,2}/} +# } +# +# Then, this would work too: +opts = { + :controller => 'content', + :action => 'calendar', + :year => '2005', + :month => '5' +} +assert_recognizes opts, 'calendar/2005/5' +------------------------------------------------------------- + +==== assert_routing( path, options, defaults={}, extras={}, [msg] ) ==== +Ensures that the path resolves into options, and the options, resolves into path. It's a two-way check to make sure your routing maps work as expected. + +This assertion is simply a wrapper around `assert_generates` and `assert_recognizes`. + +If you're going to test your routes, this assertion might be your best bet for robustness (yes, the overused buzzword of the 90's). + +[source, ruby] +------------------------------------------------------------- +opts = {:controller => "movies", :action => "movie", :id => "69"} +assert_routing "movies/movie/69", opts +------------------------------------------------------------- + +=== Testing File Uploads === +So your web app supports file uploads eh? Here's what you can do to test your uploads. + +This tip is brought to you by Chris Brinker, the letter R and the number 12. + +Chris says, '``In order to test a file being uploaded you have to mirror what cgi.rb is doing with a multipart post. Unfortunately what it does is quite long and complex, this code takes a file on your system, and turns it into what normally comes out of cgi.rb.''' + +Here are some helper methods based on Chris' work that you'll need to squirrel away either in a new unit, or cut ‘n' pasted right into your test. Any errors with this are my fault. + +[source, ruby] +------------------------------------------------------------- +# get us an object that represents an uploaded file +def uploaded_file(path, content_type="application/octet-stream", filename=nil) + filename ||= File.basename(path) + t = Tempfile.new(filename) + FileUtils.copy_file(path, t.path) + (class << t; self; end;).class_eval do + alias local_path path + define_method(:original_filename) { filename } + define_method(:content_type) { content_type } + end + return t +end + +# a JPEG helper +def uploaded_jpeg(path, filename=nil) + uploaded_file(path, 'image/jpeg', filename) +end + +# a GIF helper +def uploaded_gif(path, filename=nil) + uploaded_file(path, 'image/gif', filename) +end +------------------------------------------------------------- + +And to use this code, you'd have a test that would looks something like this: + +[source, ruby] +------------------------------------------------------------- +def test_a_file_upload + assert_equal 0, GalleryImage.count + heman = uploaded_jpeg("#{File.expand_path(RAILS_ROOT)}/text/fixtures/heman.jpg") + post :imageupload, 'imagefile' => heman + assert_redirected_to :controller => 'gallery', :action => 'view' + assert_equal 1, GalleryImage.count +end +------------------------------------------------------------- + + +== Testing Your Mailers == + +=== Keeping the postman in check === + +Your ActionMailer -- like every other part of your Rails application -- should be tested to ensure that it is working as expected. + +The goal of testing your ActionMailer is to ensure that: + + * emails are being processed (created and sent) + * the email content is correct (subject, sender, body, etc) + * the right emails are being sent at the righ times + +==== From all sides ==== + +There are two aspects of testing your mailer, the unit tests and the functional tests. +Unit tests + +In the unit tests, we run the mailer in isolation with tightly controlled inputs and compare the output to a known-value -- a fixture -- yay! more fixtures! + +==== Functional tests ==== + +In the functional tests we don't so much test the minute details produced by the mailer, instead we test that our controllers and models are using the mailer in the right way. We test to prove that the right email was sent at the right time. + +=== Unit Testing === + +In order to test that your mailer is working as expected, we can use unit tests to compare the actual results of the mailer with pre-writen examples of what should be produced. + +==== Revenge of the fixtures ==== + +For the purposes of unit testing a mailer, fixtures are used to provide an example of how output ``should'' look. Because these are example emails, and not Active Record data like the other fixtures, they are kept in their own subdirectory from the other fixtures. Don't tease them about it though, they hate that. + +When you generated your mailer (you did that right?) the generator created stub fixtures for each of the mailers actions. If you didn't use the generator you'll have to make those files yourself. + +==== The basic test case ==== + +Here is an example of what you start with. + +[source, ruby] +------------------------------------------------- +require File.dirname(__FILE__) + '/. ./test_helper' + +class MyMailerTest < Test::Unit::TestCase + FIXTURES_PATH = File.dirname(__FILE__) + '/. ./fixtures' + + def setup + ActionMailer::Base.delivery_method = :test + ActionMailer::Base.perform_deliveries = true + ActionMailer::Base.deliveries = [] + + @expected = TMail::Mail.new + end + + def test_signup + @expected.subject = 'MyMailer#signup' + @expected.body = read_fixture('signup') + @expected.date = Time.now + + assert_equal @expected.encoded, MyMailer.create_signup(@expected.date).encoded + end + + private + def read_fixture(action) + IO.readlines("#{FIXTURES_PATH}/my_mailer/#{action}") + end +end +------------------------------------------------- + +The `setup` method is mostly concerned with setting up a blank slate for the next test. However it is worth describing what each statement does + +[source, ruby] +------------------------------------------------- +ActionMailer::Base.delivery_method = :test +------------------------------------------------- + +sets the delivery method to test mode so that email will not actually be delivered (useful to avoid spamming your users while testing) but instead it will be appended to an array (ActionMailer::Base.deliveries). + +[source, ruby] +------------------------------------------------- +ActionMailer::Base.perform_deliveries = true +------------------------------------------------- + +Ensures the mail will be sent using the method specified by ActionMailer::Base.delivery_method, and finally + +[source, ruby] +------------------------------------------------- +ActionMailer::Base.deliveries = [] +------------------------------------------------- + +sets the array of sent messages to an empty array so we can be sure that anything we find there was sent as part of our current test. + +However often in unit tests, mails will not actually be sent, simply constructed, as in the example above, where the precise content of the email is checked against what it should be. Dave Thomas suggests an alternative approach, which is just to check the part of the email that is likely to break, i.e. the dynamic content. The following example assumes we have some kind of user table, and we might want to mail those users new passwords: + +[source, ruby] +------------------------------------------------- +require File.dirname(__FILE__) + '/../test_helper' +require 'my_mailer' + +class MyMailerTest < Test::Unit::TestCase + fixtures :users + FIXTURES_PATH = File.dirname(__FILE__) + '/../fixtures' + CHARSET = "utf-8" + + include ActionMailer::Quoting + + def setup + ActionMailer::Base.delivery_method = :test + ActionMailer::Base.perform_deliveries = true + ActionMailer::Base.deliveries = [] + + @expected = TMail::Mail.new + @expected.set_content_type "text", "plain", { "charset" => CHARSET } + end + + def test_reset_password + user = User.find(:first) + newpass = 'newpass' + response = MyMailer.create_reset_password(user,newpass) + assert_equal 'Your New Password', response.subject + assert_match /Dear #{user.full_name},/, response.body + assert_match /New Password: #{newpass}/, response.body + assert_equal user.email, response.to[0] + end + + private + def read_fixture(action) + IO.readlines("#{FIXTURES_PATH}/community_mailer/#{action}") + end + + def encode(subject) + quoted_printable(subject, CHARSET) + end +end +------------------------------------------------- + +and here we check the dynamic parts of the mail, specifically that we use the users' correct full name and that we give them the correct password. + +=== Functional Testing === + +Functional testing involves more than just checking that the email body, recipients and so forth are correct. In functional mail tests we call the mail deliver methods and check that the appropriate emails have been appended to the delivery list. It is fairly safe to assume that the deliver methods themselves do their job -- what we are probably more interested in is whether our own business logic is sending emails when we expect them to. For example the password reset operation we used an example in the previous section will probably be called in response to a user requesting a password reset through some sort of controller. + +[source, ruby] +---------------------------------------------------------------- +require File.dirname(__FILE__) + '/../test_helper' +require 'my_controller' + +# Raise errors beyond the default web-based presentation +class MyController; def rescue_action(e) raise e end; end + +class MyControllerTest < Test::Unit::TestCase + + def setup + @controller = MyController.new + @request, @response = ActionController::TestRequest.new, ActionController::TestResponse.new + end + + def test_reset_password + num_deliveries = ActionMailer::Base.deliveries.size + post :reset_password, :email => 'bob@test.com' + + assert_equal num_deliveries+1, ActionMailer::Base.deliveries.size + end + +end +---------------------------------------------------------------- + +=== Filtering emails in development === + +Sometimes you want to be somewhere inbetween the `:test` and `:smtp` settings. Say you're working on your development site, and you have a few testers working with you. The site isn't in production yet, but you'd like the testers to be able to receive emails from the site, but no one else. Here's a handy way to handle that situation, add this to your 'environment.rb' or 'development.rb' file + +[source, ruby] +---------------------------------------------------------------- +class ActionMailer::Base + + def perform_delivery_fixed_email(mail) + destinations = mail.destinations + if destinations.nil? + destinations = ["mymail@me.com"] + mail.subject = '[TEST-FAILURE]:'+mail.subject + else + mail.subject = '[TEST]:'+mail.subject + end + approved = ["testerone@me.com","testertwo@me.com"] + destinations = destinations.collect{|x| approved.collect{|y| (x==y ? x : nil)}}.flatten.compact + mail.to = destinations + if destinations.size > 0 + mail.ready_to_send + Net::SMTP.start(server_settings[:address], server_settings[:port], server_settings[:domain], + server_settings[:user_name], server_settings[:password], server_settings[:authentication]) do |smtp| + smtp.sendmail(mail.encoded, mail.from, destinations) + end + end + + end + +end +---------------------------------------------------------------- + diff --git a/railties/environments/boot.rb b/railties/environments/boot.rb index cd21fb9eab..6a30b54973 100644 --- a/railties/environments/boot.rb +++ b/railties/environments/boot.rb @@ -82,14 +82,14 @@ module Rails def load_rubygems require 'rubygems' - - unless rubygems_version >= '0.9.4' - $stderr.puts %(Rails requires RubyGems >= 0.9.4 (you have #{rubygems_version}). Please `gem update --system` and try again.) + min_version = '1.1.1' + unless rubygems_version >= min_version + $stderr.puts %Q(Rails requires RubyGems >= #{min_version} (you have #{rubygems_version}). Please `gem update --system` and try again.) exit 1 end rescue LoadError - $stderr.puts %(Rails requires RubyGems >= 0.9.4. Please install RubyGems and try again: http://rubygems.rubyforge.org) + $stderr.puts %Q(Rails requires RubyGems >= #{min_version}. Please install RubyGems and try again: http://rubygems.rubyforge.org) exit 1 end diff --git a/railties/environments/production.rb b/railties/environments/production.rb index 69c8b9ecb6..ec5b7bc865 100644 --- a/railties/environments/production.rb +++ b/railties/environments/production.rb @@ -4,13 +4,15 @@ # Code is not reloaded between requests config.cache_classes = true +# Enable threaded mode +# config.threadsafe! + # Use a different logger for distributed setups # config.logger = SyslogLogger.new # Full error reports are disabled and caching is turned on config.action_controller.consider_all_requests_local = false config.action_controller.perform_caching = true -config.action_view.cache_template_loading = true # Use a different cache store in production # config.cache_store = :mem_cache_store diff --git a/railties/helpers/performance_test_helper.rb b/railties/helpers/performance_test_helper.rb index f1662fa30a..1aafc7f7e5 100644 --- a/railties/helpers/performance_test_helper.rb +++ b/railties/helpers/performance_test_helper.rb @@ -1,7 +1,2 @@ require 'test_helper' -require 'action_controller/performance_test' - -ActionController::Base.perform_caching = true -ActionView::Base.cache_template_loading = true -ActiveSupport::Dependencies.mechanism = :require -Rails.logger.level = ActiveSupport::BufferedLogger::INFO +require 'performance_test_help' diff --git a/railties/html/500.html b/railties/html/500.html index 0e9c14f4c6..74142cb04a 100644 --- a/railties/html/500.html +++ b/railties/html/500.html @@ -25,6 +25,9 @@ <div class="dialog"> <h1>We're sorry, but something went wrong.</h1> <p>We've been notified about this issue and we'll take a look at it shortly.</p> + <p><small>(If you're the administrator of this website, then please read + the log file "<%= "<%s>" % "%=h RAILS_ENV %" %>.log" + to find out what went wrong.)</small></p> </div> </body> -</html>
\ No newline at end of file +</html> diff --git a/railties/html/javascripts/prototype.js b/railties/html/javascripts/prototype.js index 546f9fe449..2c70b8a7e8 100644 --- a/railties/html/javascripts/prototype.js +++ b/railties/html/javascripts/prototype.js @@ -1,5 +1,5 @@ -/* Prototype JavaScript framework, version 1.6.0.1 - * (c) 2005-2007 Sam Stephenson +/* Prototype JavaScript framework, version 1.6.0.2 + * (c) 2005-2008 Sam Stephenson * * Prototype is freely distributable under the terms of an MIT-style license. * For details, see the Prototype web site: http://www.prototypejs.org/ @@ -7,7 +7,7 @@ *--------------------------------------------------------------------------*/ var Prototype = { - Version: '1.6.0.1', + Version: '1.6.0.2', Browser: { IE: !!(window.attachEvent && !window.opera), @@ -110,7 +110,7 @@ Object.extend(Object, { try { if (Object.isUndefined(object)) return 'undefined'; if (object === null) return 'null'; - return object.inspect ? object.inspect() : object.toString(); + return object.inspect ? object.inspect() : String(object); } catch (e) { if (e instanceof RangeError) return '...'; throw e; @@ -171,7 +171,8 @@ Object.extend(Object, { }, isArray: function(object) { - return object && object.constructor === Array; + return object != null && typeof object == "object" && + 'splice' in object && 'join' in object; }, isHash: function(object) { @@ -578,7 +579,7 @@ var Template = Class.create({ } return before + String.interpret(ctx); - }.bind(this)); + }); } }); Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/; @@ -806,20 +807,20 @@ Object.extend(Enumerable, { function $A(iterable) { if (!iterable) return []; if (iterable.toArray) return iterable.toArray(); - var length = iterable.length, results = new Array(length); + var length = iterable.length || 0, results = new Array(length); while (length--) results[length] = iterable[length]; return results; } if (Prototype.Browser.WebKit) { - function $A(iterable) { + $A = function(iterable) { if (!iterable) return []; if (!(Object.isFunction(iterable) && iterable == '[object NodeList]') && iterable.toArray) return iterable.toArray(); - var length = iterable.length, results = new Array(length); + var length = iterable.length || 0, results = new Array(length); while (length--) results[length] = iterable[length]; return results; - } + }; } Array.from = $A; @@ -1298,7 +1299,7 @@ Ajax.Request = Class.create(Ajax.Base, { var contentType = response.getHeader('Content-type'); if (this.options.evalJS == 'force' - || (this.options.evalJS && contentType + || (this.options.evalJS && this.isSameOrigin() && contentType && contentType.match(/^\s*(text|application)\/(x-)?(java|ecma)script(;.*)?\s*$/i))) this.evalResponse(); } @@ -1316,9 +1317,18 @@ Ajax.Request = Class.create(Ajax.Base, { } }, + isSameOrigin: function() { + var m = this.url.match(/^\s*https?:\/\/[^\/]*/); + return !m || (m[0] == '#{protocol}//#{domain}#{port}'.interpolate({ + protocol: location.protocol, + domain: document.domain, + port: location.port ? ':' + location.port : '' + })); + }, + getHeader: function(name) { try { - return this.transport.getResponseHeader(name); + return this.transport.getResponseHeader(name) || null; } catch (e) { return null } }, @@ -1391,7 +1401,8 @@ Ajax.Response = Class.create({ if (!json) return null; json = decodeURIComponent(escape(json)); try { - return json.evalJSON(this.request.options.sanitizeJSON); + return json.evalJSON(this.request.options.sanitizeJSON || + !this.request.isSameOrigin()); } catch (e) { this.request.dispatchException(e); } @@ -1404,7 +1415,8 @@ Ajax.Response = Class.create({ this.responseText.blank()) return null; try { - return this.responseText.evalJSON(options.sanitizeJSON); + return this.responseText.evalJSON(options.sanitizeJSON || + !this.request.isSameOrigin()); } catch (e) { this.request.dispatchException(e); } @@ -1608,24 +1620,28 @@ Element.Methods = { Object.isElement(insertions) || (insertions && (insertions.toElement || insertions.toHTML))) insertions = {bottom:insertions}; - var content, t, range; + var content, insert, tagName, childNodes; - for (position in insertions) { + for (var position in insertions) { content = insertions[position]; position = position.toLowerCase(); - t = Element._insertionTranslations[position]; + insert = Element._insertionTranslations[position]; if (content && content.toElement) content = content.toElement(); if (Object.isElement(content)) { - t.insert(element, content); + insert(element, content); continue; } content = Object.toHTML(content); - range = element.ownerDocument.createRange(); - t.initializeRange(element, range); - t.insert(element, range.createContextualFragment(content.stripScripts())); + tagName = ((position == 'before' || position == 'after') + ? element.parentNode : element).tagName.toUpperCase(); + + childNodes = Element._getContentFromAnonymousElement(tagName, content.stripScripts()); + + if (position == 'top' || position == 'after') childNodes.reverse(); + childNodes.each(insert.curry(element)); content.evalScripts.bind(content).defer(); } @@ -1670,7 +1686,7 @@ Element.Methods = { }, descendants: function(element) { - return $(element).getElementsBySelector("*"); + return $(element).select("*"); }, firstDescendant: function(element) { @@ -1709,32 +1725,31 @@ Element.Methods = { element = $(element); if (arguments.length == 1) return $(element.parentNode); var ancestors = element.ancestors(); - return expression ? Selector.findElement(ancestors, expression, index) : - ancestors[index || 0]; + return Object.isNumber(expression) ? ancestors[expression] : + Selector.findElement(ancestors, expression, index); }, down: function(element, expression, index) { element = $(element); if (arguments.length == 1) return element.firstDescendant(); - var descendants = element.descendants(); - return expression ? Selector.findElement(descendants, expression, index) : - descendants[index || 0]; + return Object.isNumber(expression) ? element.descendants()[expression] : + element.select(expression)[index || 0]; }, previous: function(element, expression, index) { element = $(element); if (arguments.length == 1) return $(Selector.handlers.previousElementSibling(element)); var previousSiblings = element.previousSiblings(); - return expression ? Selector.findElement(previousSiblings, expression, index) : - previousSiblings[index || 0]; + return Object.isNumber(expression) ? previousSiblings[expression] : + Selector.findElement(previousSiblings, expression, index); }, next: function(element, expression, index) { element = $(element); if (arguments.length == 1) return $(Selector.handlers.nextElementSibling(element)); var nextSiblings = element.nextSiblings(); - return expression ? Selector.findElement(nextSiblings, expression, index) : - nextSiblings[index || 0]; + return Object.isNumber(expression) ? nextSiblings[expression] : + Selector.findElement(nextSiblings, expression, index); }, select: function() { @@ -1860,7 +1875,8 @@ Element.Methods = { do { ancestor = ancestor.parentNode; } while (!(nextAncestor = ancestor.nextSibling) && ancestor.parentNode); } - if (nextAncestor) return (e > a && e < nextAncestor.sourceIndex); + if (nextAncestor && nextAncestor.sourceIndex) + return (e > a && e < nextAncestor.sourceIndex); } while (element = element.parentNode) @@ -2004,7 +2020,7 @@ Element.Methods = { if (element) { if (element.tagName == 'BODY') break; var p = Element.getStyle(element, 'position'); - if (p == 'relative' || p == 'absolute') break; + if (p !== 'static') break; } } while (element); return Element._returnOffset(valueL, valueT); @@ -2153,46 +2169,6 @@ Element._attributeTranslations = { } }; - -if (!document.createRange || Prototype.Browser.Opera) { - Element.Methods.insert = function(element, insertions) { - element = $(element); - - if (Object.isString(insertions) || Object.isNumber(insertions) || - Object.isElement(insertions) || (insertions && (insertions.toElement || insertions.toHTML))) - insertions = { bottom: insertions }; - - var t = Element._insertionTranslations, content, position, pos, tagName; - - for (position in insertions) { - content = insertions[position]; - position = position.toLowerCase(); - pos = t[position]; - - if (content && content.toElement) content = content.toElement(); - if (Object.isElement(content)) { - pos.insert(element, content); - continue; - } - - content = Object.toHTML(content); - tagName = ((position == 'before' || position == 'after') - ? element.parentNode : element).tagName.toUpperCase(); - - if (t.tags[tagName]) { - var fragments = Element._getContentFromAnonymousElement(tagName, content.stripScripts()); - if (position == 'top' || position == 'after') fragments.reverse(); - fragments.each(pos.insert.curry(element)); - } - else element.insertAdjacentHTML(pos.adjacency, content.stripScripts()); - - content.evalScripts.bind(content).defer(); - } - - return element; - }; -} - if (Prototype.Browser.Opera) { Element.Methods.getStyle = Element.Methods.getStyle.wrap( function(proceed, element, style) { @@ -2237,12 +2213,31 @@ if (Prototype.Browser.Opera) { } else if (Prototype.Browser.IE) { - $w('positionedOffset getOffsetParent viewportOffset').each(function(method) { + // IE doesn't report offsets correctly for static elements, so we change them + // to "relative" to get the values, then change them back. + Element.Methods.getOffsetParent = Element.Methods.getOffsetParent.wrap( + function(proceed, element) { + element = $(element); + 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); var position = element.getStyle('position'); - if (position != 'static') return proceed(element); + if (position !== 'static') return proceed(element); + // Trigger hasLayout on the offset parent so that IE6 reports + // accurate offsetTop and offsetLeft values for position: fixed. + 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 }); @@ -2324,7 +2319,10 @@ else if (Prototype.Browser.IE) { }; Element._attributeTranslations.write = { - names: Object.clone(Element._attributeTranslations.read.names), + names: Object.extend({ + cellpadding: 'cellPadding', + cellspacing: 'cellSpacing' + }, Element._attributeTranslations.read.names), values: { checked: function(element, value) { element.checked = !!value; @@ -2444,7 +2442,7 @@ if (Prototype.Browser.IE || Prototype.Browser.Opera) { }; } -if (document.createElement('div').outerHTML) { +if ('outerHTML' in document.createElement('div')) { Element.Methods.replace = function(element, content) { element = $(element); @@ -2482,45 +2480,25 @@ Element._returnOffset = function(l, t) { Element._getContentFromAnonymousElement = function(tagName, html) { var div = new Element('div'), t = Element._insertionTranslations.tags[tagName]; - div.innerHTML = t[0] + html + t[1]; - t[2].times(function() { div = div.firstChild }); + if (t) { + div.innerHTML = t[0] + html + t[1]; + t[2].times(function() { div = div.firstChild }); + } else div.innerHTML = html; return $A(div.childNodes); }; Element._insertionTranslations = { - before: { - adjacency: 'beforeBegin', - insert: function(element, node) { - element.parentNode.insertBefore(node, element); - }, - initializeRange: function(element, range) { - range.setStartBefore(element); - } + before: function(element, node) { + element.parentNode.insertBefore(node, element); }, - top: { - adjacency: 'afterBegin', - insert: function(element, node) { - element.insertBefore(node, element.firstChild); - }, - initializeRange: function(element, range) { - range.selectNodeContents(element); - range.collapse(true); - } + top: function(element, node) { + element.insertBefore(node, element.firstChild); }, - bottom: { - adjacency: 'beforeEnd', - insert: function(element, node) { - element.appendChild(node); - } + bottom: function(element, node) { + element.appendChild(node); }, - after: { - adjacency: 'afterEnd', - insert: function(element, node) { - element.parentNode.insertBefore(node, element.nextSibling); - }, - initializeRange: function(element, range) { - range.setStartAfter(element); - } + after: function(element, node) { + element.parentNode.insertBefore(node, element.nextSibling); }, tags: { TABLE: ['<table>', '</table>', 1], @@ -2532,7 +2510,6 @@ Element._insertionTranslations = { }; (function() { - this.bottom.initializeRange = this.top.initializeRange; Object.extend(this.tags, { THEAD: this.tags.TBODY, TFOOT: this.tags.TBODY, @@ -2716,7 +2693,7 @@ document.viewport = { window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop); } }; -/* Portions of the Selector class are derived from Jack Slocum’s DomQuery, +/* Portions of the Selector class are derived from Jack Slocum’s DomQuery, * part of YUI-Ext version 0.40, distributed under the terms of an MIT-style * license. Please see http://www.yui-ext.com/ for more information. */ @@ -2959,13 +2936,13 @@ Object.extend(Selector, { }, criteria: { - tagName: 'n = h.tagName(n, r, "#{1}", c); c = false;', - className: 'n = h.className(n, r, "#{1}", c); c = false;', - id: 'n = h.id(n, r, "#{1}", c); c = false;', - attrPresence: 'n = h.attrPresence(n, r, "#{1}"); c = false;', + tagName: 'n = h.tagName(n, r, "#{1}", c); c = false;', + className: 'n = h.className(n, r, "#{1}", c); c = false;', + id: 'n = h.id(n, r, "#{1}", c); c = false;', + attrPresence: 'n = h.attrPresence(n, r, "#{1}", c); c = false;', attr: function(m) { m[3] = (m[5] || m[6]); - return new Template('n = h.attr(n, r, "#{1}", "#{3}", "#{2}"); c = false;').evaluate(m); + return new Template('n = h.attr(n, r, "#{1}", "#{3}", "#{2}", c); c = false;').evaluate(m); }, pseudo: function(m) { if (m[6]) m[6] = m[6].replace(/"/g, '\\"'); @@ -2989,7 +2966,8 @@ Object.extend(Selector, { tagName: /^\s*(\*|[\w\-]+)(\b|$)?/, id: /^#([\w\-\*]+)(\b|$)/, className: /^\.([\w\-\*]+)(\b|$)/, - pseudo: /^:((first|last|nth|nth-last|only)(-child|-of-type)|empty|checked|(en|dis)abled|not)(\((.*?)\))?(\b|$|(?=\s)|(?=:))/, + pseudo: +/^:((first|last|nth|nth-last|only)(-child|-of-type)|empty|checked|(en|dis)abled|not)(\((.*?)\))?(\b|$|(?=\s|[:+~>]))/, attrPresence: /^\[([\w]+)\]/, attr: /\[((?:[\w-]*:)?[\w-]+)\s*(?:([!^$*~|]?=)\s*((['"])([^\4]*?)\4|([^'"][^\]]*?)))?\]/ }, @@ -3014,7 +2992,7 @@ Object.extend(Selector, { attr: function(element, matches) { var nodeValue = Element.readAttribute(element, matches[1]); - return Selector.operators[matches[2]](nodeValue, matches[3]); + return nodeValue && Selector.operators[matches[2]](nodeValue, matches[5] || matches[6]); } }, @@ -3029,14 +3007,15 @@ Object.extend(Selector, { // marks an array of nodes for counting mark: function(nodes) { + var _true = Prototype.emptyFunction; for (var i = 0, node; node = nodes[i]; i++) - node._counted = true; + node._countedByPrototype = _true; return nodes; }, unmark: function(nodes) { for (var i = 0, node; node = nodes[i]; i++) - node._counted = undefined; + node._countedByPrototype = undefined; return nodes; }, @@ -3044,15 +3023,15 @@ Object.extend(Selector, { // "ofType" flag indicates whether we're indexing for nth-of-type // rather than nth-child index: function(parentNode, reverse, ofType) { - parentNode._counted = true; + parentNode._countedByPrototype = Prototype.emptyFunction; if (reverse) { for (var nodes = parentNode.childNodes, i = nodes.length - 1, j = 1; i >= 0; i--) { var node = nodes[i]; - if (node.nodeType == 1 && (!ofType || node._counted)) node.nodeIndex = j++; + if (node.nodeType == 1 && (!ofType || node._countedByPrototype)) node.nodeIndex = j++; } } else { for (var i = 0, j = 1, nodes = parentNode.childNodes; node = nodes[i]; i++) - if (node.nodeType == 1 && (!ofType || node._counted)) node.nodeIndex = j++; + if (node.nodeType == 1 && (!ofType || node._countedByPrototype)) node.nodeIndex = j++; } }, @@ -3061,8 +3040,8 @@ Object.extend(Selector, { if (nodes.length == 0) return nodes; var results = [], n; for (var i = 0, l = nodes.length; i < l; i++) - if (!(n = nodes[i])._counted) { - n._counted = true; + if (!(n = nodes[i])._countedByPrototype) { + n._countedByPrototype = Prototype.emptyFunction; results.push(Element.extend(n)); } return Selector.handlers.unmark(results); @@ -3114,7 +3093,7 @@ Object.extend(Selector, { // TOKEN FUNCTIONS tagName: function(nodes, root, tagName, combinator) { - tagName = tagName.toUpperCase(); + var uTagName = tagName.toUpperCase(); var results = [], h = Selector.handlers; if (nodes) { if (combinator) { @@ -3127,7 +3106,7 @@ Object.extend(Selector, { if (tagName == "*") return nodes; } for (var i = 0, node; node = nodes[i]; i++) - if (node.tagName.toUpperCase() == tagName) results.push(node); + if (node.tagName.toUpperCase() === uTagName) results.push(node); return results; } else return root.getElementsByTagName(tagName); }, @@ -3174,16 +3153,18 @@ Object.extend(Selector, { return results; }, - attrPresence: function(nodes, root, attr) { + attrPresence: function(nodes, root, attr, combinator) { if (!nodes) nodes = root.getElementsByTagName("*"); + if (nodes && combinator) nodes = this[combinator](nodes); var results = []; for (var i = 0, node; node = nodes[i]; i++) if (Element.hasAttribute(node, attr)) results.push(node); return results; }, - attr: function(nodes, root, attr, value, operator) { + attr: function(nodes, root, attr, value, operator, combinator) { if (!nodes) nodes = root.getElementsByTagName("*"); + if (nodes && combinator) nodes = this[combinator](nodes); var handler = Selector.operators[operator], results = []; for (var i = 0, node; node = nodes[i]; i++) { var nodeValue = Element.readAttribute(node, attr); @@ -3262,7 +3243,7 @@ Object.extend(Selector, { var h = Selector.handlers, results = [], indexed = [], m; h.mark(nodes); for (var i = 0, node; node = nodes[i]; i++) { - if (!node.parentNode._counted) { + if (!node.parentNode._countedByPrototype) { h.index(node.parentNode, reverse, ofType); indexed.push(node.parentNode); } @@ -3300,7 +3281,7 @@ Object.extend(Selector, { var exclusions = new Selector(selector).findElements(root); h.mark(exclusions); for (var i = 0, results = [], node; node = nodes[i]; i++) - if (!node._counted) results.push(node); + if (!node._countedByPrototype) results.push(node); h.unmark(exclusions); return results; }, @@ -3334,11 +3315,19 @@ Object.extend(Selector, { '|=': function(nv, v) { return ('-' + nv.toUpperCase() + '-').include('-' + v.toUpperCase() + '-'); } }, + split: function(expression) { + var expressions = []; + expression.scan(/(([\w#:.~>+()\s-]+|\*|\[.*?\])+)\s*(,|$)/, function(m) { + expressions.push(m[1].strip()); + }); + return expressions; + }, + matchElements: function(elements, expression) { - var matches = new Selector(expression).findElements(), h = Selector.handlers; + var matches = $$(expression), h = Selector.handlers; h.mark(matches); for (var i = 0, results = [], element; element = elements[i]; i++) - if (element._counted) results.push(element); + if (element._countedByPrototype) results.push(element); h.unmark(matches); return results; }, @@ -3351,11 +3340,7 @@ Object.extend(Selector, { }, findChildElements: function(element, expressions) { - var exprs = expressions.join(','); - expressions = []; - exprs.scan(/(([\w#:.~>+()\s-]+|\*|\[.*?\])+)\s*(,|$)/, function(m) { - expressions.push(m[1].strip()); - }); + expressions = Selector.split(expressions.join(',')); var results = [], h = Selector.handlers; for (var i = 0, l = expressions.length, selector; i < l; i++) { selector = new Selector(expressions[i].strip()); @@ -3366,13 +3351,22 @@ Object.extend(Selector, { }); if (Prototype.Browser.IE) { - // IE returns comment nodes on getElementsByTagName("*"). - // Filter them out. - Selector.handlers.concat = function(a, b) { - for (var i = 0, node; node = b[i]; i++) - if (node.tagName !== "!") a.push(node); - return a; - }; + Object.extend(Selector.handlers, { + // IE returns comment nodes on getElementsByTagName("*"). + // Filter them out. + concat: function(a, b) { + for (var i = 0, node; node = b[i]; i++) + if (node.tagName !== "!") a.push(node); + return a; + }, + + // IE improperly serializes _countedByPrototype in (inner|outer)HTML. + unmark: function(nodes) { + for (var i = 0, node; node = nodes[i]; i++) + node.removeAttribute('_countedByPrototype'); + return nodes; + } + }); } function $$() { @@ -3850,9 +3844,9 @@ Object.extend(Event, (function() { var cache = Event.cache; function getEventID(element) { - if (element._eventID) return element._eventID; + if (element._prototypeEventID) return element._prototypeEventID[0]; arguments.callee.id = arguments.callee.id || 1; - return element._eventID = ++arguments.callee.id; + return element._prototypeEventID = [++arguments.callee.id]; } function getDOMEventName(eventName) { @@ -3880,7 +3874,7 @@ Object.extend(Event, (function() { return false; Event.extend(event); - handler.call(element, event) + handler.call(element, event); }; wrapper.handler = handler; @@ -3962,11 +3956,12 @@ Object.extend(Event, (function() { if (element == document && document.createEvent && !element.dispatchEvent) element = document.documentElement; + var event; if (document.createEvent) { - var event = document.createEvent("HTMLEvents"); + event = document.createEvent("HTMLEvents"); event.initEvent("dataavailable", true, true); } else { - var event = document.createEventObject(); + event = document.createEventObject(); event.eventType = "ondataavailable"; } @@ -3995,20 +3990,21 @@ Element.addMethods({ Object.extend(document, { fire: Element.Methods.fire.methodize(), observe: Element.Methods.observe.methodize(), - stopObserving: Element.Methods.stopObserving.methodize() + stopObserving: Element.Methods.stopObserving.methodize(), + loaded: false }); (function() { /* Support for the DOMContentLoaded event is based on work by Dan Webb, Matthias Miller, Dean Edwards and John Resig. */ - var timer, fired = false; + var timer; function fireContentLoadedEvent() { - if (fired) return; + if (document.loaded) return; if (timer) window.clearInterval(timer); document.fire("dom:loaded"); - fired = true; + document.loaded = true; } if (document.addEventListener) { diff --git a/railties/lib/commands/dbconsole.rb b/railties/lib/commands/dbconsole.rb index 17acb7b68f..5be3b5dd8e 100644 --- a/railties/lib/commands/dbconsole.rb +++ b/railties/lib/commands/dbconsole.rb @@ -41,11 +41,13 @@ when "mysql" if config['password'] && include_password args << "--password=#{config['password']}" + elsif config['password'] && !config['password'].empty? + args << "-p" end args << config['database'] - exec(find_cmd('mysql5', 'mysql'), *args) + exec(find_cmd('mysql', 'mysql5'), *args) when "postgresql" ENV['PGUSER'] = config["username"] if config["username"] diff --git a/railties/lib/commands/ncgi/listener b/railties/lib/commands/ncgi/listener index 421c453f23..7079ef78a6 100644..100755 --- a/railties/lib/commands/ncgi/listener +++ b/railties/lib/commands/ncgi/listener @@ -1,4 +1,4 @@ -#!/usr/local/bin/ruby +#!/usr/bin/env ruby require 'stringio' require 'fileutils' @@ -83,4 +83,4 @@ end socket_path = ARGV.shift timeout = (ARGV.shift || 90).to_i -Listener.new(timeout, socket_path)
\ No newline at end of file +Listener.new(timeout, socket_path) diff --git a/railties/lib/commands/ncgi/tracker b/railties/lib/commands/ncgi/tracker index 859c9fa0e0..4ca12d779b 100644..100755 --- a/railties/lib/commands/ncgi/tracker +++ b/railties/lib/commands/ncgi/tracker @@ -1,4 +1,4 @@ -#!/usr/local/bin/ruby +#!/usr/bin/env ruby require 'drb' require 'thread' @@ -66,4 +66,4 @@ end socket_path = ARGV.shift instances = ARGV.shift.to_i t = Tracker.new(instances, socket_path) -t.background(ARGV.first ? ARGV.shift.to_i : 90)
\ No newline at end of file +t.background(ARGV.first ? ARGV.shift.to_i : 90) diff --git a/railties/lib/commands/plugin.rb b/railties/lib/commands/plugin.rb index 0256090d16..980244a71b 100644 --- a/railties/lib/commands/plugin.rb +++ b/railties/lib/commands/plugin.rb @@ -907,7 +907,7 @@ class RecursiveHTTPFetcher def ls @urls_to_fetch.collect do |url| - if url =~ /^svn:\/\/.*/ + if url =~ /^svn(\+ssh)?:\/\/.*/ `svn ls #{url}`.split("\n").map {|entry| "/#{entry}"} rescue nil else open(url) do |stream| diff --git a/railties/lib/commands/process/spawner.rb b/railties/lib/commands/process/spawner.rb index fd09daa55b..dc0008698a 100644 --- a/railties/lib/commands/process/spawner.rb +++ b/railties/lib/commands/process/spawner.rb @@ -66,9 +66,9 @@ class MongrelSpawner < Spawner "-l #{OPTIONS[:rails_root]}/log/mongrel.log" # Add prefix functionality to spawner's call to mongrel_rails - # Digging through monrel's project subversion server, the earliest + # Digging through mongrel's project subversion server, the earliest # Tag that has prefix implemented in the bin/mongrel_rails file - # is 0.3.15 which also happens to be the earilest tag listed. + # is 0.3.15 which also happens to be the earliest tag listed. # References: http://mongrel.rubyforge.org/svn/tags if Mongrel::Const::MONGREL_VERSION.to_f >=0.3 && !OPTIONS[:prefix].nil? cmd = cmd + " --prefix #{OPTIONS[:prefix]}" diff --git a/railties/lib/commands/runner.rb b/railties/lib/commands/runner.rb index 926bc26344..14159c3893 100644 --- a/railties/lib/commands/runner.rb +++ b/railties/lib/commands/runner.rb @@ -42,7 +42,7 @@ if code_or_file.nil? $stderr.puts "Run '#{$0} -h' for help." exit 1 elsif File.exist?(code_or_file) - eval(File.read(code_or_file)) + eval(File.read(code_or_file), nil, code_or_file) else eval(code_or_file) end diff --git a/railties/lib/commands/server.rb b/railties/lib/commands/server.rb index 7306c248fb..15f417b5be 100644 --- a/railties/lib/commands/server.rb +++ b/railties/lib/commands/server.rb @@ -23,10 +23,10 @@ server = case ARGV.first when "lighttpd", "mongrel", "new_mongrel", "webrick", "thin" ARGV.shift else - if defined?(Thin) - "thin" - elsif defined?(Mongrel) + if defined?(Mongrel) "mongrel" + elsif defined?(Thin) + "thin" elsif RUBY_PLATFORM !~ /(:?mswin|mingw)/ && !silence_stderr { `lighttpd -version` }.blank? && defined?(FCGI) "lighttpd" else diff --git a/railties/lib/fcgi_handler.rb b/railties/lib/fcgi_handler.rb index 722aa1940c..1bb55b9275 100644 --- a/railties/lib/fcgi_handler.rb +++ b/railties/lib/fcgi_handler.rb @@ -18,7 +18,6 @@ class RailsFCGIHandler attr_accessor :log_file_path attr_accessor :gc_request_period - # Initialize and run the FastCGI instance, passing arguments through to new. def self.process!(*args, &block) new(*args, &block).process! @@ -68,7 +67,6 @@ class RailsFCGIHandler end end - protected def process_each_request(provider) cgi = nil @@ -197,7 +195,7 @@ class RailsFCGIHandler # close resources as they won't be closed by # the OS when using exec logger.close rescue nil - RAILS_DEFAULT_LOGGER.close rescue nil + Rails.logger.close rescue nil exec(command_line) end diff --git a/railties/lib/initializer.rb b/railties/lib/initializer.rb index 18bcf69d69..008f1de8fa 100644 --- a/railties/lib/initializer.rb +++ b/railties/lib/initializer.rb @@ -33,7 +33,11 @@ module Rails end def logger - RAILS_DEFAULT_LOGGER + if defined?(RAILS_DEFAULT_LOGGER) + RAILS_DEFAULT_LOGGER + else + nil + end end def root @@ -45,6 +49,7 @@ module Rails end def env + require 'active_support/string_inquirer' ActiveSupport::StringInquirer.new(RAILS_ENV) end @@ -98,7 +103,7 @@ module Rails # Rails::Initializer.run(:set_load_path) # # This is useful if you only want the load path initialized, without - # incuring the overhead of completely loading the entire environment. + # incurring the overhead of completely loading the entire environment. def self.run(command = :process, configuration = Configuration.new) yield configuration if block_given? initializer = new configuration @@ -168,6 +173,15 @@ module Rails # Observers are loaded after plugins in case Observers or observed models are modified by plugins. load_observers + # Load view path cache + load_view_paths + + # Load application classes + load_application_classes + + # Disable dependency loading during request cycle + disable_dependency_loading + # Flag initialized Rails.initialized = true end @@ -266,11 +280,16 @@ module Rails @gems_dependencies_loaded = false # don't print if the gems rake tasks are being run unless $rails_gem_installer - puts %{These gems that this application depends on are missing:} - unloaded_gems.each do |gem| - puts " - #{gem.name}" - end - puts %{Run "rake gems:install" to install them.} + abort <<-end_error +Missing these required gems: + #{unloaded_gems.map { |gem| "#{gem.name} #{gem.requirement}" } * "\n "} + +You're running: + ruby #{Gem.ruby_version} at #{Gem.ruby} + rubygems #{Gem::RubyGemsVersion} at #{Gem.path * ', '} + +Run `rake gems:install` to install the missing gems. + end_error end else @gems_dependencies_loaded = true @@ -325,6 +344,26 @@ module Rails end end + def load_view_paths + if configuration.frameworks.include?(:action_view) + ActionView::PathSet::Path.eager_load_templates! if configuration.cache_classes + ActionController::Base.view_paths.load if configuration.frameworks.include?(:action_controller) + ActionMailer::Base.template_root.load if configuration.frameworks.include?(:action_mailer) + end + end + + # Eager load application classes + def load_application_classes + if configuration.cache_classes + configuration.eager_load_paths.each do |load_path| + matcher = /\A#{Regexp.escape(load_path)}(.*)\.rb\Z/ + Dir.glob("#{load_path}/**/*.rb").sort.each do |file| + require_dependency file.sub(matcher, '\1') + end + end + end + end + # For Ruby 1.8, this initialization sets $KCODE to 'u' to enable the # multibyte safe operations. Plugin authors supporting other encodings # should override this behaviour and set the relevant +default_charset+ @@ -369,7 +408,7 @@ module Rails # +STDERR+, with a log level of +WARN+. def initialize_logger # if the environment has explicitly defined a logger, use it - return if defined?(RAILS_DEFAULT_LOGGER) + return if Rails.logger unless logger = configuration.logger begin @@ -377,7 +416,6 @@ module Rails logger.level = ActiveSupport::BufferedLogger.const_get(configuration.log_level.to_s.upcase) if configuration.environment == "production" logger.auto_flushing = false - logger.set_non_blocking_io end rescue StandardError => e logger = ActiveSupport::BufferedLogger.new(STDERR) @@ -398,10 +436,11 @@ module Rails # RAILS_DEFAULT_LOGGER. def initialize_framework_logging for framework in ([ :active_record, :action_controller, :action_mailer ] & configuration.frameworks) - framework.to_s.camelize.constantize.const_get("Base").logger ||= RAILS_DEFAULT_LOGGER + framework.to_s.camelize.constantize.const_get("Base").logger ||= Rails.logger end - RAILS_CACHE.logger ||= RAILS_DEFAULT_LOGGER + ActiveSupport::Dependencies.logger ||= Rails.logger + Rails.cache.logger ||= Rails.logger end # Sets +ActionController::Base#view_paths+ and +ActionMailer::Base#template_root+ @@ -409,8 +448,11 @@ module Rails # paths have already been set, it is not changed, otherwise it is # set to use Configuration#view_path. def initialize_framework_views - ActionMailer::Base.template_root ||= configuration.view_path if configuration.frameworks.include?(:action_mailer) - ActionController::Base.view_paths = [configuration.view_path] if configuration.frameworks.include?(:action_controller) && ActionController::Base.view_paths.empty? + if configuration.frameworks.include?(:action_view) + view_path = ActionView::PathSet::Path.new(configuration.view_path, false) + ActionMailer::Base.template_root ||= view_path if configuration.frameworks.include?(:action_mailer) + ActionController::Base.view_paths = view_path if configuration.frameworks.include?(:action_controller) && ActionController::Base.view_paths.empty? + end end # If Action Controller is not one of the loaded frameworks (Configuration#frameworks) @@ -492,9 +534,16 @@ module Rails end def prepare_dispatcher + return unless configuration.frameworks.include?(:action_controller) require 'dispatcher' unless defined?(::Dispatcher) Dispatcher.define_dispatcher_callbacks(configuration.cache_classes) - Dispatcher.new(RAILS_DEFAULT_LOGGER).send :run_callbacks, :prepare_dispatch + Dispatcher.new(Rails.logger).send :run_callbacks, :prepare_dispatch + end + + def disable_dependency_loading + if configuration.cache_classes && !configuration.dependency_loading + ActiveSupport::Dependencies.unhook! + end end end @@ -523,7 +572,7 @@ module Rails # A stub for setting options on ActiveRecord::Base. attr_accessor :active_record - # A stub for setting options on ActiveRecord::Base. + # A stub for setting options on ActiveResource::Base. attr_accessor :active_resource # A stub for setting options on ActiveSupport. @@ -559,6 +608,11 @@ module Rails # All elements of this array must also be in +load_paths+. attr_accessor :load_once_paths + # 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+. + attr_accessor :eager_load_paths + # The log level to use for the default Rails logger. In production mode, # this defaults to <tt>:info</tt>. In development mode, it defaults to # <tt>:debug</tt>. @@ -625,6 +679,17 @@ module Rails !!@reload_plugins end + # Enables or disables dependency loading during the request cycle. Setting + # <tt>dependency_loading</tt> to true will allow new classes to be loaded + # during a request. Setting it to false will disable this behavior. + # + # Those who want to run in a threaded environment should disable this + # option and eager load or require all there classes on initialization. + # + # If <tt>cache_classes</tt> is disabled, dependency loaded will always be + # on. + attr_accessor :dependency_loading + # An array of gems that this rails application depends on. Rails will automatically load # these gems during installation, and allow you to install any missing gems with: # @@ -633,13 +698,17 @@ module Rails # You can add gems with the #gem method. attr_accessor :gems - # Adds a single Gem dependency to the rails application. + # Adds a single Gem dependency to the rails application. By default, it will require + # the library with the same name as the gem. Use :lib to specify a different name. # # # gem 'aws-s3', '>= 0.4.0' # # require 'aws/s3' # config.gem 'aws-s3', :lib => 'aws/s3', :version => '>= 0.4.0', \ # :source => "http://code.whytheluckystiff.net" # + # To require a library be installed, but not attempt to load it, pass :lib => false + # + # config.gem 'qrp', :version => '0.4.1', :lib => false def gem(name, options = {}) @gems << Rails::GemDependency.new(name, options) end @@ -667,11 +736,13 @@ module Rails self.frameworks = default_frameworks self.load_paths = default_load_paths self.load_once_paths = default_load_once_paths + self.eager_load_paths = default_eager_load_paths self.log_path = default_log_path self.log_level = default_log_level self.view_path = default_view_path self.controller_paths = default_controller_paths self.cache_classes = default_cache_classes + self.dependency_loading = default_dependency_loading self.whiny_nils = default_whiny_nils self.plugins = default_plugins self.plugin_paths = default_plugin_paths @@ -707,10 +778,22 @@ module Rails ::RAILS_ROOT.replace @root_path end + # Enable threaded mode. Allows concurrent requests to controller actions and + # multiple database connections. Also disables automatic dependency loading + # after boot + def threadsafe! + self.cache_classes = true + self.dependency_loading = false + self.active_record.allow_concurrency = true + self.action_controller.allow_concurrency = true + self + end + # Loads and returns the contents of the #database_configuration_file. The # contents of the file are processed via ERB before being sent through # YAML::load. def database_configuration + require 'erb' YAML::load(ERB.new(IO.read(database_configuration_file)).result) end @@ -807,6 +890,14 @@ module Rails [] end + def default_eager_load_paths + %w( + app/models + app/controllers + app/helpers + ).map { |dir| "#{root_path}/#{dir}" }.select { |dir| File.directory?(dir) } + end + def default_log_path File.join(root_path, 'log', "#{environment}.log") end @@ -833,12 +924,12 @@ module Rails paths end - def default_dependency_mechanism - :load + def default_dependency_loading + true end def default_cache_classes - false + true end def default_whiny_nils diff --git a/railties/lib/performance_test_help.rb b/railties/lib/performance_test_help.rb new file mode 100644 index 0000000000..5148b4ab77 --- /dev/null +++ b/railties/lib/performance_test_help.rb @@ -0,0 +1,5 @@ +require 'action_controller/performance_test' + +ActionController::Base.perform_caching = true +ActiveSupport::Dependencies.mechanism = :require +Rails.logger.level = ActiveSupport::BufferedLogger::INFO diff --git a/railties/lib/rails/gem_dependency.rb b/railties/lib/rails/gem_dependency.rb index f8d97840c1..471e03fa5f 100644 --- a/railties/lib/rails/gem_dependency.rb +++ b/railties/lib/rails/gem_dependency.rb @@ -58,7 +58,7 @@ module Rails def load return if @loaded || @load_paths_added == false - require(@lib || @name) + require(@lib || @name) unless @lib == false @loaded = true rescue LoadError puts $!.to_s diff --git a/railties/lib/rails/rack.rb b/railties/lib/rails/rack.rb index abcd0741bf..b4f32c2d95 100644 --- a/railties/lib/rails/rack.rb +++ b/railties/lib/rails/rack.rb @@ -1,5 +1,6 @@ module Rails module Rack + autoload :Logger, "rails/rack/logger" autoload :Static, "rails/rack/static" end end diff --git a/railties/lib/rails/rack/logger.rb b/railties/lib/rails/rack/logger.rb new file mode 100644 index 0000000000..89d02e45a9 --- /dev/null +++ b/railties/lib/rails/rack/logger.rb @@ -0,0 +1,28 @@ +module Rails + module Rack + class Logger + EnvironmentLog = "#{File.expand_path(Rails.root)}/log/#{Rails.env}.log" + + def initialize(app, log = nil) + @app = app + @path = Pathname.new(log || EnvironmentLog).cleanpath + @cursor = ::File.size(@path) + @last_checked = Time.now + end + + def call(env) + response = @app.call(env) + ::File.open(@path, 'r') do |f| + f.seek @cursor + if f.mtime > @last_checked + contents = f.read + @last_checked = f.mtime + @cursor += contents.length + print contents + end + end + response + end + end + end +end diff --git a/railties/lib/rails_generator/commands.rb b/railties/lib/rails_generator/commands.rb index d258aeaa0a..59af7308fe 100644 --- a/railties/lib/rails_generator/commands.rb +++ b/railties/lib/rails_generator/commands.rb @@ -57,6 +57,17 @@ module Rails end protected + def current_migration_number + Dir.glob("#{RAILS_ROOT}/#{@migration_directory}/[0-9]*_*.rb").inject(0) do |max, file_path| + n = File.basename(file_path).split('_', 2).first.to_i + if n > max then n else max end + end + end + + def next_migration_number + current_migration_number + 1 + end + def migration_directory(relative_path) directory(@migration_directory = relative_path) end @@ -70,7 +81,11 @@ module Rails end def next_migration_string(padding = 3) - Time.now.utc.strftime("%Y%m%d%H%M%S") + if ActiveRecord::Base.timestamped_migrations + Time.now.utc.strftime("%Y%m%d%H%M%S") + else + "%.#{padding}d" % next_migration_number + end end def gsub_file(relative_destination, regexp, *args, &block) diff --git a/railties/lib/rails_generator/generated_attribute.rb b/railties/lib/rails_generator/generated_attribute.rb index 25af3931de..a3d4a01142 100644 --- a/railties/lib/rails_generator/generated_attribute.rb +++ b/railties/lib/rails_generator/generated_attribute.rb @@ -37,6 +37,10 @@ module Rails "" end end + + def reference? + [ :references, :belongs_to ].include?(self.type) + end end end end diff --git a/railties/lib/rails_generator/generators/components/model/templates/model.rb b/railties/lib/rails_generator/generators/components/model/templates/model.rb index 8d4c89e912..6fcf393bdf 100644 --- a/railties/lib/rails_generator/generators/components/model/templates/model.rb +++ b/railties/lib/rails_generator/generators/components/model/templates/model.rb @@ -1,2 +1,5 @@ class <%= class_name %> < ActiveRecord::Base +<% attributes.select(&:reference?).each do |attribute| -%> + belongs_to :<%= attribute.name %> +<% end -%> end diff --git a/railties/lib/rails_generator/generators/components/plugin/templates/Rakefile b/railties/lib/rails_generator/generators/components/plugin/templates/Rakefile index 1824fb10fe..1824fb10fe 100755..100644 --- a/railties/lib/rails_generator/generators/components/plugin/templates/Rakefile +++ b/railties/lib/rails_generator/generators/components/plugin/templates/Rakefile diff --git a/railties/lib/rails_generator/generators/components/scaffold/USAGE b/railties/lib/rails_generator/generators/components/scaffold/USAGE index a0e4baea08..810aea16f1 100644 --- a/railties/lib/rails_generator/generators/components/scaffold/USAGE +++ b/railties/lib/rails_generator/generators/components/scaffold/USAGE @@ -1,10 +1,11 @@ Description: Scaffolds an entire resource, from model and migration to controller and views, along with a full test suite. The resource is ready to use as a - starting point for your restful, resource-oriented application. + starting point for your RESTful, resource-oriented application. - Pass the name of the model, either CamelCased or under_scored, as the first - argument, and an optional list of attribute pairs. + Pass the name of the model (in singular form), either CamelCased or + under_scored, as the first argument, and an optional list of attribute + pairs. Attribute pairs are column_name:sql_type arguments specifying the model's attributes. Timestamps are added by default, so you don't have to @@ -13,13 +14,16 @@ Description: You don't have to think up every attribute up front, but it helps to sketch out a few so you can start working with the resource immediately. - For example, `scaffold post title:string body:text published:boolean` + For example, 'scaffold post title:string body:text published:boolean' gives you a model with those three attributes, a controller that handles the create/show/update/destroy, forms to create and edit your posts, and an index that lists them all, as well as a map.resources :posts declaration in config/routes.rb. + If you want to remove all the generated files, run + 'script/destroy scaffold ModelName'. + Examples: - `./script/generate scaffold post` # no attributes, view will be anemic + `./script/generate scaffold post` `./script/generate scaffold post title:string body:text published:boolean` `./script/generate scaffold purchase order_id:integer amount:decimal` diff --git a/railties/lib/rails_generator/scripts.rb b/railties/lib/rails_generator/scripts.rb index f857f68de4..9b1a99838a 100644 --- a/railties/lib/rails_generator/scripts.rb +++ b/railties/lib/rails_generator/scripts.rb @@ -45,7 +45,7 @@ module Rails usage = "\nInstalled Generators\n" Rails::Generator::Base.sources.inject([]) do |mem, source| # Using an association list instead of a hash to preserve order, - # for esthetic reasons more than anything else. + # for aesthetic reasons more than anything else. label = source.label.to_s.capitalize pair = mem.assoc(label) mem << (pair = [label, []]) if pair.nil? diff --git a/railties/lib/rails_generator/scripts/destroy.rb b/railties/lib/rails_generator/scripts/destroy.rb index 4fcbc3e0df..a7c2a14751 100644 --- a/railties/lib/rails_generator/scripts/destroy.rb +++ b/railties/lib/rails_generator/scripts/destroy.rb @@ -3,7 +3,7 @@ require File.dirname(__FILE__) + '/../scripts' module Rails::Generator::Scripts class Destroy < Base mandatory_options :command => :destroy - + protected def usage_message usage = "\nInstalled Generators\n" @@ -15,14 +15,13 @@ module Rails::Generator::Scripts usage << <<end_blurb -This script will destroy all files created by the corresponding -script/generate command. For instance, script/destroy migration CreatePost -will delete the appropriate ###_create_post.rb file in db/migrate, while -script/destroy scaffold Post will delete the posts controller and +script/generate command. For instance, 'script/destroy migration CreatePost' +will delete the appropriate XXX_create_post.rb migration file in db/migrate, +while 'script/destroy scaffold Post' will delete the posts controller and views, post model and migration, all associated tests, and the map.resources :posts line in config/routes.rb. - -For instructions on finding new generators, run script/generate + +For instructions on finding new generators, run script/generate. end_blurb return usage end diff --git a/railties/lib/rails_generator/secret_key_generator.rb b/railties/lib/rails_generator/secret_key_generator.rb index 64fbbb90f8..5ae492312e 100644 --- a/railties/lib/rails_generator/secret_key_generator.rb +++ b/railties/lib/rails_generator/secret_key_generator.rb @@ -23,7 +23,7 @@ module Rails # Generate a random secret key by using the Win32 API. Raises LoadError # if the current platform cannot make use of the Win32 API. Raises - # SystemCallError if some other error occured. + # SystemCallError if some other error occurred. def generate_secret_with_win32_api # Following code is based on David Garamond's GUID library for Ruby. require 'Win32API' diff --git a/railties/lib/tasks/databases.rake b/railties/lib/tasks/databases.rake index 5ec712a02d..21c81b3fb5 100644 --- a/railties/lib/tasks/databases.rake +++ b/railties/lib/tasks/databases.rake @@ -182,11 +182,11 @@ namespace :db do end namespace :fixtures do - desc "Load fixtures into the current environment's database. Load specific fixtures using FIXTURES=x,y. Load from subdirectory in test/fixtures using FIXTURES_DIR=z." + desc "Load fixtures into the current environment's database. Load specific fixtures using FIXTURES=x,y. Load from subdirectory in test/fixtures using FIXTURES_DIR=z. Specify an alternative path (eg. spec/fixtures) using FIXTURES_PATH=spec/fixtures." task :load => :environment do require 'active_record/fixtures' ActiveRecord::Base.establish_connection(Rails.env) - base_dir = File.join(Rails.root, 'test', 'fixtures') + base_dir = ENV['FIXTURES_PATH'] ? File.join(Rails.root, ENV['FIXTURES_PATH']) : File.join(Rails.root, 'test', 'fixtures') fixtures_dir = ENV['FIXTURES_DIR'] ? File.join(base_dir, ENV['FIXTURES_DIR']) : base_dir (ENV['FIXTURES'] ? ENV['FIXTURES'].split(/,/).map {|f| File.join(fixtures_dir, f) } : Dir.glob(File.join(fixtures_dir, '*.{yml,csv}'))).each do |fixture_file| @@ -194,7 +194,7 @@ namespace :db do end end - desc "Search for a fixture given a LABEL or ID." + desc "Search for a fixture given a LABEL or ID. Specify an alternative path (eg. spec/fixtures) using FIXTURES_PATH=spec/fixtures." task :identify => :environment do require "active_record/fixtures" @@ -203,7 +203,8 @@ namespace :db do puts %Q(The fixture ID for "#{label}" is #{Fixtures.identify(label)}.) if label - Dir["#{RAILS_ROOT}/test/fixtures/**/*.yml"].each do |file| + base_dir = ENV['FIXTURES_PATH'] ? File.join(Rails.root, ENV['FIXTURES_PATH']) : File.join(Rails.root, 'test', 'fixtures') + Dir["#{base_dir}/**/*.yml"].each do |file| if data = YAML::load(ERB.new(IO.read(file)).result) data.keys.each do |key| key_id = Fixtures.identify(key) diff --git a/railties/lib/tasks/documentation.rake b/railties/lib/tasks/documentation.rake index 331b2450a3..f4927a0ef1 100644 --- a/railties/lib/tasks/documentation.rake +++ b/railties/lib/tasks/documentation.rake @@ -62,6 +62,7 @@ namespace :doc do options << "-o doc/plugins/#{plugin}" options << "--title '#{plugin.titlecase} Plugin Documentation'" options << '--line-numbers' << '--inline-source' + options << '--charset' << 'utf-8' options << '-T html' files.include("#{plugin_base}/lib/**/*.rb") diff --git a/railties/lib/tasks/framework.rake b/railties/lib/tasks/framework.rake index 71aea09867..66ab78c3b2 100644 --- a/railties/lib/tasks/framework.rake +++ b/railties/lib/tasks/framework.rake @@ -43,9 +43,12 @@ namespace :rails do require 'open-uri' version = ENV["RELEASE"] || "edge" target = "rails_#{version}.zip" + commits = "http://github.com/api/v1/yaml/rails/rails/commits/master" url = "http://dev.rubyonrails.org/archives/#{target}" chdir 'vendor' do + latest_revision = YAML.load(open(commits))["commits"].first["id"] + puts "Downloading Rails from #{url}" File.open('rails.zip', 'wb') do |dst| open url do |src| @@ -61,6 +64,8 @@ namespace :rails do %w(rails.zip rails/Rakefile rails/cleanlogs.sh rails/pushgems.rb rails/release.rb).each do |goner| rm_f goner end + + touch "rails/REVISION_#{latest_revision}" end puts 'Updating current scripts, javascripts, and configuration settings' diff --git a/railties/test/error_page_test.rb b/railties/test/error_page_test.rb new file mode 100644 index 0000000000..844f889aad --- /dev/null +++ b/railties/test/error_page_test.rb @@ -0,0 +1,43 @@ +require 'abstract_unit' +require 'action_controller' +require 'action_controller/test_process' + +RAILS_ENV = "test" +CURRENT_DIR = File.expand_path(File.dirname(__FILE__)) +HTML_DIR = File.expand_path(File.join(CURRENT_DIR, "..", "html")) + +module Rails + def self.public_path + CURRENT_DIR + end +end + +class ErrorPageController < ActionController::Base + def crash + raise StandardError, "crash!" + end +end + +ActionController::Routing::Routes.draw do |map| + map.connect ':controller/:action/:id' +end + +class ErrorPageControllerTest < Test::Unit::TestCase + def setup + @controller = ErrorPageController.new + @request = ActionController::TestRequest.new + @response = ActionController::TestResponse.new + + ActionController::Base.consider_all_requests_local = false + end + + def test_500_error_page_instructs_system_administrator_to_check_log_file + template = ERB.new(File.read(File.join(HTML_DIR, "500.html"))) + File.open(File.join(CURRENT_DIR, "500.html"), "w") do |f| + f.write(template.result) + end + get :crash + expected_log_file = "#{RAILS_ENV}.log" + assert_not_nil @response.body.index(expected_log_file) + end +end diff --git a/railties/test/fixtures/eager/zoo.rb b/railties/test/fixtures/eager/zoo.rb new file mode 100644 index 0000000000..8b10ef984b --- /dev/null +++ b/railties/test/fixtures/eager/zoo.rb @@ -0,0 +1,3 @@ +class Zoo + include ReptileHouse +end
\ No newline at end of file diff --git a/railties/test/fixtures/eager/zoo/reptile_house.rb b/railties/test/fixtures/eager/zoo/reptile_house.rb new file mode 100644 index 0000000000..82bbafce79 --- /dev/null +++ b/railties/test/fixtures/eager/zoo/reptile_house.rb @@ -0,0 +1,2 @@ +module Zoo::ReptileHouse +end
\ No newline at end of file diff --git a/railties/test/gem_dependency_test.rb b/railties/test/gem_dependency_test.rb index b5946aa7b8..964ca50992 100644 --- a/railties/test/gem_dependency_test.rb +++ b/railties/test/gem_dependency_test.rb @@ -11,6 +11,7 @@ uses_mocha "Plugin Tests" do @gem_with_source = Rails::GemDependency.new "hpricot", :source => "http://code.whytheluckystiff.net" @gem_with_version = Rails::GemDependency.new "hpricot", :version => "= 0.6" @gem_with_lib = Rails::GemDependency.new "aws-s3", :lib => "aws/s3" + @gem_without_load = Rails::GemDependency.new "hpricot", :lib => false end def test_configuration_adds_gem_dependency @@ -62,5 +63,13 @@ uses_mocha "Plugin Tests" do @gem_with_lib.add_load_paths @gem_with_lib.load end + + def test_gem_without_lib_loading + @gem_without_load.expects(:gem).with(@gem_without_load.name) + @gem_without_load.expects(:require).with(@gem_without_load.lib).never + @gem_without_load.add_load_paths + @gem_without_load.load + end + end end diff --git a/railties/test/generators/generator_test_helper.rb b/railties/test/generators/generator_test_helper.rb index 05dca3400e..0901b215e4 100644 --- a/railties/test/generators/generator_test_helper.rb +++ b/railties/test/generators/generator_test_helper.rb @@ -5,9 +5,10 @@ require 'fileutils' module ActiveRecord class Base class << self - attr_accessor :pluralize_table_names + attr_accessor :pluralize_table_names, :timestamped_migrations end self.pluralize_table_names = true + self.timestamped_migrations = true end module ConnectionAdapters @@ -226,7 +227,7 @@ class GeneratorTestCase < Test::Unit::TestCase end end - # Asserts that the given fixtures yaml file was generated. + # Asserts that the given fixtures YAML file was generated. # It takes a fixture name without the <tt>.yml</tt> part. # The parsed YAML tree is passed to a block. def assert_generated_fixtures_for(name) diff --git a/railties/test/generators/rails_model_generator_test.rb b/railties/test/generators/rails_model_generator_test.rb index 0bfc338566..aea2abafba 100644 --- a/railties/test/generators/rails_model_generator_test.rb +++ b/railties/test/generators/rails_model_generator_test.rb @@ -29,4 +29,20 @@ class RailsModelGeneratorTest < GeneratorTestCase assert_generated_column t, :created_at, :timestamp end end + + def test_model_with_reference_attributes_generates_belongs_to_associations + run_generator('model', %w(Product name:string supplier:references)) + + assert_generated_model_for :product do |body| + assert body =~ /^\s+belongs_to :supplier/, "#{body.inspect} should contain 'belongs_to :supplier'" + end + end + + def test_model_with_belongs_to_attributes_generates_belongs_to_associations + run_generator('model', %w(Product name:string supplier:belongs_to)) + + assert_generated_model_for :product do |body| + assert body =~ /^\s+belongs_to :supplier/, "#{body.inspect} should contain 'belongs_to :supplier'" + end + end end diff --git a/railties/test/initializer_test.rb b/railties/test/initializer_test.rb index dee7abe05f..5147eeb482 100644 --- a/railties/test/initializer_test.rb +++ b/railties/test/initializer_test.rb @@ -30,6 +30,24 @@ class Initializer_load_environment_Test < Test::Unit::TestCase end +class Initializer_eager_loading_Test < Test::Unit::TestCase + def setup + @config = ConfigurationMock.new("") + @config.cache_classes = true + @config.load_paths = [File.expand_path(File.dirname(__FILE__) + "/fixtures/eager")] + @config.eager_load_paths = [File.expand_path(File.dirname(__FILE__) + "/fixtures/eager")] + @initializer = Rails::Initializer.new(@config) + @initializer.set_load_path + @initializer.set_autoload_paths + end + + def test_eager_loading_loads_parent_classes_before_children + assert_nothing_raised do + @initializer.load_application_classes + end + end +end + uses_mocha 'Initializer after_initialize' do class Initializer_after_initialize_with_blocks_environment_Test < Test::Unit::TestCase def setup @@ -136,8 +154,27 @@ uses_mocha 'framework paths' do end end - protected + def test_action_mailer_load_paths_set_only_if_action_mailer_in_use + @config.frameworks = [:action_controller] + initializer = Rails::Initializer.new @config + initializer.send :require_frameworks + assert_nothing_raised NameError do + initializer.send :load_view_paths + end + end + + def test_action_controller_load_paths_set_only_if_action_controller_in_use + @config.frameworks = [] + initializer = Rails::Initializer.new @config + initializer.send :require_frameworks + + assert_nothing_raised NameError do + initializer.send :load_view_paths + end + end + + protected def assert_framework_path(path) assert @config.framework_paths.include?(path), "<#{path.inspect}> not found among <#{@config.framework_paths.inspect}>" |