2. 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.
