aboutsummaryrefslogtreecommitdiffstats
path: root/railties
diff options
context:
space:
mode:
authorJeff Dean <jeff@zilkey.com>2008-11-13 23:29:46 -0500
committerJeff Dean <jeff@zilkey.com>2008-11-13 23:29:46 -0500
commit4146efc380255319768031f26e63210fd4158e99 (patch)
tree019caeba5967dbfb02b65cd67e180028134e5462 /railties
parent41d0dbcb8661a866ddf4b3534b8b1efd724ecba1 (diff)
downloadrails-4146efc380255319768031f26e63210fd4158e99.tar.gz
rails-4146efc380255319768031f26e63210fd4158e99.tar.bz2
rails-4146efc380255319768031f26e63210fd4158e99.zip
Plugin guide: update generator guide to include tests
Diffstat (limited to 'railties')
-rw-r--r--railties/doc/guides/html/creating_plugins.html231
-rw-r--r--railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt4
-rw-r--r--railties/doc/guides/source/creating_plugins/basics.markdown861
-rw-r--r--railties/doc/guides/source/creating_plugins/migration_generator.txt120
-rw-r--r--railties/doc/guides/source/creating_plugins/test_setup.txt58
-rw-r--r--railties/lib/rails_generator/commands.rb2
6 files changed, 291 insertions, 985 deletions
diff --git a/railties/doc/guides/html/creating_plugins.html b/railties/doc/guides/html/creating_plugins.html
index 793cd2b7a7..5589971ec5 100644
--- a/railties/doc/guides/html/creating_plugins.html
+++ b/railties/doc/guides/html/creating_plugins.html
@@ -239,6 +239,17 @@ ul#navMain {
</li>
<li>
<a href="#_create_a_migration_generator">Create a migration generator</a>
+ <ul>
+
+ <li><a href="#_testing_generators">Testing generators</a></li>
+
+ <li><a href="#_adding_to_the_manifest">Adding to the manifest</a></li>
+
+ <li><a href="#_manually_test_the_generator">Manually test the generator</a></li>
+
+ <li><a href="#_the_usage_file">The USAGE file</a></li>
+
+ </ul>
</li>
<li>
<a href="#_add_a_custom_generator_command">Add a custom generator command</a>
@@ -433,22 +444,22 @@ create vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb
create vendor/plugins/yaffle/generators/yaffle/USAGE</tt></pre>
</div></div>
<h3 id="_setup_the_plugin_for_testing">1.3. Setup the plugin for testing</h3>
-<div class="para"><p>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.</p></div>
+<div class="para"><p>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.</p></div>
<div class="para"><p>To setup your plugin to allow for easy testing you'll need to add 3 files:</p></div>
<div class="ilist"><ul>
<li>
<p>
-A <em>database.yml</em> file with all of your connection strings.
+A <em>database.yml</em> file with all of your connection strings
</p>
</li>
<li>
<p>
-A <em>schema.rb</em> file with your table definitions.
+A <em>schema.rb</em> file with your table definitions
</p>
</li>
<li>
<p>
-A test helper that sets up the database before your tests.
+A test helper method that sets up the database
</p>
</li>
</ul></div>
@@ -457,11 +468,11 @@ A test helper that sets up the database before your tests.
<div class="content">
<pre><tt>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
@@ -473,8 +484,8 @@ postgresql:
mysql:
:adapter: mysql
:host: localhost
- :username: rails
- :password:
+ :username: root
+ :password: password
:database: yaffle_plugin_test</tt></pre>
</div></div>
<div class="para"><p>For this guide you'll need 2 tables/models, Hickwalls and Wickwalls, so add the following:</p></div>
@@ -509,34 +520,38 @@ ENV<span style="color: #990000">[</span><span style="color: #FF0000">'RAILS_ROOT
<span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'test/unit'</span>
<span style="font-weight: bold"><span style="color: #000080">require</span></span> File<span style="color: #990000">.</span>expand_path<span style="color: #990000">(</span>File<span style="color: #990000">.</span>join<span style="color: #990000">(</span>ENV<span style="color: #990000">[</span><span style="color: #FF0000">'RAILS_ROOT'</span><span style="color: #990000">],</span> <span style="color: #FF0000">'config/environment.rb'</span><span style="color: #990000">))</span>
-config <span style="color: #990000">=</span> YAML<span style="color: #990000">::</span><span style="font-weight: bold"><span style="color: #0000FF">load</span></span><span style="color: #990000">(</span>IO<span style="color: #990000">.</span>read<span style="color: #990000">(</span>File<span style="color: #990000">.</span>dirname<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">__FILE__</span></span><span style="color: #990000">)</span> <span style="color: #990000">+</span> <span style="color: #FF0000">'/database.yml'</span><span style="color: #990000">))</span>
-ActiveRecord<span style="color: #990000">::</span>Base<span style="color: #990000">.</span>logger <span style="color: #990000">=</span> Logger<span style="color: #990000">.</span>new<span style="color: #990000">(</span>File<span style="color: #990000">.</span>dirname<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">__FILE__</span></span><span style="color: #990000">)</span> <span style="color: #990000">+</span> <span style="color: #FF0000">"/debug.log"</span><span style="color: #990000">)</span>
+<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> load_schema
+ config <span style="color: #990000">=</span> YAML<span style="color: #990000">::</span><span style="font-weight: bold"><span style="color: #0000FF">load</span></span><span style="color: #990000">(</span>IO<span style="color: #990000">.</span>read<span style="color: #990000">(</span>File<span style="color: #990000">.</span>dirname<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">__FILE__</span></span><span style="color: #990000">)</span> <span style="color: #990000">+</span> <span style="color: #FF0000">'/database.yml'</span><span style="color: #990000">))</span>
+ ActiveRecord<span style="color: #990000">::</span>Base<span style="color: #990000">.</span>logger <span style="color: #990000">=</span> Logger<span style="color: #990000">.</span>new<span style="color: #990000">(</span>File<span style="color: #990000">.</span>dirname<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">__FILE__</span></span><span style="color: #990000">)</span> <span style="color: #990000">+</span> <span style="color: #FF0000">"/debug.log"</span><span style="color: #990000">)</span>
-db_adapter <span style="color: #990000">=</span> ENV<span style="color: #990000">[</span><span style="color: #FF0000">'DB'</span><span style="color: #990000">]</span>
+ db_adapter <span style="color: #990000">=</span> ENV<span style="color: #990000">[</span><span style="color: #FF0000">'DB'</span><span style="color: #990000">]</span>
-db_adapter <span style="color: #990000">||=</span>
- <span style="font-weight: bold"><span style="color: #0000FF">begin</span></span>
- <span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'rubygems'</span>
- <span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'sqlite'</span>
- <span style="color: #FF0000">'sqlite'</span>
- <span style="font-weight: bold"><span style="color: #0000FF">rescue</span></span> MissingSourceFile
+ <span style="font-style: italic"><span style="color: #9A1900"># no db passed, try one of these fine config-free DBs before bombing.</span></span>
+ db_adapter <span style="color: #990000">||=</span>
<span style="font-weight: bold"><span style="color: #0000FF">begin</span></span>
- <span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'sqlite3'</span>
- <span style="color: #FF0000">'sqlite3'</span>
+ <span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'rubygems'</span>
+ <span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'sqlite'</span>
+ <span style="color: #FF0000">'sqlite'</span>
<span style="font-weight: bold"><span style="color: #0000FF">rescue</span></span> MissingSourceFile
+ <span style="font-weight: bold"><span style="color: #0000FF">begin</span></span>
+ <span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'sqlite3'</span>
+ <span style="color: #FF0000">'sqlite3'</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">rescue</span></span> MissingSourceFile
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-<span style="font-weight: bold"><span style="color: #0000FF">if</span></span> db_adapter<span style="color: #990000">.</span><span style="font-weight: bold"><span style="color: #0000FF">nil</span></span><span style="color: #990000">?</span>
- <span style="font-weight: bold"><span style="color: #0000FF">raise</span></span> <span style="color: #FF0000">"No DB Adapter selected. Pass the DB= option to pick one, or install Sqlite or Sqlite3."</span>
-<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+ <span style="font-weight: bold"><span style="color: #0000FF">if</span></span> db_adapter<span style="color: #990000">.</span><span style="font-weight: bold"><span style="color: #0000FF">nil</span></span><span style="color: #990000">?</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">raise</span></span> <span style="color: #FF0000">"No DB Adapter selected. Pass the DB= option to pick one, or install Sqlite or Sqlite3."</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-ActiveRecord<span style="color: #990000">::</span>Base<span style="color: #990000">.</span>establish_connection<span style="color: #990000">(</span>config<span style="color: #990000">[</span>db_adapter<span style="color: #990000">])</span>
+ ActiveRecord<span style="color: #990000">::</span>Base<span style="color: #990000">.</span>establish_connection<span style="color: #990000">(</span>config<span style="color: #990000">[</span>db_adapter<span style="color: #990000">])</span>
-<span style="font-weight: bold"><span style="color: #0000FF">load</span></span><span style="color: #990000">(</span>File<span style="color: #990000">.</span>dirname<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">__FILE__</span></span><span style="color: #990000">)</span> <span style="color: #990000">+</span> <span style="color: #FF0000">"/schema.rb"</span><span style="color: #990000">)</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">load</span></span><span style="color: #990000">(</span>File<span style="color: #990000">.</span>dirname<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">__FILE__</span></span><span style="color: #990000">)</span> <span style="color: #990000">+</span> <span style="color: #FF0000">"/schema.rb"</span><span style="color: #990000">)</span>
-<span style="font-weight: bold"><span style="color: #000080">require</span></span> File<span style="color: #990000">.</span>dirname<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">__FILE__</span></span><span style="color: #990000">)</span> <span style="color: #990000">+</span> <span style="color: #FF0000">'/../init.rb'</span>
+ <span style="font-weight: bold"><span style="color: #000080">require</span></span> File<span style="color: #990000">.</span>dirname<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">__FILE__</span></span><span style="color: #990000">)</span> <span style="color: #990000">+</span> <span style="color: #FF0000">'/../init.rb'</span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
+<div class="para"><p>Now whenever you write a test that requires the database, you can call <em>load_schema</em>.</p></div>
<h3 id="_run_the_plugin_tests">1.4. Run the plugin tests</h3>
<div class="para"><p>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 <em>vendor/plugins/yaffle/test/yaffle_test.rb</em> with a sample test. Replace the contents of that file with:</p></div>
<div class="para"><p><strong>vendor/plugins/yaffle/test/yaffle_test.rb:</strong></p></div>
@@ -548,6 +563,7 @@ http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #000080">require</span></span> File<span style="color: #990000">.</span>dirname<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">__FILE__</span></span><span style="color: #990000">)</span> <span style="color: #990000">+</span> <span style="color: #FF0000">'/test_helper.rb'</span>
<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> YaffleTest <span style="color: #990000">&lt;</span> Test<span style="color: #990000">::</span>Unit<span style="color: #990000">::</span>TestCase
+ load_schema
<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Hickwall <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
@@ -800,6 +816,8 @@ http://www.gnu.org/software/src-highlite -->
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ActsAsYaffleTest <span style="color: #990000">&lt;</span> Test<span style="color: #990000">::</span>Unit<span style="color: #990000">::</span>TestCase
+ load_schema
+
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_a_hickwalls_yaffle_text_field_should_be_last_squawk
assert_equal <span style="color: #FF0000">"last_squawk"</span><span style="color: #990000">,</span> Hickwall<span style="color: #990000">.</span>yaffle_text_field
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
@@ -851,6 +869,8 @@ http://www.gnu.org/software/src-highlite -->
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ActsAsYaffleTest <span style="color: #990000">&lt;</span> Test<span style="color: #990000">::</span>Unit<span style="color: #990000">::</span>TestCase
+ load_schema
+
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_a_hickwalls_yaffle_text_field_should_be_last_squawk
assert_equal <span style="color: #FF0000">"last_squawk"</span><span style="color: #990000">,</span> Hickwall<span style="color: #990000">.</span>yaffle_text_field
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
@@ -987,31 +1007,92 @@ http://www.gnu.org/software/src-highlite -->
</div>
<h2 id="_create_a_migration_generator">5. Create a migration generator</h2>
<div class="sectionbody">
-<div class="para"><p>When you created the plugin above, you specified the &#8212;with-generator option, so you already have the generator stubs in your plugin.</p></div>
-<div class="para"><p>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.</p></div>
-<div class="para"><p>Type:</p></div>
-<div class="listingblock">
-<div class="content">
-<pre><tt>script/generate</tt></pre>
-</div></div>
-<div class="para"><p>You should see the line:</p></div>
-<div class="listingblock">
-<div class="content">
-<pre><tt>Plugins (vendor/plugins): yaffle</tt></pre>
-</div></div>
-<div class="para"><p>When you run <tt>script/generate yaffle</tt> you should see the contents of your USAGE file. For this plugin, the USAGE file looks like this:</p></div>
+<div class="para"><p>Many plugins ship with generators. When you created the plugin above, you specified the &#8212;with-generator option, so you already have the generator stubs in <em>vendor/plugins/yaffle/generators/yaffle</em>.</p></div>
+<div class="para"><p>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.</p></div>
+<div class="para"><p>To create a generator you must:</p></div>
+<div class="ilist"><ul>
+<li>
+<p>
+Add your instructions to the <em>manifest</em> method of the generator
+</p>
+</li>
+<li>
+<p>
+Add any necessary template files to the templates directory
+</p>
+</li>
+<li>
+<p>
+Test the generator manually by running various combinations of <tt>script/generate</tt> and <tt>script/destroy</tt>
+</p>
+</li>
+<li>
+<p>
+Update the USAGE file to add helpful documentation for your generator
+</p>
+</li>
+</ul></div>
+<h3 id="_testing_generators">5.1. Testing generators</h3>
+<div class="para"><p>Many rails plugin authors do not test their generators, however testing generators is quite simple. A typical generator test does the following:</p></div>
+<div class="ilist"><ul>
+<li>
+<p>
+Creates a new fake rails root directory that will serve as destination
+</p>
+</li>
+<li>
+<p>
+Runs the generator forward and backward, making whatever assertions are necessary
+</p>
+</li>
+<li>
+<p>
+Removes the fake rails root
+</p>
+</li>
+</ul></div>
+<div class="para"><p>For the generator in this section, the test could look something like this:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/test/yaffle_generator_test.rb</strong></p></div>
<div class="listingblock">
-<div class="content">
-<pre><tt>Description:
- Creates a migration that adds yaffle squawk fields to the given model
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="font-weight: bold"><span style="color: #000080">require</span></span> File<span style="color: #990000">.</span>dirname<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">__FILE__</span></span><span style="color: #990000">)</span> <span style="color: #990000">+</span> <span style="color: #FF0000">'/test_helper.rb'</span>
+<span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'rails_generator'</span>
+<span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'rails_generator/scripts/generate'</span>
+<span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'rails_generator/scripts/destroy'</span>
-Example:
- ./script/generate yaffle hickwall
+<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> YaffleTest <span style="color: #990000">&lt;</span> Test<span style="color: #990000">::</span>Unit<span style="color: #990000">::</span>TestCase
- This will create:
- db/migrate/TIMESTAMP_add_yaffle_fields_to_hickwall</tt></pre>
-</div></div>
-<div class="para"><p>Now you can add code to your generator:</p></div>
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> fake_rails_root
+ File<span style="color: #990000">.</span>join<span style="color: #990000">(</span>File<span style="color: #990000">.</span>dirname<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">__FILE__</span></span><span style="color: #990000">),</span> <span style="color: #FF0000">'rails_root'</span><span style="color: #990000">)</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> file_list
+ Dir<span style="color: #990000">.</span>glob<span style="color: #990000">(</span>File<span style="color: #990000">.</span>join<span style="color: #990000">(</span>fake_rails_root<span style="color: #990000">,</span> <span style="color: #FF0000">"db"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"migrate"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"*"</span><span style="color: #990000">))</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> setup
+ FileUtils<span style="color: #990000">.</span>mkdir_p<span style="color: #990000">(</span>fake_rails_root<span style="color: #990000">)</span>
+ <span style="color: #009900">@original_files</span> <span style="color: #990000">=</span> file_list
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> teardown
+ FileUtils<span style="color: #990000">.</span>rm_r<span style="color: #990000">(</span>fake_rails_root<span style="color: #990000">)</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_generates_correct_file_name
+ Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Scripts<span style="color: #990000">::</span>Generate<span style="color: #990000">.</span>new<span style="color: #990000">.</span>run<span style="color: #990000">([</span><span style="color: #FF0000">"yaffle"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"bird"</span><span style="color: #990000">],</span> <span style="color: #990000">:</span>destination <span style="color: #990000">=&gt;</span> fake_rails_root<span style="color: #990000">)</span>
+ new_file <span style="color: #990000">=</span> <span style="color: #990000">(</span>file_list <span style="color: #990000">-</span> <span style="color: #009900">@original_files</span><span style="color: #990000">).</span>first
+ assert_match <span style="color: #FF6600">/add_yaffle_fields_to_bird/</span><span style="color: #990000">,</span> new_file
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>You can run <em>rake</em> 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.</p></div>
+<h3 id="_adding_to_the_manifest">5.2. Adding to the manifest</h3>
+<div class="para"><p>This example will demonstrate how to use one of the built-in generator methods named <em>migration_template</em> to create a migration file. To start, update your generator file to look like this:</p></div>
<div class="para"><p><strong>vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb</strong></p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -1023,7 +1104,7 @@ http://www.gnu.org/software/src-highlite -->
record <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>m<span style="color: #990000">|</span>
m<span style="color: #990000">.</span>migration_template <span style="color: #FF0000">'migration:migration.rb'</span><span style="color: #990000">,</span> <span style="color: #FF0000">"db/migrate"</span><span style="color: #990000">,</span> <span style="color: #FF0000">{</span><span style="color: #990000">:</span>assigns <span style="color: #990000">=&gt;</span> yaffle_local_assigns<span style="color: #990000">,</span>
<span style="color: #990000">:</span>migration_file_name <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"add_yaffle_fields_to_#{custom_file_name}"</span>
- <span style="color: #FF0000">}</span>
+ <span style="color: #FF0000">}</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
@@ -1039,31 +1120,19 @@ http://www.gnu.org/software/src-highlite -->
assigns<span style="color: #990000">[:</span>class_name<span style="color: #990000">]</span> <span style="color: #990000">=</span> <span style="color: #FF0000">"add_yaffle_fields_to_#{custom_file_name}"</span>
assigns<span style="color: #990000">[:</span>table_name<span style="color: #990000">]</span> <span style="color: #990000">=</span> custom_file_name
assigns<span style="color: #990000">[:</span>attributes<span style="color: #990000">]</span> <span style="color: #990000">=</span> <span style="color: #990000">[</span>Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>GeneratedAttribute<span style="color: #990000">.</span>new<span style="color: #990000">(</span><span style="color: #FF0000">"last_squawk"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"string"</span><span style="color: #990000">)]</span>
- assigns<span style="color: #990000">[:</span>attributes<span style="color: #990000">]</span> <span style="color: #990000">&lt;&lt;</span> Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>GeneratedAttribute<span style="color: #990000">.</span>new<span style="color: #990000">(</span><span style="color: #FF0000">"last_squawked_at"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"datetime"</span><span style="color: #990000">)</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<div class="para"><p>Note that you need to be aware of whether or not table names are pluralized.</p></div>
-<div class="para"><p>This does a few things:</p></div>
-<div class="ilist"><ul>
-<li>
-<p>
-Reuses the built in rails <tt>migration_template</tt> method.
-</p>
-</li>
-<li>
-<p>
-Reuses the built-in rails migration template.
-</p>
-</li>
-</ul></div>
-<div class="para"><p>When you run the generator like</p></div>
+<div class="para"><p>The generator creates a new file in <em>db/migrate</em> with a timestamp and an <em>add_column</em> statement. It reuses the built in rails <tt>migration_template</tt> method, and reuses the built-in rails migration template.</p></div>
+<div class="para"><p>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.</p></div>
+<h3 id="_manually_test_the_generator">5.3. Manually test the generator</h3>
+<div class="para"><p>To run the generator, type the following at the command line:</p></div>
<div class="listingblock">
<div class="content">
-<pre><tt>script/generate yaffle bird</tt></pre>
+<pre><tt>./script/generate yaffle bird</tt></pre>
</div></div>
-<div class="para"><p>You will see a new file:</p></div>
+<div class="para"><p>and you will see a new file:</p></div>
<div class="para"><p><strong>db/migrate/20080529225649_add_yaffle_fields_to_birds.rb</strong></p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -1073,15 +1142,39 @@ http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> AddYaffleFieldsToBirds <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Migration
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>up
add_column <span style="color: #990000">:</span>birds<span style="color: #990000">,</span> <span style="color: #990000">:</span>last_squawk<span style="color: #990000">,</span> <span style="color: #990000">:</span>string
- add_column <span style="color: #990000">:</span>birds<span style="color: #990000">,</span> <span style="color: #990000">:</span>last_squawked_at<span style="color: #990000">,</span> <span style="color: #990000">:</span>datetime
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>down
- remove_column <span style="color: #990000">:</span>birds<span style="color: #990000">,</span> <span style="color: #990000">:</span>last_squawked_at
remove_column <span style="color: #990000">:</span>birds<span style="color: #990000">,</span> <span style="color: #990000">:</span>last_squawk
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
+<h3 id="_the_usage_file">5.4. The USAGE file</h3>
+<div class="para"><p>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:</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>script/generate</tt></pre>
+</div></div>
+<div class="para"><p>You should see something like this:</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>Installed Generators
+ Plugins (vendor/plugins): yaffle
+ Builtin: controller, integration_test, mailer, migration, model, observer, plugin, resource, scaffold, session_migration</tt></pre>
+</div></div>
+<div class="para"><p>When you run <tt>script/generate yaffle</tt> you should see the contents of your <em>vendor/plugins/yaffle/generators/yaffle/USAGE</em> file.</p></div>
+<div class="para"><p>For this plugin, update the USAGE file looks like this:</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>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</tt></pre>
+</div></div>
</div>
<h2 id="_add_a_custom_generator_command">6. Add a custom generator command</h2>
<div class="sectionbody">
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
diff --git a/railties/lib/rails_generator/commands.rb b/railties/lib/rails_generator/commands.rb
index 6b9a636847..120d428f35 100644
--- a/railties/lib/rails_generator/commands.rb
+++ b/railties/lib/rails_generator/commands.rb
@@ -73,6 +73,8 @@ module Rails
end
def existing_migrations(file_name)
+ puts "#{__FILE__}:#{__LINE__}"
+ puts @migration_directory
Dir.glob("#{@migration_directory}/[0-9]*_*.rb").grep(/[0-9]+_#{file_name}.rb$/)
end