aboutsummaryrefslogtreecommitdiffstats
path: root/railties
diff options
context:
space:
mode:
authorTomK32 <tomk32@tomk32.de>2008-06-11 19:22:51 +0200
committerTomK32 <tomk32@tomk32.de>2008-06-11 19:22:51 +0200
commit6a5ac86207765e2c041378b35c05812f9bfe68b9 (patch)
tree4b341329991f2bd08c01d2f139c4c3721a8fbe25 /railties
parentfa0cca368f74119b561595cc6ca7454f7debdf6b (diff)
parentd4b7cd99e8e7051c9d3ed6722f9627d5d4dea4e9 (diff)
downloadrails-6a5ac86207765e2c041378b35c05812f9bfe68b9.tar.gz
rails-6a5ac86207765e2c041378b35c05812f9bfe68b9.tar.bz2
rails-6a5ac86207765e2c041378b35c05812f9bfe68b9.zip
Merge branch 'master' of git@github.com:lifo/docrails
Diffstat (limited to 'railties')
-rw-r--r--railties/CHANGELOG2
-rw-r--r--railties/Rakefile10
-rw-r--r--railties/configs/databases/frontbase.yml4
-rw-r--r--railties/configs/databases/mysql.yml4
-rw-r--r--railties/configs/databases/oracle.yml6
-rw-r--r--railties/configs/databases/postgresql.yml4
-rw-r--r--railties/configs/databases/sqlite2.yml4
-rw-r--r--railties/configs/databases/sqlite3.yml4
-rw-r--r--railties/configs/initializers/new_rails_defaults.rb13
-rw-r--r--railties/doc/guides/actionview/helpers.markdown91
-rw-r--r--railties/doc/guides/actionview/partials.markdown91
-rw-r--r--railties/doc/guides/activerecord/basics.markdown56
-rw-r--r--railties/doc/guides/creating_plugins/basics.markdown862
-rw-r--r--railties/environments/environment.rb10
-rw-r--r--railties/environments/test.rb2
-rw-r--r--railties/lib/commands/console.rb4
-rw-r--r--railties/lib/commands/dbconsole.rb17
-rw-r--r--railties/lib/commands/plugin.rb2
-rw-r--r--railties/lib/commands/process/spawner.rb4
-rw-r--r--railties/lib/commands/servers/lighttpd.rb2
-rw-r--r--railties/lib/commands/servers/mongrel.rb2
-rw-r--r--railties/lib/commands/servers/webrick.rb2
-rw-r--r--railties/lib/initializer.rb94
-rw-r--r--railties/lib/rails/gem_dependency.rb15
-rw-r--r--railties/lib/rails/mongrel_server/commands.rb2
-rw-r--r--railties/lib/rails/plugin.rb17
-rw-r--r--railties/lib/rails/rack.rb5
-rw-r--r--railties/lib/rails/rack/static.rb35
-rw-r--r--railties/lib/rails/version.rb4
-rw-r--r--railties/lib/rails_generator/base.rb2
-rw-r--r--railties/lib/rails_generator/commands.rb10
-rw-r--r--railties/lib/rails_generator/generators/components/migration/USAGE8
-rw-r--r--railties/lib/rails_generator/generators/components/scaffold/USAGE14
-rw-r--r--railties/lib/rails_generator/scripts.rb2
-rw-r--r--railties/lib/rails_generator/scripts/destroy.rb13
-rw-r--r--railties/lib/rails_generator/secret_key_generator.rb2
-rw-r--r--railties/lib/tasks/databases.rake2
-rw-r--r--railties/lib/tasks/gems.rake12
-rw-r--r--railties/test/fixtures/about_yml_plugins/bad_about_yml/about.yml2
-rw-r--r--railties/test/generators/generator_test_helper.rb60
40 files changed, 1339 insertions, 156 deletions
diff --git a/railties/CHANGELOG b/railties/CHANGELOG
index 11d2926f31..fe517755ef 100644
--- a/railties/CHANGELOG
+++ b/railties/CHANGELOG
@@ -1,4 +1,4 @@
-*2.1.0 RC1 (May 11th, 2008)*
+*2.1.0 (May 31st, 2008)*
* script/dbconsole fires up the command-line database client. #102 [Steve Purcell]
diff --git a/railties/Rakefile b/railties/Rakefile
index 45ba394299..a1d1095c37 100644
--- a/railties/Rakefile
+++ b/railties/Rakefile
@@ -304,11 +304,11 @@ spec = Gem::Specification.new do |s|
EOF
s.add_dependency('rake', '>= 0.8.1')
- s.add_dependency('activesupport', '= 2.0.991' + PKG_BUILD)
- s.add_dependency('activerecord', '= 2.0.991' + PKG_BUILD)
- s.add_dependency('actionpack', '= 2.0.991' + PKG_BUILD)
- s.add_dependency('actionmailer', '= 2.0.991' + PKG_BUILD)
- s.add_dependency('activeresource', '= 2.0.991' + PKG_BUILD)
+ s.add_dependency('activesupport', '= 2.1.0' + PKG_BUILD)
+ s.add_dependency('activerecord', '= 2.1.0' + PKG_BUILD)
+ s.add_dependency('actionpack', '= 2.1.0' + PKG_BUILD)
+ s.add_dependency('actionmailer', '= 2.1.0' + PKG_BUILD)
+ s.add_dependency('activeresource', '= 2.1.0' + PKG_BUILD)
s.rdoc_options << '--exclude' << '.'
s.has_rdoc = false
diff --git a/railties/configs/databases/frontbase.yml b/railties/configs/databases/frontbase.yml
index 2eed3133a1..c0c3588be1 100644
--- a/railties/configs/databases/frontbase.yml
+++ b/railties/configs/databases/frontbase.yml
@@ -10,8 +10,8 @@ development:
username: <%= app_name %>
password: ''
-# Warning: The database defined as 'test' will be erased and
-# re-generated from your development database when you run 'rake'.
+# Warning: The database defined as "test" will be erased and
+# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
adapter: frontbase
diff --git a/railties/configs/databases/mysql.yml b/railties/configs/databases/mysql.yml
index c5c894c5e1..7fcadcdf2c 100644
--- a/railties/configs/databases/mysql.yml
+++ b/railties/configs/databases/mysql.yml
@@ -26,8 +26,8 @@ development:
host: localhost
<% end -%>
-# Warning: The database defined as 'test' will be erased and
-# re-generated from your development database when you run 'rake'.
+# Warning: The database defined as "test" will be erased and
+# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
adapter: mysql
diff --git a/railties/configs/databases/oracle.yml b/railties/configs/databases/oracle.yml
index c86cbdbaba..a1883f6256 100644
--- a/railties/configs/databases/oracle.yml
+++ b/railties/configs/databases/oracle.yml
@@ -4,7 +4,7 @@
# http://rubyforge.org/projects/ruby-oci8/
#
# Specify your database using any valid connection syntax, such as a
-# tnsnames.ora service name, or a sql connect url string of the form:
+# tnsnames.ora service name, or a SQL connect url string of the form:
#
# //host:[port][/service name]
#
@@ -23,8 +23,8 @@ development:
username: <%= app_name %>
password:
-# Warning: The database defined as 'test' will be erased and
-# re-generated from your development database when you run 'rake'.
+# Warning: The database defined as "test" will be erased and
+# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
adapter: oracle
diff --git a/railties/configs/databases/postgresql.yml b/railties/configs/databases/postgresql.yml
index c1b911a9a4..36f6e5ae49 100644
--- a/railties/configs/databases/postgresql.yml
+++ b/railties/configs/databases/postgresql.yml
@@ -30,8 +30,8 @@ development:
# The server defaults to notice.
#min_messages: warning
-# Warning: The database defined as 'test' will be erased and
-# re-generated from your development database when you run 'rake'.
+# Warning: The database defined as "test" will be erased and
+# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
adapter: postgresql
diff --git a/railties/configs/databases/sqlite2.yml b/railties/configs/databases/sqlite2.yml
index 26d3957d79..fc48bd6753 100644
--- a/railties/configs/databases/sqlite2.yml
+++ b/railties/configs/databases/sqlite2.yml
@@ -4,8 +4,8 @@ development:
adapter: sqlite
database: db/development.sqlite2
-# Warning: The database defined as 'test' will be erased and
-# re-generated from your development database when you run 'rake'.
+# Warning: The database defined as "test" will be erased and
+# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
adapter: sqlite
diff --git a/railties/configs/databases/sqlite3.yml b/railties/configs/databases/sqlite3.yml
index b444b03cd4..fff44a4124 100644
--- a/railties/configs/databases/sqlite3.yml
+++ b/railties/configs/databases/sqlite3.yml
@@ -5,8 +5,8 @@ development:
database: db/development.sqlite3
timeout: 5000
-# Warning: The database defined as 'test' will be erased and
-# re-generated from your development database when you run 'rake'.
+# Warning: The database defined as "test" will be erased and
+# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
adapter: sqlite3
diff --git a/railties/configs/initializers/new_rails_defaults.rb b/railties/configs/initializers/new_rails_defaults.rb
index b8f0e2cac2..5e60c0ade4 100644
--- a/railties/configs/initializers/new_rails_defaults.rb
+++ b/railties/configs/initializers/new_rails_defaults.rb
@@ -1,18 +1,15 @@
-# These settins change the behavior of Rails 2 apps and will be defaults
+# These settings change the behavior of Rails 2 apps and will be defaults
# for Rails 3. You can remove this initializer when Rails 3 is released.
-# Only save the attributes that have changed since the record was loaded.
-ActiveRecord::Base.partial_updates = true
-
-# Include ActiveRecord class name as root for JSON serialized output.
+# Include Active Record class name as root for JSON serialized output.
ActiveRecord::Base.include_root_in_json = true
-# Store the full class name (including module namespace) in STI type column
+# Store the full class name (including module namespace) in STI type column.
ActiveRecord::Base.store_full_sti_class = true
-# Use ISO 8601 format for JSON serialized times and dates
+# Use ISO 8601 format for JSON serialized times and dates.
ActiveSupport.use_standard_json_time_format = true
-# Don't escape HTML entities in JSON, leave that for the #json_escape helper
+# Don't escape HTML entities in JSON, leave that for the #json_escape helper.
# if you're including raw json in an HTML page.
ActiveSupport.escape_html_entities_in_json = false \ No newline at end of file
diff --git a/railties/doc/guides/actionview/helpers.markdown b/railties/doc/guides/actionview/helpers.markdown
new file mode 100644
index 0000000000..c191c5e5ef
--- /dev/null
+++ b/railties/doc/guides/actionview/helpers.markdown
@@ -0,0 +1,91 @@
+Helpers
+====================
+
+Helper Basics
+------------------------
+
+Helpers allow you to encapsulate rendering tasks as reusable functions. Helpers are modules, not classes, so their methods execute in the context in which they are called. They get included in a controller (typically the ApplicationController) using the helper function, like so
+
+ Class ApplicationController < ActionController::Base
+ …
+ helper :menu
+
+ def …
+ end
+ end
+
+In this way, methods in the menu helper are made available to any view or partial in your application. These methods can accept parameters, for example controller instance variables (eg; records or record collections gathered by you current controller), items from the view or partial’s locals[] hash or items from the params[] hash. You may wish to pass your controller instance variables and items from the params[] hash to the locals hash before rendering (See the section on partials). Helper methods can also accept an executable block of code.
+
+It is important to remember, though, that helpers are for rendering, and that they become available once a controller method has returned, while Rails is engaged in rendering the contents generated by a controller method. This means that helper methods are not available from within the methods of your controllers.
+
+Helpers can accomplish a variety of tasks, from formatting a complex tag for embedding content for a browser plugin (eg; Flash), to assembling a menu of options appropriate for the current context of your application, to generating sections of forms that get assembled on-the-fly.
+
+Helpers are organized around rendering tasks, so it is not necessary (nor necessarily desirable) to organize them around your application’s controllers or models. In fact, one of the benefits of helpers is that they are not connected via a rendering pipeline to specific controllers, like views and partials are. They can and should handle more generalized tasks.
+
+Here is a very simple, pseudo-example:
+
+ module MenuHelper
+ def menu(records, menu_options={})
+ item_options = menu_options.merge({<some stuff>})
+ items = records.collect |record| do
+ menu_item(record, options)
+ end
+ content_tag(“ul”, items, options)
+ end
+
+ def menu_item(record, item_options={}))
+ action = item_options[:action]
+ action ||= “show”
+ content_tag(“li”, link_to(record.title, :action => action, item_options)
+ end
+ end
+
+
+This helper will require that records passed into it have certain fields (notably :title). The helper could be written to use this as a default, allowing the field to be overwritten by an element of item_options.
+
+Look at the Rails API for examples of helpers included in Rails, eg; [`ActionView::Helpers::ActiveRecordHelper`](http://api.rubyonrails.org/classes/ActionView/Helpers/ActiveRecordHelper.html).
+
+Passing Blocks to Helper Methods
+------------------------
+
+We mentioned before that blocks can be passed to helper methods. This allows for an interesting wrinkle: a block passed to a helper method can cause it to render a partial, which can then be wrapped by the helper method’s output. This can make your helper method much more reusable. It doesn’t need to know anything about the internals about what it is rendering, it just contextualizes it for the page. You can also use the helper to modify the locals hash for the partial, based on some configuration information unique to the current controller. You could implement a flexible themes system in this way.
+
+
+Partials vs. Helpers?
+------------------------
+
+In general, the choice between using a partial vs. using a helper depends on the amount of flexibility you need. If the task is more about reacting to conditions than performing actual rendering, you may likely want a helper method. If you want to be able to call it from a variety of views, again, you may want to use a helper method. You can expect to extract helper methods out of code in views and partials during refactoring.
+
+
+Tutorial -- Calling a Helper [UNFINISHED]
+------------------------
+
+1. Create a Rails application using `rails helper_test`
+Notice the code:
+
+ class ApplicationController < ActionController::Base
+ helper :all # include all helpers, all the time
+For this tutorial, we'll keep this code, but you will likely want to exert more control over loading your helpers.
+
+2. Configure a database of your choice for the app.
+
+3. Inside of the `/app/helpers/` directory, create a new file called, `menu_helper.rb`. Write this in the file:
+
+ module MenuHelpers
+ def menu(records, item_proc=nil)
+ items = records.collect{ |record|
+ menu_item(record, item_proc)
+ }
+ content_tag("ul", items)
+ end
+
+ def menu_item(record, item_proc=nil)
+ item_url = item_proc.call(record)
+ item_url ||= { :action => :show }
+ content_tag("li", link_to(record.name, item_url))
+ end
+ end
+
+4. Create a scaffold for some object in your app, using `./script/generate scaffold widgets`.
+5. Create a database table for your widgets, with at least the fields `name` and `id`. Create a few widgets.
+6. Call the menu command twice from `index.html.erb`, once using the default action, and once supplying a Proc to generate urls. \ No newline at end of file
diff --git a/railties/doc/guides/actionview/partials.markdown b/railties/doc/guides/actionview/partials.markdown
new file mode 100644
index 0000000000..9f387fbafb
--- /dev/null
+++ b/railties/doc/guides/actionview/partials.markdown
@@ -0,0 +1,91 @@
+A Guide to Using Partials
+===============================
+
+This guide elaborates on the use and function of partials in Ruby on Rails. As your Rails application grows, your view templates can start to contain a lot of duplicate view code. To manage and reduce this complexity, you can by abstract view template code into partials. Partials are reusable snippets of eRB template code stored in separate files with an underscore ('_') prefix.
+
+Partials can be located anywhere in the `app/views` directory. File extensions for partials work just like other template files, they bear an extension that denotes what kind of code they generate. For example, `_animal.html.erb` and `_animal.xml.erb` are valid filenames for partials.
+
+Partials can be inserted in eRB template code by calling the `render` method with the `:partial` option. For example:
+
+ <%= render :partial => 'foo' %>
+
+This inserts the result of evaluating the template `_foo.html.erb` into the parent template file at this location. Note that `render` assumes that the partial will be in the same directory as the calling parent template and have the same file extension. Partials can be located anywhere within the `app/views` directory. To use a partial located in a different directory then it the parent, add a '/' before it:
+
+ <%= render :partial => '/common/foo' %>
+
+Loads the partial file from the `app/views/common/_foo.html.erb` directory.
+
+Abstracting views into partials can be approached in a number of different ways, depending on the situation. Sometimes, the code that you are abstracting is a specialized view of an object or a collection of objects. Other times, you can look at partials as a reusable subroutine. We'll explore each of these approaches and when to use them as well as the syntax for calling them.
+
+Partials as a View Subroutine
+-----------------------------
+
+Using the `:locals` option, you can pass a hash of values which will be treated as local variables within the partial template.
+
+ <%= render :partial => "person", :locals => { :name => "david" } %>
+
+The variable `name` contains the value `"david"` within the `_person.html.erb` template. Passing variables in this way allows you to create modular, reusable template files. Note that if you want to make local variables that are optional in some use cases, you will have to set them to a sentinel value such as `nil` when they have not been passed. So, in the example above, if the `name` variable is optional in some use cases, you must set:
+
+ <% name ||= nil -%>
+
+So that you can later check:
+
+ <% if name -%>
+ <p>Hello, <%= name %>!</p>
+ <% end -%>
+
+Otherwise, the if statement will throw an error at runtime.
+
+Another thing to be aware of is that instance variables that are visible to the parent view template are visible to the partial. So you might be tempted to do this:
+
+ <%= render :partial => "person" %>
+
+And then within the partial:
+
+ <% if @name -%>
+ <p>Hello, <%= @name %>!</p>
+ <% end -%>
+
+The potential snag here is that if multiple templates start to rely on this partial, you will need to maintain an instance variable with the same name across all of these templates and controllers. This approach can quickly become brittle if overused.
+
+Partials as a View of an Object
+--------------------------------
+
+Another way to look at partials is to view them as mini-views of a particular object or instance variable. Use the `:object` option to pass an object assigns that object to an instance variable named after the partial itself. For example:
+
+ # Renders the partial, making @new_person available through
+ # the local variable 'person'
+ render :partial => "person", :object => @new_person
+
+If the instance variable `name` in the parent template matches the name of the partial, you can use a shortcut:
+
+ render :partial => "person"
+
+Now the value that was in `@person` in the parent template is accessible as `person` in the partial.
+
+Partials as a View of a Collection
+-----------------------------------
+
+Often it is the case that you need to display not just a single object, but a collection of objects. Rather than having to constantly nest the same partial within the same iterator code, Rails provides a syntactical shortcut using the `:collection` option:
+
+ # Renders a collection of the same partial by making each element
+ # of @winners available through the local variable "person" as it
+ # builds the complete response.
+ render :partial => "person", :collection => @winners
+
+This calls the `_person.html.erb` partial for each person in the `@winners` collection. This also creates a local variable within the partial called `partial_counter` which contains the index of the current value. So for example:
+
+ <%= partial_counter %>) <%= person -%>
+
+Where `@winners` contains three people, produces the following output:
+
+ 1) Bill
+ 2) Jeff
+ 3) Nick
+
+One last detail, you can place an arbitrary snippet of code in between the objects using the `:spacer_template` option.
+
+ # Renders the same collection of partials, but also renders the
+ # person_divider partial between each person partial.
+ render :partial => "person", :collection => @winners, :spacer_template => "person_divider"
+
diff --git a/railties/doc/guides/activerecord/basics.markdown b/railties/doc/guides/activerecord/basics.markdown
new file mode 100644
index 0000000000..de882b45e6
--- /dev/null
+++ b/railties/doc/guides/activerecord/basics.markdown
@@ -0,0 +1,56 @@
+Active Record Basics
+====================
+
+
+
+The ActiveRecord Pattern
+------------------------
+
+Active Record (the library) conforms to the active record design pattern. The active record pattern is a design pattern often found in applications that use relational database. The name comes from by Martin Fowler's book *Patterns of Enterprise Application Architecture*, in which he describes an active record object as:
+
+> An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data.
+
+So, an object that follows the active record pattern encapsulates both data and behavior; in other words, they are responsible for saving and loading to the database and also for any domain logic that acts on the data. The data structure of the Active Record should exactly match that of the database: one field in the class for each column in the table.
+
+The Active Record class typically has methods that do the following:
+
+* Construct an instances of an Active Record class from a SQL result
+* Construct a new class instance for insertion into the table
+* Get and set column values
+* Wrap business logic where appropriate
+* Update existing objects and update the related rows in the database
+
+Mapping Your Database
+---------------------
+
+### Plural tables, singular classes ###
+
+### Schema lives in the database ###
+
+Creating Records
+----------------
+
+### Using save ###
+
+### Using create ###
+
+Retrieving Existing Rows
+------------------------
+
+### Using find ###
+
+### Using find_by_* ###
+
+Editing and Updating Rows
+-------------------------
+
+### Editing an instance
+
+### Using update_all/update_attributes ###
+
+Deleting Data
+-------------
+
+### Destroying a record ###
+
+### Deleting a record ### \ No newline at end of file
diff --git a/railties/doc/guides/creating_plugins/basics.markdown b/railties/doc/guides/creating_plugins/basics.markdown
new file mode 100644
index 0000000000..a7b5d53478
--- /dev/null
+++ b/railties/doc/guides/creating_plugins/basics.markdown
@@ -0,0 +1,862 @@
+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/environments/environment.rb b/railties/environments/environment.rb
index c33b80da4f..a85ade371b 100644
--- a/railties/environments/environment.rb
+++ b/railties/environments/environment.rb
@@ -21,7 +21,7 @@ Rails::Initializer.run do |config|
# config.frameworks -= [ :active_record, :active_resource, :action_mailer ]
# Specify gems that this application depends on.
- # They can then be installed with rake gem:install on new installations.
+ # They can then be installed with "rake gems:install" on new installations.
# config.gem "bj"
# config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net"
# config.gem "aws-s3", :lib => "aws/s3"
@@ -38,9 +38,9 @@ Rails::Initializer.run do |config|
# (by default production uses :info, the others :debug)
# config.log_level = :debug
- # Make Time.zone default to the specified zone, and make ActiveRecord store time values
+ # Make Time.zone default to the specified zone, and make Active Record store time values
# in the database in UTC, and return them converted to the specified local zone.
- # Run `rake -D time` for a list of tasks for finding time zone names. Uncomment to use default local time.
+ # Run "rake -D time" for a list of tasks for finding time zone names. Uncomment to use default local time.
config.time_zone = 'UTC'
# Your secret key for verifying cookie session data integrity.
@@ -54,7 +54,7 @@ Rails::Initializer.run do |config|
# Use the database for sessions instead of the cookie-based default,
# which shouldn't be used to store highly confidential information
- # (create the session table with 'rake db:sessions:create')
+ # (create the session table with "rake db:sessions:create")
# config.action_controller.session_store = :active_record_store
# Use SQL instead of Active Record's schema dumper when creating the test database.
@@ -64,4 +64,4 @@ Rails::Initializer.run do |config|
# Activate observers that should always be running
# config.active_record.observers = :cacher, :garbage_collector
-end \ No newline at end of file
+end
diff --git a/railties/environments/test.rb b/railties/environments/test.rb
index 58850a7974..1e709e1d19 100644
--- a/railties/environments/test.rb
+++ b/railties/environments/test.rb
@@ -16,7 +16,7 @@ config.action_controller.perform_caching = false
# Disable request forgery protection in test environment
config.action_controller.allow_forgery_protection = false
-# Tell ActionMailer not to deliver emails to the real world.
+# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
diff --git a/railties/lib/commands/console.rb b/railties/lib/commands/console.rb
index edffe4f1e6..2b9d92f647 100644
--- a/railties/lib/commands/console.rb
+++ b/railties/lib/commands/console.rb
@@ -24,9 +24,9 @@ ENV['RAILS_ENV'] = case ARGV.first
end
if options[:sandbox]
- puts "Loading #{ENV['RAILS_ENV']} environment in sandbox (Rails #{Rails::VERSION::STRING})"
+ puts "Loading #{ENV['RAILS_ENV']} environment in sandbox (Rails #{Rails.version})"
puts "Any modifications you make will be rolled back on exit"
else
- puts "Loading #{ENV['RAILS_ENV']} environment (Rails #{Rails::VERSION::STRING})"
+ puts "Loading #{ENV['RAILS_ENV']} environment (Rails #{Rails.version})"
end
exec "#{options[:irb]} #{libs} --simple-prompt"
diff --git a/railties/lib/commands/dbconsole.rb b/railties/lib/commands/dbconsole.rb
index 3e5010c688..17acb7b68f 100644
--- a/railties/lib/commands/dbconsole.rb
+++ b/railties/lib/commands/dbconsole.rb
@@ -2,8 +2,13 @@ require 'erb'
require 'yaml'
require 'optparse'
+include_password = false
+
OptionParser.new do |opt|
- opt.banner = "Usage: dbconsole [environment]"
+ opt.banner = "Usage: dbconsole [options] [environment]"
+ opt.on("-p", "--include-password", "Automatically provide the database from database.yml") do |v|
+ include_password = true
+ end
opt.parse!(ARGV)
abort opt.to_s unless (0..1).include?(ARGV.size)
end
@@ -31,19 +36,23 @@ when "mysql"
'port' => '--port',
'socket' => '--socket',
'username' => '--user',
- 'password' => '--password',
'encoding' => '--default-character-set'
}.map { |opt, arg| "#{arg}=#{config[opt]}" if config[opt] }.compact
+ if config['password'] && include_password
+ args << "--password=#{config['password']}"
+ end
+
args << config['database']
exec(find_cmd('mysql5', 'mysql'), *args)
when "postgresql"
+ ENV['PGUSER'] = config["username"] if config["username"]
ENV['PGHOST'] = config["host"] if config["host"]
ENV['PGPORT'] = config["port"].to_s if config["port"]
- ENV['PGPASSWORD'] = config["password"].to_s if config["password"]
- exec(find_cmd('psql'), '-U', config["username"], config["database"])
+ ENV['PGPASSWORD'] = config["password"].to_s if config["password"] && include_password
+ exec(find_cmd('psql'), config["database"])
when "sqlite"
exec(find_cmd('sqlite'), config["database"])
diff --git a/railties/lib/commands/plugin.rb b/railties/lib/commands/plugin.rb
index d12d002c4e..105819ce90 100644
--- a/railties/lib/commands/plugin.rb
+++ b/railties/lib/commands/plugin.rb
@@ -163,7 +163,7 @@ class Plugin
end
def git_url?
- @uri =~ /^git:\/\// || @url =~ /\.git$/
+ @uri =~ /^git:\/\// || @uri =~ /\.git$/
end
def installed?
diff --git a/railties/lib/commands/process/spawner.rb b/railties/lib/commands/process/spawner.rb
index fd09daa55b..dc0008698a 100644
--- a/railties/lib/commands/process/spawner.rb
+++ b/railties/lib/commands/process/spawner.rb
@@ -66,9 +66,9 @@ class MongrelSpawner < Spawner
"-l #{OPTIONS[:rails_root]}/log/mongrel.log"
# Add prefix functionality to spawner's call to mongrel_rails
- # Digging through monrel's project subversion server, the earliest
+ # Digging through mongrel's project subversion server, the earliest
# Tag that has prefix implemented in the bin/mongrel_rails file
- # is 0.3.15 which also happens to be the earilest tag listed.
+ # is 0.3.15 which also happens to be the earliest tag listed.
# References: http://mongrel.rubyforge.org/svn/tags
if Mongrel::Const::MONGREL_VERSION.to_f >=0.3 && !OPTIONS[:prefix].nil?
cmd = cmd + " --prefix #{OPTIONS[:prefix]}"
diff --git a/railties/lib/commands/servers/lighttpd.rb b/railties/lib/commands/servers/lighttpd.rb
index 07d4f9d0bf..c9d13e86f3 100644
--- a/railties/lib/commands/servers/lighttpd.rb
+++ b/railties/lib/commands/servers/lighttpd.rb
@@ -62,7 +62,7 @@ config = IO.read(config_file)
default_port, default_ip = 3000, '0.0.0.0'
port = config.scan(/^\s*server.port\s*=\s*(\d+)/).first rescue default_port
ip = config.scan(/^\s*server.bind\s*=\s*"([^"]+)"/).first rescue default_ip
-puts "=> Rails application starting on http://#{ip || default_ip}:#{port || default_port}"
+puts "=> Rails #{Rails.version} application starting on http://#{ip || default_ip}:#{port || default_port}"
tail_thread = nil
diff --git a/railties/lib/commands/servers/mongrel.rb b/railties/lib/commands/servers/mongrel.rb
index f59265e698..7bb110f63a 100644
--- a/railties/lib/commands/servers/mongrel.rb
+++ b/railties/lib/commands/servers/mongrel.rb
@@ -32,7 +32,7 @@ ARGV.clone.options do |opts|
opts.parse!
end
-puts "=> Rails application starting on http://#{OPTIONS[:ip]}:#{OPTIONS[:port]}"
+puts "=> Rails #{Rails.version} application starting on http://#{OPTIONS[:ip]}:#{OPTIONS[:port]}"
parameters = [
"start",
diff --git a/railties/lib/commands/servers/webrick.rb b/railties/lib/commands/servers/webrick.rb
index b950376150..18c8897cc8 100644
--- a/railties/lib/commands/servers/webrick.rb
+++ b/railties/lib/commands/servers/webrick.rb
@@ -61,6 +61,6 @@ require 'webrick_server'
OPTIONS['working_directory'] = File.expand_path(RAILS_ROOT)
-puts "=> Rails application started on http://#{OPTIONS[:ip]}:#{OPTIONS[:port]}"
+puts "=> Rails #{Rails.version} application started on http://#{OPTIONS[:ip]}:#{OPTIONS[:port]}"
puts "=> Ctrl-C to shutdown server; call with --help for options" if OPTIONS[:server_type] == WEBrick::SimpleServer
DispatchServlet.dispatch(OPTIONS)
diff --git a/railties/lib/initializer.rb b/railties/lib/initializer.rb
index dfd43042be..ec065e6f3c 100644
--- a/railties/lib/initializer.rb
+++ b/railties/lib/initializer.rb
@@ -8,6 +8,7 @@ require 'rails/version'
require 'rails/plugin/locator'
require 'rails/plugin/loader'
require 'rails/gem_dependency'
+require 'rails/rack'
RAILS_ENV = (ENV['RAILS_ENV'] || 'development').dup unless defined?(RAILS_ENV)
@@ -43,6 +44,10 @@ module Rails
RAILS_CACHE
end
+ def version
+ VERSION::STRING
+ end
+
def public_path
@@public_path ||= self.root ? File.join(self.root, "public") : "public"
end
@@ -82,7 +87,7 @@ module Rails
# Rails::Initializer.run(:set_load_path)
#
# This is useful if you only want the load path initialized, without
- # incuring the overhead of completely loading the entire environment.
+ # incurring the overhead of completely loading the entire environment.
def self.run(command = :process, configuration = Configuration.new)
yield configuration if block_given?
initializer = new configuration
@@ -136,7 +141,8 @@ module Rails
# pick up any gems that plugins depend on
add_gem_load_paths
load_gems
-
+ check_gem_dependencies
+
load_application_initializers
# the framework is now fully initialized
@@ -149,6 +155,7 @@ module Rails
initialize_routing
# Observers are loaded after plugins in case Observers or observed models are modified by plugins.
+
load_observers
end
@@ -160,12 +167,12 @@ module Rails
end
# If Rails is vendored and RubyGems is available, install stub GemSpecs
- # for Rails, ActiveSupport, ActiveRecord, ActionPack, ActionMailer, and
- # ActiveResource. This allows Gem plugins to depend on Rails even when
+ # for Rails, Active Support, Active Record, Action Pack, Action Mailer, and
+ # Active Resource. This allows Gem plugins to depend on Rails even when
# the Gem version of Rails shouldn't be loaded.
def install_gem_spec_stubs
unless Rails.respond_to?(:vendor_rails?)
- abort "Your config/boot.rb is outdated: Run 'rake rails:update'."
+ abort %{Your config/boot.rb is outdated: Run "rake rails:update".}
end
if Rails.vendor_rails?
@@ -210,8 +217,8 @@ module Rails
end
# Requires all frameworks specified by the Configuration#frameworks
- # list. By default, all frameworks (ActiveRecord, ActiveSupport,
- # ActionPack, ActionMailer, and ActiveResource) are loaded.
+ # list. By default, all frameworks (Active Record, Active Support,
+ # Action Pack, Action Mailer, and Active Resource) are loaded.
def require_frameworks
configuration.frameworks.each { |framework| require(framework.to_s) }
rescue LoadError => e
@@ -237,7 +244,24 @@ module Rails
end
def load_gems
- @configuration.gems.each &:load
+ @configuration.gems.each(&:load)
+ end
+
+ def check_gem_dependencies
+ unloaded_gems = @configuration.gems.reject { |g| g.loaded? }
+ if unloaded_gems.size > 0
+ @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.}
+ end
+ else
+ @gems_dependencies_loaded = true
+ end
end
# Loads all plugins in <tt>config.plugin_paths</tt>. <tt>plugin_paths</tt>
@@ -283,12 +307,8 @@ module Rails
end
def load_observers
- if configuration.frameworks.include?(:active_record)
- if @configuration.gems.any? { |g| !g.loaded? }
- puts "Unable to instantiate observers, some gems that this application depends on are missing. Run 'rake gems:install'"
- else
- ActiveRecord::Base.instantiate_observers
- end
+ if @gems_dependencies_loaded && configuration.frameworks.include?(:active_record)
+ ActiveRecord::Base.instantiate_observers
end
end
@@ -326,7 +346,7 @@ module Rails
end
end
- # If the +RAILS_DEFAULT_LOGGER+ constant is already set, this initialization
+ # If the RAILS_DEFAULT_LOGGER constant is already set, this initialization
# routine does nothing. If the constant is not set, and Configuration#logger
# is not +nil+, this also does nothing. Otherwise, a new logger instance
# is created at Configuration#log_path, with a default log level of
@@ -359,10 +379,10 @@ module Rails
silence_warnings { Object.const_set "RAILS_DEFAULT_LOGGER", logger }
end
- # Sets the logger for ActiveRecord, ActionController, and ActionMailer
+ # Sets the logger for Active Record, Action Controller, and Action Mailer
# (but only for those frameworks that are to be loaded). If the framework's
# logger is already set, it is not changed, otherwise it is set to use
- # +RAILS_DEFAULT_LOGGER+.
+ # RAILS_DEFAULT_LOGGER.
def initialize_framework_logging
for framework in ([ :active_record, :action_controller, :action_mailer ] & configuration.frameworks)
framework.to_s.camelize.constantize.const_get("Base").logger ||= RAILS_DEFAULT_LOGGER
@@ -380,7 +400,7 @@ module Rails
ActionController::Base.view_paths = [configuration.view_path] if configuration.frameworks.include?(:action_controller) && ActionController::Base.view_paths.empty?
end
- # If ActionController is not one of the loaded frameworks (Configuration#frameworks)
+ # If Action Controller is not one of the loaded frameworks (Configuration#frameworks)
# this does nothing. Otherwise, it loads the routing definitions and sets up
# loading module used to lazily load controllers (Configuration#controller_paths).
def initialize_routing
@@ -409,13 +429,13 @@ module Rails
end
end
- # Sets the default value for Time.zone, and turns on ActiveRecord time_zone_aware_attributes.
+ # Sets the default value for Time.zone, and turns on ActiveRecord::Base#time_zone_aware_attributes.
# If assigned value cannot be matched to a TimeZone, an exception will be raised.
def initialize_time_zone
if configuration.time_zone
zone_default = Time.send!(:get_zone, configuration.time_zone)
unless zone_default
- raise "Value assigned to config.time_zone not recognized. Run `rake -D time` for a list of tasks for finding appropriate time zone names."
+ raise %{Value assigned to config.time_zone not recognized. Run "rake -D time" for a list of tasks for finding appropriate time zone names.}
end
Time.zone_default = zone_default
if configuration.frameworks.include?(:active_record)
@@ -443,14 +463,18 @@ module Rails
# Fires the user-supplied after_initialize block (Configuration#after_initialize)
def after_initialize
- configuration.after_initialize_blocks.each do |block|
- block.call
+ if @gems_dependencies_loaded
+ configuration.after_initialize_blocks.each do |block|
+ block.call
+ end
end
end
def load_application_initializers
- Dir["#{configuration.root_path}/config/initializers/**/*.rb"].sort.each do |initializer|
- load(initializer)
+ if @gems_dependencies_loaded
+ Dir["#{configuration.root_path}/config/initializers/**/*.rb"].sort.each do |initializer|
+ load(initializer)
+ end
end
end
@@ -475,22 +499,22 @@ module Rails
# The application's base directory.
attr_reader :root_path
- # A stub for setting options on ActionController::Base
+ # A stub for setting options on ActionController::Base.
attr_accessor :action_controller
- # A stub for setting options on ActionMailer::Base
+ # A stub for setting options on ActionMailer::Base.
attr_accessor :action_mailer
- # A stub for setting options on ActionView::Base
+ # A stub for setting options on ActionView::Base.
attr_accessor :action_view
- # A stub for setting options on ActiveRecord::Base
+ # A stub for setting options on ActiveRecord::Base.
attr_accessor :active_record
- # A stub for setting options on ActiveRecord::Base
+ # A stub for setting options on ActiveRecord::Base.
attr_accessor :active_resource
- # A stub for setting options on ActiveSupport
+ # A stub for setting options on ActiveSupport.
attr_accessor :active_support
# Whether or not classes should be cached (set to false if you want
@@ -618,9 +642,9 @@ module Rails
end
alias_method :breakpoint_server=, :breakpoint_server
- # Sets the default time_zone. Setting this will enable time_zone
- # awareness for ActiveRecord models and set the ActiveRecord default
- # timezone to :utc.
+ # Sets the default +time_zone+. Setting this will enable +time_zone+
+ # awareness for Active Record models and set the Active Record default
+ # timezone to <tt>:utc</tt>.
attr_accessor :time_zone
# Create a new Configuration instance, initialized with the default
@@ -685,7 +709,7 @@ module Rails
end
# Return the currently selected environment. By default, it returns the
- # value of the +RAILS_ENV+ constant.
+ # value of the RAILS_ENV constant.
def environment
::RAILS_ENV
end
@@ -843,7 +867,7 @@ end
# Needs to be duplicated from Active Support since its needed before Active
# Support is available. Here both Options and Hash are namespaced to prevent
-# conflicts with other implementations AND with the classes residing in ActiveSupport.
+# conflicts with other implementations AND with the classes residing in Active Support.
class Rails::OrderedOptions < Array #:nodoc:
def []=(key, value)
key = key.to_sym
diff --git a/railties/lib/rails/gem_dependency.rb b/railties/lib/rails/gem_dependency.rb
index 2034841cd2..9f088a18dd 100644
--- a/railties/lib/rails/gem_dependency.rb
+++ b/railties/lib/rails/gem_dependency.rb
@@ -31,12 +31,13 @@ module Rails
args << @requirement.to_s if @requirement
gem *args
else
- $LOAD_PATH << File.join(unpacked_paths.first, 'lib')
+ $LOAD_PATH.unshift File.join(unpacked_paths.first, 'lib')
+ ext = File.join(unpacked_paths.first, 'ext')
+ $LOAD_PATH.unshift(ext) if File.exist?(ext)
@frozen = true
end
@load_paths_added = true
rescue Gem::LoadError
- puts $!.to_s
end
def dependencies
@@ -73,7 +74,9 @@ module Rails
end
def install
- Gem::GemRunner.new.run(install_command)
+ cmd = "#{gem_command} #{install_command.join(' ')}"
+ puts cmd
+ puts %x(#{cmd})
end
def unpack_to(directory)
@@ -100,10 +103,14 @@ private ###################################################################
def specification
@spec ||= Gem.source_index.search(Gem::Dependency.new(@name, @requirement)).sort_by { |s| s.version }.last
end
+
+ def gem_command
+ RUBY_PLATFORM =~ /win32/ ? 'gem.bat' : 'gem'
+ end
def install_command
cmd = %w(install) << @name
- cmd << "--version" << "#{@requirement.to_s}" if @requirement
+ cmd << "--version" << %("#{@requirement.to_s}") if @requirement
cmd << "--source" << @source if @source
cmd
end
diff --git a/railties/lib/rails/mongrel_server/commands.rb b/railties/lib/rails/mongrel_server/commands.rb
index 3786a56fde..0a92f418ad 100644
--- a/railties/lib/rails/mongrel_server/commands.rb
+++ b/railties/lib/rails/mongrel_server/commands.rb
@@ -119,7 +119,7 @@ module Rails
config = RailsConfigurator.new(settings) do
defaults[:log] = $stdout if defaults[:environment] == 'development'
- Mongrel.log("=> Rails application starting on http://#{defaults[:host]}:#{defaults[:port]}")
+ Mongrel.log("=> Rails #{Rails.version} application starting on http://#{defaults[:host]}:#{defaults[:port]}")
unless defaults[:daemon]
Mongrel.log("=> Call with -d to detach")
diff --git a/railties/lib/rails/plugin.rb b/railties/lib/rails/plugin.rb
index 04f7e37a20..256f4b0132 100644
--- a/railties/lib/rails/plugin.rb
+++ b/railties/lib/rails/plugin.rb
@@ -98,23 +98,18 @@ module Rails
end
end
- # This Plugin subclass represents a Gem plugin. It behaves exactly like a
- # "traditional" Rails plugin, but doesn't expose any additional load paths,
- # since RubyGems has already taken care of things.
+ # This Plugin subclass represents a Gem plugin. Although RubyGems has already
+ # taken care of $LOAD_PATHs, it exposes its load_paths to add them
+ # to Dependencies.load_paths.
class GemPlugin < Plugin
-
# Initialize this plugin from a Gem::Specification.
def initialize(spec)
- super(File.join(spec.full_gem_path, "rails"))
+ super(File.join(spec.full_gem_path))
@name = spec.name
end
- def valid?
- true
- end
-
- def load_paths
- []
+ def init_path
+ File.join(directory, 'rails', 'init.rb')
end
end
end \ No newline at end of file
diff --git a/railties/lib/rails/rack.rb b/railties/lib/rails/rack.rb
new file mode 100644
index 0000000000..abcd0741bf
--- /dev/null
+++ b/railties/lib/rails/rack.rb
@@ -0,0 +1,5 @@
+module Rails
+ module Rack
+ autoload :Static, "rails/rack/static"
+ end
+end
diff --git a/railties/lib/rails/rack/static.rb b/railties/lib/rails/rack/static.rb
new file mode 100644
index 0000000000..45eb0e5921
--- /dev/null
+++ b/railties/lib/rails/rack/static.rb
@@ -0,0 +1,35 @@
+module Rails
+ module Rack
+ class Static
+ FILE_METHODS = %w(GET HEAD).freeze
+
+ def initialize(app)
+ @app = app
+ @file_server = ::Rack::File.new(File.join(RAILS_ROOT, "public"))
+ end
+
+ def call(env)
+ path = env['PATH_INFO'].chomp('/')
+ method = env['REQUEST_METHOD']
+ cached_path = (path.empty? ? 'index' : path) + ::ActionController::Base.page_cache_extension
+
+ if FILE_METHODS.include?(method)
+ if file_exist?(path)
+ return @file_server.call(env)
+ elsif file_exist?(cached_path)
+ env['PATH_INFO'] = cached_path
+ return @file_server.call(env)
+ end
+ end
+
+ @app.call(env)
+ end
+
+ private
+ def file_exist?(path)
+ full_path = File.join(@file_server.root, ::Rack::Utils.unescape(path))
+ File.file?(full_path) && File.readable?(full_path)
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/version.rb b/railties/lib/rails/version.rb
index fea63beea9..48d24da52e 100644
--- a/railties/lib/rails/version.rb
+++ b/railties/lib/rails/version.rb
@@ -1,8 +1,8 @@
module Rails
module VERSION #:nodoc:
MAJOR = 2
- MINOR = 0
- TINY = 991
+ MINOR = 1
+ TINY = 0
STRING = [MAJOR, MINOR, TINY].join('.')
end
diff --git a/railties/lib/rails_generator/base.rb b/railties/lib/rails_generator/base.rb
index 1ebcff9062..b5cfe79867 100644
--- a/railties/lib/rails_generator/base.rb
+++ b/railties/lib/rails_generator/base.rb
@@ -36,7 +36,7 @@ module Rails
# view.html.erb
#
# The directory name (+controller+) matches the name of the generator file
- # (controller_generator.rb) and class (+ControllerGenerator+). The files
+ # (controller_generator.rb) and class (ControllerGenerator). The files
# that will be copied or used as templates are stored in the +templates+
# directory.
#
diff --git a/railties/lib/rails_generator/commands.rb b/railties/lib/rails_generator/commands.rb
index 03b7d354a6..c0f8d05dde 100644
--- a/railties/lib/rails_generator/commands.rb
+++ b/railties/lib/rails_generator/commands.rb
@@ -155,7 +155,7 @@ HELP
# such as the rest of the user's app.
def class_collisions(*class_names)
- # Initialize some check varibles
+ # Initialize some check variables
last_class = Object
current_class = nil
name = nil
@@ -380,12 +380,14 @@ HELP
# Thanks to Florian Gross (flgr).
def raise_class_collision(class_name)
message = <<end_message
- The name '#{class_name}' is reserved by Ruby on Rails.
+ The name '#{class_name}' is either already used in your application or reserved by Ruby on Rails.
Please choose an alternative and run this generator again.
end_message
if suggest = find_synonyms(class_name)
- message << "\n Suggestions: \n\n"
- message << suggest.join("\n")
+ if suggest.any?
+ message << "\n Suggestions: \n\n"
+ message << suggest.join("\n")
+ end
end
raise UsageError, message
end
diff --git a/railties/lib/rails_generator/generators/components/migration/USAGE b/railties/lib/rails_generator/generators/components/migration/USAGE
index 3e914a5d7b..b83c657963 100644
--- a/railties/lib/rails_generator/generators/components/migration/USAGE
+++ b/railties/lib/rails_generator/generators/components/migration/USAGE
@@ -2,7 +2,7 @@ Description:
Stubs out a new database migration. Pass the migration name, either
CamelCased or under_scored, and an optional list of attribute pairs as arguments.
- A migration class is generated in db/migrate prefixed by the latest migration number.
+ A migration class is generated in db/migrate prefixed by a timestamp of the current date and time.
You can name your migration in either of these formats to generate add/remove
column lines from supplied attributes: AddColumnsToTable or RemoveColumnsFromTable
@@ -10,12 +10,12 @@ Description:
Example:
`./script/generate migration AddSslFlag`
- With 4 existing migrations, this creates the AddSslFlag migration in
- db/migrate/005_add_ssl_flag.rb
+ If the current date is May 14, 2008 and the current time 09:09:12, this creates the AddSslFlag migration
+ db/migrate/20080514090912_add_ssl_flag.rb
`./script/generate migration AddTitleBodyToPost title:string body:text published:boolean`
- This will create the AddTitleBodyToPost in db/migrate/005_add_title_body_to_post.rb with
+ This will create the AddTitleBodyToPost in db/migrate/20080514090912_add_title_body_to_post.rb with
this in the Up migration:
add_column :posts, :title, :string
diff --git a/railties/lib/rails_generator/generators/components/scaffold/USAGE b/railties/lib/rails_generator/generators/components/scaffold/USAGE
index a0e4baea08..810aea16f1 100644
--- a/railties/lib/rails_generator/generators/components/scaffold/USAGE
+++ b/railties/lib/rails_generator/generators/components/scaffold/USAGE
@@ -1,10 +1,11 @@
Description:
Scaffolds an entire resource, from model and migration to controller and
views, along with a full test suite. The resource is ready to use as a
- starting point for your restful, resource-oriented application.
+ starting point for your RESTful, resource-oriented application.
- Pass the name of the model, either CamelCased or under_scored, as the first
- argument, and an optional list of attribute pairs.
+ Pass the name of the model (in singular form), either CamelCased or
+ under_scored, as the first argument, and an optional list of attribute
+ pairs.
Attribute pairs are column_name:sql_type arguments specifying the
model's attributes. Timestamps are added by default, so you don't have to
@@ -13,13 +14,16 @@ Description:
You don't have to think up every attribute up front, but it helps to
sketch out a few so you can start working with the resource immediately.
- For example, `scaffold post title:string body:text published:boolean`
+ For example, 'scaffold post title:string body:text published:boolean'
gives you a model with those three attributes, a controller that handles
the create/show/update/destroy, forms to create and edit your posts, and
an index that lists them all, as well as a map.resources :posts
declaration in config/routes.rb.
+ If you want to remove all the generated files, run
+ 'script/destroy scaffold ModelName'.
+
Examples:
- `./script/generate scaffold post` # no attributes, view will be anemic
+ `./script/generate scaffold post`
`./script/generate scaffold post title:string body:text published:boolean`
`./script/generate scaffold purchase order_id:integer amount:decimal`
diff --git a/railties/lib/rails_generator/scripts.rb b/railties/lib/rails_generator/scripts.rb
index f857f68de4..9b1a99838a 100644
--- a/railties/lib/rails_generator/scripts.rb
+++ b/railties/lib/rails_generator/scripts.rb
@@ -45,7 +45,7 @@ module Rails
usage = "\nInstalled Generators\n"
Rails::Generator::Base.sources.inject([]) do |mem, source|
# Using an association list instead of a hash to preserve order,
- # for esthetic reasons more than anything else.
+ # for aesthetic reasons more than anything else.
label = source.label.to_s.capitalize
pair = mem.assoc(label)
mem << (pair = [label, []]) if pair.nil?
diff --git a/railties/lib/rails_generator/scripts/destroy.rb b/railties/lib/rails_generator/scripts/destroy.rb
index 4fcbc3e0df..a7c2a14751 100644
--- a/railties/lib/rails_generator/scripts/destroy.rb
+++ b/railties/lib/rails_generator/scripts/destroy.rb
@@ -3,7 +3,7 @@ require File.dirname(__FILE__) + '/../scripts'
module Rails::Generator::Scripts
class Destroy < Base
mandatory_options :command => :destroy
-
+
protected
def usage_message
usage = "\nInstalled Generators\n"
@@ -15,14 +15,13 @@ module Rails::Generator::Scripts
usage << <<end_blurb
-This script will destroy all files created by the corresponding
-script/generate command. For instance, script/destroy migration CreatePost
-will delete the appropriate ###_create_post.rb file in db/migrate, while
-script/destroy scaffold Post will delete the posts controller and
+script/generate command. For instance, 'script/destroy migration CreatePost'
+will delete the appropriate XXX_create_post.rb migration file in db/migrate,
+while 'script/destroy scaffold Post' will delete the posts controller and
views, post model and migration, all associated tests, and the map.resources
:posts line in config/routes.rb.
-
-For instructions on finding new generators, run script/generate
+
+For instructions on finding new generators, run script/generate.
end_blurb
return usage
end
diff --git a/railties/lib/rails_generator/secret_key_generator.rb b/railties/lib/rails_generator/secret_key_generator.rb
index 64fbbb90f8..5ae492312e 100644
--- a/railties/lib/rails_generator/secret_key_generator.rb
+++ b/railties/lib/rails_generator/secret_key_generator.rb
@@ -23,7 +23,7 @@ module Rails
# Generate a random secret key by using the Win32 API. Raises LoadError
# if the current platform cannot make use of the Win32 API. Raises
- # SystemCallError if some other error occured.
+ # SystemCallError if some other error occurred.
def generate_secret_with_win32_api
# Following code is based on David Garamond's GUID library for Ruby.
require 'Win32API'
diff --git a/railties/lib/tasks/databases.rake b/railties/lib/tasks/databases.rake
index f40f8463f7..8077d0a401 100644
--- a/railties/lib/tasks/databases.rake
+++ b/railties/lib/tasks/databases.rake
@@ -173,7 +173,7 @@ namespace :db do
pending_migrations.each do |pending_migration|
puts ' %4d %s' % [pending_migration.version, pending_migration.name]
end
- abort "Run `rake db:migrate` to update your database then try again."
+ abort %{Run "rake db:migrate" to update your database then try again.}
end
end
end
diff --git a/railties/lib/tasks/gems.rake b/railties/lib/tasks/gems.rake
index c18fea2d60..0321e60e0f 100644
--- a/railties/lib/tasks/gems.rake
+++ b/railties/lib/tasks/gems.rake
@@ -1,5 +1,5 @@
desc "List the gems that this rails application depends on"
-task :gems => :environment do
+task :gems => 'gems:base' do
Rails.configuration.gems.each do |gem|
code = gem.loaded? ? (gem.frozen? ? "F" : "I") : " "
puts "[#{code}] #{gem.name} #{gem.requirement.to_s}"
@@ -10,8 +10,14 @@ task :gems => :environment do
end
namespace :gems do
+ task :base do
+ $rails_gem_installer = true
+ Rake::Task[:environment].invoke
+ end
+
desc "Build any native extensions for unpacked gems"
task :build do
+ $rails_gem_installer = true
require 'rails/gem_builder'
Dir[File.join(RAILS_ROOT, 'vendor', 'gems', '*')].each do |gem_dir|
spec_file = File.join(gem_dir, '.specification')
@@ -24,14 +30,14 @@ namespace :gems do
end
desc "Installs all required gems for this application."
- task :install => :environment do
+ task :install => :base do
require 'rubygems'
require 'rubygems/gem_runner'
Rails.configuration.gems.each { |gem| gem.install unless gem.loaded? }
end
desc "Unpacks the specified gem into vendor/gems."
- task :unpack => :environment do
+ task :unpack => :base do
require 'rubygems'
require 'rubygems/gem_runner'
Rails.configuration.gems.each do |gem|
diff --git a/railties/test/fixtures/about_yml_plugins/bad_about_yml/about.yml b/railties/test/fixtures/about_yml_plugins/bad_about_yml/about.yml
index 79d5721a53..fe80872a16 100644
--- a/railties/test/fixtures/about_yml_plugins/bad_about_yml/about.yml
+++ b/railties/test/fixtures/about_yml_plugins/bad_about_yml/about.yml
@@ -1 +1 @@
-# an empty yaml file - any content in here seems to get parsed as a string \ No newline at end of file
+# an empty YAML file - any content in here seems to get parsed as a string \ No newline at end of file
diff --git a/railties/test/generators/generator_test_helper.rb b/railties/test/generators/generator_test_helper.rb
index c99df6e2d3..80d5b145be 100644
--- a/railties/test/generators/generator_test_helper.rb
+++ b/railties/test/generators/generator_test_helper.rb
@@ -86,19 +86,19 @@ class GeneratorTestCase < Test::Unit::TestCase
# don't complain, test/unit
end
- # Instantiates the Generator
+ # Instantiates the Generator.
def build_generator(name, params)
Rails::Generator::Base.instance(name, params)
end
- # Runs the create command (like the command line does)
+ # Runs the +create+ command (like the command line does).
def run_generator(name, params)
silence_generator do
build_generator(name, params).command(:create).invoke!
end
end
- # Silences the logger temporarily and returns the output as a String
+ # Silences the logger temporarily and returns the output as a String.
def silence_generator
logger_original = Rails::Generator::Base.logger
myout = StringIO.new
@@ -108,7 +108,7 @@ class GeneratorTestCase < Test::Unit::TestCase
myout.string
end
- # asserts that the given controller was generated.
+ # Asserts that the given controller was generated.
# It takes a name or symbol without the <tt>_controller</tt> part and an optional super class.
# The contents of the class source file is passed to a block.
def assert_generated_controller_for(name, parent = "ApplicationController")
@@ -117,44 +117,44 @@ class GeneratorTestCase < Test::Unit::TestCase
end
end
- # asserts that the given model was generated.
+ # Asserts that the given model was generated.
# It takes a name or symbol and an optional super class.
- # the contents of the class source file is passed to a block.
+ # The contents of the class source file is passed to a block.
def assert_generated_model_for(name, parent = "ActiveRecord::Base")
assert_generated_class "app/models/#{name.to_s.underscore}", parent do |body|
yield body if block_given?
end
end
- # asserts that the given helper was generated.
- # It takes a name or symbol without the <tt>_helper</tt> part
- # the contents of the module source file is passed to a block.
+ # Asserts that the given helper was generated.
+ # It takes a name or symbol without the <tt>_helper</tt> part.
+ # The contents of the module source file is passed to a block.
def assert_generated_helper_for(name)
assert_generated_module "app/helpers/#{name.to_s.underscore}_helper" do |body|
yield body if block_given?
end
end
- # asserts that the given functional test was generated.
+ # Asserts that the given functional test was generated.
# It takes a name or symbol without the <tt>_controller_test</tt> part and an optional super class.
- # the contents of the class source file is passed to a block.
+ # The contents of the class source file is passed to a block.
def assert_generated_functional_test_for(name, parent = "ActionController::TestCase")
assert_generated_class "test/functional/#{name.to_s.underscore}_controller_test",parent do |body|
yield body if block_given?
end
end
- # asserts that the given unit test was generated.
+ # Asserts that the given unit test was generated.
# It takes a name or symbol without the <tt>_test</tt> part and an optional super class.
- # the contents of the class source file is passed to a block.
+ # The contents of the class source file is passed to a block.
def assert_generated_unit_test_for(name, parent = "ActiveSupport::TestCase")
assert_generated_class "test/unit/#{name.to_s.underscore}_test", parent do |body|
yield body if block_given?
end
end
- # asserts that the given file was generated.
- # the contents of the file is passed to a block.
+ # Asserts that the given file was generated.
+ # The contents of the file is passed to a block.
def assert_generated_file(path)
assert_file_exists(path)
File.open("#{RAILS_ROOT}/#{path}") do |f|
@@ -168,9 +168,9 @@ class GeneratorTestCase < Test::Unit::TestCase
"The file '#{RAILS_ROOT}/#{path}' should exist"
end
- # asserts that the given class source file was generated.
+ # Asserts that the given class source file was generated.
# It takes a path without the <tt>.rb</tt> part and an optional super class.
- # the contents of the class source file is passed to a block.
+ # The contents of the class source file is passed to a block.
def assert_generated_class(path, parent = nil)
# FIXME: Sucky way to detect namespaced classes
if path.split('/').size > 3
@@ -187,9 +187,9 @@ class GeneratorTestCase < Test::Unit::TestCase
end
end
- # asserts that the given module source file was generated.
+ # Asserts that the given module source file was generated.
# It takes a path without the <tt>.rb</tt> part.
- # the contents of the class source file is passed to a block.
+ # The contents of the class source file is passed to a block.
def assert_generated_module(path)
# FIXME: Sucky way to detect namespaced modules
if path.split('/').size > 3
@@ -206,18 +206,18 @@ class GeneratorTestCase < Test::Unit::TestCase
end
end
- # asserts that the given css stylesheet file was generated.
+ # Asserts that the given CSS stylesheet file was generated.
# It takes a path without the <tt>.css</tt> part.
- # the contents of the stylesheet source file is passed to a block.
+ # The contents of the stylesheet source file is passed to a block.
def assert_generated_stylesheet(path)
assert_generated_file("public/stylesheets/#{path}.css") do |body|
yield body if block_given?
end
end
- # asserts that the given yaml file was generated.
+ # Asserts that the given YAML file was generated.
# It takes a path without the <tt>.yml</tt> part.
- # the parsed yaml tree is passed to a block.
+ # The parsed YAML tree is passed to a block.
def assert_generated_yaml(path)
assert_generated_file("#{path}.yml") do |body|
yaml = YAML.load(body)
@@ -226,18 +226,18 @@ class GeneratorTestCase < Test::Unit::TestCase
end
end
- # asserts that the given fixtures yaml file was generated.
+ # Asserts that the given fixtures YAML file was generated.
# It takes a fixture name without the <tt>.yml</tt> part.
- # the parsed yaml tree is passed to a block.
+ # The parsed YAML tree is passed to a block.
def assert_generated_fixtures_for(name)
assert_generated_yaml "test/fixtures/#{name.to_s.underscore}" do |yaml|
yield yaml if block_given?
end
end
- # asserts that the given views were generated.
+ # Asserts that the given views were generated.
# It takes a controller name and a list of views (including extensions).
- # The body of each view is passed to a block
+ # The body of each view is passed to a block.
def assert_generated_views_for(name, *actions)
actions.each do |action|
assert_generated_file("app/views/#{name.to_s.underscore}/#{action}") do |body|
@@ -262,7 +262,7 @@ class GeneratorTestCase < Test::Unit::TestCase
assert !File.exist?(migration_file), "should not create migration #{migration_file}"
end
- # asserts that the given resource was added to the routes.
+ # Asserts that the given resource was added to the routes.
def assert_added_route_for(name)
assert_generated_file("config/routes.rb") do |body|
assert_match /map.resources :#{name.to_s.underscore}/, body,
@@ -270,7 +270,7 @@ class GeneratorTestCase < Test::Unit::TestCase
end
end
- # asserts that the given methods are defined in the body.
+ # Asserts that the given methods are defined in the body.
# This does assume standard rails code conventions with regards to the source code.
# The body of each individual method is passed to a block.
def assert_has_method(body, *methods)
@@ -280,7 +280,7 @@ class GeneratorTestCase < Test::Unit::TestCase
end
end
- # asserts that the given column is defined in the migration
+ # Asserts that the given column is defined in the migration.
def assert_generated_column(body, name, type)
assert_match /t\.#{type.to_s} :#{name.to_s}/, body, "should have column #{name.to_s} defined"
end