Why DRYML?

Posted over 7 years back at The Hobo Blog

Why? Rails already has a bunch of mechanisms for re-use within views. Namely: layouts, partials and helpers. Each serves a different purpose, and yet, IMHO, there’s still a gap. I find that small fragments of mark-up tend to crop up over and over in my views. Yes I could extract them into paritals or helpers, but I find myself disinclined to do so.

Helpers are good for small bits of dynamic content, but not so convenient for re-use of HTML fragments - I don’t really want to embed loads of HTML in strings in Ruby source. Nor do I want to make excessive use of the tag helper. I want to put mark-up in mark-up files.

So partials would be appropriate. But each partial needs it’s own file, which again discourages me from making heavy use of them.

Finally, and prefixed with a big ol’ IMHO – dang are those ERB scriptlets ever ugly! If you ever needed to call a helper passing in HTML mark-up in the parameters, that’s HTML within Ruby within HTML – not pretty. Hey, it works right? This is not a criticism of ERB. The syntax used (<%= ... %>) is like that for a reason. ERB doesn’t need fixing. DRYML supports ERB scriptlets, but allows you to hide them away behind nice clean custom tags, leaving you with beautiful clean templates swoon where you can see what’s going on at a glance.

Defining a tag essentially just creates a new helper method for you, and a use of that tag is nothing more than a call to that helper. This is just syntax. Witness:

hello_world.dryml

<def tag="hello">Hello World!</def>

<p>Here it is: <hello/></p>

<p>And here it is again: <%= hello %></p>

Groovy baby :-)

(check out the Hello World post to see how to get set up so you can try this)

And just as you can call a tag from Ruby instead of mark-up, you can define them in Ruby if you wish. You can do so in your helpers. Try this

app/helpers/application_helper.rb

module ApplicationHelper

  include Hobo::DefineTags

  def_tag :from_ruby do
    "As easy as that eh?"
  end

end

That will give you a <from_ruby/> tag in all of your DRYML templates. If your tag contains more code than mark-up, it’s cleaner to define it in a module like this.

You could even define the tag in a helper module and call it from an ERB scriptlet, but that would be kinda strange… Hey – knock yourself out, it’s all good :-)

I’m trying not to get ahead of myself because there’s a Quick Guide to DRYML coming right up. I just want to show you that this is just a thin layer on top of your regular Rails template. They’re just purdier is all.

Actually there’s a lot more under the hood in DRYML – it’s not just syntax. We’ll get there.

Getting Started: Hello World in DRYML

Posted over 7 years back at The Hobo Blog

Hello World will never get old for me. What more could you need to get yourself oriented in a new technology? I remember the first time I managed to string the whole J2EE stack together. All that technology – JNDI, RMI, EJB… All just to get “Hello World” on the screen. Hmmm. Can’t say I miss that too much.

Where was I?

Oh yes. One of the main features of Hobo is DRYML - an new template engine that extends ERB with user-defined tags. Thats right: extends. DRYML templates can use erb scriptlets just like regular RHTML templates.

We’re going to create a custom tag <hello> which will render - you guessed it - “Hello World” on the page. Obviously, the real goal here is to get Hobo installed and verify that it’s running.

To run Hobo you need Rails 1.2, which at the time of writing is available as release-candidate 1. Install it like this:

gem install rails --source http://gems.rubyonrails.org -y

To install Hobo into a new Rails app, simply:

$ rails hobo_hello_world
$ cd hobo_hello_world
$ ./script/plugin install svn://hobocentral.net/hobo/trunk

Next, there are one or two directories and files that Hobo expects to find. Create these with the handy generator:

$ ./script/generate hobo
  create  app/views/hobolib
  create  app/views/hobolib/themes
  create  app/views/hobolib/application.dryml

OK, Hobo is now at your service! Before we can have a Hello World view, of course, we’ll need a controller:

$ ./script/generate controller hello

No need to edit that. We’ll just go straight for the view.

File: app/views/hello/hello_world.dryml

<def tag="hello">Hello World!</def>

<p>Here it comes... Can you stand it??!</p>

