aboutsummaryrefslogtreecommitdiffstats
path: root/railties
diff options
context:
space:
mode:
authorHongli Lai (Phusion) <hongli@phusion.nl>2008-08-08 13:48:30 +0200
committerHongli Lai (Phusion) <hongli@phusion.nl>2008-08-08 13:48:30 +0200
commit920ad94598a9b90d048cb7cb19a34d7cb9e80392 (patch)
tree77e016c3a03fc2ad0cf290e9e38f166b327c1622 /railties
parent62d8a1c84406f8021c74a02fea320cf2fb129adf (diff)
parentd2553c3409843986be2c00394687828195b913dc (diff)
downloadrails-920ad94598a9b90d048cb7cb19a34d7cb9e80392.tar.gz
rails-920ad94598a9b90d048cb7cb19a34d7cb9e80392.tar.bz2
rails-920ad94598a9b90d048cb7cb19a34d7cb9e80392.zip
Merge branch 'master' of git@github.com:lifo/docrails
Diffstat (limited to 'railties')
-rw-r--r--railties/CHANGELOG11
-rwxr-xr-x[-rw-r--r--]railties/bin/about0
-rwxr-xr-x[-rw-r--r--]railties/bin/console0
-rwxr-xr-x[-rw-r--r--]railties/bin/destroy0
-rwxr-xr-x[-rw-r--r--]railties/bin/generate0
-rwxr-xr-x[-rw-r--r--]railties/bin/performance/benchmarker0
-rwxr-xr-x[-rw-r--r--]railties/bin/performance/profiler0
-rwxr-xr-x[-rw-r--r--]railties/bin/performance/request0
-rwxr-xr-x[-rw-r--r--]railties/bin/plugin0
-rwxr-xr-x[-rw-r--r--]railties/bin/process/inspector0
-rwxr-xr-x[-rw-r--r--]railties/bin/process/reaper0
-rwxr-xr-x[-rw-r--r--]railties/bin/process/spawner0
-rwxr-xr-x[-rw-r--r--]railties/bin/runner0
-rwxr-xr-x[-rw-r--r--]railties/bin/server0
-rw-r--r--railties/config.ru17
-rw-r--r--[-rwxr-xr-x]railties/configs/apache.conf0
-rwxr-xr-xrailties/dispatches/dispatch.fcgi2
-rwxr-xr-xrailties/dispatches/dispatch.rb4
-rwxr-xr-x[-rw-r--r--]railties/dispatches/gateway.cgi4
-rw-r--r--railties/doc/guides/actionview/helpers.markdown20
-rw-r--r--railties/doc/guides/actionview/partials.markdown15
-rw-r--r--railties/doc/guides/activerecord/basics.markdown2
-rw-r--r--railties/doc/guides/creating_plugins/acts_as_yaffle.txt6
-rw-r--r--railties/doc/guides/creating_plugins/basics.markdown861
-rw-r--r--railties/doc/guides/creating_plugins/creating_plugins.txt4
-rw-r--r--railties/doc/guides/creating_plugins/migration_generator.txt8
-rw-r--r--railties/doc/guides/creating_plugins/odds_and_ends.txt4
-rw-r--r--railties/doc/guides/creating_plugins/preparation.txt2
-rw-r--r--railties/doc/guides/creating_plugins/string_to_squawk.txt8
-rw-r--r--railties/doc/guides/creating_plugins/view_helper.txt2
-rw-r--r--railties/doc/guides/securing_rails_applications/creating_records_directly_from_form_parameters.txt2
-rw-r--r--railties/doc/guides/testing_rails_applications/testing_rails_applications.txt32
-rw-r--r--railties/environments/boot.rb8
-rw-r--r--railties/environments/environment.rb3
-rw-r--r--railties/environments/production.rb1
-rw-r--r--railties/helpers/performance_test_helper.rb6
-rw-r--r--railties/html/javascripts/prototype.js304
-rw-r--r--railties/lib/commands/dbconsole.rb4
-rwxr-xr-x[-rw-r--r--]railties/lib/commands/ncgi/listener4
-rwxr-xr-x[-rw-r--r--]railties/lib/commands/ncgi/tracker4
-rw-r--r--railties/lib/commands/plugin.rb49
-rw-r--r--railties/lib/commands/server.rb6
-rw-r--r--railties/lib/initializer.rb88
-rw-r--r--railties/lib/performance_test_help.rb5
-rw-r--r--railties/lib/rails_generator/commands.rb17
-rw-r--r--railties/lib/rails_generator/generators/applications/app/app_generator.rb1
-rw-r--r--[-rwxr-xr-x]railties/lib/rails_generator/generators/components/plugin/templates/Rakefile0
-rw-r--r--railties/lib/tasks/databases.rake34
-rw-r--r--railties/test/generators/generator_test_helper.rb3
-rw-r--r--railties/test/initializer_test.rb21
50 files changed, 1287 insertions, 275 deletions
diff --git a/railties/CHANGELOG b/railties/CHANGELOG
index 1b9bdb57f2..6df7c568dc 100644
--- a/railties/CHANGELOG
+++ b/railties/CHANGELOG
@@ -1,5 +1,16 @@
*Edge*
+* 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
+ script/plugin install git://github.com/dchelimsky/rspec.git -r 'tag 1.1.4'
+
* Added Rails.initialized? flag [Josh Peek]
* Make rake test:uncommitted work with Git. [Tim Pope]
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
index c191c5e5ef..c702e83ff9 100644
--- a/railties/doc/guides/actionview/helpers.markdown
+++ b/railties/doc/guides/actionview/helpers.markdown
@@ -16,11 +16,11 @@ Helpers allow you to encapsulate rendering tasks as reusable functions. Helpers
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.
+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 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.
+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:
@@ -60,18 +60,18 @@ In general, the choice between using a partial vs. using a helper depends on the
Tutorial -- Calling a Helper [UNFINISHED]
------------------------
-1. Create a Rails application using `rails helper_test`
-Notice the code:
-
+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:
+3. Inside of the `/app/helpers/` directory, create a new file called, `menu_helper.rb`. Write this in the file:
- module MenuHelpers
+ module MenuHelpers
def menu(records, item_proc=nil)
items = records.collect{ |record|
menu_item(record, item_proc)
@@ -86,6 +86,6 @@ For this tutorial, we'll keep this code, but you will likely want to exert more
end
end
-4. Create a scaffold for some object in your app, using `./script/generate scaffold widgets`.
+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
index 9f387fbafb..2988b933bc 100644
--- a/railties/doc/guides/actionview/partials.markdown
+++ b/railties/doc/guides/actionview/partials.markdown
@@ -1,9 +1,9 @@
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.
+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 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:
@@ -20,7 +20,7 @@ Abstracting views into partials can be approached in a number of different ways,
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.
+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" } %>
@@ -34,7 +34,7 @@ So that you can later check:
<p>Hello, <%= name %>!</p>
<% end -%>
-Otherwise, the if statement will throw an error at runtime.
+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:
@@ -46,7 +46,7 @@ And then within the partial:
<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.
+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
--------------------------------
@@ -61,7 +61,7 @@ If the instance variable `name` in the parent template matches the name of the p
render :partial => "person"
-Now the value that was in `@person` in the parent template is accessible as `person` in the partial.
+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
-----------------------------------
@@ -83,9 +83,8 @@ Where `@winners` contains three people, produces the following output:
2) Jeff
3) Nick
-One last detail, you can place an arbitrary snippet of code in between the objects using the `:spacer_template` option.
+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
index de882b45e6..0d030fabf9 100644
--- a/railties/doc/guides/activerecord/basics.markdown
+++ b/railties/doc/guides/activerecord/basics.markdown
@@ -16,7 +16,7 @@ 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
+* Get and set column values
* Wrap business logic where appropriate
* Update existing objects and update the related rows in the database
diff --git a/railties/doc/guides/creating_plugins/acts_as_yaffle.txt b/railties/doc/guides/creating_plugins/acts_as_yaffle.txt
index ad5aa76d61..12d40deb18 100644
--- a/railties/doc/guides/creating_plugins/acts_as_yaffle.txt
+++ b/railties/doc/guides/creating_plugins/acts_as_yaffle.txt
@@ -17,7 +17,7 @@ end
class ActsAsYaffleTest < Test::Unit::TestCase
end
------------------------------------------------------
-
+
[source, ruby]
------------------------------------------------------
# File: vendor/plugins/lib/acts_as_yaffle.rb
@@ -40,11 +40,11 @@ module Yaffle
def acts_as_something
send :include, InstanceMethods
end
- end
+ end
module InstanceMethods
# any method placed here will apply to instaces, like @hickwall
- end
+ end
end
------------------------------------------------------
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
index e684a5850f..f2ed6ed8bb 100644
--- a/railties/doc/guides/creating_plugins/creating_plugins.txt
+++ b/railties/doc/guides/creating_plugins/creating_plugins.txt
@@ -1,7 +1,7 @@
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.
+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:
@@ -56,7 +56,7 @@ ActionController::Routing::Routes.draw do |map|
map.yaffles
end
-------------------------------------------
-
+
In addition you'll learn how to:
* test your plugins.
diff --git a/railties/doc/guides/creating_plugins/migration_generator.txt b/railties/doc/guides/creating_plugins/migration_generator.txt
index ed501e4284..598a0c8437 100644
--- a/railties/doc/guides/creating_plugins/migration_generator.txt
+++ b/railties/doc/guides/creating_plugins/migration_generator.txt
@@ -7,7 +7,7 @@ We'll be relying on the built-in rails generate template for this tutorial. Goi
Type:
script/generate
-
+
You should see the line:
Plugins (vendor/plugins): yaffle
@@ -34,13 +34,13 @@ Now you can add code to your generator:
class YaffleGenerator < Rails::Generator::NamedBase
def manifest
record do |m|
- m.migration_template 'migration:migration.rb', "db/migrate", {:assigns => yaffle_local_assigns,
+ 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
+ private
def custom_file_name
custom_name = class_name.underscore.downcase
custom_name = custom_name.pluralize if ActiveRecord::Base.pluralize_table_names
@@ -68,7 +68,7 @@ This does a few things:
When you run the generator like
script/generate yaffle bird
-
+
You will see a new file:
[source, ruby]
diff --git a/railties/doc/guides/creating_plugins/odds_and_ends.txt b/railties/doc/guides/creating_plugins/odds_and_ends.txt
index 91c7d5e60b..eb127f73ca 100644
--- a/railties/doc/guides/creating_plugins/odds_and_ends.txt
+++ b/railties/doc/guides/creating_plugins/odds_and_ends.txt
@@ -2,7 +2,7 @@
=== Work with init.rb ===
-The plugin initializer script 'init.rb' is invoked via `eval` (not `require`) so it has slightly different behavior.
+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:
@@ -21,7 +21,7 @@ end
OR you can use `module_eval` or `class_eval`:
----------------------------------------------------
+---------------------------------------------------
# File: vendor/plugins/yaffle/init.rb
Hash.class_eval do
diff --git a/railties/doc/guides/creating_plugins/preparation.txt b/railties/doc/guides/creating_plugins/preparation.txt
index e200fa254f..77e3a3561f 100644
--- a/railties/doc/guides/creating_plugins/preparation.txt
+++ b/railties/doc/guides/creating_plugins/preparation.txt
@@ -123,7 +123,7 @@ ActiveRecord::Schema.define(:version => 0) do
end
# File: vendor/plugins/yaffle/test/test_helper.rb
-
+
ENV['RAILS_ENV'] = 'test'
ENV['RAILS_ROOT'] ||= File.dirname(__FILE__) + '/../../../..'
diff --git a/railties/doc/guides/creating_plugins/string_to_squawk.txt b/railties/doc/guides/creating_plugins/string_to_squawk.txt
index 9aaf9e2675..50516cef69 100644
--- a/railties/doc/guides/creating_plugins/string_to_squawk.txt
+++ b/railties/doc/guides/creating_plugins/string_to_squawk.txt
@@ -50,7 +50,7 @@ Your test should fail with `no such file to load -- ./test/../lib/core_ext.rb (L
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]
@@ -73,14 +73,14 @@ 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
diff --git a/railties/doc/guides/creating_plugins/view_helper.txt b/railties/doc/guides/creating_plugins/view_helper.txt
index 1c3c4a4833..b03a190e1a 100644
--- a/railties/doc/guides/creating_plugins/view_helper.txt
+++ b/railties/doc/guides/creating_plugins/view_helper.txt
@@ -36,7 +36,7 @@ require "view_helpers"
ActionView::Base.send :include, YaffleViewHelper
---------------------------------------------------------------
-Then add the view helpers file and
+Then add the view helpers file and
[source, ruby]
---------------------------------------------------------------
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
index f602fb7c28..b237c4a17f 100644
--- 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
@@ -9,7 +9,7 @@ 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"
+ 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?
);
diff --git a/railties/doc/guides/testing_rails_applications/testing_rails_applications.txt b/railties/doc/guides/testing_rails_applications/testing_rails_applications.txt
index 5ab2756780..a775ed2f09 100644
--- a/railties/doc/guides/testing_rails_applications/testing_rails_applications.txt
+++ b/railties/doc/guides/testing_rails_applications/testing_rails_applications.txt
@@ -17,7 +17,7 @@ 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?
+== Testing 1-2-3... is this thing on?
=== What are These Strange Creatures?
@@ -212,7 +212,7 @@ class SecretAgent
attr_accessor :username
attr_accessor :password
- # our "constructor"
+ # our "constructor"
def initialize(username,password)
@username = username
@password = password
@@ -323,7 +323,7 @@ test_bam_zap_sock_pow(HelloTestCase) [/example/test.rb:62]:
2) Error:
test_uh_oh_hotdog(HelloTestCase):
-NameError: undefined local variable or method 'does_this_var_speak_korean' for
+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
@@ -618,9 +618,9 @@ 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
+ id: 1
+ name: David Heinemeier Hansson
+ birthday: 1979-10-15
profession: Systems development
steve:
@@ -640,9 +640,9 @@ A CSV fixture looks like this:
--------------------------------------------------------------
id, username, password, stretchable, comments
-1, sclaus, ihatekids, false, I like to say ""Ho! Ho! Ho!""
+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"
+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:
@@ -916,7 +916,7 @@ For example, let's say we have a `MoviesController` with an action called `movie
def movie
@movie = Movie.find(params[:id])
if @movie.nil?
- flash['message'] = "That movie has been burned."
+ flash['message'] = "That movie has been burned."
redirect_to :controller => 'error', :action => 'missing'
end
end
@@ -928,7 +928,7 @@ Now, to test out if the proper movie is being set, we could have a series of tes
----------------------------------------------------
# this test proves that fetching a movie works
def test_successfully_finding_a_movie
- get :movie, "id" => "1"
+ get :movie, "id" => "1"
assert_not_nil assigns["movie"]
assert_equal 1, assigns["movie"].id
assert flash.empty?
@@ -936,7 +936,7 @@ end
# and when we can't find a movie...
def test_movie_not_found
- get :movie, "id" => "666999"
+ get :movie, "id" => "666999"
assert_nil assigns["movie"]
assert flash.has_key?("message")
assert assigns.empty?
@@ -966,7 +966,7 @@ Ensures the expected template was responsible for rendering. For example:
+
[source, ruby]
--------------------------------------
-assert_template "user/profile"
+assert_template "user/profile"
--------------------------------------
+
This code will fail unless the template located at app/views/user/profile.rhtml was rendered.
@@ -1035,9 +1035,9 @@ These examples are taken from the same docs too:
[source, ruby]
-------------------------------------------------------------
# assert that there is a "span" tag
- assert_tag :tag => "span"
+ assert_tag :tag => "span"
- # assert that there is a "span" inside of a "div"
+ # 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
@@ -1272,7 +1272,7 @@ require 'my_mailer'
class MyMailerTest < Test::Unit::TestCase
fixtures :users
FIXTURES_PATH = File.dirname(__FILE__) + '/../fixtures'
- CHARSET = "utf-8"
+ CHARSET = "utf-8"
include ActionMailer::Quoting
@@ -1358,7 +1358,7 @@ class ActionMailer::Base
mail.to = destinations
if destinations.size > 0
mail.ready_to_send
- Net::SMTP.start(server_settings[:address], server_settings[:port], server_settings[:domain],
+ 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
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/environment.rb b/railties/environments/environment.rb
index a85ade371b..0d818f8446 100644
--- a/railties/environments/environment.rb
+++ b/railties/environments/environment.rb
@@ -63,5 +63,6 @@ Rails::Initializer.run do |config|
# config.active_record.schema_format = :sql
# Activate observers that should always be running
- # config.active_record.observers = :cacher, :garbage_collector
+ # Please note that observers generated using script/generate observer need to have an _observer suffix
+ # config.active_record.observers = :cacher, :garbage_collector, :forum_observer
end
diff --git a/railties/environments/production.rb b/railties/environments/production.rb
index 69c8b9ecb6..e915e8be73 100644
--- a/railties/environments/production.rb
+++ b/railties/environments/production.rb
@@ -10,7 +10,6 @@ config.cache_classes = true
# 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 3c4c7fb740..1aafc7f7e5 100644
--- a/railties/helpers/performance_test_helper.rb
+++ b/railties/helpers/performance_test_helper.rb
@@ -1,6 +1,2 @@
require 'test_helper'
-require 'action_controller/performance_test'
-
-ActionController::Base.perform_caching = true
-ActiveSupport::Dependencies.mechanism = :require
-Rails.logger.level = ActiveSupport::BufferedLogger::INFO
+require 'performance_test_help'
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..e0a2abe73d 100644
--- a/railties/lib/commands/dbconsole.rb
+++ b/railties/lib/commands/dbconsole.rb
@@ -6,7 +6,7 @@ include_password = false
OptionParser.new do |opt|
opt.banner = "Usage: dbconsole [options] [environment]"
- opt.on("-p", "--include-password", "Automatically provide the database from database.yml") do |v|
+ opt.on("-p", "--include-password", "Automatically provide the password from database.yml") do |v|
include_password = true
end
opt.parse!(ARGV)
@@ -41,6 +41,8 @@ when "mysql"
if config['password'] && include_password
args << "--password=#{config['password']}"
+ elsif config['password'] && !config['password'].empty?
+ args << "-p"
end
args << config['database']
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 ce4b0d051d..980244a71b 100644
--- a/railties/lib/commands/plugin.rb
+++ b/railties/lib/commands/plugin.rb
@@ -43,6 +43,16 @@
# plugin is pulled via `svn checkout` or `svn export` but looks
# exactly the same.
#
+# Specifying revisions:
+#
+# * Subversion revision is a single integer.
+#
+# * Git revision format:
+# - full - 'refs/tags/1.8.0' or 'refs/heads/experimental'
+# - short: 'experimental' (equivalent to 'refs/heads/experimental')
+# 'tag 1.8.0' (equivalent to 'refs/tags/1.8.0')
+#
+#
# This is Free Software, copyright 2005 by Ryan Tomayko (rtomayko@gmail.com)
# and is licensed MIT: (http://www.opensource.org/licenses/mit-license.php)
@@ -175,7 +185,7 @@ class Plugin
method ||= rails_env.best_install_method?
if :http == method
method = :export if svn_url?
- method = :clone if git_url?
+ method = :git if git_url?
end
uninstall if installed? and options[:force]
@@ -255,8 +265,25 @@ class Plugin
end
end
- def install_using_clone(options = {})
- git_command :clone, options
+ def install_using_git(options = {})
+ root = rails_env.root
+ install_path = mkdir_p "#{root}/vendor/plugins/#{name}"
+ Dir.chdir install_path do
+ init_cmd = "git init"
+ init_cmd += " -q" if options[:quiet] and not $verbose
+ puts init_cmd if $verbose
+ system(init_cmd)
+ base_cmd = "git pull --depth 1 #{uri}"
+ base_cmd += " -q" if options[:quiet] and not $verbose
+ base_cmd += " #{options[:revision]}" if options[:revision]
+ puts base_cmd if $verbose
+ if system(base_cmd)
+ puts "removing: .git" if $verbose
+ rm_rf ".git"
+ else
+ rm_rf install_path
+ end
+ end
end
def svn_command(cmd, options = {})
@@ -268,16 +295,6 @@ class Plugin
puts base_cmd if $verbose
system(base_cmd)
end
-
- def git_command(cmd, options = {})
- root = rails_env.root
- mkdir_p "#{root}/vendor/plugins"
- base_cmd = "git #{cmd} --depth 1 #{uri} \"#{root}/vendor/plugins/#{name}\""
- puts base_cmd if $verbose
- puts "removing: #{root}/vendor/plugins/#{name}/.git"
- system(base_cmd)
- rm_rf "#{root}/vendor/plugins/#{name}/.git"
- end
def guess_name(url)
@name = File.basename(url)
@@ -756,8 +773,8 @@ module Commands
"Suppresses the output from installation.",
"Ignored if -v is passed (./script/plugin -v install ...)") { |v| @options[:quiet] = true }
o.on( "-r REVISION", "--revision REVISION",
- "Checks out the given revision from subversion.",
- "Ignored if subversion is not used.") { |v| @options[:revision] = v }
+ "Checks out the given revision from subversion or git.",
+ "Ignored if subversion/git is not used.") { |v| @options[:revision] = v }
o.on( "-f", "--force",
"Reinstalls a plugin if it's already installed.") { |v| @options[:force] = true }
o.separator ""
@@ -890,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/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/initializer.rb b/railties/lib/initializer.rb
index dbd24df9b0..a2d08e2938 100644
--- a/railties/lib/initializer.rb
+++ b/railties/lib/initializer.rb
@@ -168,6 +168,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 +275,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 +339,24 @@ module Rails
end
end
+ def load_view_paths
+ ActionView::PathSet::Path.eager_load_templates! if configuration.cache_classes
+ ActionMailer::Base.template_root.load if configuration.frameworks.include?(:action_mailer)
+ ActionController::Base.view_paths.load if configuration.frameworks.include?(:action_controller)
+ 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").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+
@@ -377,7 +409,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)
@@ -409,8 +440,9 @@ 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?
+ 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
# If Action Controller is not one of the loaded frameworks (Configuration#frameworks)
@@ -492,10 +524,17 @@ 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
end
+
+ def disable_dependency_loading
+ if configuration.cache_classes && !configuration.dependency_loading
+ ActiveSupport::Dependencies.unhook!
+ end
+ end
end
# The Configuration class holds all the parameters for the Initializer and
@@ -559,6 +598,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 +669,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:
#
@@ -667,11 +722,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
@@ -711,6 +768,7 @@ module Rails
# 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 +865,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 +899,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_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/generators/applications/app/app_generator.rb b/railties/lib/rails_generator/generators/applications/app/app_generator.rb
index 80e8eabfd3..98fe163455 100644
--- a/railties/lib/rails_generator/generators/applications/app/app_generator.rb
+++ b/railties/lib/rails_generator/generators/applications/app/app_generator.rb
@@ -46,6 +46,7 @@ class AppGenerator < Rails::Generator::Base
# Root
m.file "fresh_rakefile", "Rakefile"
m.file "README", "README"
+ m.file "config.ru", "config.ru"
# Application
m.template "helpers/application.rb", "app/controllers/application.rb", :assigns => { :app_name => @app_name, :app_secret => md5.hexdigest }
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/tasks/databases.rake b/railties/lib/tasks/databases.rake
index 75fba8b45a..5ec712a02d 100644
--- a/railties/lib/tasks/databases.rake
+++ b/railties/lib/tasks/databases.rake
@@ -141,6 +141,9 @@ namespace :db do
when 'mysql'
ActiveRecord::Base.establish_connection(config)
puts ActiveRecord::Base.connection.charset
+ when 'postgresql'
+ ActiveRecord::Base.establish_connection(config)
+ puts ActiveRecord::Base.connection.encoding
else
puts 'sorry, your database adapter is not supported yet, feel free to submit a patch'
end
@@ -179,12 +182,15 @@ namespace :db do
end
namespace :fixtures do
- desc "Load fixtures into the current environment's database. Load specific fixtures using FIXTURES=x,y"
+ 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."
task :load => :environment do
require 'active_record/fixtures'
- ActiveRecord::Base.establish_connection(RAILS_ENV.to_sym)
- (ENV['FIXTURES'] ? ENV['FIXTURES'].split(/,/) : Dir.glob(File.join(RAILS_ROOT, 'test', 'fixtures', '*.{yml,csv}'))).each do |fixture_file|
- Fixtures.create_fixtures('test/fixtures', File.basename(fixture_file, '.*'))
+ ActiveRecord::Base.establish_connection(Rails.env)
+ base_dir = 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|
+ Fixtures.create_fixtures(File.dirname(fixture_file), File.basename(fixture_file, '.*'))
end
end
@@ -215,14 +221,14 @@ namespace :db do
desc "Create a db/schema.rb file that can be portably used against any DB supported by AR"
task :dump => :environment do
require 'active_record/schema_dumper'
- File.open(ENV['SCHEMA'] || "db/schema.rb", "w") do |file|
+ File.open(ENV['SCHEMA'] || "#{RAILS_ROOT}/db/schema.rb", "w") do |file|
ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, file)
end
end
desc "Load a schema.rb file into the database"
task :load => :environment do
- file = ENV['SCHEMA'] || "db/schema.rb"
+ file = ENV['SCHEMA'] || "#{RAILS_ROOT}/db/schema.rb"
load(file)
end
end
@@ -234,7 +240,7 @@ namespace :db do
case abcs[RAILS_ENV]["adapter"]
when "mysql", "oci", "oracle"
ActiveRecord::Base.establish_connection(abcs[RAILS_ENV])
- File.open("db/#{RAILS_ENV}_structure.sql", "w+") { |f| f << ActiveRecord::Base.connection.structure_dump }
+ File.open("#{RAILS_ROOT}/db/#{RAILS_ENV}_structure.sql", "w+") { |f| f << ActiveRecord::Base.connection.structure_dump }
when "postgresql"
ENV['PGHOST'] = abcs[RAILS_ENV]["host"] if abcs[RAILS_ENV]["host"]
ENV['PGPORT'] = abcs[RAILS_ENV]["port"].to_s if abcs[RAILS_ENV]["port"]
@@ -252,13 +258,13 @@ namespace :db do
when "firebird"
set_firebird_env(abcs[RAILS_ENV])
db_string = firebird_db_string(abcs[RAILS_ENV])
- sh "isql -a #{db_string} > db/#{RAILS_ENV}_structure.sql"
+ sh "isql -a #{db_string} > #{RAILS_ROOT}/db/#{RAILS_ENV}_structure.sql"
else
raise "Task not supported by '#{abcs["test"]["adapter"]}'"
end
if ActiveRecord::Base.connection.supports_migrations?
- File.open("db/#{RAILS_ENV}_structure.sql", "a") { |f| f << ActiveRecord::Base.connection.dump_schema_information }
+ File.open("#{RAILS_ROOT}/db/#{RAILS_ENV}_structure.sql", "a") { |f| f << ActiveRecord::Base.connection.dump_schema_information }
end
end
end
@@ -281,28 +287,28 @@ namespace :db do
when "mysql"
ActiveRecord::Base.establish_connection(:test)
ActiveRecord::Base.connection.execute('SET foreign_key_checks = 0')
- IO.readlines("db/#{RAILS_ENV}_structure.sql").join.split("\n\n").each do |table|
+ IO.readlines("#{RAILS_ROOT}/db/#{RAILS_ENV}_structure.sql").join.split("\n\n").each do |table|
ActiveRecord::Base.connection.execute(table)
end
when "postgresql"
ENV['PGHOST'] = abcs["test"]["host"] if abcs["test"]["host"]
ENV['PGPORT'] = abcs["test"]["port"].to_s if abcs["test"]["port"]
ENV['PGPASSWORD'] = abcs["test"]["password"].to_s if abcs["test"]["password"]
- `psql -U "#{abcs["test"]["username"]}" -f db/#{RAILS_ENV}_structure.sql #{abcs["test"]["database"]}`
+ `psql -U "#{abcs["test"]["username"]}" -f #{RAILS_ROOT}/db/#{RAILS_ENV}_structure.sql #{abcs["test"]["database"]}`
when "sqlite", "sqlite3"
dbfile = abcs["test"]["database"] || abcs["test"]["dbfile"]
- `#{abcs["test"]["adapter"]} #{dbfile} < db/#{RAILS_ENV}_structure.sql`
+ `#{abcs["test"]["adapter"]} #{dbfile} < #{RAILS_ROOT}/db/#{RAILS_ENV}_structure.sql`
when "sqlserver"
`osql -E -S #{abcs["test"]["host"]} -d #{abcs["test"]["database"]} -i db\\#{RAILS_ENV}_structure.sql`
when "oci", "oracle"
ActiveRecord::Base.establish_connection(:test)
- IO.readlines("db/#{RAILS_ENV}_structure.sql").join.split(";\n\n").each do |ddl|
+ IO.readlines("#{RAILS_ROOT}/db/#{RAILS_ENV}_structure.sql").join.split(";\n\n").each do |ddl|
ActiveRecord::Base.connection.execute(ddl)
end
when "firebird"
set_firebird_env(abcs["test"])
db_string = firebird_db_string(abcs["test"])
- sh "isql -i db/#{RAILS_ENV}_structure.sql #{db_string}"
+ sh "isql -i #{RAILS_ROOT}/db/#{RAILS_ENV}_structure.sql #{db_string}"
else
raise "Task not supported by '#{abcs["test"]["adapter"]}'"
end
diff --git a/railties/test/generators/generator_test_helper.rb b/railties/test/generators/generator_test_helper.rb
index 80d5b145be..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
diff --git a/railties/test/initializer_test.rb b/railties/test/initializer_test.rb
index dee7abe05f..07303a510e 100644
--- a/railties/test/initializer_test.rb
+++ b/railties/test/initializer_test.rb
@@ -136,8 +136,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}>"