The explicit Ruby metaclass you know you always wanted
When you define a “static” or “class” method on a Ruby class, it actually stores the method on that class’s metaclass/singleton class/eigenclass.
_why’s metaid gem gives you a metaclass method to explicit access this object:
require 'metaid'
class Person
def self.oldest
# find oldest person
end
end
Person.methods.grep(/oldest/) # => ['oldest']
Person.metaclass.instance_methods.grep(/oldest/) # => ['oldest']
So now here’s a new, fun way to access the metaclass of a class, look for a constant suffixed with ‘Metaclass’. For the Person class, look for PersonMetaclass. Yep, we can have explicit metaclass constants. Or try PersonClass or PersonEigen or PersonEigenclass. No one can agree on what they are called, so I made them all work.
$ gem install magic_metaclass $ irb
In irb try:
require 'rubygems' require 'magic_metaclass' class Person; end Person # => Person PersonMetaclass # => #<Class:Person> PersonClass # => #<Class:Person> PersonEigenclass # => #<Class:Person> PersonEigen # => #<Class:Person>
Neat.
Finally, the example from above:
class Person
def self.oldest
# find oldest person
end
end
PersonMetaclass.instance_methods.grep(/oldest/) # => ['oldest']
I wrote this gem with no known use cases. If you find any, let me know.
Rails 2.0 TextMate bundle - Tasty Tidbit - respond_to and view navigation
The new release of the Rails TextMate bundle is coming soon. Its guaranteed to be shiny, sparkly and will fit in with any home or office decor. More importantly, it will be upgraded for Rails 2.0.
Today is the first Tasty Tidbit - a demonstration of one of the snazzy new features coming to your Macintosh soon.
In this Tasty Tidbit, we look at respond_to and the ability to create and navigate to view templates based on the selected format block, such as wants.js -> .js.rjs.
Cannot see the embedded video? Want the Hi-Def version? Download the video (5 Mb).
Contribute to the Bundle
To clone the git repository and start sharing your own personal goodness, see previous article.
One-stop JavaScript Unit Testing for Rails 2.0
Previously, I mentioned a multi-step/multi-project solution to doing JavaScript Unit Testing for Rails, including an autotest script to make TDD life easier for the autotest-addicted.
It was too many steps, too many different projects, and too much dependence on prototypejs. So let’s fix this via the spanky new newjs (introduced here):
Instead of several steps, there is now two steps:
cd myrailsapp # rails 2.0 app
sudo gem install newjs # v1.3.1+
script/generate javascript_test application
create vendor/plugins/javascript_unittest/lib
create vendor/plugins/javascript_unittest/tasks
create test/javascript/assets/jsunittest.js
create test/javascript/assets/unittest.css
create config/javascript_test_autotest.yml.sample
create vendor/plugins/javascript_unittest/lib/jstest.rb
create vendor/plugins/javascript_unittest/tasks/runner.rake
create vendor/plugins/javascript_unittest/tasks/autotest.rake
create vendor/plugins/javascript_unittest/README
create test/javascript/application_test.html
create script/rstakeout
create script/js_autotest
It installs all assets, gives you a rake test:javascripts task, gives you script/js_autotest, and finally (and most importantly), creates the application_test.html test stub.
As always, you can also run a single test file by loading it into a browser.
Prototype independence
Previously, the test suite - unittest.js - had a dependency on prototypejs. This was wonderful if you’re developing in prototypejs, but could cause some grief if you weren’t.
newjs now comes packed with an identical test suite - jsunittest - but it is built without a dependency on prototypejs.
Merb et al support
I wrote a rails generator because I used Rails. If a merb/other framework (Ruby or non-Ruby) wants a similar generator, just ask. Its pretty simple - I copy over the rails_generators folder into a merb_generators folder in newjs and change some things based on your frameworks’ structure.
Alternate test suite support
If you like another test suite, and want it included in the generators, this might require some additional effort on your part. It probably has different mechanisms for launching runners etc; whereas I was able to steal the rake tests + support libraries from prototypejs. But, it can be done.
Peepcode
These tools will be discussed in animated detail in the forth coming Peepcode “JavaScript Unit Testing”.
Get ready for the TextMate “Trundle to Rails 2.0 Bundle”
Have you noticed lately that the Rails TextMate git pull origin two_point_oohbundle (also installed with e - the Text Editor for Windows) isn’t quite as helpful as it once was - guiding and amplifying your rails app development.
Your resourceful/restful rails apps are now filled with named routes, but none of the helpers (link_to, redirect_to, etc) use them. The default view template was still rhtml for a long time (latest svn trunk fixes this to be html.erb, though Marc Jeanson is having a crack at supporting both through a per-project config file).
Or perhaps you were hoping for some snippets for new features of Rails 2.0: assert_difference (asd), assert_select (ass), respond_to (rst).
Or just maybe, you’ve been updating your local bundle to Rails 2.0 already? Please say yes, please say yes. If you are saying “yes”, read at the bottom for how/where to send me the patches. If you are saying “no”, read at the bottom for how/where to start creating patches and sending them to me.
Firstly, DHH didn’t write the Rails bundle
I didn’t know this - I just assumed the guy who created Rails and helped promote TextMate also created the Ruby on Rails TextMate bundle. Instead if was WWF’s “The Rock” himself Duane Johnson (figurines sold separately, and may look different to the real Duane Johnson who writes Rails code instead of prancing around in his underpants with other adult males in confined spaces).
The TextMate SVN logs say that it the bundle was first committed in Jan 2005. Its now Jan 2008. That’s three years of maintaining a suite of code that thousands of people take for granted every day writing Rails code. What a champion.
Like the Australian Cricket team’s wicketkeeper, Adam Gilchrist, he’s also retiring at the top of his game.
New Maintainer… me
Instead of maintaining my own projects, I’ve decided to maintain this one. I love the TextMate bundles. Before I had a Mac, I ported them across to RadRails and many RadRailers entered a golden era of snippet happiness.
My bundle-fu may not be the equivalent of Bruce Lee, but I’m keen to see my favourite Rails tool live on strong.
Bleeding edge bundle
Whilst the TextMate SVN administrators process the maintainer change request (Allan is on holidays somewhere and he took the house keys with him), you might think all is lost!
Never.
The straight-off-the-cow bleeding edge Rails bundle can be accessed via Git. Specifically the branch two_point_ooh.
So, let’s all do away with our pre-existing Rails bundle and live on the edge.
cd ~/"Library/Application Support/TextMate/Bundles/" mv "Ruby on Rails.tmbundle" "RoR.tmbundle.orig" git clone git://github.com/drnic/ruby-on-rails-tmbundle.git "Ruby on Rails.tmbundle" cd "Ruby on Rails.tmbundle" git checkout --track -b two_point_ooh origin/two_point_ooh git pull
Now, back in TextMate, go to menu “Bundles” > “Bundle Editor” > “Reload Bundles”.
You, my friend, are sitting pretty.
Upgrading to when newer blood is on the bleeding edge
Coming back for more?
cd ~/"Library/Application Support/TextMate/Bundles/Ruby on Rails.tmbundle" git checkout two_point_ooh # optional; only if you changed to another branch etc git pull
Now, back in TextMate, go to menu “Bundles” > “Bundle Editor” > “Reload Bundles”.
Bathe yourself in glory. Splash it all over yourself.
Submitting patches
If you go into TextMate, launch the Bundle Editor (Cmd+Alt+Ctrl+B) and change something in the Ruby on Rails bundle, then files will added/changed within your local git clone.
What I mean is, you can very simply submit patches now. [When I say "simply", I mean, "I think this is the best approach but I could be completely wrong here..."] Git is so cool that I don’t know what its doing most of the time; but let’s hang in there as a team.
cd ~/"Library/Application Support/TextMate/Bundles/Ruby on Rails.tmbundle" git add . # to add any new files/snippets/commands you created; TextMate uses one file per snippet git commit -a -m "Useful message about this patch goes here" git diff -p HEAD^ HEAD
[Theoretically] this creates a patch based on your most recent commit. So you can easily create patches for changes even if your repository and the remote/central/bleeding edge repository look different.
If your patch was created over several commits, then replace HEAD^ with HEAD~4, if there were 4 commits.
I think. God I could be wrong about this though.
Just try your best and if it works, let me know and I’ll remove all this “I don’t know what I’m talking about” text and future readers will think I know everything. Web 2.0 rocks.
Send patches to…
Me drnicwilliams@gmail.com [update] or via the new Google Group.
Want to fork the git repo? Use a free account at Gitorious or GitHub.
|
|
| Ruby on Rails: TextMate |
| Visit this group |
Trundle to Rails 2.0 Bundle
Arguably, we just keep patching the bundle forever and bleeding edges will continue to live happily within the blood and muck of said existence.
But, lots of other people want nicely zipped up bundles. No doubt “e - the Text Editor” will want a “released” version so they can clean it of all the ugly things they can’t yet replicate like Macros. And eventually I’ll push it all down to the SVN repo and it will be released with future TextMate upgrades.
So, there will be a “Rails 2.0 compatible” grand opening one day soon. Probably before 14th of March 2008, when I’m giving a “What’s new in Rails 2.0?” talk at QCON London. Showing off the new bundle will be sweet.
That gives us 6 wks to refactor this bundle to make it a shining example of all that is wonderful in Rails 2.0. Every patch helps.
[Please consider Rails 1.2.6 and before developers when conceiving of patches, and please consult your doctor if pain persists.]
Autotesting Javascript in Rails
I used to love Javascript so much that it would scare me. Why? Because I used to never write any tests. No unit tests. No integration tests (e.g. Selenium). Why? I didn’t know how. Not properly. I didn’t know how to write Javascript unit tests with an autotesting tool, like ZenTest’s autotest command.
And now…
I am now free to write as much Javascript as I like knowing forever I’ll write Javascript tests first, and Javascript in libraries second. TDD for Javascript beckons!
Below is a “getting started” tutorial, a helpful autotesting plugin, and hints about a TextMate bundle for Javascript Unit Testing and a future Peepcode on Javascript Unit Testing.
Installation
Fundamentally, the ideas here are app server-neutral. We’re using the unittest.js library from scriptaculous. But here I’ll show/demo the Rails plugins that make this all uber easy to get started.
Firstly, create a blank rails app, or use an existing app. The tutorial should be non-invasive - just a few “demo” files to delete when you’re done. This tutorial is independent of your app.
ruby script/plugin install javascript_test mkdir test/javascript ln -s ../../vendor/plugins/javascript_test/assets/ test/javascript/assets
For Windows people copy vendor/plugins/javascript_test/assets into test/javascript/assets, as you don’t have symbolic links, which is sad.
At this stage, you can add and commit these files to your project. The rest of this article is destructible demo files and tests.
Creating javascript tests
Let’s say
$ ruby script/generate javascript_test maths
exists test/javascript
exists public/javascripts
create test/javascript/maths_test.html
create public/javascripts/maths.js
maths.js is just a blank javascript file. The important file is maths_test.html. Its packed with lots of “getting started” goodies.
Open test/javascript/maths_test.html and find the testTruth method.
testTruth: function() { with(this) {
assert(true);
}}
This is an example of a javascript test method, with a sample assert call. It has the same api as the Ruby test::unit assert call. Thomas Fuchs’ presentation Adventures in JavaScript testing gives a good rundown of the available assert methods (and the BDD style syntax that is available). I’m also preparing a TextMate bundle to generate the assert calls, with the same “as”, “ase”, “asnn” tab completions as the Ruby bundle. It makes me happy when using it.
Running unit tests
The most holistic way to run your javascript unittests, is against all the browsers you have on your local machine. The javascript_test plugin comes with a rake task for this: test:javascripts
$ rake test:javascripts (in /Users/nicwilliams/Documents/rails_apps/imindi_theme) /test/javascript/maths_test.html on Safari: SUCCESS /test/javascript/maths_test.html of Firefox: SUCCESS Skipping Internet Explorer, not supported on this OS Skipping Konqueror, not supported on this OS
In the browsers you’ll see:
It runs all your tests on all browsers. That’s great for a Continuous Integration process, but for me, coming from the ZenTest world of autotest, I only want to run those tests for which something has changed.
I want continual feedback. Small change, run small test. autotest gives me that for Ruby, but rake test:javascript doesn’t.
Autotesting javascript tests
On my Mac, I’ve set up something as a starting point for autotesting javascript tests, based on the “small change, run small test” principle.
$ ruby script/plugin install http://drnicutilities.rubyforge.org/svn/plugins/javascript_test_autotest/ . . Edit config/javascript_test_autotest.yml for the browser(s) to use for autotesting.
Open config/javascript_test_autotest.yml and uncomment the browser(s) you want to autotest with. I autotest on Safari on the Mac, even though I develop/debug on Firefox, because it reloads each page in the same tab, which I like, and I’m having problems getting this to work into Firefox at all.
My yml file looks like:
browsers: safari: '/Applications/Safari.app/Contents/MacOS/Safari'
So, the current version is known to work for Mac OS X and Safari. If you get this plugin working on different O/S and browsers, let me know below or please submit a patch to http://groups.google.com/group/drnicutilities
From a command line:
$ script/js_autotest Watching public/javascripts/controls.js, public/javascripts/application.js, test/javascript/maths_test.html, public/javascripts/effects.js, public/javascripts/dragdrop.js, public/javascripts/prototype.js Files: 6
Let’s TDD with js_autotest
In test/javascript/maths_test.html, replace testTruth, with the following and save:
// Maths class should exist
testMathsClassShouldExist: function() { with(this) {
assert(Maths, 'Where is Maths?');
}},
js_autotest will automatically load maths_test.html into your browser, and its tests executed.
Now, let’s fix the problem by creating the Maths javascript class. In public/javascripts/maths.js, add:
var Maths = Class.create();
Maths.prototype = {
initialize: function() {
}
}
js_autotest will again automatically reload maths_test.html into your browser, and its tests executed.
Yay for TDD and Yay for “small change, run small test”.
Peepcode
I love Geoffrey’s Peepcodes. Geoffrey has all my money in Peepcode credits. More importantly, Geoffrey’s due to give birth this year to #1 child. Geoffrey, who works from home, is blissfully unaware that soon he’ll be a full-time father and part-time Peepcode author. This could mean fewer peepcodes on important peepcode-worthy topics.
I always wished there was a Peepcode on Javascript Unit Testing. It would take many blog posts to cover as much as can be covered in a single 60 minutes peepcode. So, we’re writing/videoing one.
As a Javascript developer [has anyone ever heard of a Javascript Users Group?] let me know what specifically you’d like covered in this video, so I don’t accidently miss something.
[optional] Install some patches
There was a section here about some patches that could be applied. These have now been applied, and javascript_test plugin has been updated with prototype 1.6.0.1. Life is good.