<p style="font-size: 500%"> <hello/> </p>

That’s it. Start your engines:

$ ./script/server

And browse yourself over to localhost:3000/hello/hello_world

Outstanding work people. If that has whet your appetite and you want more, I suggest you haul your digital assets over to either Why DRYML? or A Quick Guide to DRYML.

Getting Started: Hello World in DRYML

Posted over 7 years back at The Hobo Blog

Hello World will never get old for me. What more could you need to get yourself oriented in a new technology? I remember the first time I managed to string the whole J2EE stack together. All that technology – JNDI, RMI, EJB… All just to get “Hello World” on the screen. Hmmm. Can’t say I miss that too much.

Where was I?

Oh yes. One of the main features of Hobo is DRYML - an new template engine that extends ERB with user-defined tags. Thats right: extends. DRYML templates can use erb scriptlets just like regular RHTML templates.

We’re going to create a custom tag <hello> which will render - you guessed it - “Hello World” on the page. Obviously, the real goal here is to get Hobo installed and verify that it’s running.

To run Hobo you need Rails 1.2, which at the time of writing is available as release-candidate 1. Install it like this:

gem install rails --source http://gems.rubyonrails.org -y

To install Hobo into a new Rails app, simply:

$ rails hobo_hello_world
$ cd hobo_hello_world
$ ./script/plugin install svn://hobocentral.net/hobo/trunk

Next, there are one or two directories and files that Hobo expects to find. Create these with the handy generator:

$ ./script/generate hobo
  create  app/views/hobolib
  create  app/views/hobolib/themes
  create  app/views/hobolib/application.dryml

OK, Hobo is now at your service! Before we can have a Hello World view, of course, we’ll need a controller:

$ ./script/generate controller hello

No need to edit that. We’ll just go straight for the view.

File: app/views/hello/hello_world.dryml

<def tag="hello">Hello World!</def>

<p>Here it comes... Can you stand it??!</p>

<p style="font-size: 500%"> <hello/> </p>

That’s it. Start your engines:

$ ./script/server

And browse yourself over to localhost:3000/hello/hello_world

Outstanding work people. If that has whet your appetite and you want more, I suggest you haul your digital assets over to either Why DRYML? or A Quick Guide to DRYML.

On Premature Optimization

Posted over 7 years back at RailsExpress.blog

The alert reader of my blog might have noticed that I really care about performance. Some people even have accused me of being “obsessed” with it. Very often these statements are accompanied by Tony Hoare’s famous line: “Premature optimization is the root of all evil.”, which was later repeated by Donald Knuth.

I’ve always admired the work of Hoare and Knuth and I’m well aware of the famous quote on premature optimization. And they’re absolutely right: premature optimization is evil.

However, what lots of people seem to miss out, is that the most important word in his statement is “premature”.

If you don’t give any consideration to performance, you will be sure to avoid premature optimization. But you might have made a design decision which simply cannot be reverted without huge cost at a later stage of the project.

Let me give you an example: I once was asked to evaluate a project because it had performance problems. The software was intended to be used in a call center, which requires really fast response times. It turned out that the external company hired to implement this software, had made the decision to write the UI dialogs in a custom templating language, for which they had written an interpreter. The interpreter had been written in Visual Basic, which, at that time, was an interpreter as well.

So in effect, the dialogs were running c1*c2 times slower than necessary, where c1 and c2 are the interpreter overheads. It’s probably safe to assume the software ran about 25-50 times slower than necessary. And even top of the line hardware with 2 processors wasn’t able to make the package run fast enough.

In the end, the whole project was canceled, after pouring millions of EUR into it. And the problem was solved by buying another call center wholesale. I still believe today, that if some consideration had been given to performance questions during the architectural design phase, this disaster could have been avoided.

So, yes, premature optimization is evil, but no consideration for performance issues is just as bad.

Update: BTW, I was prompted to write this little piece after reading a blog entry
about a talk delivered at the Web 2.0 conference. It clearly shows that speed matters down to sub second resolution, even for web applications. I wouldn’t be surprised, if a well known UI axiom gets proven to hold in web context as well: response time should be below 100ms for graphical user interfaces. Making it faster is almost unnoticeable to the end user, but slower than 100ms does have negative effects.

