From ccd9ef158953e30e66a4da143314955cd64e71c8 Mon Sep 17 00:00:00 2001 From: Jeff Dean Date: Wed, 12 Nov 2008 01:21:09 -0500 Subject: Updated preparation section of plugins guide --- .../source/creating_plugins/odds_and_ends.txt | 21 +++++----- .../guides/source/creating_plugins/preparation.txt | 47 ++++++++++------------ 2 files changed, 33 insertions(+), 35 deletions(-) (limited to 'railties/doc/guides/source/creating_plugins') diff --git a/railties/doc/guides/source/creating_plugins/odds_and_ends.txt b/railties/doc/guides/source/creating_plugins/odds_and_ends.txt index eb127f73ca..32da7ed7f3 100644 --- a/railties/doc/guides/source/creating_plugins/odds_and_ends.txt +++ b/railties/doc/guides/source/creating_plugins/odds_and_ends.txt @@ -4,27 +4,30 @@ 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: +If you reopen any classes in init.rb itself your changes will potentially be made to the wrong module. As a rule, it's better not to open any classes in `init.rb`, and it makes the plugin more difficult to turn into a gem. -The first way is to explicitly define the top-level module space for all modules and classes, like `::Hash`: +A better alternative is to reopen the class in a different file, and require that file from `init.rb`. + +If you must reopen a class in `init.rb`, there are various techniques. One way is to use `module_eval` or `class_eval`: + +*vendor/plugins/yaffle/init.rb* [source, ruby] --------------------------------------------------- -# File: vendor/plugins/yaffle/init.rb - -class ::Hash +Hash.class_eval do def is_a_special_hash? true end end --------------------------------------------------- -OR you can use `module_eval` or `class_eval`: +Another way is to explicitly define the top-level module space for all modules and classes, like `::Hash`: ---------------------------------------------------- -# File: vendor/plugins/yaffle/init.rb +*vendor/plugins/yaffle/init.rb* -Hash.class_eval do +[source, ruby] +--------------------------------------------------- +class ::Hash def is_a_special_hash? true end diff --git a/railties/doc/guides/source/creating_plugins/preparation.txt b/railties/doc/guides/source/creating_plugins/preparation.txt index 77e3a3561f..83717c7ac8 100644 --- a/railties/doc/guides/source/creating_plugins/preparation.txt +++ b/railties/doc/guides/source/creating_plugins/preparation.txt @@ -2,11 +2,12 @@ === 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 examples in this guide require that you have a working rails application. To create a simple rails app execute: ------------------------------------------------ -rails plugin_demo -cd plugin_demo +gem install rails +rails yaffle_guide +cd yaffle_guide script/generate scaffold bird name:string rake db:migrate script/server @@ -14,25 +15,28 @@ script/server Then navigate to http://localhost:3000/birds. Make sure you have a functioning rails app before continuing. +.Editor's note: NOTE: The aforementioned instructions will work for sqlite3. For more detailed instructions on how to create a rails app for other databases see the API docs. -=== Create the plugin === +=== Generate the plugin skeleton === -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. +Rails ships with a plugin generator which creates a basic plugin skeleton. Pass the plugin name, either 'CamelCased' or 'under_scored', as an argument. Pass `\--with-generator` to add an example generator also. This creates a plugin in 'vendor/plugins' including an 'init.rb' and 'README' as well as standard 'lib', 'task', and 'test' directories. Examples: ---------------------------------------------- -./script/generate plugin BrowserFilters -./script/generate plugin BrowserFilters --with-generator +./script/generate plugin yaffle +./script/generate plugin yaffle --with-generator ---------------------------------------------- -Later in the plugin we will create a generator, so go ahead and add the `\--with-generator` option now: +To get more detailed help on the plugin generator, type `./script/generate plugin`. + +Later on this guide will describe how to work with generators, so go ahead and generate your plugin with the `\--with-generator` option now: ---------------------------------------------- -script/generate plugin yaffle --with-generator +./script/generate plugin yaffle --with-generator ---------------------------------------------- You should see the following output: @@ -57,19 +61,10 @@ create vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb create vendor/plugins/yaffle/generators/yaffle/USAGE ---------------------------------------------- -For this plugin you won't need the file 'vendor/plugins/yaffle/lib/yaffle.rb' so you can delete that. - ----------------------------------------------- -rm vendor/plugins/yaffle/lib/yaffle.rb ----------------------------------------------- - -.Editor's note: -NOTE: Many plugin authors prefer to keep this file, and add all of the require statements in it. That way, they only line in init.rb would be `require "yaffle"`. If you are developing a plugin that has a lot of files in the lib directory, you may want to create a subdirectory like lib/yaffle and store your files in there. That way your init.rb file stays clean - === Setup the plugin for testing === -Testing plugins that use the entire Rails stack can be complex, and the generator doesn't offer any help. In this tutorial you will learn how to test your plugin against multiple different adapters using ActiveRecord. This tutorial will not cover how to use fixtures in plugin tests. +In this guide you will learn how to test your plugin against multiple different adapters using Active Record. This guide 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: @@ -77,8 +72,6 @@ To setup your plugin to allow for easy testing you'll need to add 3 files: * A 'schema.rb' file with your table definitions. * A test helper that sets up the database before your tests. -For this plugin you'll need 2 tables/models, Hickwalls and Wickwalls, so add the following files: - *vendor/plugins/yaffle/test/database.yml:* ---------------------------------------------- @@ -105,7 +98,9 @@ mysql: :database: yaffle_plugin_test ---------------------------------------------- -*vendor/plugins/yaffle/test/test_helper.rb:* +For this guide you'll need 2 tables/models, Hickwalls and Wickwalls, so add the following: + +*vendor/plugins/yaffle/test/schema.rb:* [source, ruby] ---------------------------------------------- @@ -121,9 +116,12 @@ ActiveRecord::Schema.define(:version => 0) do t.datetime :last_tweeted_at end end +---------------------------------------------- -# File: vendor/plugins/yaffle/test/test_helper.rb +*vendor/plugins/yaffle/test/test_helper.rb:* +[source, ruby] +---------------------------------------------- ENV['RAILS_ENV'] = 'test' ENV['RAILS_ROOT'] ||= File.dirname(__FILE__) + '/../../../..' @@ -135,7 +133,6 @@ 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' @@ -160,10 +157,8 @@ 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 ---------------------------------------------- -- cgit v1.2.3 From 6b143ab86f88cf9e0572352c9afec4936995b4a4 Mon Sep 17 00:00:00 2001 From: Jeff Dean Date: Wed, 12 Nov 2008 01:33:53 -0500 Subject: Plugins Guide: added example of how to run tests, including how to run with multiple databases --- .../guides/source/creating_plugins/preparation.txt | 58 ++++++++++++++++++++++ 1 file changed, 58 insertions(+) (limited to 'railties/doc/guides/source/creating_plugins') diff --git a/railties/doc/guides/source/creating_plugins/preparation.txt b/railties/doc/guides/source/creating_plugins/preparation.txt index 83717c7ac8..dc9ef6bc29 100644 --- a/railties/doc/guides/source/creating_plugins/preparation.txt +++ b/railties/doc/guides/source/creating_plugins/preparation.txt @@ -162,3 +162,61 @@ end class Wickwall < ActiveRecord::Base end ---------------------------------------------- + +=== Run the plugin tests === + +Once you have these files in place, you can write your first test to ensure that your plugin-testing setup is correct. By default rails generates a file in 'vendor/plugins/yaffle/test/yaffle_test.rb' with a sample test. Replace the contents of that file with: + +*vendor/plugins/yaffle/test/yaffle_test.rb:* + +[source, ruby] +---------------------------------------------- +require File.dirname(__FILE__) + '/test_helper.rb' + +class YaffleTest < Test::Unit::TestCase + + def test_active_record_classes_from_test_helper + assert_kind_of Hickwall, Hickwall.new + assert_kind_of Wickwall, Wickwall.new + end + +end +---------------------------------------------- + +To run this, go to the plugin directory and run `rake`: + +---------------------------------------------- +cd vendor/plugins/yaffle +rake +---------------------------------------------- + +You should see output like: + +---------------------------------------------- +/opt/local/bin/ruby -Ilib:lib "/opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader.rb" "test/yaffle_test.rb" +-- create_table(:hickwalls, {:force=>true}) + -> 0.0220s +-- create_table(:wickwalls, {:force=>true}) + -> 0.0077s +-- initialize_schema_migrations_table() + -> 0.0007s +-- assume_migrated_upto_version(0) + -> 0.0007s +Loaded suite /opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader +Started +. +Finished in 0.002236 seconds. + +1 test, 1 assertion, 0 failures, 0 errors +---------------------------------------------- + +By default the setup above runs your tests with sqlite or sqlite3. To run tests with one of the other connection strings specified in database.yml, pass the DB environment variable to rake: + +---------------------------------------------- +rake DB=sqlite +rake DB=sqlite3 +rake DB=mysql +rake DB=postgresql +---------------------------------------------- + +Now you are ready to test-drive your plugin! -- cgit v1.2.3 From 7f24653e7a39da9eb85b282e929d0712b2f1c9b7 Mon Sep 17 00:00:00 2001 From: Jeff Dean Date: Wed, 12 Nov 2008 01:48:02 -0500 Subject: Plugins guide: Cleanup the intro --- .../doc/guides/source/creating_plugins/index.txt | 88 +++++++--------------- 1 file changed, 26 insertions(+), 62 deletions(-) (limited to 'railties/doc/guides/source/creating_plugins') diff --git a/railties/doc/guides/source/creating_plugins/index.txt b/railties/doc/guides/source/creating_plugins/index.txt index f2ed6ed8bb..d3042f8d56 100644 --- a/railties/doc/guides/source/creating_plugins/index.txt +++ b/railties/doc/guides/source/creating_plugins/index.txt @@ -1,68 +1,32 @@ The Basics of Creating Rails Plugins ==================================== -Pretend for a moment that you are an avid bird watcher. Your favorite bird is the Yaffle, and you want to create a plugin that allows other developers to share in the Yaffle goodness. - -In this tutorial you will learn how to create a plugin that includes: - - * Core Extensions - extending String with a `to_squawk` method: -+ -[source, ruby] -------------------------------------------- -# Anywhere -"hello!".to_squawk # => "squawk! hello!" -------------------------------------------- - -* An `acts_as_yaffle` method for ActiveRecord models that adds a `squawk` method: -+ -[source, ruby] -------------------------------------------- -class Hickwall < ActiveRecord::Base - acts_as_yaffle :yaffle_text_field => :last_sang_at -end - -Hickwall.new.squawk("Hello World") -------------------------------------------- - -* A view helper that will print out squawking info: -+ -[source, ruby] -------------------------------------------- -squawk_info_for(@hickwall) -------------------------------------------- - -* A generator that creates a migration to add squawk columns to a model: -+ -------------------------------------------- -script/generate yaffle hickwall -------------------------------------------- - -* A custom generator command: -+ -[source, ruby] -------------------------------------------- -class YaffleGenerator < Rails::Generator::NamedBase - def manifest - m.yaffle_definition - end -end -------------------------------------------- - -* A custom route method: -+ -[source, ruby] -------------------------------------------- -ActionController::Routing::Routes.draw do |map| - map.yaffles -end -------------------------------------------- - -In addition you'll learn how to: - - * test your plugins. - * work with 'init.rb', how to store model, views, controllers, helpers and even other plugins in your plugins. - * create documentation for your plugin. - * write custom Rake tasks in your plugin. +A Rails plugin is either an extension or a modification of the core framework. Plugins provide: + + * a way for developers to share bleeding-edge ideas without hurting the stable code base + * a segmented architecture so that units of code can be fixed or updated on their own release schedule + * an outlet for the core developers so that they don’t have to include every cool new feature under the sun + +After reading this guide you should be familiar with: + + * Creating a plugin from scratch + * Writing and running tests for the plugin + * Storing models, views, controllers, helpers and even other plugins in your plugins + * Writing generators + * Writing custom Rake tasks in your plugin + * Generating RDoc documentation for your plugin + * Avoiding common pitfalls with 'init.rb' + +This guide describes how to build a test-driven plugin that will: + + * Extend core ruby classes like Hash and String + * Add methods to ActiveRecord::Base in the tradition of the 'acts_as' plugins + * Add a view helper that can be used in erb templates + * Add a new generator that will generate a migration + * Add a custom generator command + * A custom route method that can be used in routes.rb + +For the purpose of this guide pretend for a moment that you are an avid bird watcher. Your favorite bird is the Yaffle, and you want to create a plugin that allows other developers to share in the Yaffle goodness. First, you need to get setup for development. include::preparation.txt[] -- cgit v1.2.3 From 40bc386ed8cc403050292ab19428f1e467fa1737 Mon Sep 17 00:00:00 2001 From: Jeff Dean Date: Wed, 12 Nov 2008 02:05:19 -0500 Subject: Plugin Guide: cleaned up file paths, made formatting more consistent --- .../source/creating_plugins/acts_as_yaffle.txt | 29 ++++++++++++---------- .../source/creating_plugins/custom_generator.txt | 14 +++++------ .../source/creating_plugins/custom_route.txt | 16 ++++++------ .../creating_plugins/migration_generator.txt | 20 +++++++++------ .../source/creating_plugins/odds_and_ends.txt | 4 +-- .../source/creating_plugins/string_to_squawk.txt | 21 ++++++++-------- .../guides/source/creating_plugins/view_helper.txt | 12 ++++----- 7 files changed, 62 insertions(+), 54 deletions(-) (limited to 'railties/doc/guides/source/creating_plugins') diff --git a/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt b/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt index 12d40deb18..06878543e4 100644 --- a/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt +++ b/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt @@ -4,10 +4,10 @@ A common pattern in plugins is to add a method called `acts_as_something` to mod 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. +*vendor/plugins/yaffle/test/acts_as_yaffle_test.rb* + [source, ruby] ------------------------------------------------------ -# File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb - require File.dirname(__FILE__) + '/test_helper.rb' class Hickwall < ActiveRecord::Base @@ -18,16 +18,18 @@ class ActsAsYaffleTest < Test::Unit::TestCase end ------------------------------------------------------ +*vendor/plugins/lib/acts_as_yaffle.rb* + [source, ruby] ------------------------------------------------------ -# File: vendor/plugins/lib/acts_as_yaffle.rb - module Yaffle end ------------------------------------------------------ One of the most common plugin patterns for `acts_as_yaffle` plugins is to structure your file like so: +*vendor/plugins/lib/acts_as_yaffle.rb* + [source, ruby] ------------------------------------------------------ module Yaffle @@ -65,10 +67,10 @@ 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: +*vendor/plugins/yaffle/test/acts_as_yaffle_test.rb* + [source, ruby] ------------------------------------------------------ -# File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb - require File.dirname(__FILE__) + '/test_helper.rb' class ActsAsYaffleTest < Test::Unit::TestCase @@ -92,10 +94,10 @@ end To make these tests pass, you could modify your `acts_as_yaffle` file like so: +*vendor/plugins/yaffle/lib/acts_as_yaffle.rb* + [source, ruby] ------------------------------------------------------ -# File: vendor/plugins/yaffle/lib/acts_as_yaffle.rb - module Yaffle def self.included(base) base.send :extend, ClassMethods @@ -117,10 +119,10 @@ end Now you can add tests for the instance methods, and the instance method itself: +*vendor/plugins/yaffle/test/acts_as_yaffle_test.rb* + [source, ruby] ------------------------------------------------------ -# File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb - require File.dirname(__FILE__) + '/test_helper.rb' class ActsAsYaffleTest < Test::Unit::TestCase @@ -163,10 +165,10 @@ class ActsAsYaffleTest < Test::Unit::TestCase end ------------------------------------------------------ +*vendor/plugins/yaffle/lib/acts_as_yaffle.rb* + [source, ruby] ------------------------------------------------------ -# File: vendor/plugins/yaffle/lib/acts_as_yaffle.rb - module Yaffle def self.included(base) base.send :extend, ClassMethods @@ -190,4 +192,5 @@ module Yaffle end ------------------------------------------------------ -Note the use of `write_attribute` to write to the field in model. +.Editor's note: +NOTE: The use of `write_attribute` to write to the field in model is just one example of how a plugin can interact with the model, and will not always be the right method to use. For example, you could also use `send("#{self.class.yaffle_text_field}=", string.to_squawk)`. diff --git a/railties/doc/guides/source/creating_plugins/custom_generator.txt b/railties/doc/guides/source/creating_plugins/custom_generator.txt index 6d9613ea01..a8cf1b48ce 100644 --- a/railties/doc/guides/source/creating_plugins/custom_generator.txt +++ b/railties/doc/guides/source/creating_plugins/custom_generator.txt @@ -8,19 +8,20 @@ You may have noticed above that you can used one of the built-in rails migration Working with the internals of generators is beyond the scope of this tutorial, but here is a basic example: +*vendor/plugins/yaffle/init.rb* + [source, ruby] ----------------------------------------------------------- -# File: vendor/plugins/yaffle/init.rb require "commands" Rails::Generator::Commands::Create.send :include, Yaffle::Generator::Commands::Create Rails::Generator::Commands::Destroy.send :include, Yaffle::Generator::Commands::Destroy Rails::Generator::Commands::List.send :include, Yaffle::Generator::Commands::List ----------------------------------------------------------- +*vendor/plugins/yaffle/lib/commands.rb* + [source, ruby] ----------------------------------------------------------- -# File: vendor/plugins/yaffle/lib/commands.rb - require 'rails_generator' require 'rails_generator/commands' @@ -49,16 +50,15 @@ module Yaffle #:nodoc: end ----------------------------------------------------------- +*vendor/plugins/yaffle/generators/yaffle/templates/definition.txt* ----------------------------------------------------------- -# File: vendor/plugins/yaffle/generators/yaffle/templates/definition.txt - Yaffle is a bird ----------------------------------------------------------- +*vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb* + [source, ruby] ----------------------------------------------------------- -# File: vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb - class YaffleGenerator < Rails::Generator::NamedBase def manifest m.yaffle_definition diff --git a/railties/doc/guides/source/creating_plugins/custom_route.txt b/railties/doc/guides/source/creating_plugins/custom_route.txt index 7e399247ee..1fce902a4e 100644 --- a/railties/doc/guides/source/creating_plugins/custom_route.txt +++ b/railties/doc/guides/source/creating_plugins/custom_route.txt @@ -2,10 +2,10 @@ 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. +*vendor/plugins/yaffle/test/routing_test.rb* + [source, ruby] -------------------------------------------------------- -# File: vendor/plugins/yaffle/test/routing_test.rb - require "#{File.dirname(__FILE__)}/test_helper" class RoutingTest < Test::Unit::TestCase @@ -33,18 +33,18 @@ class RoutingTest < Test::Unit::TestCase end -------------------------------------------------------- +*vendor/plugins/yaffle/init.rb* + [source, ruby] -------------------------------------------------------- -# File: vendor/plugins/yaffle/init.rb - require "routing" ActionController::Routing::RouteSet::Mapper.send :include, Yaffle::Routing::MapperExtensions -------------------------------------------------------- +*vendor/plugins/yaffle/lib/routing.rb* + [source, ruby] -------------------------------------------------------- -# File: vendor/plugins/yaffle/lib/routing.rb - module Yaffle #:nodoc: module Routing #:nodoc: module MapperExtensions @@ -56,10 +56,10 @@ module Yaffle #:nodoc: end -------------------------------------------------------- +*config/routes.rb* + [source, ruby] -------------------------------------------------------- -# File: config/routes.rb - ActionController::Routing::Routes.draw do |map| ... map.yaffles diff --git a/railties/doc/guides/source/creating_plugins/migration_generator.txt b/railties/doc/guides/source/creating_plugins/migration_generator.txt index 598a0c8437..1a477a69ab 100644 --- a/railties/doc/guides/source/creating_plugins/migration_generator.txt +++ b/railties/doc/guides/source/creating_plugins/migration_generator.txt @@ -6,11 +6,15 @@ We'll be relying on the built-in rails generate template for this tutorial. Goi Type: - script/generate +------------------------------------------------------------------ +script/generate +------------------------------------------------------------------ You should see the line: - Plugins (vendor/plugins): yaffle +------------------------------------------------------------------ +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: @@ -27,10 +31,10 @@ Example: Now you can add code to your generator: +*vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb* + [source, ruby] ------------------------------------------------------------------ -# File: vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb - class YaffleGenerator < Rails::Generator::NamedBase def manifest record do |m| @@ -67,14 +71,16 @@ This does a few things: When you run the generator like - script/generate yaffle bird +------------------------------------------------------------------ +script/generate yaffle bird +------------------------------------------------------------------ You will see a new file: +*db/migrate/20080529225649_add_yaffle_fields_to_birds.rb* + [source, ruby] ------------------------------------------------------------------ -# File: db/migrate/20080529225649_add_yaffle_fields_to_birds.rb - class AddYaffleFieldsToBirds < ActiveRecord::Migration def self.up add_column :birds, :last_squawk, :string diff --git a/railties/doc/guides/source/creating_plugins/odds_and_ends.txt b/railties/doc/guides/source/creating_plugins/odds_and_ends.txt index 32da7ed7f3..88cd4fe9ed 100644 --- a/railties/doc/guides/source/creating_plugins/odds_and_ends.txt +++ b/railties/doc/guides/source/creating_plugins/odds_and_ends.txt @@ -81,10 +81,10 @@ When you created the plugin with the built-in rails generator, it generated a ra Many plugin authors put all of their rake tasks into a common namespace that is the same as the plugin, like so: +*vendor/plugins/yaffle/tasks/yaffle.rake* + [source, ruby] --------------------------------------------------------- -# File: vendor/plugins/yaffle/tasks/yaffle.rake - namespace :yaffle do desc "Prints out the word 'Yaffle'" task :squawk => :environment do diff --git a/railties/doc/guides/source/creating_plugins/string_to_squawk.txt b/railties/doc/guides/source/creating_plugins/string_to_squawk.txt index 50516cef69..63f1131442 100644 --- a/railties/doc/guides/source/creating_plugins/string_to_squawk.txt +++ b/railties/doc/guides/source/creating_plugins/string_to_squawk.txt @@ -10,10 +10,10 @@ Most plugins store their code classes in the plugin's lib directory. When you a 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: +*vendor/plugins/yaffle/test/core_ext_test.rb* + [source, ruby] -------------------------------------------------------- -# File: vendor/plugins/yaffle/test/core_ext_test.rb - require 'test/unit' class CoreExtTest < Test::Unit::TestCase @@ -26,11 +26,10 @@ end Start off by removing the default test, and adding a require statement for your test helper. +*vendor/plugins/yaffle/test/core_ext_test.rb* + [source, ruby] -------------------------------------------------------- -# File: vendor/plugins/yaffle/test/core_ext_test.rb - -require 'test/unit' require File.dirname(__FILE__) + '/test_helper.rb' class CoreExtTest < Test::Unit::TestCase @@ -53,10 +52,10 @@ 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: +*vendor/plugins/yaffle/init.rb* + [source, ruby] -------------------------------------------------------- -# File: vendor/plugins/yaffle/init.rb - class CoreExtTest < Test::Unit::TestCase def test_string_should_respond_to_squawk assert_equal true, "".respond_to?(:to_squawk) @@ -72,17 +71,17 @@ class CoreExtTest < Test::Unit::TestCase end -------------------------------------------------------- +*vendor/plugins/yaffle/init.rb* + [source, ruby] -------------------------------------------------------- -# File: vendor/plugins/yaffle/init.rb - require "core_ext" -------------------------------------------------------- +*vendor/plugins/yaffle/lib/core_ext.rb* + [source, ruby] -------------------------------------------------------- -# File: vendor/plugins/yaffle/lib/core_ext.rb - String.class_eval do def to_squawk "squawk! #{self}".strip diff --git a/railties/doc/guides/source/creating_plugins/view_helper.txt b/railties/doc/guides/source/creating_plugins/view_helper.txt index b03a190e1a..4eaec93824 100644 --- a/railties/doc/guides/source/creating_plugins/view_helper.txt +++ b/railties/doc/guides/source/creating_plugins/view_helper.txt @@ -8,10 +8,10 @@ Creating a view helper is a 3-step process: First, create the test to define the functionality you want: +*vendor/plugins/yaffle/test/view_helpers_test.rb* + [source, ruby] --------------------------------------------------------------- -# File: vendor/plugins/yaffle/test/view_helpers_test.rb - require File.dirname(__FILE__) + '/test_helper.rb' include YaffleViewHelper @@ -28,20 +28,20 @@ end Then add the following statements to init.rb: +*vendor/plugins/yaffle/init.rb* + [source, ruby] --------------------------------------------------------------- -# File: vendor/plugins/yaffle/init.rb - require "view_helpers" ActionView::Base.send :include, YaffleViewHelper --------------------------------------------------------------- Then add the view helpers file and +*vendor/plugins/yaffle/lib/view_helpers.rb* + [source, ruby] --------------------------------------------------------------- -# File: vendor/plugins/yaffle/lib/view_helpers.rb - module YaffleViewHelper def squawk_info_for(yaffle) returning "" do |result| -- cgit v1.2.3 From bc75de8e4f60a774423290872aeb25d09561531b Mon Sep 17 00:00:00 2001 From: Jeff Dean Date: Thu, 13 Nov 2008 00:51:54 -0500 Subject: Plugin Guide: updated core_extensions section --- .../guides/source/creating_plugins/core_ext.txt | 126 ++++++++++++ .../doc/guides/source/creating_plugins/index.txt | 4 +- .../source/creating_plugins/odds_and_ends.txt | 34 ---- .../guides/source/creating_plugins/preparation.txt | 222 --------------------- .../source/creating_plugins/string_to_squawk.txt | 102 ---------- .../guides/source/creating_plugins/test_setup.txt | 222 +++++++++++++++++++++ 6 files changed, 350 insertions(+), 360 deletions(-) create mode 100644 railties/doc/guides/source/creating_plugins/core_ext.txt delete mode 100644 railties/doc/guides/source/creating_plugins/preparation.txt delete mode 100644 railties/doc/guides/source/creating_plugins/string_to_squawk.txt create mode 100644 railties/doc/guides/source/creating_plugins/test_setup.txt (limited to 'railties/doc/guides/source/creating_plugins') diff --git a/railties/doc/guides/source/creating_plugins/core_ext.txt b/railties/doc/guides/source/creating_plugins/core_ext.txt new file mode 100644 index 0000000000..33d3dc8ce7 --- /dev/null +++ b/railties/doc/guides/source/creating_plugins/core_ext.txt @@ -0,0 +1,126 @@ +== Extending core classes == + +This section will explain how to add a method to String that will be available anywhere in your rails app by: + + * Writing tests for the desired behavior + * Creating and requiring the correct files + + +=== Working with init.rb === + +When rails loads plugins it looks for the file named init.rb. However, the plugin initializer script 'init.rb' is invoked via `eval` (not `require`) so it has slightly different behavior. + +Under certain circumstances if you reopen classes or modules in 'init.rb' itself, you may inadvertently create a new class, rather than reopening an existing class. A better alternative is to reopen the class in a different file, and require that file from `init.rb`. + +If you must reopen a class in `init.rb` you can use `module_eval` or `class_eval`: + +*vendor/plugins/yaffle/init.rb* + +[source, ruby] +--------------------------------------------------- +Hash.class_eval do + def is_a_special_hash? + true + end +end +--------------------------------------------------- + +Another way is to explicitly define the top-level module space for all modules and classes, like `::Hash`: + +*vendor/plugins/yaffle/init.rb* + +[source, ruby] +--------------------------------------------------- +class ::Hash + def is_a_special_hash? + true + end +end +--------------------------------------------------- + +=== Creating the test === + +In this example you will add a method to String named `to_squawk`. To begin, create a new test file with a few assertions: + +*vendor/plugins/yaffle/test/core_ext_test.rb* + +[source, ruby] +-------------------------------------------------------- +require File.dirname(__FILE__) + '/test_helper.rb' + +class CoreExtTest < Test::Unit::TestCase + def test_to_squawk_prepends_the_word_squawk + assert_equal "squawk! Hello World", "Hello World".to_squawk + end +end +-------------------------------------------------------- + +Navigate to your plugin directory and run `rake test`: + +-------------------------------------------------------- +cd vendor/plugins/yaffle +rake test +-------------------------------------------------------- + +The test above should fail with the message: + +-------------------------------------------------------- + 1) Error: +test_to_squawk_prepends_the_word_squawk(CoreExtTest): +NoMethodError: undefined method `to_squawk' for "Hello World":String + ./test/core_ext_test.rb:5:in `test_to_squawk_prepends_the_word_squawk' +-------------------------------------------------------- + +Great - now you are ready to start development. + +=== Organize your files === + +A common pattern in rails plugins is to set up the file structure something like this: + +-------------------------------------------------------- +|-- init.rb +|-- lib +| |-- yaffle +| | `-- core_ext.rb +| `-- yaffle.rb +-------------------------------------------------------- + +The first thing we need to to is to require our 'lib/yaffle.rb' file from 'init.rb': + +*vendor/plugins/yaffle/init.rb* + +[source, ruby] +-------------------------------------------------------- +require 'yaffle' +-------------------------------------------------------- + +Then in 'lib/yaffle.rb' require 'lib/core_ext.rb': + +*vendor/plugins/yaffle/lib/yaffle.rb* + +[source, ruby] +-------------------------------------------------------- +require "yaffle/core_ext" +-------------------------------------------------------- + +Finally, create the 'core_ext.rb' file and add the 'to_squawk' method: + +*vendor/plugins/yaffle/lib/yaffle/core_ext.rb* + +[source, ruby] +-------------------------------------------------------- +String.class_eval do + def to_squawk + "squawk! #{self}".strip + end +end +-------------------------------------------------------- + +To test that your method does what it says it does, run the unit tests with `rake` from your plugin directory. To see this in action, fire up a console and start squawking: + +-------------------------------------------------------- +$ ./script/console +>> "Hello World".to_squawk +=> "squawk! Hello World" +-------------------------------------------------------- + diff --git a/railties/doc/guides/source/creating_plugins/index.txt b/railties/doc/guides/source/creating_plugins/index.txt index d3042f8d56..91d7027323 100644 --- a/railties/doc/guides/source/creating_plugins/index.txt +++ b/railties/doc/guides/source/creating_plugins/index.txt @@ -29,9 +29,9 @@ This guide describes how to build a test-driven plugin that will: For the purpose of this guide pretend for a moment that you are an avid bird watcher. Your favorite bird is the Yaffle, and you want to create a plugin that allows other developers to share in the Yaffle goodness. First, you need to get setup for development. -include::preparation.txt[] +include::test_setup.txt[] -include::string_to_squawk.txt[] +include::core_ext.txt[] include::acts_as_yaffle.txt[] diff --git a/railties/doc/guides/source/creating_plugins/odds_and_ends.txt b/railties/doc/guides/source/creating_plugins/odds_and_ends.txt index 88cd4fe9ed..a52e1c8fdb 100644 --- a/railties/doc/guides/source/creating_plugins/odds_and_ends.txt +++ b/railties/doc/guides/source/creating_plugins/odds_and_ends.txt @@ -1,39 +1,5 @@ == Odds and ends == -=== Work with init.rb === - -The plugin initializer script 'init.rb' is invoked via `eval` (not `require`) so it has slightly different behavior. - -If you reopen any classes in init.rb itself your changes will potentially be made to the wrong module. As a rule, it's better not to open any classes in `init.rb`, and it makes the plugin more difficult to turn into a gem. - -A better alternative is to reopen the class in a different file, and require that file from `init.rb`. - -If you must reopen a class in `init.rb`, there are various techniques. One way is to use `module_eval` or `class_eval`: - -*vendor/plugins/yaffle/init.rb* - -[source, ruby] ---------------------------------------------------- -Hash.class_eval do - def is_a_special_hash? - true - end -end ---------------------------------------------------- - -Another way is to explicitly define the top-level module space for all modules and classes, like `::Hash`: - -*vendor/plugins/yaffle/init.rb* - -[source, ruby] ---------------------------------------------------- -class ::Hash - def is_a_special_hash? - true - end -end ---------------------------------------------------- - === Generate RDoc Documentation === Once your plugin is stable, the tests pass on all database and you are ready to deploy do everyone else a favor and document it! Luckily, writing documentation for your plugin is easy. diff --git a/railties/doc/guides/source/creating_plugins/preparation.txt b/railties/doc/guides/source/creating_plugins/preparation.txt deleted file mode 100644 index dc9ef6bc29..0000000000 --- a/railties/doc/guides/source/creating_plugins/preparation.txt +++ /dev/null @@ -1,222 +0,0 @@ -== Preparation == - -=== Create the basic app === - -The examples in this guide require that you have a working rails application. To create a simple rails app execute: - ------------------------------------------------- -gem install rails -rails yaffle_guide -cd yaffle_guide -script/generate scaffold bird name:string -rake db:migrate -script/server ------------------------------------------------- - -Then navigate to http://localhost:3000/birds. Make sure you have a functioning rails app before continuing. - -.Editor's note: -NOTE: The aforementioned instructions will work for sqlite3. For more detailed instructions on how to create a rails app for other databases see the API docs. - - -=== Generate the plugin skeleton === - -Rails ships with a plugin generator which creates a basic plugin skeleton. Pass the plugin name, either 'CamelCased' or 'under_scored', as an argument. Pass `\--with-generator` to add an example generator also. - -This creates a plugin in 'vendor/plugins' including an 'init.rb' and 'README' as well as standard 'lib', 'task', and 'test' directories. - -Examples: ----------------------------------------------- -./script/generate plugin yaffle -./script/generate plugin yaffle --with-generator ----------------------------------------------- - -To get more detailed help on the plugin generator, type `./script/generate plugin`. - -Later on this guide will describe how to work with generators, so go ahead and generate your plugin with the `\--with-generator` option now: - ----------------------------------------------- -./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 ----------------------------------------------- - - -=== Setup the plugin for testing === - -In this guide you will learn how to test your plugin against multiple different adapters using Active Record. This guide 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. - -*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 ----------------------------------------------- - -For this guide you'll need 2 tables/models, Hickwalls and Wickwalls, so add the following: - -*vendor/plugins/yaffle/test/schema.rb:* - -[source, ruby] ----------------------------------------------- -ActiveRecord::Schema.define(:version => 0) do - create_table :hickwalls, :force => true do |t| - t.string :name - t.string :last_squawk - t.datetime :last_squawked_at - end - create_table :wickwalls, :force => true do |t| - t.string :name - t.string :last_tweet - t.datetime :last_tweeted_at - end -end ----------------------------------------------- - -*vendor/plugins/yaffle/test/test_helper.rb:* - -[source, ruby] ----------------------------------------------- -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'] - -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 -end - -class Wickwall < ActiveRecord::Base -end ----------------------------------------------- - -=== Run the plugin tests === - -Once you have these files in place, you can write your first test to ensure that your plugin-testing setup is correct. By default rails generates a file in 'vendor/plugins/yaffle/test/yaffle_test.rb' with a sample test. Replace the contents of that file with: - -*vendor/plugins/yaffle/test/yaffle_test.rb:* - -[source, ruby] ----------------------------------------------- -require File.dirname(__FILE__) + '/test_helper.rb' - -class YaffleTest < Test::Unit::TestCase - - def test_active_record_classes_from_test_helper - assert_kind_of Hickwall, Hickwall.new - assert_kind_of Wickwall, Wickwall.new - end - -end ----------------------------------------------- - -To run this, go to the plugin directory and run `rake`: - ----------------------------------------------- -cd vendor/plugins/yaffle -rake ----------------------------------------------- - -You should see output like: - ----------------------------------------------- -/opt/local/bin/ruby -Ilib:lib "/opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader.rb" "test/yaffle_test.rb" --- create_table(:hickwalls, {:force=>true}) - -> 0.0220s --- create_table(:wickwalls, {:force=>true}) - -> 0.0077s --- initialize_schema_migrations_table() - -> 0.0007s --- assume_migrated_upto_version(0) - -> 0.0007s -Loaded suite /opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader -Started -. -Finished in 0.002236 seconds. - -1 test, 1 assertion, 0 failures, 0 errors ----------------------------------------------- - -By default the setup above runs your tests with sqlite or sqlite3. To run tests with one of the other connection strings specified in database.yml, pass the DB environment variable to rake: - ----------------------------------------------- -rake DB=sqlite -rake DB=sqlite3 -rake DB=mysql -rake DB=postgresql ----------------------------------------------- - -Now you are ready to test-drive your plugin! diff --git a/railties/doc/guides/source/creating_plugins/string_to_squawk.txt b/railties/doc/guides/source/creating_plugins/string_to_squawk.txt deleted file mode 100644 index 63f1131442..0000000000 --- a/railties/doc/guides/source/creating_plugins/string_to_squawk.txt +++ /dev/null @@ -1,102 +0,0 @@ -== 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: - -*vendor/plugins/yaffle/test/core_ext_test.rb* - -[source, ruby] --------------------------------------------------------- -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. - -*vendor/plugins/yaffle/test/core_ext_test.rb* - -[source, ruby] --------------------------------------------------------- -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: - -*vendor/plugins/yaffle/init.rb* - -[source, ruby] --------------------------------------------------------- -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 --------------------------------------------------------- - -*vendor/plugins/yaffle/init.rb* - -[source, ruby] --------------------------------------------------------- -require "core_ext" --------------------------------------------------------- - -*vendor/plugins/yaffle/lib/core_ext.rb* - -[source, ruby] --------------------------------------------------------- -String.class_eval do - def to_squawk - "squawk! #{self}".strip - end -end --------------------------------------------------------- - -When monkey-patching existing classes it's often better to use `class_eval` instead of opening the class directly. - -To test that your method does what it says it does, run the unit tests. To test this manually, fire up a console and start squawking: - --------------------------------------------------------- -$ ./script/console ->> "Hello World".to_squawk -=> "squawk! Hello World" --------------------------------------------------------- - -If that worked, congratulations! You just created your first test-driven plugin that extends a core ruby class. diff --git a/railties/doc/guides/source/creating_plugins/test_setup.txt b/railties/doc/guides/source/creating_plugins/test_setup.txt new file mode 100644 index 0000000000..dc9ef6bc29 --- /dev/null +++ b/railties/doc/guides/source/creating_plugins/test_setup.txt @@ -0,0 +1,222 @@ +== Preparation == + +=== Create the basic app === + +The examples in this guide require that you have a working rails application. To create a simple rails app execute: + +------------------------------------------------ +gem install rails +rails yaffle_guide +cd yaffle_guide +script/generate scaffold bird name:string +rake db:migrate +script/server +------------------------------------------------ + +Then navigate to http://localhost:3000/birds. Make sure you have a functioning rails app before continuing. + +.Editor's note: +NOTE: The aforementioned instructions will work for sqlite3. For more detailed instructions on how to create a rails app for other databases see the API docs. + + +=== Generate the plugin skeleton === + +Rails ships with a plugin generator which creates a basic plugin skeleton. Pass the plugin name, either 'CamelCased' or 'under_scored', as an argument. Pass `\--with-generator` to add an example generator also. + +This creates a plugin in 'vendor/plugins' including an 'init.rb' and 'README' as well as standard 'lib', 'task', and 'test' directories. + +Examples: +---------------------------------------------- +./script/generate plugin yaffle +./script/generate plugin yaffle --with-generator +---------------------------------------------- + +To get more detailed help on the plugin generator, type `./script/generate plugin`. + +Later on this guide will describe how to work with generators, so go ahead and generate your plugin with the `\--with-generator` option now: + +---------------------------------------------- +./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 +---------------------------------------------- + + +=== Setup the plugin for testing === + +In this guide you will learn how to test your plugin against multiple different adapters using Active Record. This guide 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. + +*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 +---------------------------------------------- + +For this guide you'll need 2 tables/models, Hickwalls and Wickwalls, so add the following: + +*vendor/plugins/yaffle/test/schema.rb:* + +[source, ruby] +---------------------------------------------- +ActiveRecord::Schema.define(:version => 0) do + create_table :hickwalls, :force => true do |t| + t.string :name + t.string :last_squawk + t.datetime :last_squawked_at + end + create_table :wickwalls, :force => true do |t| + t.string :name + t.string :last_tweet + t.datetime :last_tweeted_at + end +end +---------------------------------------------- + +*vendor/plugins/yaffle/test/test_helper.rb:* + +[source, ruby] +---------------------------------------------- +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'] + +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 +end + +class Wickwall < ActiveRecord::Base +end +---------------------------------------------- + +=== Run the plugin tests === + +Once you have these files in place, you can write your first test to ensure that your plugin-testing setup is correct. By default rails generates a file in 'vendor/plugins/yaffle/test/yaffle_test.rb' with a sample test. Replace the contents of that file with: + +*vendor/plugins/yaffle/test/yaffle_test.rb:* + +[source, ruby] +---------------------------------------------- +require File.dirname(__FILE__) + '/test_helper.rb' + +class YaffleTest < Test::Unit::TestCase + + def test_active_record_classes_from_test_helper + assert_kind_of Hickwall, Hickwall.new + assert_kind_of Wickwall, Wickwall.new + end + +end +---------------------------------------------- + +To run this, go to the plugin directory and run `rake`: + +---------------------------------------------- +cd vendor/plugins/yaffle +rake +---------------------------------------------- + +You should see output like: + +---------------------------------------------- +/opt/local/bin/ruby -Ilib:lib "/opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader.rb" "test/yaffle_test.rb" +-- create_table(:hickwalls, {:force=>true}) + -> 0.0220s +-- create_table(:wickwalls, {:force=>true}) + -> 0.0077s +-- initialize_schema_migrations_table() + -> 0.0007s +-- assume_migrated_upto_version(0) + -> 0.0007s +Loaded suite /opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader +Started +. +Finished in 0.002236 seconds. + +1 test, 1 assertion, 0 failures, 0 errors +---------------------------------------------- + +By default the setup above runs your tests with sqlite or sqlite3. To run tests with one of the other connection strings specified in database.yml, pass the DB environment variable to rake: + +---------------------------------------------- +rake DB=sqlite +rake DB=sqlite3 +rake DB=mysql +rake DB=postgresql +---------------------------------------------- + +Now you are ready to test-drive your plugin! -- cgit v1.2.3 From 41d0dbcb8661a866ddf4b3534b8b1efd724ecba1 Mon Sep 17 00:00:00 2001 From: Jeff Dean Date: Thu, 13 Nov 2008 01:44:34 -0500 Subject: Plugin guide: update acts_as section --- .../source/creating_plugins/acts_as_yaffle.txt | 121 ++++++++++----------- .../guides/source/creating_plugins/core_ext.txt | 66 ++++++----- .../guides/source/creating_plugins/test_setup.txt | 18 +-- 3 files changed, 97 insertions(+), 108 deletions(-) (limited to 'railties/doc/guides/source/creating_plugins') diff --git a/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt b/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt index 06878543e4..41ffa61537 100644 --- a/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt +++ b/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt @@ -1,8 +1,8 @@ -== Add an `acts_as_yaffle` method to ActiveRecord == +== Add an `acts_as_yaffle` method to Active Record == -A common pattern in plugins is to add a method called `acts_as_something` to models. In this case, you want to write a method called `acts_as_yaffle` that adds a `squawk` method to your models. +A common pattern in plugins is to add a method called 'acts_as_something' to models. In this case, you want to write a method called 'acts_as_yaffle' that adds a 'squawk' method to your 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. +To begin, set up your files so that you have: *vendor/plugins/yaffle/test/acts_as_yaffle_test.rb* @@ -10,25 +10,31 @@ To keep things clean, create a new test file called 'acts_as_yaffle_test.rb' in ------------------------------------------------------ require File.dirname(__FILE__) + '/test_helper.rb' -class Hickwall < ActiveRecord::Base - acts_as_yaffle -end - class ActsAsYaffleTest < Test::Unit::TestCase end ------------------------------------------------------ -*vendor/plugins/lib/acts_as_yaffle.rb* +*vendor/plugins/yaffle/lib/yaffle.rb* + +[source, ruby] +------------------------------------------------------ +require 'yaffle/acts_as_yaffle' +------------------------------------------------------ + +*vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb* [source, ruby] ------------------------------------------------------ module Yaffle + # your code will go here end ------------------------------------------------------ -One of the most common plugin patterns for `acts_as_yaffle` plugins is to structure your file like so: +Note that after requiring 'acts_as_yaffle' you also have to include it into ActiveRecord::Base so that your plugin methods will be available to the rails models. + +One of the most common plugin patterns for 'acts_as_yaffle' plugins is to structure your file like so: -*vendor/plugins/lib/acts_as_yaffle.rb* +*vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb* [source, ruby] ------------------------------------------------------ @@ -52,20 +58,11 @@ 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. +=== Add a class method === -Back in your `acts_as_yaffle` file, update ClassMethods like so: +This plugin will expect that you've added a method to your model named 'last_squawk'. However, the plugin users might have already defined a method on their model named 'last_squawk' that they use for something else. This plugin will allow the name to be changed by adding a class method called 'yaffle_text_field'. -[source, ruby] ------------------------------------------------------- -module ClassMethods - def acts_as_yaffle(options = {}) - send :include, InstanceMethods - end -end ------------------------------------------------------- - -Now that test should pass. Since your plugin is going to work with field names, you need to allow people to define the field names, in case there is a naming conflict. You can write a few simple tests for this: +To start out, write a failing test that shows the behavior you'd like: *vendor/plugins/yaffle/test/acts_as_yaffle_test.rb* @@ -73,28 +70,28 @@ Now that test should pass. Since your plugin is going to work with field names, ------------------------------------------------------ require File.dirname(__FILE__) + '/test_helper.rb' +class Hickwall < ActiveRecord::Base + acts_as_yaffle +end + +class Wickwall < ActiveRecord::Base + acts_as_yaffle :yaffle_text_field => :last_tweet +end + 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: -*vendor/plugins/yaffle/lib/acts_as_yaffle.rb* +*vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb* [source, ruby] ------------------------------------------------------ @@ -105,19 +102,20 @@ module Yaffle module ClassMethods def acts_as_yaffle(options = {}) - cattr_accessor :yaffle_text_field, :yaffle_date_field + cattr_accessor :yaffle_text_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 + +ActiveRecord::Base.send :include, Yaffle ------------------------------------------------------ -Now you can add tests for the instance methods, and the instance method itself: +=== Add an instance method === + +This plugin will add a method named 'squawk' to any Active Record objects that call 'acts_as_yaffle'. The 'squawk' method will simply set the value of one of the fields in the database. + +To start out, write a failing test that shows the behavior you'd like: *vendor/plugins/yaffle/test/acts_as_yaffle_test.rb* @@ -125,47 +123,40 @@ Now you can add tests for the instance methods, and the instance method itself: ------------------------------------------------------ require File.dirname(__FILE__) + '/test_helper.rb' -class ActsAsYaffleTest < Test::Unit::TestCase +class Hickwall < ActiveRecord::Base + acts_as_yaffle +end + +class Wickwall < ActiveRecord::Base + acts_as_yaffle :yaffle_text_field => :last_tweet +end +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 + 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_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 + 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 + assert_equal "squawk! Hello World", wickwall.last_tweet + end end ------------------------------------------------------ -*vendor/plugins/yaffle/lib/acts_as_yaffle.rb* +Run this test to make sure the last two tests fail, then update 'acts_as_yaffle.rb' to look like this: + +*vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb* [source, ruby] ------------------------------------------------------ @@ -176,9 +167,8 @@ module Yaffle module ClassMethods def acts_as_yaffle(options = {}) - cattr_accessor :yaffle_text_field, :yaffle_date_field + cattr_accessor :yaffle_text_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 @@ -186,10 +176,11 @@ module Yaffle 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 + +ActiveRecord::Base.send :include, Yaffle ------------------------------------------------------ .Editor's note: diff --git a/railties/doc/guides/source/creating_plugins/core_ext.txt b/railties/doc/guides/source/creating_plugins/core_ext.txt index 33d3dc8ce7..9bb7691b83 100644 --- a/railties/doc/guides/source/creating_plugins/core_ext.txt +++ b/railties/doc/guides/source/creating_plugins/core_ext.txt @@ -5,39 +5,6 @@ This section will explain how to add a method to String that will be available a * Writing tests for the desired behavior * Creating and requiring the correct files - -=== Working with init.rb === - -When rails loads plugins it looks for the file named init.rb. However, the plugin initializer script 'init.rb' is invoked via `eval` (not `require`) so it has slightly different behavior. - -Under certain circumstances if you reopen classes or modules in 'init.rb' itself, you may inadvertently create a new class, rather than reopening an existing class. A better alternative is to reopen the class in a different file, and require that file from `init.rb`. - -If you must reopen a class in `init.rb` you can use `module_eval` or `class_eval`: - -*vendor/plugins/yaffle/init.rb* - -[source, ruby] ---------------------------------------------------- -Hash.class_eval do - def is_a_special_hash? - true - end -end ---------------------------------------------------- - -Another way is to explicitly define the top-level module space for all modules and classes, like `::Hash`: - -*vendor/plugins/yaffle/init.rb* - -[source, ruby] ---------------------------------------------------- -class ::Hash - def is_a_special_hash? - true - end -end ---------------------------------------------------- - === Creating the test === In this example you will add a method to String named `to_squawk`. To begin, create a new test file with a few assertions: @@ -75,7 +42,7 @@ Great - now you are ready to start development. === Organize your files === -A common pattern in rails plugins is to set up the file structure something like this: +A common pattern in rails plugins is to set up the file structure like this: -------------------------------------------------------- |-- init.rb @@ -124,3 +91,34 @@ $ ./script/console => "squawk! Hello World" -------------------------------------------------------- +=== Working with init.rb === + +When rails loads plugins it looks for the file named init.rb. However, when the plugin is initialized, 'init.rb' is invoked via `eval` (not `require`) so it has slightly different behavior. + +Under certain circumstances if you reopen classes or modules in 'init.rb' you may inadvertently create a new class, rather than reopening an existing class. A better alternative is to reopen the class in a different file, and require that file from `init.rb`, as shown above. + +If you must reopen a class in `init.rb` you can use `module_eval` or `class_eval` to avoid any issues: + +*vendor/plugins/yaffle/init.rb* + +[source, ruby] +--------------------------------------------------- +Hash.class_eval do + def is_a_special_hash? + true + end +end +--------------------------------------------------- + +Another way is to explicitly define the top-level module space for all modules and classes, like `::Hash`: + +*vendor/plugins/yaffle/init.rb* + +[source, ruby] +--------------------------------------------------- +class ::Hash + def is_a_special_hash? + true + end +end +--------------------------------------------------- diff --git a/railties/doc/guides/source/creating_plugins/test_setup.txt b/railties/doc/guides/source/creating_plugins/test_setup.txt index dc9ef6bc29..583d058494 100644 --- a/railties/doc/guides/source/creating_plugins/test_setup.txt +++ b/railties/doc/guides/source/creating_plugins/test_setup.txt @@ -155,12 +155,6 @@ ActiveRecord::Base.establish_connection(config[db_adapter]) load(File.dirname(__FILE__) + "/schema.rb") require File.dirname(__FILE__) + '/../init.rb' - -class Hickwall < ActiveRecord::Base -end - -class Wickwall < ActiveRecord::Base -end ---------------------------------------------- === Run the plugin tests === @@ -175,9 +169,15 @@ require File.dirname(__FILE__) + '/test_helper.rb' class YaffleTest < Test::Unit::TestCase - def test_active_record_classes_from_test_helper - assert_kind_of Hickwall, Hickwall.new - assert_kind_of Wickwall, Wickwall.new + class Hickwall < ActiveRecord::Base + end + + class Wickwall < ActiveRecord::Base + end + + def test_schema_has_loaded_correctly + assert_equal [], Hickwall.all + assert_equal [], Wickwall.all end end -- cgit v1.2.3 From 4146efc380255319768031f26e63210fd4158e99 Mon Sep 17 00:00:00 2001 From: Jeff Dean Date: Thu, 13 Nov 2008 23:29:46 -0500 Subject: Plugin guide: update generator guide to include tests --- .../source/creating_plugins/acts_as_yaffle.txt | 4 + .../guides/source/creating_plugins/basics.markdown | 861 --------------------- .../creating_plugins/migration_generator.txt | 120 ++- .../guides/source/creating_plugins/test_setup.txt | 58 +- 4 files changed, 127 insertions(+), 916 deletions(-) delete mode 100644 railties/doc/guides/source/creating_plugins/basics.markdown (limited to 'railties/doc/guides/source/creating_plugins') diff --git a/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt b/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt index 41ffa61537..de116af7db 100644 --- a/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt +++ b/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt @@ -79,6 +79,8 @@ class Wickwall < ActiveRecord::Base end class ActsAsYaffleTest < Test::Unit::TestCase + load_schema + def test_a_hickwalls_yaffle_text_field_should_be_last_squawk assert_equal "last_squawk", Hickwall.yaffle_text_field end @@ -132,6 +134,8 @@ class Wickwall < ActiveRecord::Base end class ActsAsYaffleTest < Test::Unit::TestCase + load_schema + def test_a_hickwalls_yaffle_text_field_should_be_last_squawk assert_equal "last_squawk", Hickwall.yaffle_text_field end diff --git a/railties/doc/guides/source/creating_plugins/basics.markdown b/railties/doc/guides/source/creating_plugins/basics.markdown deleted file mode 100644 index f59e8728d7..0000000000 --- a/railties/doc/guides/source/creating_plugins/basics.markdown +++ /dev/null @@ -1,861 +0,0 @@ -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/source/creating_plugins/migration_generator.txt b/railties/doc/guides/source/creating_plugins/migration_generator.txt index 1a477a69ab..743d512132 100644 --- a/railties/doc/guides/source/creating_plugins/migration_generator.txt +++ b/railties/doc/guides/source/creating_plugins/migration_generator.txt @@ -1,35 +1,68 @@ == 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. +Many plugins ship with generators. When you created the plugin above, you specified the --with-generator option, so you already have the generator stubs in 'vendor/plugins/yaffle/generators/yaffle'. -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. +Building generators is a complex topic unto itself and this section will cover one small aspect of generators: creating a generator that adds a time-stamped migration. -Type: +To create a generator you must: ------------------------------------------------------------------- -script/generate ------------------------------------------------------------------- + * Add your instructions to the 'manifest' method of the generator + * Add any necessary template files to the templates directory + * Test the generator manually by running various combinations of `script/generate` and `script/destroy` + * Update the USAGE file to add helpful documentation for your generator -You should see the line: +=== Testing generators === ------------------------------------------------------------------- -Plugins (vendor/plugins): yaffle ------------------------------------------------------------------- +Many rails plugin authors do not test their generators, however testing generators is quite simple. A typical generator test does the following: + + * Creates a new fake rails root directory that will serve as destination + * Runs the generator forward and backward, making whatever assertions are necessary + * Removes the fake rails root + +For the generator in this section, the test could look something like this: -When you run `script/generate yaffle` you should see the contents of your USAGE file. For this plugin, the USAGE file looks like this: +*vendor/plugins/yaffle/test/yaffle_generator_test.rb* +[source, ruby] ------------------------------------------------------------------ -Description: - Creates a migration that adds yaffle squawk fields to the given model +require File.dirname(__FILE__) + '/test_helper.rb' +require 'rails_generator' +require 'rails_generator/scripts/generate' +require 'rails_generator/scripts/destroy' -Example: - ./script/generate yaffle hickwall +class YaffleTest < Test::Unit::TestCase - This will create: - db/migrate/TIMESTAMP_add_yaffle_fields_to_hickwall + def fake_rails_root + File.join(File.dirname(__FILE__), 'rails_root') + end + + def file_list + Dir.glob(File.join(fake_rails_root, "db", "migrate", "*")) + end + + def setup + FileUtils.mkdir_p(fake_rails_root) + @original_files = file_list + end + + def teardown + FileUtils.rm_r(fake_rails_root) + end + + def test_generates_correct_file_name + Rails::Generator::Scripts::Generate.new.run(["yaffle", "bird"], :destination => fake_rails_root) + new_file = (file_list - @original_files).first + assert_match /add_yaffle_fields_to_bird/, new_file + end + +end ------------------------------------------------------------------ -Now you can add code to your generator: +You can run 'rake' from the plugin directory to see this fail. Unless you are doing more advanced generator commands it typically suffices to just test the Generate script, and trust that rails will handle the Destroy and Update commands for you. + +=== Adding to the manifest === + +This example will demonstrate how to use one of the built-in generator methods named 'migration_template' to create a migration file. To start, update your generator file to look like this: *vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb* @@ -40,7 +73,7 @@ class YaffleGenerator < Rails::Generator::NamedBase 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 @@ -56,26 +89,24 @@ class YaffleGenerator < Rails::Generator::NamedBase 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. +The generator creates a new file in 'db/migrate' with a timestamp and an 'add_column' statement. It reuses the built in rails `migration_template` method, and reuses the built-in rails migration template. -This does a few things: +It's courteous to check to see if table names are being pluralized whenever you create a generator that needs to be aware of table names. This way people using your generator won't have to manually change the generated files if they've turned pluralization off. - * Reuses the built in rails `migration_template` method. - * Reuses the built-in rails migration template. +=== Manually test the generator === -When you run the generator like +To run the generator, type the following at the command line: ------------------------------------------------------------------ -script/generate yaffle bird +./script/generate yaffle bird ------------------------------------------------------------------ -You will see a new file: +and you will see a new file: *db/migrate/20080529225649_add_yaffle_fields_to_birds.rb* @@ -84,12 +115,43 @@ You will see a new file: 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 ------------------------------------------------------------------ + + + +=== The USAGE file === + +Rails ships with several built-in generators. You can see all of the generators available to you by typing the following at the command line: + +------------------------------------------------------------------ +script/generate +------------------------------------------------------------------ + +You should see something like this: + +------------------------------------------------------------------ +Installed Generators + Plugins (vendor/plugins): yaffle + Builtin: controller, integration_test, mailer, migration, model, observer, plugin, resource, scaffold, session_migration +------------------------------------------------------------------ + +When you run `script/generate yaffle` you should see the contents of your 'vendor/plugins/yaffle/generators/yaffle/USAGE' file. + +For this plugin, update 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 +------------------------------------------------------------------ diff --git a/railties/doc/guides/source/creating_plugins/test_setup.txt b/railties/doc/guides/source/creating_plugins/test_setup.txt index 583d058494..4bcb2d5c2b 100644 --- a/railties/doc/guides/source/creating_plugins/test_setup.txt +++ b/railties/doc/guides/source/creating_plugins/test_setup.txt @@ -64,24 +64,24 @@ create vendor/plugins/yaffle/generators/yaffle/USAGE === Setup the plugin for testing === -In this guide you will learn how to test your plugin against multiple different adapters using Active Record. This guide will not cover how to use fixtures in plugin tests. +If your plugin interacts with a database, you'll need to setup a database connection. In this guide you will learn how to test your plugin against multiple different database adapters using Active Record. This guide 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. + * A 'database.yml' file with all of your connection strings + * A 'schema.rb' file with your table definitions + * A test helper method that sets up the database *vendor/plugins/yaffle/test/database.yml:* ---------------------------------------------- sqlite: :adapter: sqlite - :dbfile: yaffle_plugin.sqlite.db + :dbfile: vendor/plugins/yaffle/test/yaffle_plugin.sqlite.db sqlite3: :adapter: sqlite3 - :dbfile: yaffle_plugin.sqlite3.db + :dbfile: vendor/plugins/yaffle/test/yaffle_plugin.sqlite3.db postgresql: :adapter: postgresql @@ -93,8 +93,8 @@ postgresql: mysql: :adapter: mysql :host: localhost - :username: rails - :password: + :username: root + :password: password :database: yaffle_plugin_test ---------------------------------------------- @@ -128,35 +128,40 @@ 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") +def load_schema + config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml')) + ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log") -db_adapter = ENV['DB'] + db_adapter = ENV['DB'] -db_adapter ||= - begin - require 'rubygems' - require 'sqlite' - 'sqlite' - rescue MissingSourceFile + # no db passed, try one of these fine config-free DBs before bombing. + db_adapter ||= begin - require 'sqlite3' - 'sqlite3' + require 'rubygems' + require 'sqlite' + 'sqlite' rescue MissingSourceFile + begin + require 'sqlite3' + 'sqlite3' + rescue MissingSourceFile + end end - end -if db_adapter.nil? - raise "No DB Adapter selected. Pass the DB= option to pick one, or install Sqlite or Sqlite3." -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]) + ActiveRecord::Base.establish_connection(config[db_adapter]) -load(File.dirname(__FILE__) + "/schema.rb") + load(File.dirname(__FILE__) + "/schema.rb") -require File.dirname(__FILE__) + '/../init.rb' + require File.dirname(__FILE__) + '/../init.rb' +end ---------------------------------------------- +Now whenever you write a test that requires the database, you can call 'load_schema'. + === Run the plugin tests === Once you have these files in place, you can write your first test to ensure that your plugin-testing setup is correct. By default rails generates a file in 'vendor/plugins/yaffle/test/yaffle_test.rb' with a sample test. Replace the contents of that file with: @@ -168,6 +173,7 @@ Once you have these files in place, you can write your first test to ensure that require File.dirname(__FILE__) + '/test_helper.rb' class YaffleTest < Test::Unit::TestCase + load_schema class Hickwall < ActiveRecord::Base end -- cgit v1.2.3 From 8a9bd56ca0d43c703f330e378474ddbdca2acd8e Mon Sep 17 00:00:00 2001 From: Jeff Dean Date: Fri, 14 Nov 2008 00:38:52 -0500 Subject: Plugin Guide: updated test setup and generator sections --- .../source/creating_plugins/custom_generator.txt | 69 ----------------- .../source/creating_plugins/generator_method.txt | 89 ++++++++++++++++++++++ .../doc/guides/source/creating_plugins/index.txt | 2 +- .../guides/source/creating_plugins/test_setup.txt | 2 - 4 files changed, 90 insertions(+), 72 deletions(-) delete mode 100644 railties/doc/guides/source/creating_plugins/custom_generator.txt create mode 100644 railties/doc/guides/source/creating_plugins/generator_method.txt (limited to 'railties/doc/guides/source/creating_plugins') diff --git a/railties/doc/guides/source/creating_plugins/custom_generator.txt b/railties/doc/guides/source/creating_plugins/custom_generator.txt deleted file mode 100644 index a8cf1b48ce..0000000000 --- a/railties/doc/guides/source/creating_plugins/custom_generator.txt +++ /dev/null @@ -1,69 +0,0 @@ -== 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: - -*vendor/plugins/yaffle/init.rb* - -[source, ruby] ------------------------------------------------------------ -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 ------------------------------------------------------------ - -*vendor/plugins/yaffle/lib/commands.rb* - -[source, ruby] ------------------------------------------------------------ -require 'rails_generator' -require 'rails_generator/commands' - -module Yaffle #:nodoc: - module Generator #:nodoc: - module Commands #:nodoc: - module Create - def yaffle_definition - file("definition.txt", "definition.txt") - end - end - - module Destroy - def yaffle_definition - file("definition.txt", "definition.txt") - end - end - - module List - def yaffle_definition - file("definition.txt", "definition.txt") - end - end - end - end -end ------------------------------------------------------------ - -*vendor/plugins/yaffle/generators/yaffle/templates/definition.txt* ------------------------------------------------------------ -Yaffle is a bird ------------------------------------------------------------ - -*vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb* - -[source, ruby] ------------------------------------------------------------ -class YaffleGenerator < Rails::Generator::NamedBase - def manifest - m.yaffle_definition - end -end ------------------------------------------------------------ - -This example just uses the built-in "file" method, but you could do anything that Ruby allows. diff --git a/railties/doc/guides/source/creating_plugins/generator_method.txt b/railties/doc/guides/source/creating_plugins/generator_method.txt new file mode 100644 index 0000000000..126692f2c4 --- /dev/null +++ b/railties/doc/guides/source/creating_plugins/generator_method.txt @@ -0,0 +1,89 @@ +== Add a custom generator command == + +You may have noticed above that you can used one of the built-in rails migration commands `migration_template`. If your plugin needs to add and remove lines of text from existing files you will need to write your own generator methods. + +This section describes how you you can create your own commands to add and remove a line of text from 'routes.rb'. This example creates a very simple method that adds or removes a text file. + +To start, add the following test method: + +*vendor/plugins/yaffle/test/generator_test.rb* + +[source, ruby] +----------------------------------------------------------- +def test_generates_definition + Rails::Generator::Scripts::Generate.new.run(["yaffle", "bird"], :destination => fake_rails_root) + definition = File.read(File.join(fake_rails_root, "definition.txt")) + assert_match /Yaffle\:/, definition +end +----------------------------------------------------------- + +Run `rake` to watch the test fail, then make the test pass add the following: + +*vendor/plugins/yaffle/generators/yaffle/templates/definition.txt* + +----------------------------------------------------------- +Yaffle: A bird +----------------------------------------------------------- + +*vendor/plugins/yaffle/lib/yaffle.rb* + +[source, ruby] +----------------------------------------------------------- +require "yaffle/commands" +----------------------------------------------------------- + +*vendor/plugins/yaffle/lib/commands.rb* + +[source, ruby] +----------------------------------------------------------- +require 'rails_generator' +require 'rails_generator/commands' + +module Yaffle #:nodoc: + module Generator #:nodoc: + module Commands #:nodoc: + module Create + def yaffle_definition + file("definition.txt", "definition.txt") + end + end + + module Destroy + def yaffle_definition + file("definition.txt", "definition.txt") + end + end + + module List + def yaffle_definition + file("definition.txt", "definition.txt") + end + end + + module Update + def yaffle_definition + file("definition.txt", "definition.txt") + end + end + end + end +end + +Rails::Generator::Commands::Create.send :include, Yaffle::Generator::Commands::Create +Rails::Generator::Commands::Destroy.send :include, Yaffle::Generator::Commands::Destroy +Rails::Generator::Commands::List.send :include, Yaffle::Generator::Commands::List +Rails::Generator::Commands::Update.send :include, Yaffle::Generator::Commands::Update +----------------------------------------------------------- + +Finally, call your new method in the manifest: + +*vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb* + +[source, ruby] +----------------------------------------------------------- +class YaffleGenerator < Rails::Generator::NamedBase + def manifest + m.yaffle_definition + end +end +----------------------------------------------------------- diff --git a/railties/doc/guides/source/creating_plugins/index.txt b/railties/doc/guides/source/creating_plugins/index.txt index 91d7027323..bd7dfe65c3 100644 --- a/railties/doc/guides/source/creating_plugins/index.txt +++ b/railties/doc/guides/source/creating_plugins/index.txt @@ -39,7 +39,7 @@ include::view_helper.txt[] include::migration_generator.txt[] -include::custom_generator.txt[] +include::generator_method.txt[] include::custom_route.txt[] diff --git a/railties/doc/guides/source/creating_plugins/test_setup.txt b/railties/doc/guides/source/creating_plugins/test_setup.txt index 4bcb2d5c2b..9e6763bc30 100644 --- a/railties/doc/guides/source/creating_plugins/test_setup.txt +++ b/railties/doc/guides/source/creating_plugins/test_setup.txt @@ -153,9 +153,7 @@ def load_schema end ActiveRecord::Base.establish_connection(config[db_adapter]) - load(File.dirname(__FILE__) + "/schema.rb") - require File.dirname(__FILE__) + '/../init.rb' end ---------------------------------------------- -- cgit v1.2.3 From 7eb249291d1c8a8af14c52de4767a36ba8f924e3 Mon Sep 17 00:00:00 2001 From: Jeff Dean Date: Fri, 14 Nov 2008 02:29:12 -0500 Subject: Plugin guide: added model and controller sections --- .../guides/source/creating_plugins/controllers.txt | 59 +++++++++++++++++ .../doc/guides/source/creating_plugins/index.txt | 8 ++- .../creating_plugins/migration_generator.txt | 5 +- .../doc/guides/source/creating_plugins/models.txt | 76 ++++++++++++++++++++++ .../source/creating_plugins/odds_and_ends.txt | 22 ------- .../guides/source/creating_plugins/test_setup.txt | 3 + 6 files changed, 146 insertions(+), 27 deletions(-) create mode 100644 railties/doc/guides/source/creating_plugins/controllers.txt create mode 100644 railties/doc/guides/source/creating_plugins/models.txt (limited to 'railties/doc/guides/source/creating_plugins') diff --git a/railties/doc/guides/source/creating_plugins/controllers.txt b/railties/doc/guides/source/creating_plugins/controllers.txt new file mode 100644 index 0000000000..ee408adb1d --- /dev/null +++ b/railties/doc/guides/source/creating_plugins/controllers.txt @@ -0,0 +1,59 @@ +== Add a controller == + +This section describes how to add a controller named 'woodpeckers' to your plugin that will behave the same as a controller in your main app. This is very similar to adding a model. + +You can test your plugin's controller as you would test any other controller: + +*vendor/plugins/yaffle/yaffle/woodpeckers_controller_test.rb:* + +[source, ruby] +---------------------------------------------- +require File.dirname(__FILE__) + '/test_helper.rb' +require 'woodpeckers_controller' +require 'action_controller/test_process' + +class WoodpeckersController; def rescue_action(e) raise e end; end + +class WoodpeckersControllerTest < Test::Unit::TestCase + def setup + @controller = WoodpeckersController.new + @request = ActionController::TestRequest.new + @response = ActionController::TestResponse.new + end + + def test_index + get :index + assert_response :success + end +end +---------------------------------------------- + +This is just a simple test to make sure the controller is being loaded correctly. After watching it fail with `rake`, you can make it pass like so: + +*vendor/plugins/yaffle/lib/yaffle.rb:* + +[source, ruby] +---------------------------------------------- +%w{ models controllers }.each do |dir| + path = File.join(File.dirname(__FILE__), 'app', dir) + $LOAD_PATH << path + ActiveSupport::Dependencies.load_paths << path + ActiveSupport::Dependencies.load_once_paths.delete(path) +end +---------------------------------------------- + + +*vendor/plugins/yaffle/lib/app/controllers/woodpeckers_controller.rb:* + +[source, ruby] +---------------------------------------------- +class WoodpeckersController < ActionController::Base + + def index + render :text => "Squawk!" + end + +end +---------------------------------------------- + +Now your test should be passing, and you should be able to use the Woodpeckers controller in your app. If you add a route for the woodpeckers controller you can start up your server and go to http://localhost:3000/woodpeckers to see your controller in action. diff --git a/railties/doc/guides/source/creating_plugins/index.txt b/railties/doc/guides/source/creating_plugins/index.txt index bd7dfe65c3..67e6aec39c 100644 --- a/railties/doc/guides/source/creating_plugins/index.txt +++ b/railties/doc/guides/source/creating_plugins/index.txt @@ -35,12 +35,16 @@ include::core_ext.txt[] include::acts_as_yaffle.txt[] -include::view_helper.txt[] - include::migration_generator.txt[] include::generator_method.txt[] +include::models.txt[] + +include::controllers.txt[] + +include::view_helper.txt[] + include::custom_route.txt[] include::odds_and_ends.txt[] diff --git a/railties/doc/guides/source/creating_plugins/migration_generator.txt b/railties/doc/guides/source/creating_plugins/migration_generator.txt index 743d512132..f4fc32481c 100644 --- a/railties/doc/guides/source/creating_plugins/migration_generator.txt +++ b/railties/doc/guides/source/creating_plugins/migration_generator.txt @@ -1,4 +1,4 @@ -== Create a migration generator == +== Create a generator == Many plugins ship with generators. When you created the plugin above, you specified the --with-generator option, so you already have the generator stubs in 'vendor/plugins/yaffle/generators/yaffle'. @@ -30,7 +30,7 @@ require 'rails_generator' require 'rails_generator/scripts/generate' require 'rails_generator/scripts/destroy' -class YaffleTest < Test::Unit::TestCase +class GeneratorTest < Test::Unit::TestCase def fake_rails_root File.join(File.dirname(__FILE__), 'rails_root') @@ -124,7 +124,6 @@ end ------------------------------------------------------------------ - === The USAGE file === Rails ships with several built-in generators. You can see all of the generators available to you by typing the following at the command line: diff --git a/railties/doc/guides/source/creating_plugins/models.txt b/railties/doc/guides/source/creating_plugins/models.txt new file mode 100644 index 0000000000..458edec80a --- /dev/null +++ b/railties/doc/guides/source/creating_plugins/models.txt @@ -0,0 +1,76 @@ +== Add a model == + +This section describes how to add a model named 'Woodpecker' to your plugin that will behave the same as a model in your main app. When storing models, controllers, views and helpers in your plugin, it's customary to keep them in directories that match the rails directories. For this example, create a file structure like this: + +--------------------------------------------------------- +vendor/plugins/yaffle/ +|-- lib +| |-- app +| | |-- controllers +| | |-- helpers +| | |-- models +| | | `-- woodpecker.rb +| | `-- views +| |-- yaffle +| | |-- acts_as_yaffle.rb +| | |-- commands.rb +| | `-- core_ext.rb +| `-- yaffle.rb +--------------------------------------------------------- + +As always, start with a test: + +*vendor/plugins/yaffle/yaffle/woodpecker_test.rb:* + +[source, ruby] +---------------------------------------------- +require File.dirname(__FILE__) + '/test_helper.rb' + +class WoodpeckerTest < Test::Unit::TestCase + load_schema + + def test_woodpecker + assert_kind_of Woodpecker, Woodpecker.new + end +end +---------------------------------------------- + +This is just a simple test to make sure the class is being loaded correctly. After watching it fail with `rake`, you can make it pass like so: + +*vendor/plugins/yaffle/lib/yaffle.rb:* + +[source, ruby] +---------------------------------------------- +%w{ models }.each do |dir| + path = File.join(File.dirname(__FILE__), 'app', dir) + $LOAD_PATH << path + ActiveSupport::Dependencies.load_paths << path + ActiveSupport::Dependencies.load_once_paths.delete(path) +end +---------------------------------------------- + +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. Removing directories from the 'load_once_paths' allow those changes to picked up as soon as you save the file - without having to restart the web server. This is particularly useful as you develop the plugin. + + +*vendor/plugins/yaffle/lib/app/models/woodpecker.rb:* + +[source, ruby] +---------------------------------------------- +class Woodpecker < ActiveRecord::Base +end +---------------------------------------------- + +Finally, add the following to your plugin's 'schema.rb': + +*vendor/plugins/yaffle/test/schema.rb:* + +[source, ruby] +---------------------------------------------- +ActiveRecord::Schema.define(:version => 0) do + create_table :woodpeckers, :force => true do |t| + t.string :name + end +end +---------------------------------------------- + +Now your test should be passing, and you should be able to use the Woodpecker model from within your rails app, and any changes made to it are reflected immediately when running in development mode. \ No newline at end of file diff --git a/railties/doc/guides/source/creating_plugins/odds_and_ends.txt b/railties/doc/guides/source/creating_plugins/odds_and_ends.txt index a52e1c8fdb..e328c04a79 100644 --- a/railties/doc/guides/source/creating_plugins/odds_and_ends.txt +++ b/railties/doc/guides/source/creating_plugins/odds_and_ends.txt @@ -19,28 +19,6 @@ Once your comments are good to go, navigate to your plugin directory and run: rake rdoc - -=== Store models, views, helpers, and controllers in your plugins === - -You can easily store models, views, helpers and controllers in plugins. Just create a folder for each in the lib folder, add them to the load path and remove them from the load once path: - -[source, ruby] ---------------------------------------------------------- -# File: vendor/plugins/yaffle/init.rb - -%w{ models controllers helpers }.each do |dir| - path = File.join(directory, 'lib', dir) - $LOAD_PATH << path - Dependencies.load_paths << path - Dependencies.load_once_paths.delete(path) -end ---------------------------------------------------------- - -Adding directories to the load path makes them appear just like files in the the main app directory - except that they are only loaded once, so you have to restart the web server to see the changes in the browser. - -Adding directories to the load once paths allow those changes to picked up as soon as you save the file - without having to restart the web server. - - === Write custom Rake tasks in your plugin === When you created the plugin with the built-in rails generator, it generated a rake file for you in 'vendor/plugins/yaffle/tasks/yaffle.rake'. Any rake task you add here will be available to the app. diff --git a/railties/doc/guides/source/creating_plugins/test_setup.txt b/railties/doc/guides/source/creating_plugins/test_setup.txt index 9e6763bc30..6ea2a37fa7 100644 --- a/railties/doc/guides/source/creating_plugins/test_setup.txt +++ b/railties/doc/guides/source/creating_plugins/test_setup.txt @@ -115,6 +115,9 @@ ActiveRecord::Schema.define(:version => 0) do t.string :last_tweet t.datetime :last_tweeted_at end + create_table :woodpeckers, :force => true do |t| + t.string :name + end end ---------------------------------------------- -- cgit v1.2.3 From 88a13fad4fae2c2088188008248e15498a2ca466 Mon Sep 17 00:00:00 2001 From: Jeff Dean Date: Fri, 14 Nov 2008 03:02:05 -0500 Subject: Rails plugin: Expanded helpers section --- .../doc/guides/source/creating_plugins/helpers.txt | 51 ++++++++++++++++++ .../doc/guides/source/creating_plugins/index.txt | 2 +- .../guides/source/creating_plugins/view_helper.txt | 61 ---------------------- 3 files changed, 52 insertions(+), 62 deletions(-) create mode 100644 railties/doc/guides/source/creating_plugins/helpers.txt delete mode 100644 railties/doc/guides/source/creating_plugins/view_helper.txt (limited to 'railties/doc/guides/source/creating_plugins') diff --git a/railties/doc/guides/source/creating_plugins/helpers.txt b/railties/doc/guides/source/creating_plugins/helpers.txt new file mode 100644 index 0000000000..51b4cebb01 --- /dev/null +++ b/railties/doc/guides/source/creating_plugins/helpers.txt @@ -0,0 +1,51 @@ +== Add a helper == + +This section describes how to add a helper named 'WoodpeckersHelper' to your plugin that will behave the same as a helper in your main app. This is very similar to adding a model and a controller. + +You can test your plugin's helper as you would test any other helper: + +*vendor/plugins/yaffle/test/woodpeckers_helper_test.rb* + +[source, ruby] +--------------------------------------------------------------- +require File.dirname(__FILE__) + '/test_helper.rb' +include WoodpeckersHelper + +class WoodpeckersHelperTest < Test::Unit::TestCase + def test_tweet + assert_equal "Tweet! Hello", tweet("Hello") + end +end +--------------------------------------------------------------- + +This is just a simple test to make sure the helper is being loaded correctly. After watching it fail with `rake`, you can make it pass like so: + +*vendor/plugins/yaffle/lib/yaffle.rb:* + +[source, ruby] +---------------------------------------------- +%w{ models controllers helpers }.each do |dir| + path = File.join(File.dirname(__FILE__), 'app', dir) + $LOAD_PATH << path + ActiveSupport::Dependencies.load_paths << path + ActiveSupport::Dependencies.load_once_paths.delete(path) +end + +ActionView::Base.send :include, WoodpeckersHelper +---------------------------------------------- + + +*vendor/plugins/yaffle/lib/app/helpers/woodpeckers_helper.rb:* + +[source, ruby] +---------------------------------------------- +module WoodpeckersHelper + + def tweet(text) + "Tweet! #{text}" + end + +end +---------------------------------------------- + +Now your test should be passing, and you should be able to use the Woodpeckers helper in your app. diff --git a/railties/doc/guides/source/creating_plugins/index.txt b/railties/doc/guides/source/creating_plugins/index.txt index 67e6aec39c..19484e2830 100644 --- a/railties/doc/guides/source/creating_plugins/index.txt +++ b/railties/doc/guides/source/creating_plugins/index.txt @@ -43,7 +43,7 @@ include::models.txt[] include::controllers.txt[] -include::view_helper.txt[] +include::helpers.txt[] include::custom_route.txt[] diff --git a/railties/doc/guides/source/creating_plugins/view_helper.txt b/railties/doc/guides/source/creating_plugins/view_helper.txt deleted file mode 100644 index 4eaec93824..0000000000 --- a/railties/doc/guides/source/creating_plugins/view_helper.txt +++ /dev/null @@ -1,61 +0,0 @@ -== Create a `squawk_info_for` view helper == - -Creating a view helper is a 3-step process: - - * Add an appropriately named file to the 'lib' directory. - * Require the file and hooks in 'init.rb'. - * Write the tests. - -First, create the test to define the functionality you want: - -*vendor/plugins/yaffle/test/view_helpers_test.rb* - -[source, ruby] ---------------------------------------------------------------- -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: - -*vendor/plugins/yaffle/init.rb* - -[source, ruby] ---------------------------------------------------------------- -require "view_helpers" -ActionView::Base.send :include, YaffleViewHelper ---------------------------------------------------------------- - -Then add the view helpers file and - -*vendor/plugins/yaffle/lib/view_helpers.rb* - -[source, ruby] ---------------------------------------------------------------- -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) ---------------------------------------------------------------- -- cgit v1.2.3 From fa9ea057d1252a578f8e056defef41b93853bc8b Mon Sep 17 00:00:00 2001 From: Jeff Dean Date: Fri, 14 Nov 2008 03:14:09 -0500 Subject: Plugin guide: updated to start working with GemPlugin --- railties/doc/guides/source/creating_plugins/core_ext.txt | 5 ++--- railties/doc/guides/source/creating_plugins/gem.txt | 1 + railties/doc/guides/source/creating_plugins/test_setup.txt | 3 ++- 3 files changed, 5 insertions(+), 4 deletions(-) create mode 100644 railties/doc/guides/source/creating_plugins/gem.txt (limited to 'railties/doc/guides/source/creating_plugins') diff --git a/railties/doc/guides/source/creating_plugins/core_ext.txt b/railties/doc/guides/source/creating_plugins/core_ext.txt index 9bb7691b83..ca8efc3df1 100644 --- a/railties/doc/guides/source/creating_plugins/core_ext.txt +++ b/railties/doc/guides/source/creating_plugins/core_ext.txt @@ -45,16 +45,15 @@ Great - now you are ready to start development. A common pattern in rails plugins is to set up the file structure like this: -------------------------------------------------------- -|-- init.rb |-- lib | |-- yaffle | | `-- core_ext.rb | `-- yaffle.rb -------------------------------------------------------- -The first thing we need to to is to require our 'lib/yaffle.rb' file from 'init.rb': +The first thing we need to to is to require our 'lib/yaffle.rb' file from 'rails/init.rb': -*vendor/plugins/yaffle/init.rb* +*vendor/plugins/yaffle/rails/init.rb* [source, ruby] -------------------------------------------------------- diff --git a/railties/doc/guides/source/creating_plugins/gem.txt b/railties/doc/guides/source/creating_plugins/gem.txt new file mode 100644 index 0000000000..93f5e0ee89 --- /dev/null +++ b/railties/doc/guides/source/creating_plugins/gem.txt @@ -0,0 +1 @@ +http://www.mbleigh.com/2008/6/11/gemplugins-a-brief-introduction-to-the-future-of-rails-plugins \ No newline at end of file diff --git a/railties/doc/guides/source/creating_plugins/test_setup.txt b/railties/doc/guides/source/creating_plugins/test_setup.txt index 6ea2a37fa7..64236ff110 100644 --- a/railties/doc/guides/source/creating_plugins/test_setup.txt +++ b/railties/doc/guides/source/creating_plugins/test_setup.txt @@ -61,6 +61,7 @@ create vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb create vendor/plugins/yaffle/generators/yaffle/USAGE ---------------------------------------------- +To begin just change one thing - move 'init.rb' to 'rails/init.rb'. === Setup the plugin for testing === @@ -157,7 +158,7 @@ def load_schema ActiveRecord::Base.establish_connection(config[db_adapter]) load(File.dirname(__FILE__) + "/schema.rb") - require File.dirname(__FILE__) + '/../init.rb' + require File.dirname(__FILE__) + '/../rails/init.rb' end ---------------------------------------------- -- cgit v1.2.3 From 097b4678f6d52e86a9d46ba6c862e6eb6ef7bbdd Mon Sep 17 00:00:00 2001 From: Jeff Dean Date: Sun, 16 Nov 2008 20:30:42 -0500 Subject: Plugin Guide: added section on migrations, updated generator section, tightened up spacing of P's inside LI's --- .../source/creating_plugins/acts_as_yaffle.txt | 2 +- .../guides/source/creating_plugins/appendix.txt | 73 ++++--- .../guides/source/creating_plugins/controllers.txt | 2 +- .../source/creating_plugins/custom_route.txt | 69 ------- .../doc/guides/source/creating_plugins/gem.txt | 2 + .../source/creating_plugins/generator_commands.txt | 140 +++++++++++++ .../source/creating_plugins/generator_method.txt | 89 -------- .../guides/source/creating_plugins/generators.txt | 103 +++++++++ .../doc/guides/source/creating_plugins/helpers.txt | 2 +- .../doc/guides/source/creating_plugins/index.txt | 16 +- .../creating_plugins/migration_generator.txt | 156 -------------- .../guides/source/creating_plugins/migrations.txt | 209 +++++++++++++++++++ .../doc/guides/source/creating_plugins/models.txt | 2 +- .../doc/guides/source/creating_plugins/routes.txt | 69 +++++++ .../doc/guides/source/creating_plugins/setup.txt | 64 ++++++ .../guides/source/creating_plugins/test_setup.txt | 230 --------------------- .../doc/guides/source/creating_plugins/tests.txt | 165 +++++++++++++++ 17 files changed, 809 insertions(+), 584 deletions(-) delete mode 100644 railties/doc/guides/source/creating_plugins/custom_route.txt create mode 100644 railties/doc/guides/source/creating_plugins/generator_commands.txt delete mode 100644 railties/doc/guides/source/creating_plugins/generator_method.txt create mode 100644 railties/doc/guides/source/creating_plugins/generators.txt delete mode 100644 railties/doc/guides/source/creating_plugins/migration_generator.txt create mode 100644 railties/doc/guides/source/creating_plugins/migrations.txt create mode 100644 railties/doc/guides/source/creating_plugins/routes.txt create mode 100644 railties/doc/guides/source/creating_plugins/setup.txt delete mode 100644 railties/doc/guides/source/creating_plugins/test_setup.txt create mode 100644 railties/doc/guides/source/creating_plugins/tests.txt (limited to 'railties/doc/guides/source/creating_plugins') diff --git a/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt b/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt index de116af7db..674f086e17 100644 --- a/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt +++ b/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt @@ -1,4 +1,4 @@ -== Add an `acts_as_yaffle` method to Active Record == +== Add an 'acts_as' method to Active Record == A common pattern in plugins is to add a method called 'acts_as_something' to models. In this case, you want to write a method called 'acts_as_yaffle' that adds a 'squawk' method to your models. diff --git a/railties/doc/guides/source/creating_plugins/appendix.txt b/railties/doc/guides/source/creating_plugins/appendix.txt index a78890ccd5..d890f861b5 100644 --- a/railties/doc/guides/source/creating_plugins/appendix.txt +++ b/railties/doc/guides/source/creating_plugins/appendix.txt @@ -6,41 +6,54 @@ * http://nubyonrails.com/articles/2006/05/09/the-complete-guide-to-rails-plugins-part-ii * http://github.com/technoweenie/attachment_fu/tree/master * http://daddy.platte.name/2007/05/rails-plugins-keep-initrb-thin.html + * http://www.mbleigh.com/2008/6/11/gemplugins-a-brief-introduction-to-the-future-of-rails-plugins === Final plugin directory structure === The final plugin should have a directory structure that looks something like this: ------------------------------------------------ - |-- MIT-LICENSE - |-- README - |-- Rakefile - |-- generators - | `-- yaffle - | |-- USAGE - | |-- templates - | | `-- definition.txt - | `-- yaffle_generator.rb - |-- init.rb - |-- install.rb - |-- lib - | |-- acts_as_yaffle.rb - | |-- commands.rb - | |-- core_ext.rb - | |-- routing.rb - | `-- view_helpers.rb - |-- tasks - | `-- yaffle_tasks.rake - |-- test - | |-- acts_as_yaffle_test.rb - | |-- core_ext_test.rb - | |-- database.yml - | |-- debug.log - | |-- routing_test.rb - | |-- schema.rb - | |-- test_helper.rb - | `-- view_helpers_test.rb - |-- uninstall.rb - `-- yaffle_plugin.sqlite3.db +vendor/plugins/yaffle/ +|-- MIT-LICENSE +|-- README +|-- Rakefile +|-- generators +| `-- yaffle +| |-- USAGE +| |-- templates +| | `-- definition.txt +| `-- yaffle_generator.rb +|-- install.rb +|-- lib +| |-- app +| | |-- controllers +| | | `-- woodpeckers_controller.rb +| | |-- helpers +| | | `-- woodpeckers_helper.rb +| | `-- models +| | `-- woodpecker.rb +| |-- yaffle +| | |-- acts_as_yaffle.rb +| | |-- commands.rb +| | `-- core_ext.rb +| `-- yaffle.rb +|-- rails +| `-- init.rb +|-- tasks +| `-- yaffle_tasks.rake +|-- test +| |-- acts_as_yaffle_test.rb +| |-- core_ext_test.rb +| |-- database.yml +| |-- debug.log +| |-- generator_test.rb +| |-- schema.rb +| |-- test_helper.rb +| |-- woodpecker_test.rb +| |-- woodpeckers_controller_test.rb +| |-- wookpeckers_helper_test.rb +| |-- yaffle_plugin.sqlite3.db +| `-- yaffle_test.rb +`-- uninstall.rb ------------------------------------------------ diff --git a/railties/doc/guides/source/creating_plugins/controllers.txt b/railties/doc/guides/source/creating_plugins/controllers.txt index ee408adb1d..4f4417b416 100644 --- a/railties/doc/guides/source/creating_plugins/controllers.txt +++ b/railties/doc/guides/source/creating_plugins/controllers.txt @@ -1,4 +1,4 @@ -== Add a controller == +== Controllers == This section describes how to add a controller named 'woodpeckers' to your plugin that will behave the same as a controller in your main app. This is very similar to adding a model. diff --git a/railties/doc/guides/source/creating_plugins/custom_route.txt b/railties/doc/guides/source/creating_plugins/custom_route.txt deleted file mode 100644 index 1fce902a4e..0000000000 --- a/railties/doc/guides/source/creating_plugins/custom_route.txt +++ /dev/null @@ -1,69 +0,0 @@ -== 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. - -*vendor/plugins/yaffle/test/routing_test.rb* - -[source, ruby] --------------------------------------------------------- -require "#{File.dirname(__FILE__)}/test_helper" - -class RoutingTest < Test::Unit::TestCase - - def setup - ActionController::Routing::Routes.draw do |map| - map.yaffles - end - end - - def test_yaffles_route - assert_recognition :get, "/yaffles", :controller => "yaffles_controller", :action => "index" - end - - 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 --------------------------------------------------------- - -*vendor/plugins/yaffle/init.rb* - -[source, ruby] --------------------------------------------------------- -require "routing" -ActionController::Routing::RouteSet::Mapper.send :include, Yaffle::Routing::MapperExtensions --------------------------------------------------------- - -*vendor/plugins/yaffle/lib/routing.rb* - -[source, ruby] --------------------------------------------------------- -module Yaffle #:nodoc: - module Routing #:nodoc: - module MapperExtensions - def yaffles - @set.add_route("/yaffles", {:controller => "yaffles_controller", :action => "index"}) - end - end - end -end --------------------------------------------------------- - -*config/routes.rb* - -[source, ruby] --------------------------------------------------------- -ActionController::Routing::Routes.draw do |map| - ... - map.yaffles -end --------------------------------------------------------- - -You can also see if your routes work by running `rake routes` from your app directory. diff --git a/railties/doc/guides/source/creating_plugins/gem.txt b/railties/doc/guides/source/creating_plugins/gem.txt index 93f5e0ee89..8a0bbb3bc0 100644 --- a/railties/doc/guides/source/creating_plugins/gem.txt +++ b/railties/doc/guides/source/creating_plugins/gem.txt @@ -1 +1,3 @@ +== Gems == + http://www.mbleigh.com/2008/6/11/gemplugins-a-brief-introduction-to-the-future-of-rails-plugins \ No newline at end of file diff --git a/railties/doc/guides/source/creating_plugins/generator_commands.txt b/railties/doc/guides/source/creating_plugins/generator_commands.txt new file mode 100644 index 0000000000..5cce81c8bd --- /dev/null +++ b/railties/doc/guides/source/creating_plugins/generator_commands.txt @@ -0,0 +1,140 @@ +== Generator Commands == + +You may have noticed above that you can used one of the built-in rails migration commands `migration_template`. If your plugin needs to add and remove lines of text from existing files you will need to write your own generator methods. + +This section describes how you you can create your own commands to add and remove a line of text from 'config/routes.rb'. + +To start, add the following test method: + +*vendor/plugins/yaffle/test/route_generator_test.rb* + +[source, ruby] +----------------------------------------------------------- +require File.dirname(__FILE__) + '/test_helper.rb' +require 'rails_generator' +require 'rails_generator/scripts/generate' +require 'rails_generator/scripts/destroy' + +class RouteGeneratorTest < Test::Unit::TestCase + + def fake_rails_root + File.join(File.dirname(__FILE__), "rails_root") + end + + def routes_path + File.join(fake_rails_root, "config", "routes.rb") + end + + def setup + FileUtils.mkdir_p(File.join(fake_rails_root, "config")) + end + + def teardown + FileUtils.rm_r(fake_rails_root) + end + + def test_generates_route + content = <<-END + ActionController::Routing::Routes.draw do |map| + map.connect ':controller/:action/:id' + map.connect ':controller/:action/:id.:format' + end + END + File.open(routes_path, 'wb') {|f| f.write(content) } + + Rails::Generator::Scripts::Generate.new.run(["yaffle_route"], :destination => fake_rails_root) + assert_match /map\.yaffle/, File.read(routes_path) + end + + def test_destroys_route + content = <<-END + ActionController::Routing::Routes.draw do |map| + map.yaffle + map.connect ':controller/:action/:id' + map.connect ':controller/:action/:id.:format' + end + END + File.open(routes_path, 'wb') {|f| f.write(content) } + + Rails::Generator::Scripts::Destroy.new.run(["yaffle_route"], :destination => fake_rails_root) + assert_no_match /map\.yaffle/, File.read(routes_path) + end +end +----------------------------------------------------------- + +Run `rake` to watch the test fail, then make the test pass add the following: + +*vendor/plugins/yaffle/lib/yaffle.rb* + +[source, ruby] +----------------------------------------------------------- +require "yaffle/commands" +----------------------------------------------------------- + +*vendor/plugins/yaffle/lib/yaffle/commands.rb* + +[source, ruby] +----------------------------------------------------------- +require 'rails_generator' +require 'rails_generator/commands' + +module Yaffle #:nodoc: + module Generator #:nodoc: + module Commands #:nodoc: + module Create + def yaffle_route + logger.route "map.yaffle" + look_for = 'ActionController::Routing::Routes.draw do |map|' + unless options[:pretend] + gsub_file('config/routes.rb', /(#{Regexp.escape(look_for)})/mi){|match| "#{match}\n map.yaffle\n"} + end + end + end + + module Destroy + def yaffle_route + logger.route "map.yaffle" + gsub_file 'config/routes.rb', /\n.+?map\.yaffle/mi, '' + end + end + + module List + def yaffle_route + end + end + + module Update + def yaffle_route + end + end + end + end +end + +Rails::Generator::Commands::Create.send :include, Yaffle::Generator::Commands::Create +Rails::Generator::Commands::Destroy.send :include, Yaffle::Generator::Commands::Destroy +Rails::Generator::Commands::List.send :include, Yaffle::Generator::Commands::List +Rails::Generator::Commands::Update.send :include, Yaffle::Generator::Commands::Update +----------------------------------------------------------- + +*vendor/plugins/yaffle/generators/yaffle/yaffle_route_generator.rb* + +[source, ruby] +----------------------------------------------------------- +class YaffleRouteGenerator < Rails::Generator::Base + def manifest + record do |m| + m.yaffle_route + end + end +end +----------------------------------------------------------- + +To see this work, type: + +----------------------------------------------------------- +./script/generate yaffle_route +./script/destroy yaffle_route +----------------------------------------------------------- + +NOTE: If you haven't set up the custom route from above, 'script/destroy' will fail and you'll have to remove it manually. \ No newline at end of file diff --git a/railties/doc/guides/source/creating_plugins/generator_method.txt b/railties/doc/guides/source/creating_plugins/generator_method.txt deleted file mode 100644 index 126692f2c4..0000000000 --- a/railties/doc/guides/source/creating_plugins/generator_method.txt +++ /dev/null @@ -1,89 +0,0 @@ -== Add a custom generator command == - -You may have noticed above that you can used one of the built-in rails migration commands `migration_template`. If your plugin needs to add and remove lines of text from existing files you will need to write your own generator methods. - -This section describes how you you can create your own commands to add and remove a line of text from 'routes.rb'. This example creates a very simple method that adds or removes a text file. - -To start, add the following test method: - -*vendor/plugins/yaffle/test/generator_test.rb* - -[source, ruby] ------------------------------------------------------------ -def test_generates_definition - Rails::Generator::Scripts::Generate.new.run(["yaffle", "bird"], :destination => fake_rails_root) - definition = File.read(File.join(fake_rails_root, "definition.txt")) - assert_match /Yaffle\:/, definition -end ------------------------------------------------------------ - -Run `rake` to watch the test fail, then make the test pass add the following: - -*vendor/plugins/yaffle/generators/yaffle/templates/definition.txt* - ------------------------------------------------------------ -Yaffle: A bird ------------------------------------------------------------ - -*vendor/plugins/yaffle/lib/yaffle.rb* - -[source, ruby] ------------------------------------------------------------ -require "yaffle/commands" ------------------------------------------------------------ - -*vendor/plugins/yaffle/lib/commands.rb* - -[source, ruby] ------------------------------------------------------------ -require 'rails_generator' -require 'rails_generator/commands' - -module Yaffle #:nodoc: - module Generator #:nodoc: - module Commands #:nodoc: - module Create - def yaffle_definition - file("definition.txt", "definition.txt") - end - end - - module Destroy - def yaffle_definition - file("definition.txt", "definition.txt") - end - end - - module List - def yaffle_definition - file("definition.txt", "definition.txt") - end - end - - module Update - def yaffle_definition - file("definition.txt", "definition.txt") - end - end - end - end -end - -Rails::Generator::Commands::Create.send :include, Yaffle::Generator::Commands::Create -Rails::Generator::Commands::Destroy.send :include, Yaffle::Generator::Commands::Destroy -Rails::Generator::Commands::List.send :include, Yaffle::Generator::Commands::List -Rails::Generator::Commands::Update.send :include, Yaffle::Generator::Commands::Update ------------------------------------------------------------ - -Finally, call your new method in the manifest: - -*vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb* - -[source, ruby] ------------------------------------------------------------ -class YaffleGenerator < Rails::Generator::NamedBase - def manifest - m.yaffle_definition - end -end ------------------------------------------------------------ diff --git a/railties/doc/guides/source/creating_plugins/generators.txt b/railties/doc/guides/source/creating_plugins/generators.txt new file mode 100644 index 0000000000..eb0fbb5ee9 --- /dev/null +++ b/railties/doc/guides/source/creating_plugins/generators.txt @@ -0,0 +1,103 @@ +== Generators == + +Many plugins ship with generators. When you created the plugin above, you specified the --with-generator option, so you already have the generator stubs in 'vendor/plugins/yaffle/generators/yaffle'. + +Building generators is a complex topic unto itself and this section will cover one small aspect of generators: creating a generator that adds a time-stamped migration. + +To add a generator to a plugin: + + * Write a test + * Add your instructions to the 'manifest' method of the generator + * Add any necessary template files to the templates directory + * Update the USAGE file to add helpful documentation for your generator + +=== Testing generators === + +Many rails plugin authors do not test their generators, however testing generators is quite simple. A typical generator test does the following: + + * Creates a new fake rails root directory that will serve as destination + * Runs the generator + * Asserts that the correct files were generated + * Removes the fake rails root + +This section will describe how to create a simple generator that adds a file. For the generator in this section, the test could look something like this: + +*vendor/plugins/yaffle/test/definition_generator_test.rb* + +[source, ruby] +------------------------------------------------------------------ +require File.dirname(__FILE__) + '/test_helper.rb' +require 'rails_generator' +require 'rails_generator/scripts/generate' + +class DefinitionGeneratorTest < Test::Unit::TestCase + + def fake_rails_root + File.join(File.dirname(__FILE__), 'rails_root') + end + + def file_list + Dir.glob(File.join(fake_rails_root, "*")) + end + + def setup + FileUtils.mkdir_p(fake_rails_root) + @original_files = file_list + end + + def teardown + FileUtils.rm_r(fake_rails_root) + end + + def test_generates_correct_file_name + Rails::Generator::Scripts::Generate.new.run(["yaffle_definition"], :destination => fake_rails_root) + new_file = (file_list - @original_files).first + assert_equal "definition.txt", File.basename(new_file) + end + +end +------------------------------------------------------------------ + +You can run 'rake' from the plugin directory to see this fail. Unless you are doing more advanced generator commands it typically suffices to just test the Generate script, and trust that rails will handle the Destroy and Update commands for you. + +To make it pass, create the generator: + +*vendor/plugins/yaffle/generators/yaffle_definition/yaffle_definition_generator.rb* + +[source, ruby] +------------------------------------------------------------------ +class YaffleDefinitionGenerator < Rails::Generator::Base + def manifest + record do |m| + m.file "definition.txt", "definition.txt" + end + end +end +------------------------------------------------------------------ + +=== The USAGE file === + +If you plan to distribute your plugin, developers will expect at least a minimum of documentation. You can add simple documentation to the generator by updating the USAGE file. + +Rails ships with several built-in generators. You can see all of the generators available to you by typing the following at the command line: + +------------------------------------------------------------------ +./script/generate +------------------------------------------------------------------ + +You should see something like this: + +------------------------------------------------------------------ +Installed Generators + Plugins (vendor/plugins): yaffle_definition + Builtin: controller, integration_test, mailer, migration, model, observer, plugin, resource, scaffold, session_migration +------------------------------------------------------------------ + +When you run `script/generate yaffle_definition -h` you should see the contents of your 'vendor/plugins/yaffle/generators/yaffle_definition/USAGE'. + +For this plugin, update the USAGE file could look like this: + +------------------------------------------------------------------ +Description: + Adds a file with the definition of a Yaffle to the app's main directory +------------------------------------------------------------------ diff --git a/railties/doc/guides/source/creating_plugins/helpers.txt b/railties/doc/guides/source/creating_plugins/helpers.txt index 51b4cebb01..c2273813dd 100644 --- a/railties/doc/guides/source/creating_plugins/helpers.txt +++ b/railties/doc/guides/source/creating_plugins/helpers.txt @@ -1,4 +1,4 @@ -== Add a helper == +== Helpers == This section describes how to add a helper named 'WoodpeckersHelper' to your plugin that will behave the same as a helper in your main app. This is very similar to adding a model and a controller. diff --git a/railties/doc/guides/source/creating_plugins/index.txt b/railties/doc/guides/source/creating_plugins/index.txt index 19484e2830..5d10fa4f31 100644 --- a/railties/doc/guides/source/creating_plugins/index.txt +++ b/railties/doc/guides/source/creating_plugins/index.txt @@ -29,23 +29,27 @@ This guide describes how to build a test-driven plugin that will: For the purpose of this guide pretend for a moment that you are an avid bird watcher. Your favorite bird is the Yaffle, and you want to create a plugin that allows other developers to share in the Yaffle goodness. First, you need to get setup for development. -include::test_setup.txt[] +include::setup.txt[] + +include::tests.txt[] include::core_ext.txt[] include::acts_as_yaffle.txt[] -include::migration_generator.txt[] - -include::generator_method.txt[] - include::models.txt[] include::controllers.txt[] include::helpers.txt[] -include::custom_route.txt[] +include::routes.txt[] + +include::generators.txt[] + +include::generator_commands.txt[] + +include::migrations.txt[] include::odds_and_ends.txt[] diff --git a/railties/doc/guides/source/creating_plugins/migration_generator.txt b/railties/doc/guides/source/creating_plugins/migration_generator.txt deleted file mode 100644 index f4fc32481c..0000000000 --- a/railties/doc/guides/source/creating_plugins/migration_generator.txt +++ /dev/null @@ -1,156 +0,0 @@ -== Create a generator == - -Many plugins ship with generators. When you created the plugin above, you specified the --with-generator option, so you already have the generator stubs in 'vendor/plugins/yaffle/generators/yaffle'. - -Building generators is a complex topic unto itself and this section will cover one small aspect of generators: creating a generator that adds a time-stamped migration. - -To create a generator you must: - - * Add your instructions to the 'manifest' method of the generator - * Add any necessary template files to the templates directory - * Test the generator manually by running various combinations of `script/generate` and `script/destroy` - * Update the USAGE file to add helpful documentation for your generator - -=== Testing generators === - -Many rails plugin authors do not test their generators, however testing generators is quite simple. A typical generator test does the following: - - * Creates a new fake rails root directory that will serve as destination - * Runs the generator forward and backward, making whatever assertions are necessary - * Removes the fake rails root - -For the generator in this section, the test could look something like this: - -*vendor/plugins/yaffle/test/yaffle_generator_test.rb* - -[source, ruby] ------------------------------------------------------------------- -require File.dirname(__FILE__) + '/test_helper.rb' -require 'rails_generator' -require 'rails_generator/scripts/generate' -require 'rails_generator/scripts/destroy' - -class GeneratorTest < Test::Unit::TestCase - - def fake_rails_root - File.join(File.dirname(__FILE__), 'rails_root') - end - - def file_list - Dir.glob(File.join(fake_rails_root, "db", "migrate", "*")) - end - - def setup - FileUtils.mkdir_p(fake_rails_root) - @original_files = file_list - end - - def teardown - FileUtils.rm_r(fake_rails_root) - end - - def test_generates_correct_file_name - Rails::Generator::Scripts::Generate.new.run(["yaffle", "bird"], :destination => fake_rails_root) - new_file = (file_list - @original_files).first - assert_match /add_yaffle_fields_to_bird/, new_file - end - -end ------------------------------------------------------------------- - -You can run 'rake' from the plugin directory to see this fail. Unless you are doing more advanced generator commands it typically suffices to just test the Generate script, and trust that rails will handle the Destroy and Update commands for you. - -=== Adding to the manifest === - -This example will demonstrate how to use one of the built-in generator methods named 'migration_template' to create a migration file. To start, update your generator file to look like this: - -*vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb* - -[source, ruby] ------------------------------------------------------------------- -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")] - end - end -end ------------------------------------------------------------------- - -The generator creates a new file in 'db/migrate' with a timestamp and an 'add_column' statement. It reuses the built in rails `migration_template` method, and reuses the built-in rails migration template. - -It's courteous to check to see if table names are being pluralized whenever you create a generator that needs to be aware of table names. This way people using your generator won't have to manually change the generated files if they've turned pluralization off. - -=== Manually test the generator === - -To run the generator, type the following at the command line: - ------------------------------------------------------------------- -./script/generate yaffle bird ------------------------------------------------------------------- - -and you will see a new file: - -*db/migrate/20080529225649_add_yaffle_fields_to_birds.rb* - -[source, ruby] ------------------------------------------------------------------- -class AddYaffleFieldsToBirds < ActiveRecord::Migration - def self.up - add_column :birds, :last_squawk, :string - end - - def self.down - remove_column :birds, :last_squawk - end -end ------------------------------------------------------------------- - - -=== The USAGE file === - -Rails ships with several built-in generators. You can see all of the generators available to you by typing the following at the command line: - ------------------------------------------------------------------- -script/generate ------------------------------------------------------------------- - -You should see something like this: - ------------------------------------------------------------------- -Installed Generators - Plugins (vendor/plugins): yaffle - Builtin: controller, integration_test, mailer, migration, model, observer, plugin, resource, scaffold, session_migration ------------------------------------------------------------------- - -When you run `script/generate yaffle` you should see the contents of your 'vendor/plugins/yaffle/generators/yaffle/USAGE' file. - -For this plugin, update 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 ------------------------------------------------------------------- diff --git a/railties/doc/guides/source/creating_plugins/migrations.txt b/railties/doc/guides/source/creating_plugins/migrations.txt new file mode 100644 index 0000000000..7154f0bc06 --- /dev/null +++ b/railties/doc/guides/source/creating_plugins/migrations.txt @@ -0,0 +1,209 @@ +== Migrations == + +If your plugin requires changes to the app's database you will likely want to somehow add migrations. Rails does not include any built-in support for calling migrations from plugins, but you can still make it easy for developers to call migrations from plugins. + +If you have a very simple needs, like creating a table that will always have the same name and columns, then you can use a more simple solution, like creating a custom rake task or method. If your migration needs user input to supply table names or other options, you probably want to opt for generating a migration. + +Let's say you have the following migration in your plugin: + +*vendor/plugins/yaffle/lib/db/migrate/20081116181115_create_birdhouses.rb:* + +[source, ruby] +---------------------------------------------- +class CreateBirdhouses < ActiveRecord::Migration + def self.up + create_table :birdhouses, :force => true do |t| + t.string :name + t.timestamps + end + end + + def self.down + drop_table :birdhouses + end +end +---------------------------------------------- + +Here are a few possibilities for how to allow developers to use your plugin migrations: + +=== Create a custom rake task === + +*vendor/plugins/yaffle/lib/db/migrate/20081116181115_create_birdhouses.rb:* + +[source, ruby] +---------------------------------------------- +class CreateBirdhouses < ActiveRecord::Migration + def self.up + create_table :birdhouses, :force => true do |t| + t.string :name + t.timestamps + end + end + + def self.down + drop_table :birdhouses + end +end +---------------------------------------------- + + +*vendor/plugins/yaffle/tasks/yaffle.rake:* + +[source, ruby] +---------------------------------------------- +namespace :db do + namespace :migrate do + desc "Migrate the database through scripts in vendor/plugins/yaffle/lib/db/migrate and update db/schema.rb by invoking db:schema:dump. Target specific version with VERSION=x. Turn off output with VERBOSE=false." + task :yaffle => :environment do + ActiveRecord::Migration.verbose = ENV["VERBOSE"] ? ENV["VERBOSE"] == "true" : true + ActiveRecord::Migrator.migrate("vendor/plugins/yaffle/lib/db/migrate/", ENV["VERSION"] ? ENV["VERSION"].to_i : nil) + Rake::Task["db:schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby + end + end +end +---------------------------------------------- + +=== Call plugin migrations from regular migrations === + +*vendor/plugins/yaffle/lib/yaffle.rb:* + +[source, ruby] +---------------------------------------------- +Dir.glob(File.join(File.dirname(__FILE__), "db", "migrate", "*")).each do |file| + require file +end +---------------------------------------------- + +*db/migrate/20081116181115_create_birdhouses.rb:* + +[source, ruby] +---------------------------------------------- +class CreateBirdhouses < ActiveRecord::Migration + def self.up + Yaffle::CreateBirdhouses.up + end + + def self.down + Yaffle::CreateBirdhouses.down + end +end +---------------------------------------------- + +NOTE: several plugin frameworks such as Desert and Engines provide more advanced plugin functionality. + +== Generating migrations == + +Generating migrations has several advantages over other methods. Namely, you can allow other developers to more easily customize the migration. The flow looks like this: + + * call your script/generate script and pass in whatever options they need + * examine the generated migration, adding/removing columns or other options as necessary + +This example will demonstrate how to use one of the built-in generator methods named 'migration_template' to create a migration file. Extending the rails migration generator requires a somewhat intimate knowledge of the migration generator internals, so it's best to write a test first: + +*vendor/plugins/yaffle/test/yaffle_migration_generator_test.rb* + +[source, ruby] +------------------------------------------------------------------ +require File.dirname(__FILE__) + '/test_helper.rb' +require 'rails_generator' +require 'rails_generator/scripts/generate' +require 'rails_generator/scripts/destroy' + +class MigrationGeneratorTest < Test::Unit::TestCase + + def fake_rails_root + File.join(File.dirname(__FILE__), 'rails_root') + end + + def file_list + Dir.glob(File.join(fake_rails_root, "db", "migrate", "*")) + end + + def setup + FileUtils.mkdir_p(fake_rails_root) + @original_files = file_list + end + + def teardown + FileUtils.rm_r(fake_rails_root) + end + + def test_generates_correct_file_name + Rails::Generator::Scripts::Generate.new.run(["yaffle", "some_name_nobody_is_likely_to_ever_use_in_a_real_migration"], :destination => fake_rails_root) + new_file = (file_list - @original_files).first + assert_match /add_yaffle_fields_to_some_name_nobody_is_likely_to_ever_use_in_a_real_migrations/, new_file + assert_match /add_column :some_name_nobody_is_likely_to_ever_use_in_a_real_migrations do |t|/, File.read(new_file) + end + + def test_pluralizes_properly + ActiveRecord::Base.pluralize_table_names = false + Rails::Generator::Scripts::Generate.new.run(["yaffle", "some_name_nobody_is_likely_to_ever_use_in_a_real_migration"], :destination => fake_rails_root) + new_file = (file_list - @original_files).first + assert_match /add_yaffle_fields_to_some_name_nobody_is_likely_to_ever_use_in_a_real_migration/, new_file + assert_match /add_column :some_name_nobody_is_likely_to_ever_use_in_a_real_migration do |t|/, File.read(new_file) + end + +end +------------------------------------------------------------------ + +NOTE: the migration generator checks to see if a migation already exists, and it's hard-coded to check the 'db/migrate' directory. As a result, if your test tries to generate a migration that already exists in the app, it will fail. The easy workaround is to make sure that the name you generate in your test is very unlikely to actually appear in the app. + +After running the test with 'rake' you can make it pass with: + +*vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb* + +[source, ruby] +------------------------------------------------------------------ +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")] + end + end +end +------------------------------------------------------------------ + +The generator creates a new file in 'db/migrate' with a timestamp and an 'add_column' statement. It reuses the built in rails `migration_template` method, and reuses the built-in rails migration template. + +It's courteous to check to see if table names are being pluralized whenever you create a generator that needs to be aware of table names. This way people using your generator won't have to manually change the generated files if they've turned pluralization off. + +To run the generator, type the following at the command line: + +------------------------------------------------------------------ +./script/generate yaffle_migration bird +------------------------------------------------------------------ + +and you will see a new file: + +*db/migrate/20080529225649_add_yaffle_fields_to_birds.rb* + +[source, ruby] +------------------------------------------------------------------ +class AddYaffleFieldsToBirds < ActiveRecord::Migration + def self.up + add_column :birds, :last_squawk, :string + end + + def self.down + remove_column :birds, :last_squawk + end +end +------------------------------------------------------------------ + diff --git a/railties/doc/guides/source/creating_plugins/models.txt b/railties/doc/guides/source/creating_plugins/models.txt index 458edec80a..dfe11f9c4e 100644 --- a/railties/doc/guides/source/creating_plugins/models.txt +++ b/railties/doc/guides/source/creating_plugins/models.txt @@ -1,4 +1,4 @@ -== Add a model == +== Models == This section describes how to add a model named 'Woodpecker' to your plugin that will behave the same as a model in your main app. When storing models, controllers, views and helpers in your plugin, it's customary to keep them in directories that match the rails directories. For this example, create a file structure like this: diff --git a/railties/doc/guides/source/creating_plugins/routes.txt b/railties/doc/guides/source/creating_plugins/routes.txt new file mode 100644 index 0000000000..cdc20e998e --- /dev/null +++ b/railties/doc/guides/source/creating_plugins/routes.txt @@ -0,0 +1,69 @@ +== Routes == + +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. + +*vendor/plugins/yaffle/test/routing_test.rb* + +[source, ruby] +-------------------------------------------------------- +require "#{File.dirname(__FILE__)}/test_helper" + +class RoutingTest < Test::Unit::TestCase + + def setup + ActionController::Routing::Routes.draw do |map| + map.yaffles + end + end + + def test_yaffles_route + assert_recognition :get, "/yaffles", :controller => "yaffles_controller", :action => "index" + end + + 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 +-------------------------------------------------------- + +*vendor/plugins/yaffle/init.rb* + +[source, ruby] +-------------------------------------------------------- +require "routing" +ActionController::Routing::RouteSet::Mapper.send :include, Yaffle::Routing::MapperExtensions +-------------------------------------------------------- + +*vendor/plugins/yaffle/lib/routing.rb* + +[source, ruby] +-------------------------------------------------------- +module Yaffle #:nodoc: + module Routing #:nodoc: + module MapperExtensions + def yaffles + @set.add_route("/yaffles", {:controller => "yaffles_controller", :action => "index"}) + end + end + end +end +-------------------------------------------------------- + +*config/routes.rb* + +[source, ruby] +-------------------------------------------------------- +ActionController::Routing::Routes.draw do |map| + ... + map.yaffles +end +-------------------------------------------------------- + +You can also see if your routes work by running `rake routes` from your app directory. diff --git a/railties/doc/guides/source/creating_plugins/setup.txt b/railties/doc/guides/source/creating_plugins/setup.txt new file mode 100644 index 0000000000..fcf5b459e6 --- /dev/null +++ b/railties/doc/guides/source/creating_plugins/setup.txt @@ -0,0 +1,64 @@ +== Setup == + +=== Create the basic app === + +The examples in this guide require that you have a working rails application. To create a simple rails app execute: + +------------------------------------------------ +gem install rails +rails yaffle_guide +cd yaffle_guide +script/generate scaffold bird name:string +rake db:migrate +script/server +------------------------------------------------ + +Then navigate to http://localhost:3000/birds. Make sure you have a functioning rails app before continuing. + +.Editor's note: +NOTE: The aforementioned instructions will work for sqlite3. For more detailed instructions on how to create a rails app for other databases see the API docs. + + +=== Generate the plugin skeleton === + +Rails ships with a plugin generator which creates a basic plugin skeleton. Pass the plugin name, either 'CamelCased' or 'under_scored', as an argument. Pass `\--with-generator` to add an example generator also. + +This creates a plugin in 'vendor/plugins' including an 'init.rb' and 'README' as well as standard 'lib', 'task', and 'test' directories. + +Examples: +---------------------------------------------- +./script/generate plugin yaffle +./script/generate plugin yaffle --with-generator +---------------------------------------------- + +To get more detailed help on the plugin generator, type `./script/generate plugin`. + +Later on this guide will describe how to work with generators, so go ahead and generate your plugin with the `\--with-generator` option now: + +---------------------------------------------- +./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 +---------------------------------------------- + +To begin just change one thing - move 'init.rb' to 'rails/init.rb'. diff --git a/railties/doc/guides/source/creating_plugins/test_setup.txt b/railties/doc/guides/source/creating_plugins/test_setup.txt deleted file mode 100644 index 64236ff110..0000000000 --- a/railties/doc/guides/source/creating_plugins/test_setup.txt +++ /dev/null @@ -1,230 +0,0 @@ -== Preparation == - -=== Create the basic app === - -The examples in this guide require that you have a working rails application. To create a simple rails app execute: - ------------------------------------------------- -gem install rails -rails yaffle_guide -cd yaffle_guide -script/generate scaffold bird name:string -rake db:migrate -script/server ------------------------------------------------- - -Then navigate to http://localhost:3000/birds. Make sure you have a functioning rails app before continuing. - -.Editor's note: -NOTE: The aforementioned instructions will work for sqlite3. For more detailed instructions on how to create a rails app for other databases see the API docs. - - -=== Generate the plugin skeleton === - -Rails ships with a plugin generator which creates a basic plugin skeleton. Pass the plugin name, either 'CamelCased' or 'under_scored', as an argument. Pass `\--with-generator` to add an example generator also. - -This creates a plugin in 'vendor/plugins' including an 'init.rb' and 'README' as well as standard 'lib', 'task', and 'test' directories. - -Examples: ----------------------------------------------- -./script/generate plugin yaffle -./script/generate plugin yaffle --with-generator ----------------------------------------------- - -To get more detailed help on the plugin generator, type `./script/generate plugin`. - -Later on this guide will describe how to work with generators, so go ahead and generate your plugin with the `\--with-generator` option now: - ----------------------------------------------- -./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 ----------------------------------------------- - -To begin just change one thing - move 'init.rb' to 'rails/init.rb'. - -=== Setup the plugin for testing === - -If your plugin interacts with a database, you'll need to setup a database connection. In this guide you will learn how to test your plugin against multiple different database adapters using Active Record. This guide 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 method that sets up the database - -*vendor/plugins/yaffle/test/database.yml:* - ----------------------------------------------- -sqlite: - :adapter: sqlite - :dbfile: vendor/plugins/yaffle/test/yaffle_plugin.sqlite.db - -sqlite3: - :adapter: sqlite3 - :dbfile: vendor/plugins/yaffle/test/yaffle_plugin.sqlite3.db - -postgresql: - :adapter: postgresql - :username: postgres - :password: postgres - :database: yaffle_plugin_test - :min_messages: ERROR - -mysql: - :adapter: mysql - :host: localhost - :username: root - :password: password - :database: yaffle_plugin_test ----------------------------------------------- - -For this guide you'll need 2 tables/models, Hickwalls and Wickwalls, so add the following: - -*vendor/plugins/yaffle/test/schema.rb:* - -[source, ruby] ----------------------------------------------- -ActiveRecord::Schema.define(:version => 0) do - create_table :hickwalls, :force => true do |t| - t.string :name - t.string :last_squawk - t.datetime :last_squawked_at - end - create_table :wickwalls, :force => true do |t| - t.string :name - t.string :last_tweet - t.datetime :last_tweeted_at - end - create_table :woodpeckers, :force => true do |t| - t.string :name - end -end ----------------------------------------------- - -*vendor/plugins/yaffle/test/test_helper.rb:* - -[source, ruby] ----------------------------------------------- -ENV['RAILS_ENV'] = 'test' -ENV['RAILS_ROOT'] ||= File.dirname(__FILE__) + '/../../../..' - -require 'test/unit' -require File.expand_path(File.join(ENV['RAILS_ROOT'], 'config/environment.rb')) - -def load_schema - config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml')) - ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log") - - db_adapter = ENV['DB'] - - # no db passed, try one of these fine config-free DBs before bombing. - db_adapter ||= - begin - require 'rubygems' - require 'sqlite' - 'sqlite' - rescue MissingSourceFile - begin - require 'sqlite3' - 'sqlite3' - rescue MissingSourceFile - end - end - - if db_adapter.nil? - raise "No DB Adapter selected. Pass the DB= option to pick one, or install Sqlite or Sqlite3." - end - - ActiveRecord::Base.establish_connection(config[db_adapter]) - load(File.dirname(__FILE__) + "/schema.rb") - require File.dirname(__FILE__) + '/../rails/init.rb' -end ----------------------------------------------- - -Now whenever you write a test that requires the database, you can call 'load_schema'. - -=== Run the plugin tests === - -Once you have these files in place, you can write your first test to ensure that your plugin-testing setup is correct. By default rails generates a file in 'vendor/plugins/yaffle/test/yaffle_test.rb' with a sample test. Replace the contents of that file with: - -*vendor/plugins/yaffle/test/yaffle_test.rb:* - -[source, ruby] ----------------------------------------------- -require File.dirname(__FILE__) + '/test_helper.rb' - -class YaffleTest < Test::Unit::TestCase - load_schema - - class Hickwall < ActiveRecord::Base - end - - class Wickwall < ActiveRecord::Base - end - - def test_schema_has_loaded_correctly - assert_equal [], Hickwall.all - assert_equal [], Wickwall.all - end - -end ----------------------------------------------- - -To run this, go to the plugin directory and run `rake`: - ----------------------------------------------- -cd vendor/plugins/yaffle -rake ----------------------------------------------- - -You should see output like: - ----------------------------------------------- -/opt/local/bin/ruby -Ilib:lib "/opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader.rb" "test/yaffle_test.rb" --- create_table(:hickwalls, {:force=>true}) - -> 0.0220s --- create_table(:wickwalls, {:force=>true}) - -> 0.0077s --- initialize_schema_migrations_table() - -> 0.0007s --- assume_migrated_upto_version(0) - -> 0.0007s -Loaded suite /opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader -Started -. -Finished in 0.002236 seconds. - -1 test, 1 assertion, 0 failures, 0 errors ----------------------------------------------- - -By default the setup above runs your tests with sqlite or sqlite3. To run tests with one of the other connection strings specified in database.yml, pass the DB environment variable to rake: - ----------------------------------------------- -rake DB=sqlite -rake DB=sqlite3 -rake DB=mysql -rake DB=postgresql ----------------------------------------------- - -Now you are ready to test-drive your plugin! diff --git a/railties/doc/guides/source/creating_plugins/tests.txt b/railties/doc/guides/source/creating_plugins/tests.txt new file mode 100644 index 0000000000..ef6dab2f9f --- /dev/null +++ b/railties/doc/guides/source/creating_plugins/tests.txt @@ -0,0 +1,165 @@ +== Tests == + +If your plugin interacts with a database, you'll need to setup a database connection. In this guide you will learn how to test your plugin against multiple different database adapters using Active Record. This guide 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 method that sets up the database + +*vendor/plugins/yaffle/test/database.yml:* + +---------------------------------------------- +sqlite: + :adapter: sqlite + :dbfile: vendor/plugins/yaffle/test/yaffle_plugin.sqlite.db + +sqlite3: + :adapter: sqlite3 + :dbfile: vendor/plugins/yaffle/test/yaffle_plugin.sqlite3.db + +postgresql: + :adapter: postgresql + :username: postgres + :password: postgres + :database: yaffle_plugin_test + :min_messages: ERROR + +mysql: + :adapter: mysql + :host: localhost + :username: root + :password: password + :database: yaffle_plugin_test +---------------------------------------------- + +For this guide you'll need 2 tables/models, Hickwalls and Wickwalls, so add the following: + +*vendor/plugins/yaffle/test/schema.rb:* + +[source, ruby] +---------------------------------------------- +ActiveRecord::Schema.define(:version => 0) do + create_table :hickwalls, :force => true do |t| + t.string :name + t.string :last_squawk + t.datetime :last_squawked_at + end + create_table :wickwalls, :force => true do |t| + t.string :name + t.string :last_tweet + t.datetime :last_tweeted_at + end + create_table :woodpeckers, :force => true do |t| + t.string :name + end +end +---------------------------------------------- + +*vendor/plugins/yaffle/test/test_helper.rb:* + +[source, ruby] +---------------------------------------------- +ENV['RAILS_ENV'] = 'test' +ENV['RAILS_ROOT'] ||= File.dirname(__FILE__) + '/../../../..' + +require 'test/unit' +require File.expand_path(File.join(ENV['RAILS_ROOT'], 'config/environment.rb')) + +def load_schema + config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml')) + ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log") + + db_adapter = ENV['DB'] + + # no db passed, try one of these fine config-free DBs before bombing. + db_adapter ||= + begin + require 'rubygems' + require 'sqlite' + 'sqlite' + rescue MissingSourceFile + begin + require 'sqlite3' + 'sqlite3' + rescue MissingSourceFile + end + end + + if db_adapter.nil? + raise "No DB Adapter selected. Pass the DB= option to pick one, or install Sqlite or Sqlite3." + end + + ActiveRecord::Base.establish_connection(config[db_adapter]) + load(File.dirname(__FILE__) + "/schema.rb") + require File.dirname(__FILE__) + '/../rails/init.rb' +end +---------------------------------------------- + +Now whenever you write a test that requires the database, you can call 'load_schema'. + +=== Run the plugin tests === + +Once you have these files in place, you can write your first test to ensure that your plugin-testing setup is correct. By default rails generates a file in 'vendor/plugins/yaffle/test/yaffle_test.rb' with a sample test. Replace the contents of that file with: + +*vendor/plugins/yaffle/test/yaffle_test.rb:* + +[source, ruby] +---------------------------------------------- +require File.dirname(__FILE__) + '/test_helper.rb' + +class YaffleTest < Test::Unit::TestCase + load_schema + + class Hickwall < ActiveRecord::Base + end + + class Wickwall < ActiveRecord::Base + end + + def test_schema_has_loaded_correctly + assert_equal [], Hickwall.all + assert_equal [], Wickwall.all + end + +end +---------------------------------------------- + +To run this, go to the plugin directory and run `rake`: + +---------------------------------------------- +cd vendor/plugins/yaffle +rake +---------------------------------------------- + +You should see output like: + +---------------------------------------------- +/opt/local/bin/ruby -Ilib:lib "/opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader.rb" "test/yaffle_test.rb" +-- create_table(:hickwalls, {:force=>true}) + -> 0.0220s +-- create_table(:wickwalls, {:force=>true}) + -> 0.0077s +-- initialize_schema_migrations_table() + -> 0.0007s +-- assume_migrated_upto_version(0) + -> 0.0007s +Loaded suite /opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader +Started +. +Finished in 0.002236 seconds. + +1 test, 1 assertion, 0 failures, 0 errors +---------------------------------------------- + +By default the setup above runs your tests with sqlite or sqlite3. To run tests with one of the other connection strings specified in database.yml, pass the DB environment variable to rake: + +---------------------------------------------- +rake DB=sqlite +rake DB=sqlite3 +rake DB=mysql +rake DB=postgresql +---------------------------------------------- + +Now you are ready to test-drive your plugin! -- cgit v1.2.3 From 6b8500ce48f45f18696f6215b8a01f5cf0e328b5 Mon Sep 17 00:00:00 2001 From: Jeff Dean Date: Sun, 16 Nov 2008 22:27:08 -0500 Subject: Rails guide: Added PluginGem section, reorganized the odds and ends. --- .../guides/source/creating_plugins/appendix.txt | 26 ++++++-- .../guides/source/creating_plugins/controllers.txt | 2 +- .../doc/guides/source/creating_plugins/gem.txt | 3 - .../doc/guides/source/creating_plugins/gems.txt | 50 ++++++++++++++++ .../doc/guides/source/creating_plugins/index.txt | 6 +- .../guides/source/creating_plugins/migrations.txt | 4 +- .../source/creating_plugins/odds_and_ends.txt | 69 ---------------------- .../doc/guides/source/creating_plugins/rdoc.txt | 18 ++++++ .../doc/guides/source/creating_plugins/tasks.txt | 29 +++++++++ 9 files changed, 126 insertions(+), 81 deletions(-) delete mode 100644 railties/doc/guides/source/creating_plugins/gem.txt create mode 100644 railties/doc/guides/source/creating_plugins/gems.txt delete mode 100644 railties/doc/guides/source/creating_plugins/odds_and_ends.txt create mode 100644 railties/doc/guides/source/creating_plugins/rdoc.txt create mode 100644 railties/doc/guides/source/creating_plugins/tasks.txt (limited to 'railties/doc/guides/source/creating_plugins') diff --git a/railties/doc/guides/source/creating_plugins/appendix.txt b/railties/doc/guides/source/creating_plugins/appendix.txt index d890f861b5..19f677c5fd 100644 --- a/railties/doc/guides/source/creating_plugins/appendix.txt +++ b/railties/doc/guides/source/creating_plugins/appendix.txt @@ -1,5 +1,7 @@ == Appendix == +If you prefer to use RSpec instead of tets, you may be interested in the http://github.com/pat-maddox/rspec-plugin-generator/tree/master[RSpec Plugin Generator]. + === References === * http://nubyonrails.com/articles/the-complete-guide-to-rails-plugins-part-i @@ -13,16 +15,23 @@ The final plugin should have a directory structure that looks something like this: ------------------------------------------------ -vendor/plugins/yaffle/ |-- MIT-LICENSE |-- README |-- Rakefile |-- generators -| `-- yaffle +| |-- yaffle_definition +| | |-- USAGE +| | |-- templates +| | | `-- definition.txt +| | `-- yaffle_definition_generator.rb +| |-- yaffle_migration +| | |-- USAGE +| | |-- templates +| | `-- yaffle_migration_generator.rb +| `-- yaffle_route | |-- USAGE | |-- templates -| | `-- definition.txt -| `-- yaffle_generator.rb +| `-- yaffle_route_generator.rb |-- install.rb |-- lib | |-- app @@ -32,11 +41,16 @@ vendor/plugins/yaffle/ | | | `-- woodpeckers_helper.rb | | `-- models | | `-- woodpecker.rb +| |-- db +| | `-- migrate +| | `-- 20081116181115_create_birdhouses.rb | |-- yaffle | | |-- acts_as_yaffle.rb | | |-- commands.rb | | `-- core_ext.rb | `-- yaffle.rb +|-- pkg +| `-- yaffle-0.0.1.gem |-- rails | `-- init.rb |-- tasks @@ -46,7 +60,9 @@ vendor/plugins/yaffle/ | |-- core_ext_test.rb | |-- database.yml | |-- debug.log -| |-- generator_test.rb +| |-- definition_generator_test.rb +| |-- migration_generator_test.rb +| |-- route_generator_test.rb | |-- schema.rb | |-- test_helper.rb | |-- woodpecker_test.rb diff --git a/railties/doc/guides/source/creating_plugins/controllers.txt b/railties/doc/guides/source/creating_plugins/controllers.txt index 4f4417b416..e38cf8251e 100644 --- a/railties/doc/guides/source/creating_plugins/controllers.txt +++ b/railties/doc/guides/source/creating_plugins/controllers.txt @@ -4,7 +4,7 @@ This section describes how to add a controller named 'woodpeckers' to your plugi You can test your plugin's controller as you would test any other controller: -*vendor/plugins/yaffle/yaffle/woodpeckers_controller_test.rb:* +*vendor/plugins/yaffle/test/woodpeckers_controller_test.rb:* [source, ruby] ---------------------------------------------- diff --git a/railties/doc/guides/source/creating_plugins/gem.txt b/railties/doc/guides/source/creating_plugins/gem.txt deleted file mode 100644 index 8a0bbb3bc0..0000000000 --- a/railties/doc/guides/source/creating_plugins/gem.txt +++ /dev/null @@ -1,3 +0,0 @@ -== Gems == - -http://www.mbleigh.com/2008/6/11/gemplugins-a-brief-introduction-to-the-future-of-rails-plugins \ No newline at end of file diff --git a/railties/doc/guides/source/creating_plugins/gems.txt b/railties/doc/guides/source/creating_plugins/gems.txt new file mode 100644 index 0000000000..67d55adb3a --- /dev/null +++ b/railties/doc/guides/source/creating_plugins/gems.txt @@ -0,0 +1,50 @@ +== PluginGems == + +Turning your rails plugin into a gem is a simple and straightforward task. This section will cover how to turn your plugin into a gem. It will not cover how to distribute that gem. + +Historically rails plugins loaded the plugin's 'init.rb' file. In fact some plugins contain all of their code in that one file. To be compatible with plugins, 'init.rb' was moved to 'rails/init.rb'. + +It's common practice to put any developer-centric rake tasks (such as tests, rdoc and gem package tasks) in 'Rakefile'. A rake task that packages the gem might look like this: + +*vendor/plugins/yaffle/Rakefile:* + +[source, ruby] +---------------------------------------------- +PKG_FILES = FileList[ + '[a-zA-Z]*', + 'generators/**/*', + 'lib/**/*', + 'rails/**/*', + 'tasks/**/*', + 'test/**/*' +] + +spec = Gem::Specification.new do |s| + s.name = "yaffle" + s.version = "0.0.1" + s.author = "Gleeful Yaffler" + s.email = "yaffle@example.com" + s.homepage = "http://yafflers.example.com/" + s.platform = Gem::Platform::RUBY + s.summary = "Sharing Yaffle Goodness" + s.files = PKG_FILES.to_a + s.require_path = "lib" + s.has_rdoc = false + s.extra_rdoc_files = ["README"] +end + +desc 'Turn this plugin into a gem.' +Rake::GemPackageTask.new(spec) do |pkg| + pkg.gem_spec = spec +end +---------------------------------------------- + +To build and install the gem locally, run the following commands: + +---------------------------------------------- +cd vendor/plugins/yaffle +rake gem +sudo gem install pkg/yaffle-0.0.1.gem +---------------------------------------------- + +To test this, create a new rails app, add 'config.gem "yaffle"' to environment.rb and all of your plugin's functionality will be available to you. \ No newline at end of file diff --git a/railties/doc/guides/source/creating_plugins/index.txt b/railties/doc/guides/source/creating_plugins/index.txt index 5d10fa4f31..0607bc7487 100644 --- a/railties/doc/guides/source/creating_plugins/index.txt +++ b/railties/doc/guides/source/creating_plugins/index.txt @@ -51,6 +51,10 @@ include::generator_commands.txt[] include::migrations.txt[] -include::odds_and_ends.txt[] +include::tasks.txt[] + +include::gems.txt[] + +include::rdoc.txt[] include::appendix.txt[] diff --git a/railties/doc/guides/source/creating_plugins/migrations.txt b/railties/doc/guides/source/creating_plugins/migrations.txt index 7154f0bc06..4dd932734d 100644 --- a/railties/doc/guides/source/creating_plugins/migrations.txt +++ b/railties/doc/guides/source/creating_plugins/migrations.txt @@ -63,7 +63,7 @@ namespace :db do end ---------------------------------------------- -=== Call plugin migrations from regular migrations === +=== Call migrations directly === *vendor/plugins/yaffle/lib/yaffle.rb:* @@ -91,7 +91,7 @@ end NOTE: several plugin frameworks such as Desert and Engines provide more advanced plugin functionality. -== Generating migrations == +=== Generate migrations === Generating migrations has several advantages over other methods. Namely, you can allow other developers to more easily customize the migration. The flow looks like this: diff --git a/railties/doc/guides/source/creating_plugins/odds_and_ends.txt b/railties/doc/guides/source/creating_plugins/odds_and_ends.txt deleted file mode 100644 index e328c04a79..0000000000 --- a/railties/doc/guides/source/creating_plugins/odds_and_ends.txt +++ /dev/null @@ -1,69 +0,0 @@ -== Odds and ends == - -=== 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 - -=== 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: - -*vendor/plugins/yaffle/tasks/yaffle.rake* - -[source, ruby] ---------------------------------------------------------- -namespace :yaffle do - desc "Prints out the word 'Yaffle'" - task :squawk => :environment do - puts "squawk!" - end -end ---------------------------------------------------------- - -When you run `rake -T` from your plugin you will see: - ---------------------------------------------------------- -yaffle:squawk # Prints out the word 'Yaffle' ---------------------------------------------------------- - -You can add as many files as you want in the tasks directory, and if they end in .rake Rails will pick them up. - -=== Store plugins in alternate locations === - -You can store plugins wherever you want - you just have to add those plugins to the plugins path in 'environment.rb'. - -Since the plugin is only loaded after the plugin paths are defined, you can't redefine this in your plugins - but it may be good to now. - -You can even store plugins inside of other plugins for complete plugin madness! - -[source, ruby] ---------------------------------------------------------- -config.plugin_paths << File.join(RAILS_ROOT,"vendor","plugins","yaffle","lib","plugins") ---------------------------------------------------------- - -=== Create your own Plugin Loaders and Plugin Locators === - -If the built-in plugin behavior is inadequate, you can change almost every aspect of the location and loading process. You can write your own plugin locators and plugin loaders, but that's beyond the scope of this tutorial. - - -=== Use Custom Plugin Generators === - -If you are an RSpec fan, you can install the `rspec_plugin_generator` gem, which will generate the spec folder and database for you. See http://github.com/pat-maddox/rspec-plugin-generator/tree/master. - diff --git a/railties/doc/guides/source/creating_plugins/rdoc.txt b/railties/doc/guides/source/creating_plugins/rdoc.txt new file mode 100644 index 0000000000..0f6f843c42 --- /dev/null +++ b/railties/doc/guides/source/creating_plugins/rdoc.txt @@ -0,0 +1,18 @@ +== RDoc Documentation == + +Once your plugin is stable and you are ready to deploy do everyone else a favor and document it! Luckily, writing documentation for your plugin is easy. + +The first step is to update the README file with detailed information about how to use your plugin. A few key things to include are: + + * Your name + * How to install + * How to add the functionality to the app (several examples of common use cases) + * Warning, gotchas or tips that might help save users time + +Once your README is solid, go through and add rdoc comments to all of the methods that developers will use. It's also customary to add '#:nodoc:' comments to those parts of the code that are not part of the public api. + +Once your comments are good to go, navigate to your plugin directory and run: + +--------------------------------------------------------- +rake rdoc +--------------------------------------------------------- diff --git a/railties/doc/guides/source/creating_plugins/tasks.txt b/railties/doc/guides/source/creating_plugins/tasks.txt new file mode 100644 index 0000000000..c71ba42bb0 --- /dev/null +++ b/railties/doc/guides/source/creating_plugins/tasks.txt @@ -0,0 +1,29 @@ +== Rake tasks == + +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: + +*vendor/plugins/yaffle/tasks/yaffle.rake* + +[source, ruby] +--------------------------------------------------------- +namespace :yaffle do + desc "Prints out the word 'Yaffle'" + task :squawk => :environment do + puts "squawk!" + end +end +--------------------------------------------------------- + +When you run `rake -T` from your plugin you will see: + +--------------------------------------------------------- +... +yaffle:squawk # Prints out the word 'Yaffle' +... +--------------------------------------------------------- + +You can add as many files as you want in the tasks directory, and if they end in .rake Rails will pick them up. + +Note that tasks from 'vendor/plugins/yaffle/Rakefile' are not available to the main app. \ No newline at end of file -- cgit v1.2.3 From e08af7219795d28fe9e9eb5f0dc2e7488541382e Mon Sep 17 00:00:00 2001 From: Jeff Dean Date: Sun, 16 Nov 2008 23:09:12 -0500 Subject: Rails guide: Misc reorganization --- .../guides/source/creating_plugins/core_ext.txt | 27 +--------------------- .../source/creating_plugins/generator_commands.txt | 1 + .../guides/source/creating_plugins/migrations.txt | 2 ++ .../doc/guides/source/creating_plugins/setup.txt | 22 +++++++++++++++++- .../doc/guides/source/creating_plugins/tests.txt | 6 ++--- 5 files changed, 28 insertions(+), 30 deletions(-) (limited to 'railties/doc/guides/source/creating_plugins') diff --git a/railties/doc/guides/source/creating_plugins/core_ext.txt b/railties/doc/guides/source/creating_plugins/core_ext.txt index ca8efc3df1..efef0e1f70 100644 --- a/railties/doc/guides/source/creating_plugins/core_ext.txt +++ b/railties/doc/guides/source/creating_plugins/core_ext.txt @@ -1,11 +1,6 @@ == Extending core classes == -This section will explain how to add a method to String that will be available anywhere in your rails app by: - - * Writing tests for the desired behavior - * Creating and requiring the correct files - -=== Creating the test === +This section will explain how to add a method to String that will be available anywhere in your rails app. In this example you will add a method to String named `to_squawk`. To begin, create a new test file with a few assertions: @@ -40,26 +35,6 @@ NoMethodError: undefined method `to_squawk' for "Hello World":String Great - now you are ready to start development. -=== Organize your files === - -A common pattern in rails plugins is to set up the file structure like this: - --------------------------------------------------------- -|-- lib -| |-- yaffle -| | `-- core_ext.rb -| `-- yaffle.rb --------------------------------------------------------- - -The first thing we need to to is to require our 'lib/yaffle.rb' file from 'rails/init.rb': - -*vendor/plugins/yaffle/rails/init.rb* - -[source, ruby] --------------------------------------------------------- -require 'yaffle' --------------------------------------------------------- - Then in 'lib/yaffle.rb' require 'lib/core_ext.rb': *vendor/plugins/yaffle/lib/yaffle.rb* diff --git a/railties/doc/guides/source/creating_plugins/generator_commands.txt b/railties/doc/guides/source/creating_plugins/generator_commands.txt index 5cce81c8bd..3ace3c7318 100644 --- a/railties/doc/guides/source/creating_plugins/generator_commands.txt +++ b/railties/doc/guides/source/creating_plugins/generator_commands.txt @@ -137,4 +137,5 @@ To see this work, type: ./script/destroy yaffle_route ----------------------------------------------------------- +.Editor's note: NOTE: If you haven't set up the custom route from above, 'script/destroy' will fail and you'll have to remove it manually. \ No newline at end of file diff --git a/railties/doc/guides/source/creating_plugins/migrations.txt b/railties/doc/guides/source/creating_plugins/migrations.txt index 4dd932734d..d158004ea3 100644 --- a/railties/doc/guides/source/creating_plugins/migrations.txt +++ b/railties/doc/guides/source/creating_plugins/migrations.txt @@ -89,6 +89,7 @@ class CreateBirdhouses < ActiveRecord::Migration end ---------------------------------------------- +.Editor's note: NOTE: several plugin frameworks such as Desert and Engines provide more advanced plugin functionality. === Generate migrations === @@ -146,6 +147,7 @@ class MigrationGeneratorTest < Test::Unit::TestCase end ------------------------------------------------------------------ +.Editor's note: NOTE: the migration generator checks to see if a migation already exists, and it's hard-coded to check the 'db/migrate' directory. As a result, if your test tries to generate a migration that already exists in the app, it will fail. The easy workaround is to make sure that the name you generate in your test is very unlikely to actually appear in the app. After running the test with 'rake' you can make it pass with: diff --git a/railties/doc/guides/source/creating_plugins/setup.txt b/railties/doc/guides/source/creating_plugins/setup.txt index fcf5b459e6..cd4b6ecb04 100644 --- a/railties/doc/guides/source/creating_plugins/setup.txt +++ b/railties/doc/guides/source/creating_plugins/setup.txt @@ -61,4 +61,24 @@ create vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb create vendor/plugins/yaffle/generators/yaffle/USAGE ---------------------------------------------- -To begin just change one thing - move 'init.rb' to 'rails/init.rb'. +=== Organize your files === + +To make it easy to organize your files and to make the plugin more compatible with GemPlugins, start out by altering your file system to look like this: + +-------------------------------------------------------- +|-- lib +| |-- yaffle +| `-- yaffle.rb +`-- rails + | + `-- init.rb +-------------------------------------------------------- + +*vendor/plugins/yaffle/rails/init.rb* + +[source, ruby] +-------------------------------------------------------- +require 'yaffle' +-------------------------------------------------------- + +Now you can add any 'require' statements to 'lib/yaffle.rb' and keep 'init.rb' clean. \ No newline at end of file diff --git a/railties/doc/guides/source/creating_plugins/tests.txt b/railties/doc/guides/source/creating_plugins/tests.txt index ef6dab2f9f..47611542cb 100644 --- a/railties/doc/guides/source/creating_plugins/tests.txt +++ b/railties/doc/guides/source/creating_plugins/tests.txt @@ -1,13 +1,13 @@ == Tests == -If your plugin interacts with a database, you'll need to setup a database connection. In this guide you will learn how to test your plugin against multiple different database adapters using Active Record. This guide 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: +In this guide you will learn how to test your plugin against multiple different database adapters using Active Record. To setup your plugin to allow for easy testing you'll need to add 3 files: * A 'database.yml' file with all of your connection strings * A 'schema.rb' file with your table definitions * A test helper method that sets up the database +=== Test Setup === + *vendor/plugins/yaffle/test/database.yml:* ---------------------------------------------- -- cgit v1.2.3 From 236142d23eb083d0a755d29d6365925ae5cc9f03 Mon Sep 17 00:00:00 2001 From: Jeff Dean Date: Mon, 17 Nov 2008 00:15:20 -0500 Subject: Rails plugin: misc error fixes. --- .../guides/source/creating_plugins/appendix.txt | 30 +++++++++++++++++++++- .../guides/source/creating_plugins/controllers.txt | 4 +++ .../guides/source/creating_plugins/core_ext.txt | 6 ++--- .../source/creating_plugins/generator_commands.txt | 29 +++++++++++---------- .../guides/source/creating_plugins/generators.txt | 18 +++++++------ .../doc/guides/source/creating_plugins/helpers.txt | 2 -- .../guides/source/creating_plugins/migrations.txt | 26 ++++++++++--------- .../doc/guides/source/creating_plugins/models.txt | 6 ++--- .../doc/guides/source/creating_plugins/routes.txt | 16 +++++------- .../doc/guides/source/creating_plugins/tasks.txt | 2 -- 10 files changed, 85 insertions(+), 54 deletions(-) (limited to 'railties/doc/guides/source/creating_plugins') diff --git a/railties/doc/guides/source/creating_plugins/appendix.txt b/railties/doc/guides/source/creating_plugins/appendix.txt index 19f677c5fd..5c3bd20a1b 100644 --- a/railties/doc/guides/source/creating_plugins/appendix.txt +++ b/railties/doc/guides/source/creating_plugins/appendix.txt @@ -10,6 +10,32 @@ If you prefer to use RSpec instead of tets, you may be interested in the http:// * http://daddy.platte.name/2007/05/rails-plugins-keep-initrb-thin.html * http://www.mbleigh.com/2008/6/11/gemplugins-a-brief-introduction-to-the-future-of-rails-plugins +=== Contents of 'lib/yaffle.rb' === + +*vendor/plugins/yaffle/lib/yaffle.rb:* + +[source, ruby] +---------------------------------------------- +require "yaffle/core_ext" +require "yaffle/acts_as_yaffle" +require "yaffle/commands" +require "yaffle/routing" + +%w{ models controllers helpers }.each do |dir| + path = File.join(File.dirname(__FILE__), 'app', dir) + $LOAD_PATH << path + ActiveSupport::Dependencies.load_paths << path + ActiveSupport::Dependencies.load_once_paths.delete(path) +end + +# optionally: +# Dir.glob(File.join(File.dirname(__FILE__), "db", "migrate", "*")).each do |file| +# require file +# end + +---------------------------------------------- + + === Final plugin directory structure === The final plugin should have a directory structure that looks something like this: @@ -47,7 +73,8 @@ The final plugin should have a directory structure that looks something like thi | |-- yaffle | | |-- acts_as_yaffle.rb | | |-- commands.rb -| | `-- core_ext.rb +| | |-- core_ext.rb +| | `-- routing.rb | `-- yaffle.rb |-- pkg | `-- yaffle-0.0.1.gem @@ -63,6 +90,7 @@ The final plugin should have a directory structure that looks something like thi | |-- definition_generator_test.rb | |-- migration_generator_test.rb | |-- route_generator_test.rb +| |-- routes_test.rb | |-- schema.rb | |-- test_helper.rb | |-- woodpecker_test.rb diff --git a/railties/doc/guides/source/creating_plugins/controllers.txt b/railties/doc/guides/source/creating_plugins/controllers.txt index e38cf8251e..7afdef032d 100644 --- a/railties/doc/guides/source/creating_plugins/controllers.txt +++ b/railties/doc/guides/source/creating_plugins/controllers.txt @@ -19,6 +19,10 @@ class WoodpeckersControllerTest < Test::Unit::TestCase @controller = WoodpeckersController.new @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new + + ActionController::Routing::Routes.draw do |map| + map.resources :woodpeckers + end end def test_index diff --git a/railties/doc/guides/source/creating_plugins/core_ext.txt b/railties/doc/guides/source/creating_plugins/core_ext.txt index efef0e1f70..cbedb9eaf2 100644 --- a/railties/doc/guides/source/creating_plugins/core_ext.txt +++ b/railties/doc/guides/source/creating_plugins/core_ext.txt @@ -67,13 +67,13 @@ $ ./script/console === Working with init.rb === -When rails loads plugins it looks for the file named init.rb. However, when the plugin is initialized, 'init.rb' is invoked via `eval` (not `require`) so it has slightly different behavior. +When rails loads plugins it looks for the file named 'init.rb' or 'rails/init.rb'. However, when the plugin is initialized, 'init.rb' is invoked via `eval` (not `require`) so it has slightly different behavior. Under certain circumstances if you reopen classes or modules in 'init.rb' you may inadvertently create a new class, rather than reopening an existing class. A better alternative is to reopen the class in a different file, and require that file from `init.rb`, as shown above. If you must reopen a class in `init.rb` you can use `module_eval` or `class_eval` to avoid any issues: -*vendor/plugins/yaffle/init.rb* +*vendor/plugins/yaffle/rails/init.rb* [source, ruby] --------------------------------------------------- @@ -86,7 +86,7 @@ end Another way is to explicitly define the top-level module space for all modules and classes, like `::Hash`: -*vendor/plugins/yaffle/init.rb* +*vendor/plugins/yaffle/rails/init.rb* [source, ruby] --------------------------------------------------- diff --git a/railties/doc/guides/source/creating_plugins/generator_commands.txt b/railties/doc/guides/source/creating_plugins/generator_commands.txt index 3ace3c7318..f60ea3d8f1 100644 --- a/railties/doc/guides/source/creating_plugins/generator_commands.txt +++ b/railties/doc/guides/source/creating_plugins/generator_commands.txt @@ -17,14 +17,6 @@ require 'rails_generator/scripts/destroy' class RouteGeneratorTest < Test::Unit::TestCase - def fake_rails_root - File.join(File.dirname(__FILE__), "rails_root") - end - - def routes_path - File.join(fake_rails_root, "config", "routes.rb") - end - def setup FileUtils.mkdir_p(File.join(fake_rails_root, "config")) end @@ -43,13 +35,13 @@ class RouteGeneratorTest < Test::Unit::TestCase File.open(routes_path, 'wb') {|f| f.write(content) } Rails::Generator::Scripts::Generate.new.run(["yaffle_route"], :destination => fake_rails_root) - assert_match /map\.yaffle/, File.read(routes_path) + assert_match /map\.yaffles/, File.read(routes_path) end def test_destroys_route content = <<-END ActionController::Routing::Routes.draw do |map| - map.yaffle + map.yaffles map.connect ':controller/:action/:id' map.connect ':controller/:action/:id.:format' end @@ -57,8 +49,19 @@ class RouteGeneratorTest < Test::Unit::TestCase File.open(routes_path, 'wb') {|f| f.write(content) } Rails::Generator::Scripts::Destroy.new.run(["yaffle_route"], :destination => fake_rails_root) - assert_no_match /map\.yaffle/, File.read(routes_path) + assert_no_match /map\.yaffles/, File.read(routes_path) end + + private + + def fake_rails_root + File.join(File.dirname(__FILE__), "rails_root") + end + + def routes_path + File.join(fake_rails_root, "config", "routes.rb") + end + end ----------------------------------------------------------- @@ -86,7 +89,7 @@ module Yaffle #:nodoc: logger.route "map.yaffle" look_for = 'ActionController::Routing::Routes.draw do |map|' unless options[:pretend] - gsub_file('config/routes.rb', /(#{Regexp.escape(look_for)})/mi){|match| "#{match}\n map.yaffle\n"} + gsub_file('config/routes.rb', /(#{Regexp.escape(look_for)})/mi){|match| "#{match}\n map.yaffles\n"} end end end @@ -94,7 +97,7 @@ module Yaffle #:nodoc: module Destroy def yaffle_route logger.route "map.yaffle" - gsub_file 'config/routes.rb', /\n.+?map\.yaffle/mi, '' + gsub_file 'config/routes.rb', /\n.+?map\.yaffles/mi, '' end end diff --git a/railties/doc/guides/source/creating_plugins/generators.txt b/railties/doc/guides/source/creating_plugins/generators.txt index eb0fbb5ee9..8ef46561d1 100644 --- a/railties/doc/guides/source/creating_plugins/generators.txt +++ b/railties/doc/guides/source/creating_plugins/generators.txt @@ -32,14 +32,6 @@ require 'rails_generator/scripts/generate' class DefinitionGeneratorTest < Test::Unit::TestCase - def fake_rails_root - File.join(File.dirname(__FILE__), 'rails_root') - end - - def file_list - Dir.glob(File.join(fake_rails_root, "*")) - end - def setup FileUtils.mkdir_p(fake_rails_root) @original_files = file_list @@ -54,6 +46,16 @@ class DefinitionGeneratorTest < Test::Unit::TestCase new_file = (file_list - @original_files).first assert_equal "definition.txt", File.basename(new_file) end + + private + + def fake_rails_root + File.join(File.dirname(__FILE__), 'rails_root') + end + + def file_list + Dir.glob(File.join(fake_rails_root, "*")) + end end ------------------------------------------------------------------ diff --git a/railties/doc/guides/source/creating_plugins/helpers.txt b/railties/doc/guides/source/creating_plugins/helpers.txt index c2273813dd..fa4227be41 100644 --- a/railties/doc/guides/source/creating_plugins/helpers.txt +++ b/railties/doc/guides/source/creating_plugins/helpers.txt @@ -30,8 +30,6 @@ This is just a simple test to make sure the helper is being loaded correctly. A ActiveSupport::Dependencies.load_paths << path ActiveSupport::Dependencies.load_once_paths.delete(path) end - -ActionView::Base.send :include, WoodpeckersHelper ---------------------------------------------- diff --git a/railties/doc/guides/source/creating_plugins/migrations.txt b/railties/doc/guides/source/creating_plugins/migrations.txt index d158004ea3..e7d2e09069 100644 --- a/railties/doc/guides/source/creating_plugins/migrations.txt +++ b/railties/doc/guides/source/creating_plugins/migrations.txt @@ -108,29 +108,21 @@ This example will demonstrate how to use one of the built-in generator methods n require File.dirname(__FILE__) + '/test_helper.rb' require 'rails_generator' require 'rails_generator/scripts/generate' -require 'rails_generator/scripts/destroy' class MigrationGeneratorTest < Test::Unit::TestCase - def fake_rails_root - File.join(File.dirname(__FILE__), 'rails_root') - end - - def file_list - Dir.glob(File.join(fake_rails_root, "db", "migrate", "*")) - end - def setup FileUtils.mkdir_p(fake_rails_root) @original_files = file_list end def teardown + ActiveRecord::Base.pluralize_table_names = true FileUtils.rm_r(fake_rails_root) end def test_generates_correct_file_name - Rails::Generator::Scripts::Generate.new.run(["yaffle", "some_name_nobody_is_likely_to_ever_use_in_a_real_migration"], :destination => fake_rails_root) + Rails::Generator::Scripts::Generate.new.run(["yaffle_migration", "some_name_nobody_is_likely_to_ever_use_in_a_real_migration"], :destination => fake_rails_root) new_file = (file_list - @original_files).first assert_match /add_yaffle_fields_to_some_name_nobody_is_likely_to_ever_use_in_a_real_migrations/, new_file assert_match /add_column :some_name_nobody_is_likely_to_ever_use_in_a_real_migrations do |t|/, File.read(new_file) @@ -138,12 +130,21 @@ class MigrationGeneratorTest < Test::Unit::TestCase def test_pluralizes_properly ActiveRecord::Base.pluralize_table_names = false - Rails::Generator::Scripts::Generate.new.run(["yaffle", "some_name_nobody_is_likely_to_ever_use_in_a_real_migration"], :destination => fake_rails_root) + Rails::Generator::Scripts::Generate.new.run(["yaffle_migration", "some_name_nobody_is_likely_to_ever_use_in_a_real_migration"], :destination => fake_rails_root) new_file = (file_list - @original_files).first assert_match /add_yaffle_fields_to_some_name_nobody_is_likely_to_ever_use_in_a_real_migration/, new_file assert_match /add_column :some_name_nobody_is_likely_to_ever_use_in_a_real_migration do |t|/, File.read(new_file) end + + private + def fake_rails_root + File.join(File.dirname(__FILE__), 'rails_root') + end + def file_list + Dir.glob(File.join(fake_rails_root, "db", "migrate", "*")) + end + end ------------------------------------------------------------------ @@ -156,7 +157,7 @@ After running the test with 'rake' you can make it pass with: [source, ruby] ------------------------------------------------------------------ -class YaffleGenerator < Rails::Generator::NamedBase +class YaffleMigrationGenerator < Rails::Generator::NamedBase def manifest record do |m| m.migration_template 'migration:migration.rb', "db/migrate", {:assigns => yaffle_local_assigns, @@ -169,6 +170,7 @@ class YaffleGenerator < Rails::Generator::NamedBase def custom_file_name custom_name = class_name.underscore.downcase custom_name = custom_name.pluralize if ActiveRecord::Base.pluralize_table_names + custom_name end def yaffle_local_assigns diff --git a/railties/doc/guides/source/creating_plugins/models.txt b/railties/doc/guides/source/creating_plugins/models.txt index dfe11f9c4e..8b66de0f99 100644 --- a/railties/doc/guides/source/creating_plugins/models.txt +++ b/railties/doc/guides/source/creating_plugins/models.txt @@ -66,10 +66,8 @@ Finally, add the following to your plugin's 'schema.rb': [source, ruby] ---------------------------------------------- -ActiveRecord::Schema.define(:version => 0) do - create_table :woodpeckers, :force => true do |t| - t.string :name - end +create_table :woodpeckers, :force => true do |t| + t.string :name end ---------------------------------------------- diff --git a/railties/doc/guides/source/creating_plugins/routes.txt b/railties/doc/guides/source/creating_plugins/routes.txt index cdc20e998e..249176729c 100644 --- a/railties/doc/guides/source/creating_plugins/routes.txt +++ b/railties/doc/guides/source/creating_plugins/routes.txt @@ -22,10 +22,6 @@ class RoutingTest < Test::Unit::TestCase 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 @@ -33,15 +29,16 @@ class RoutingTest < Test::Unit::TestCase end -------------------------------------------------------- -*vendor/plugins/yaffle/init.rb* +Once you see the tests fail by running 'rake', you can make them pass with: + +*vendor/plugins/yaffle/lib/yaffle.rb* [source, ruby] -------------------------------------------------------- -require "routing" -ActionController::Routing::RouteSet::Mapper.send :include, Yaffle::Routing::MapperExtensions +require "yaffle/routing" -------------------------------------------------------- -*vendor/plugins/yaffle/lib/routing.rb* +*vendor/plugins/yaffle/lib/yaffle/routing.rb* [source, ruby] -------------------------------------------------------- @@ -54,6 +51,8 @@ module Yaffle #:nodoc: end end end + +ActionController::Routing::RouteSet::Mapper.send :include, Yaffle::Routing::MapperExtensions -------------------------------------------------------- *config/routes.rb* @@ -61,7 +60,6 @@ end [source, ruby] -------------------------------------------------------- ActionController::Routing::Routes.draw do |map| - ... map.yaffles end -------------------------------------------------------- diff --git a/railties/doc/guides/source/creating_plugins/tasks.txt b/railties/doc/guides/source/creating_plugins/tasks.txt index c71ba42bb0..d848c2cfa1 100644 --- a/railties/doc/guides/source/creating_plugins/tasks.txt +++ b/railties/doc/guides/source/creating_plugins/tasks.txt @@ -19,9 +19,7 @@ end When you run `rake -T` from your plugin you will see: --------------------------------------------------------- -... yaffle:squawk # Prints out the word 'Yaffle' -... --------------------------------------------------------- You can add as many files as you want in the tasks directory, and if they end in .rake Rails will pick them up. -- cgit v1.2.3 From 3fbd9acc5c6418cffe8b2676f9e9e69ee1a84847 Mon Sep 17 00:00:00 2001 From: Jeff Dean Date: Mon, 17 Nov 2008 00:45:20 -0500 Subject: Plugin guide: Edits --- railties/doc/guides/source/creating_plugins/appendix.txt | 3 ++- railties/doc/guides/source/creating_plugins/generators.txt | 9 +-------- railties/doc/guides/source/creating_plugins/routes.txt | 4 +++- 3 files changed, 6 insertions(+), 10 deletions(-) (limited to 'railties/doc/guides/source/creating_plugins') diff --git a/railties/doc/guides/source/creating_plugins/appendix.txt b/railties/doc/guides/source/creating_plugins/appendix.txt index 5c3bd20a1b..340c03dd4e 100644 --- a/railties/doc/guides/source/creating_plugins/appendix.txt +++ b/railties/doc/guides/source/creating_plugins/appendix.txt @@ -1,6 +1,6 @@ == Appendix == -If you prefer to use RSpec instead of tets, you may be interested in the http://github.com/pat-maddox/rspec-plugin-generator/tree/master[RSpec Plugin Generator]. +If you prefer to use RSpec instead of Test::Unit, you may be interested in the http://github.com/pat-maddox/rspec-plugin-generator/tree/master[RSpec Plugin Generator]. === References === @@ -9,6 +9,7 @@ If you prefer to use RSpec instead of tets, you may be interested in the http:// * http://github.com/technoweenie/attachment_fu/tree/master * http://daddy.platte.name/2007/05/rails-plugins-keep-initrb-thin.html * http://www.mbleigh.com/2008/6/11/gemplugins-a-brief-introduction-to-the-future-of-rails-plugins + * http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2. === Contents of 'lib/yaffle.rb' === diff --git a/railties/doc/guides/source/creating_plugins/generators.txt b/railties/doc/guides/source/creating_plugins/generators.txt index 8ef46561d1..f856bec7a2 100644 --- a/railties/doc/guides/source/creating_plugins/generators.txt +++ b/railties/doc/guides/source/creating_plugins/generators.txt @@ -2,14 +2,7 @@ Many plugins ship with generators. When you created the plugin above, you specified the --with-generator option, so you already have the generator stubs in 'vendor/plugins/yaffle/generators/yaffle'. -Building generators is a complex topic unto itself and this section will cover one small aspect of generators: creating a generator that adds a time-stamped migration. - -To add a generator to a plugin: - - * Write a test - * Add your instructions to the 'manifest' method of the generator - * Add any necessary template files to the templates directory - * Update the USAGE file to add helpful documentation for your generator +Building generators is a complex topic unto itself and this section will cover one small aspect of generators: generating a simple text file. === Testing generators === diff --git a/railties/doc/guides/source/creating_plugins/routes.txt b/railties/doc/guides/source/creating_plugins/routes.txt index 249176729c..dc1bf09fd1 100644 --- a/railties/doc/guides/source/creating_plugins/routes.txt +++ b/railties/doc/guides/source/creating_plugins/routes.txt @@ -1,6 +1,8 @@ == Routes == -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. +In a standard 'routes.rb' file you use routes like 'map.connect' or 'map.resources'. You can add your own custom routes from a plugin. This section will describe how to add a custom method called that can be called with 'map.yaffles'. + +Testing routes from plugins is slightly different from testing routes in a standard rails app. To begin, add a test like this: *vendor/plugins/yaffle/test/routing_test.rb* -- cgit v1.2.3