SqlSessionStore gains support for SQLite

Posted over 7 years back at RailsExpress.blog

Ted X Toth has submitted the code for a SQLite session class implementation for SqlSessionStore. I have checked it into the subversion repository.

Thank you very much Ted!

Down w/ with_scope

Posted over 7 years back at zerosum dirt(nap) - Home

We need to delete some stuff. But when we delete items, we don’t really delete them because hey, we don’t have to (we might want them later, no?) So we have an attribute on the model, deleted, which is null if the item is current. When we delete an item, we update_attributes to set deleted to the current datetime.

Yes, yes, I know, this is really common stuff. But hold on, this is where it gets kind of interesting. We want to call find on the model, like always, and only get back current items that have not been deleted. Oh, and we don’t want to have to pass in the condition every time, because that’s just gross. We’d just like to, well, add the condition to the scope. This is where the magic of with_scope can help us out.

Let’s declare a method find_current on the model:

def self.find_current
  find(:all, :conditions => "deleted IS NULL")
end

Well that works for our base case (finding all current items) but it’s pretty inflexible. What if I want to pass in an ID, specify a limit, additional conditions, etc?

def self.find_current(*args)
  with_scope(:find => { :conditions => "deleted IS NULL" }) do
    find(*args)
  end
end

The answer is to use with_scope, which allows us to specify conditions here that will apply throughout the course of the block. Now we can do things like:

Item.find_current(:all, :limit => 10)
Item.find_current(:first, :conditions => "name LIKE '%perishable%'")
Item.find_current(13)

Which invoke the find_current method on the model with our additional parameters and includes our deleted condition in the scope automatically.

K, so still not exactly rocket science, but it is a nice, clean solution to a common issue for sure. Unfortunately, with_scope isn’t found in my copy of Agile Web Development with Rails, which is my main reason for noting it here. Hopefully it’ll be in v2! Some other helpful bloggers are out there though, check out Ryan Daigle’s blog, which is where Ian found the article that got us started on this path.

How fast is fast enough?

Posted over 7 years back at The Hobo Blog

Bud Fox: How much is enough?

Gordon Gekko: It's not a question of enough, pal. It's a zero sum game, somebody wins, somebody loses. Money itself isn't lost or made, it's simply transferred from one perception to another.

I’m a bit of a Gordon Gekko myself when it comes to programming. Greed is good. Remember? Greed works. I’m greedy for speed. Seems to me pretty reasonable that I should be able to build a nice looking, usable, fully-ajaxified database app in what? A couple of hours? That would be fast enough. Then I’d be satisfied grin.

To be clear, I’m only talking about a basic front end to a database here. You know the drill: create, update, delete, link things together. A blog, a simple content management system, a shop, an events diary, an issue tracker… The list goes on and on. All these kinds of sites are overwhelmingly similar. If I’m having to sweat a lot of code to get a site like this working, surely I must be repeating myself from the last site I built? Real programmers don’t repeat themselves. (Got that? I said: real programmers don’t repeat themselves)

Of course, any interesting web app is going to need a bunch of code to make it tick. Your job aint going anywhere just yet Mr. Programmer (except to Bangalore of course). I just don’t want to waste my life hacking on uninteresting sites. Or to be more accurate, on the uninteresting parts (there are a lot!) of my otherwise brain-meltingly exciting sites.

In fact there’s a bunch of stuff out there that will build a database front-end for you, in an instant. The Python world has Django, and the same for Rails is not far off. The Streamlined guys seem to be doing a great job. With one caveat: it’s called an Admin Interface. Not for public consumption.

So if an admin interface can be derived automatically from the data model, surely a genuine end-user interface can’t take that long? They are mere mortals, I believe, these administrators.

This is exactly what Hobo is trying to achieve - to take the automation of the out-of-the-box admin interface along with the flexibility of hand-coded views, and mix ‘em up in a big ‘ol pot to see what comes out.

Like the Scriptaculous guys have it - it’s about the user interface, baby!

This pretty much reflects my experience with hacking on Rails apps. The data-layer has been reduced to blissful simplicity. The move to CRUD as a design strategy makes the idea of a one-size-fits-all controller look pretty doable. But the views… I seem to spend 80% of my time hacking view code.

Not for much longer! :-)

Soon I’ll be able to say:

<page title="search">
  <hey_cut_the_drama_and_give_me_a_search_page_already/>
</page>
<page tile="Search">
  <hey_cut_the_drama_and_give_me_a_search_page_already/>
</page>

Of course, it’s all open-source so if it works, please help yourselves :-)

Feeling greedy?

(p.s. What a load of old waffle eh?! I’ll make sure the next post has some actual content. Y’know, like, er, code and stuff)

How fast is fast enough?

Posted over 7 years back at The Hobo Blog

Bud Fox: How much is enough?

Gordon Gekko: It's not a question of enough, pal. It's a zero sum game, somebody wins, somebody loses. Money itself isn't lost or made, it's simply transferred from one perception to another.

I’m a bit of a Gordon Gekko myself when it comes to programming. Greed is good. Remember? Greed works. I’m greedy for speed. Seems to me pretty reasonable that I should be able to build a nice looking, usable, fully-ajaxified database app in what? A couple of hours? That would be fast enough. Then I’d be satisfied grin.

To be clear, I’m only talking about a basic front end to a database here. You know the drill: create, update, delete, link things together. A blog, a simple content management system, a shop, an events diary, an issue tracker… The list goes on and on. All these kinds of sites are overwhelmingly similar. If I’m having to sweat a lot of code to get a site like this working, surely I must be repeating myself from the last site I built? Real programmers don’t repeat themselves. (Got that? I said: real programmers don’t repeat themselves)

Of course, any interesting web app is going to need a bunch of code to make it tick. Your job aint going anywhere just yet Mr. Programmer (except to Bangalore of course). I just don’t want to waste my life hacking on uninteresting sites. Or to be more accurate, on the uninteresting parts (there are a lot!) of my otherwise brain-meltingly exciting sites.

In fact there’s a bunch of stuff out there that will build a database front-end for you, in an instant. The Python world has Django, and the same for Rails is not far off. The Streamlined guys seem to be doing a great job. With one caveat: it’s called an Admin Interface. Not for public consumption.

So if an admin interface can be derived automatically from the data model, surely a genuine end-user interface can’t take that long? They are mere mortals, I believe, these administrators.

This is exactly what Hobo is trying to achieve - to take the automation of the out-of-the-box admin interface along with the flexibility of hand-coded views, and mix ‘em up in a big ‘ol pot to see what comes out.

Like the Scriptaculous guys have it - it’s about the user interface, baby!

This pretty much reflects my experience with hacking on Rails apps. The data-layer has been reduced to blissful simplicity. The move to CRUD as a design strategy makes the idea of a one-size-fits-all controller look pretty doable. But the views… I seem to spend 80% of my time hacking view code.

Not for much longer! :-)

Soon I’ll be able to say:

<page title="search">
  <hey_cut_the_drama_and_give_me_a_search_page_already/>
</page>
<page tile="Search">
  <hey_cut_the_drama_and_give_me_a_search_page_already/>
</page>

Of course, it’s all open-source so if it works, please help yourselves :-)

Feeling greedy?

(p.s. What a load of old waffle eh?! I’ll make sure the next post has some actual content. Y’know, like, er, code and stuff)

Welcome to the Hobo Blog :-)

Posted over 7 years back at The Hobo Blog

I’m so glad Wordpress didn’t turn that smiley into a cute little gif. Old Skool man!

Welcome to the Hobo Blog :-)

Posted over 7 years back at The Hobo Blog

I’m so glad Wordpress didn’t turn that smiley into a cute little gif. Old Skool man!

In My Younger And More Vulnerable Years...

Posted over 7 years back at zerosum dirt(nap) - Home

Thus began the Zerosum dev blog, a place for folks who work on our code to muse about daily development happenings and such.

I’ve never been one to keep a blog, personally, but I think of this area as a useful place for us to post about things that don’t belong in our project trac wiki or elsewhere. Things you want to share with others. Things like: “Wow cool, Ian found a new way to do X that totally rocks. Spread the word” and “Rails migrations rule, check out this snippet!”, and “Saw this thing on Foo’s blog about how to do Y without needing Z. Maybe we should think about refactoring the BlahController to do that too?”

You get the idea.

Josh Schairbaum and Dan Manges - Ruby on Rails Podcast

Posted over 7 years back at Ruby on Rails Podcast

Correspondent Robert Stevenson interviews two developers from investment banking company JPMorgan Chase.

Integration Testing in Ruby on Rails — How to maintain sessions while testing in Rails

Posted over 7 years back at Ajax on Rails


Well, its a natural feel to get amazed out of every other delighted feature provided by RubyonRails and so appreciating it before actually talking about the feature in every second post. This line is for those people who have published that the worst thing about rails is that every rails programmer always just focus on the appreciation of rails and not on the framework per se. As i think the reason behind his(let say) perception is that he might not have tried rails and probably in all posts he have been through yet is that he would have got jealous out of gaining popularity of ruby on rails over jsp and asp and else, and therefore he might not be reading the whole post due to which he just remained untouched with the real appreciable features.
Anyhow, here is my post on a fantastic rails feature – Integration Testing…
RoR is the only web application framework which provides an inbuilt high level of testing. Out of the whole testing the most interesting real time testing is Integrations Testing where you can synchronize with the sessions too unlike in the Functional Testing.

Where exactly we should use Integration Testing ?
Whenever we need to test a series of functionalities which belongs to more than one controller , we should go for Integration Testing and not the Functional one.

Since the functional and unit testing are controller and model centric respectively, rails automatically creates the related functional and unit tests files. But as integrations testing is not confined in any criteria of a specific controller or model, we have to create the integrations file manually… Well, nothing is headache in rails. Its a simple pre-written script, all you need is to call that script with a name you like for whole story you wish to test in the integration test.

Here is a real example of Integration Test in Ruby on Rails

Considerations for test…
We will simply test

  • signing in
  • posting a new article
  • deleting an article with xml_http_request (ajax post request)

Create the test file by running


ruby script/generate integration_test initial_features

Make sure that now you have the file /test/integration/initial_features_test.rb. Rails automatically appends _test at the end of the file name.

For god sake Lets start the testing now :-)
Code for the file /test/integration/initial_features_test.rb


require "#{File.dirname(__FILE__)}/../test_helper"

class InitialFeaturesTest < ActionController::IntegrationTest
  fixtures :users, :articles

  def test_initial_features
     user = user_for_test
     user.try_to_signin
     user.signin
     user.post_an_article
     user.delete_an_article_with_xhr
  end

  def user_for_test
    open_session do |user|
      def user.try_to_signin
        assert_nil session[:user] # assert_session_has & _has_no have been deprecated
        get "user/signin"
        assert_response :success
        post "user/signin", :email=>"test failure string", :password=>"test failure string"
        assert_nil session[:user]
      end
      def user.signin
        assert_nil session[:user]
        user = users(:first)
        post "user/signin", :email=>user.email, :password=>user.password
        assert_not_nil session[:user]
        assert_response :redirect
        assert_redirected_to "articles/show"
        # now as the session is set once, we need not to signin again
      end
      def user.post_an_article
        get "articles/show"
        assert_response :success
        assert_template "articles/show"
        user = session[:user]
        articles_count = user.articles.length
        post_via_redirect "article/new", :title=>"Integration Tetsing in Rails", :description=>"another relishing rails feature"
        assert_template "articles/show"
        assert_equal articles_count.next, user.reload.articles.length
      end
      def user.delete_an_article_with_xhr
        user = session[:user]
        articles_count = user.articles.length
        xml_http_request "articles/delete", :id=>articles(:first).id
        assert_equal articles_count-1,user.reload.articles.length
      end
    end
  end

end

Although these are not that high level integration tests that rails can provide but its just an overview on the integration tests. I will explain them soon.

Exploring TextMate...a Ruby perspective

Posted over 7 years back at Luke Redpath - Home

Marshall Vandegrift has posted an interesting screencast showing off Emacs as a tool for Ruby/Rails development. I enjoyed the screencast, and Emacs certainly has cool features but all I could think whilst watching it was (WARNING: FLAMEBAIT ALERT!)…“urgh, its soooo ugly, how could anybody work with that all day. And TextMate does all of this and in a much nicer way…”.

It got me thinking about how I use TextMate every day and whether I really take full advantage of its built-in commands and snippets for Ruby and Rails development. I wondered how many of the features in the above Emacs screencast were already in TextMate and the answer was…most of them! This inspired write a post about some of my favorite TextMate snippets and hopefully you’ll find out about a few you didn’t know about.

Whether you are a new or seasoned TextMate user, its really worth spending some time to learn some of the more useful snippets in the bundles for the languages that you are using. I’m sure most Ruby and Rails developers are aware of the basics such as do..end completion and the various snippets for creating classes, modules and methods. What follows is an overview of some of the cooler functionality built into the Ruby/Rails bundles that you might not have come across. There is a certain amount of mental overhead in learning these snippets but if you can you will find yourself being even more productive.

But first…

If you are running a stock TextMate install, you’ll only have the default set of bundles. There is a wealth of bundles in the Macromates Subversion repository. I won’t repeat the installation instructions here, but I will mention a small tip for managing your bundles.

The Macromates repository has a lot of bundles and the chances are you will only need a small selection of them. Installing all the bundles slows down TextMate’s opening times and adds a lot of noise to the Bundles/Snippets menus. Instead of simply checking out all of the bundles into your /Library/Application Support/TextMate folder, create a folder in a Subversion repository of your own, and check the empty folder out to /Library/Application Support/TextMate. Now, add all the folders in the Macromates repository except the Bundles folder to your repository as an svn:externals entry. Next, create a Bundles folder and check this in. Finally, add all of the Bundles that you want as svn:externals entries in the Bundles folder.

If the above sounds too complicated or time-consuming, you can use my own setup as a starting point.

Syntax constructs

Note: for the rest of this article, I will put any relevant tab-triggers in square brackets.

The TextMate Ruby bundle has snippets for most of the common declarations that you are likely to use…there are definitions for classes [cla], modules [mod] and methods [def] and other common blocks such as conditional statements [if, ife, elsif], loops [until, while], exception handling [begin] and generic blocks [do].

The class and module snippets, like a lot of newer snippets, use a single tab expansion for multiple snippets, with the different options appearing as a contextual menu. This reduces the overhead of learning lots of obscure triggers and gives you a good overview of what you can do with a particular trigger. The class snippets, for example, have variations for creating standard classes, classes with inheritance, classes with a generated initialize template and more. You can even create a new Test::Unit testcase, complete with the necessary requires, Test::Unit::TestCase inheritance and a default test method with a single trigger [tc].

Finally, there are snippets for many of the common tasks performed when writing a Ruby script, such as entering the shebang line [rb], requiring files [req], generating symbol => value key/value pairs for hashes [:], lambda blocks [lam], and one of my favorites, path-from-here [patfh] which is used for getting the path relative to the current script and generates:

File.join(File.dirname(__FILE__), *%w<strong>[rel path here]</strong>)

h3. Writing classes/modules

In addition to the snippets for defining classes and modules, there are some other goodies too.

If you want to add Enumerable support to your class, you need to include the Enumerable module and define an each method. To do this in Textmate, simply create a new class then inside your class definition, use the Enumerable snippet [Enum]. This will generate something like this for you:

class Foo
  include Enumerable

  def each(&block)

  end
end

In a similar fashion, the Comparable snippet [Comp] will include the Comparable module and create a stub <=> method for you to fill in.

Defining attributes for your class is a breeze – TextMate contains snippets for attr_reader ®, attr_writer [w] and attr_accessor [rw]. You can define class methods just as easily as you define instance methods [defs], alias methods [am] and overwrite method_missing [mm]. Don’t forget the singleton class for helping out with that meta-programming goodness [sin].

Other cool snippets

There are plenty of snippets for all of your favorite iterators including each [ea], each_pair [eap], collect/map [col/map] and everybody’s favorite, inject [inj]. There are too many to mention here – there are snippets for all of the common iterators and block methods defined in Enumerable and other collection classes, as well as snippets for iterating over files.

How often do you fire up IRB just to run a simple snippet of code? I do…but why waste time loading up IRB when you can execute lines of Ruby directly in TextMate? Simply write a line of Ruby code, then run the “Execute line as Ruby” command [Ctrl + Shift + E]. The result of the expression will be inserted directly on the next line.

Finally, some personal favorites. Trying to convert all those string keys to symbols in your Rails app to make things much easier to read? TextMate makes it easy to switch between strings and symbols – simply move the cursor onto the string/symbol you want to switch and hit [Ctrl + :].

Interested to know whats going on under the hood of the library that you’ve required in your script? Put the cursor over the require line, and hit [Cmd + Shift + D]. If TextMate can find the required file, it will open it for you. How cool is that?

A final, Rails-related mention goes to the Rails migration snippets. There are only three commands you need to know: columns, tables and indexes [mcol, mtab, mind]. All of the common migration commands are supported and where possible, the snippets will generate your self.down method for you, whilst you are writing the self.up method! A particularly good example of this is “Drop and Create table” – type in the name of the table you want to drop, hit tab twice and it will populate self.down using the relevant section of your schema.rb. Clever stuff.

Writing your own bundles

Of course, the real power behind TextMate lies not only in its pretty good set of existing bundles, but the ability to write your own. Writing snippets is the easiest of the lot and I really advise you to create your own “personal” bundle to store all of the little snippets tailor-made for you. The next step up is writing commands and here is the killer feature – you can write your commands in whatever language you know best, as long as TextMate can find the interpreter (it uses a shebang line at the top of your command). A lot of the built-in commands are written in Bash, but many of the Ruby commands are written in, unsurprisingly, Ruby. Take a look at some of the built-in commands to give you an idea of what you can do.

Here are some of the bundles that I’ve written that are available for all:

* RSpec TextMate Bundle * RESTful Rails – snippets for RESTful Rails development * UJS4Rails Bundle – snippets for the UJS Rails plugin

The last two are still very much under development but the RSpec bundle is pretty comprehensive and covers all of the built-in expectations, as well as the mocking API, Rails integration and spec runners.

Feedback

Have you got any favorite snippets that you want to share with the world? Let me know. You can use the comments below, although I advise for anything but short snippets that you pastie them and post the link.

Vox Populi

Posted over 7 years back at Ryan Tomayko's Writings

The following is the full text of a paper by Sir Francis Galton first published in the March 7, 1907 issue of the scientific journal, NATURE. The piece is referenced in the February 18, 2005 episode of WNYC's most excellent RadioLab program. A scan of the paper on its original facsimile is available as PDF. It seemed a shame that what is possibly the first solid explanation for why Google's ranking algorithm is so capable should be hidden from it.

In these democratic days, any investigation into the trustworthiness and peculiarities of popular judgments is of interest. The material about to be discussed refers to a small matter, but is much to the point.

A weight-judging competition was carried on at the annual show of the West of England Fat Stock and Poultry Exhibition recently held at Plymouth (England). A fat ox having been selected, competitors bought stamped and numbered cards, for 6d. each, on which to inscribe their respective names, addresses, and estimates of what the ox would weigh after it had been slaughtered and “dressed.” Those who guessed most successfully received prizes. About 800 tickets were issued, which were kindly lent me for examination after they had fulfilled their immediate purpose. These afforded excellent material. The judgements were [unbiassed] by passion and uninfluenced by oratory and the like. The sixpenny fee deterred practical joking, and the hope of a prize and the joy of competition prompted each competitor to do his best. The competitors included butchers and farmers, some of whom were highly expert in judging the weight of cattle; others were probably guided by such information as they might pick up, and by their own fancies. The average competitor was probably as well fitted for making a just estimate of the dressed weight of the ox, as an average voter is of judging the merits of most political issues on which he votes, and the variety among the voters to judge justly was probably much the same in either case.

After weeding thirteen cards out of the collection, as being defective or illegible, there remained 787 for discussion. I arrayed them in order of magnitudes of the estimates, and converted the cwt., quarters, and lbs. in which they were made, into lbs., under which form they will be treated.

Distribution of the estimates of the dressed weight of a particular living ox, made by 787 different persons.

Degrees of the length of Array 0°-100° Estimates in lbs. Centiles Excess of Observed over Normal
Observed Deviates from 1207 lbs. Normal p.e. = 37
5 1074 -133 -90 +43
10 1109 -98 -70 +28
15 1126 -81 -57 +24
20 1148 -59 -46 +13
q1 25 1162 -45 -37 +8
30 1174 -33 -29 +4
35 1181 -26 -21 +5
40 1188 -19 -14 +5
45 1197 -10 -7 +3
m 50 1207 0 0 0
55 1214 +7 +7 0
60 1219 +12 +14 -2
65 1225 +18 +21 -3
70 1230 +23 +29 -6
q3 75 1236 +29 +37 -8
80 1243 +36 +46 -10
85 1254 +47 +57 -10
90 1267 +52 +70 -18
95 1293 +86 +90 -4

q1, q3, the first and third quartiles, stand at 25° and 75° respectively. m, the median or middlemost value, stands at 50°. The dressed weight proved to be 1198 lbs.

According to the democratic principle of “one vote one value,” the middlemost estimate expresses the vox populi, every other estimate being condemned as too low or high by a majority of the voters (for fuller explanation see One Vote, One Value, NATURE, February 28, p. 414). Now the middlemost estimate is 1207 lb., and the weight of the dressed ox proved to be 1198 lb.; so the vox populi was in this case 9 lb., or 0.8 per cent. of the whole weight too high. The distribution of the estimates about their middlemost value was of the usual type, so far that they clustered closely in its neighbourhood and became rapidly more sparse as the distance from it increased.

But they were not scattered symmetrically. One quarter of them deviated more than 45 lb. above the middlemost (3.7 per cent.), and another quarter deviated more than 29 lb. below it (2.4 per cent.), therefore the range of the two middle quarters, that is, of the middlemost half, lay within those limits. It would be an equal chance that the estimate written on any card picked at random out of the collection lay within or without those limits. In other words, the “probably error” of a single observation may be reckoned as 1/2(45 + 29), or 37 lb. (3.1 per cent.). Taking this for the p.e. of the normal curve that is best adapted for comparison with the observed values, the results are obtained which appear in above table, and graphically in the diagram1.

The abnormality of the distribution of the estimates now becomes manifest, and is of this kind. The competitors may be imagined to have erred normally in the first instance, and then to have magnified all errors that were positive. The lower half of the “observed” curve agrees for a large part of its range with a normal curve having the p.e. = 45, and the upper half with one having its p.e. = 29. I have not sufficient knowledge of the mental methods followed by those who judge weights to offer a useful opinion as to the cause of this curious anomaly. It is partly a psychological question, in answering which the various psychophysical investigations of Fechner and other would have to be taken into account. Also the anomaly may be partly due to the use of a small variety of different methods, or formulae, so that the estimates are not homogeneous in that respect.

It appears then, in this particular instance, that the vox populi is correct to within 1 per cent. of the real value, and that the individual estimates are abnormally distributed in such a way that it is an equal chance whether one of them, selected at random, falls within or without the limits of -3.7 per cent. and +2.4 per cent. of their middlemost value.

This result is, I think, more creditable to the trustworthiness of a democratic judgement than might have been expected.

The authorities of the more important cattle shows might do service to statistics if they made a practice of preserving the sets of cards of this description, that they may obtain on future occasions, and loaned them under proper restrictions, as these have been, for statistical discussion. The fact of the cards being numbered makes it possible to ascertain whether any given set is complete.

Francis Galton.


Notes

1 The original article included a diagram that illustrated the normal vs. observed curve. I plan on adding this at some point but have not yet had the time to try to emulate the hand-written diagram with modern plotting tools.