Dr Nic

Showcase of CoffeeScript – 2.5 mins for your next Dev Group meeting

If you are giving an “Introduction to CoffeeScript” talk at your local developer group in the future, I have a 2:30min video you might find exciting to show. CoffeeScript is so cool that I thought it really needed to be put to music. Hard rock music. AC/DC.

I finished my session at NordicRuby with this video and I think it helped get lots of people excited about CoffeeScript.

Because of it’s heavy dependence of the backing song – the screencast is boring without it – I’m kind of screwed as to how to distribute it to other presenters. The licensing rules of including music and it’s 600Mb size are prohibitive.

What the hell. I’ve included an inline sample above; and the links to the 600Mb version is below. All self-promotional “Dr Nic made this shiny video” bits have been removed. Go for gold. Share the CoffeeScript excitement.

NordicRuby

NordicRuby finished 5 days ago, but many of the attendees and speakers are only finally winding down. Executed with the style, excitement and pizazz of Unspace’s RubyFringe and FutureRuby conferences, I had a brilliant time in Gothenburg. If NordicRuby’s organiser’s Elabs host the event again in 2011 I highly recommend attending. Carefully selected and sequenced speakers from around the world, 30 minute talks with 30 minute breaks over two days, an hour of lightning talks each day, and parties every night. Phew.

To CJ and Lilly, the organisers, the other speakers and all the attendees, thanks for an awesome experience in Sweden. Looking forward to coming back next year.

Why CoffeeScript?

JavaScript has a wonderful feature or two: it’s everywhere and it’s getting really fast. Unfortunately, its syntax was heavily influenced by Java/C++ and other popular goliaths of the time. But the JavaScript runtime is sweet. JavaScript syntax, not so sweet.

Like .NET and it’s selection of languages, the JVM and it’s growing smorgasbord of languages, I think the JavaScript runtime could benefit from more experimentation with alternate languages and/or syntaxes. Objective-J was one attempt. CoffeeScript is another.

Of the two, I like CoffeeScript. A lot.

Demonstrating CoffeeScript at Dev meetups

The video flies through core ideas pretty quickly, so I ran through syntax examples on a slide first, and then said “You know, I think this would go better to music,” and played the video.

Download and Demo

The purpose of offering the 600Mb video version is for the growing number of people doing CoffeeScript talks at their local software dev groups. The music in it is not licensed, not mine, but sounds awesome.

Please play the video with speakers. AC/DC on mute is a cruel act. Also watching the text jump around without the music is probably weird to watch. AC/DC and CoffeeScript. Perfect match, I think.

Formats: Torrent | Download (600Mb)

Tack så mycket

Swedish for “Thank you very much,” pronounced like “tuck sa-meekeh” or thereabouts.

If you use the video at all, I’d really appreciate it if you left a comment below!

How to make a good home-made Open Source

Want to be the funniest person at the next hacker’s picnic? Point at a bottle of red ketchup with its lid next to it on the table and pronounce “Hey look, Open Source.”

Be ready with follow-ups like “Can you pass me the Haml?”

If you’ve used Ruby on Rails, Apache, Emacs, or Linux then you would have been impressed by the awesome quality of these free bits of software which are so important to us. They are free, they are important, and they are awesome.

Paying money for poor commercial software makes awesome, important free software appear even more awesome and important.

The facts seem gloomy. You are a humble developer. Awesome, important free software is a Herculean achievement.

Conclusion? You implicitly believe you will never write awesome, important free software.

But “never” is an awfully long time. And is the only goal “awesome, important free software”?

Reasons to write?

Personally, I don’t think I’ve ever created an open source project that is either important or awesome. I think my motivations for open source — my own projects or stuff added to other’s projects — is either:

“Wouldn’t it be cool if you could do XYZ?” or “Seriously. Why can’t I do XYZ?”

I was either amused or annoyed. Dr Nic’s Magic Models was a joke. ChocTop was vented frustration.

Perhaps there are different reasons. I find the following examples inspiring.

I think the late Why the Lucky Stiff created entertaining free software.

Tim Lucas created artistic free software (‘View Source’ to see the header comment)

Christian Neukirchen created liberating free software.

Ryan Davis created free tools.

Chris Wanstrath ports free software.

Is there a muse that you can choose?

What other reasons are there for writing examples? Perhaps leave comments below and I’ll add them to the list above.

Who? Me?

And “awesome” sounds awfully challenging to aim for. Surely, “Awesome” is just one end of a scale with “Worthless” at the other end. “Moderately Good”, “Average”, “Below Average”, and “Where are the test cases?!” are in the middle.

Have you ever visited a friend who you find putting on the finishing touches to a 6’ by 4’ canvas painting of their entire family from their last Christmas dinner together, and they say “want to help?” Unlikely. Fortunately open source software “paintings” are a free-for-all.

You can write Libraries, Adaptors, Applications, Frameworks, Tools, Extensions and Services.

You don’t even need to create new free software. Fix something that someone else broke. Add a feature that was missing. Write documentation after you eventually figured out what to do.

Mid-Year’s Resolution

It’s now April. If you’re still looking for a 2010 New Year’s Resolution, borrow this one: “Write some open source software.”

If you’re going to RailsConf, perhaps come along to my tutorial The 8 Steps to Contributing to OSS or let’s catch up in the corridors. It’s going to be a great RailsConf!

rails2010_header_bg

Using CoffeeScript in Rails and even on Heroku

I’m pretty excited about CoffeeScript as a clean-syntax replacement for pure JavaScript.

What is CoffeeScript?

Imagine all the syntactical delights of Ruby and Haml for your JavaScript. You write in a nice language, but get normal JavaScript at runtime. All whilst having full access to 3rd-party JavaScript libraries (jQuery, PrototypeJS), debugging support (it becomes pure, readable JavaScript), existing support from test suites (it’s normal JavaScript) and growing support from various text editors (TextMate, Vim, Emacs).

What simple delights?

No trailing semi-colons. No { some_code() } function/closure brackets. String interpolation. Multi-line strings. Explicit class syntax. Array slicing. An existential ? operator.

Scroll down the home page for awesome example after example.

These aren’t library extensions. This is clean, purposeful syntax.

You can play with the joyful syntax of CoffeeScript on the website. After reading the basic examples on the CoffeeScript home page, press “TRY COFFEESCRIPT” in the header menu.

As you play with the syntax, the equivalent JavaScript is printed on the right hand side (see image above).

How nice is that syntax? Very.

Installing CoffeeScript

  1. Install NodeJS
  2. Install CoffeeScript

For NodeJS (get latest release URL; using 0.1.31 as 0.1.32 doesn’t unpack for me):

cd /usr/local/src
wget http://nodejs.org/dist/node-v0.1.31.tar.gz
tar xfv node-v0.1.31.tar.gz
cd node-v0.1.31
./configure
make
sudo make install

For CoffeeScript (get latest release URL):

cd /usr/local/src
wget http://github.com/jashkenas/coffee-script/tarball/0.5.5
tar xfv jashkenas-coffee-script-bcf7b3f.tar.gz
cd jashkenas-coffee-script-bcf7b3f
sudo bin/cake install

Now test that everything is in place:

$ coffee --version
CoffeeScript version 0.5.5
$ coffee -e "sys: require 'sys'; sys.puts 'hello world\n'"
hello world

Phew!

Note, in the command-line/on the server, you are using the NodeJS JavaScript environment. It supports the CommonJS API for loading modules (normal JavaScript: var sys = require('sys')).

Um, but how do I use it in my web app?

Your application source code will have *.coffee files containing your sexy, short CoffeeScript. But at runtime, the browser needs the generated JavaScript.

I’ve been using the Jonas Nicklas’ bistro_car gem:

gem install bistro_car
mkdir -p app/scripts

In your Rails config/environment.rb file, add:

config.gem 'bistro_car'

And in your layouts, such as app/views/layouts/application.html.erb add to the <head> or the bottom:

<%= coffee_script_bundle %>

Now you’re good to go. Add your CoffeeScript files in app/scripts/*.coffee and they will be automatically available as JavaScript.

WARNING: Check your version of CoffeeScript

Check that this hasn’t happened:

$ coffee --version
CoffeeScript version 0.3.2
$ which coffee
/usr/bin/coffee

Arrgh, we should be using /usr/local/bin/coffee. bistro_car currently installs the old rubygem-based version of coffee-script; and you might be unlucky to have your $PATH find the wrong one first.

Either delete it (sudo rm /usr/bin/coffee and restart your shell) or make sure /usr/local/bin is earlier in your $PATH than /usr/bin, where RubyGems installed the old, unnecessary version of coffee command.

Let’s drink the CoffeeScript

Create a file app/scripts/application.coffee with contents:

powers: [1,2,3,4].map (i) -> i * i
alert powers

Load up a view in a browser and see [1,4,9,16]. You win! Throw in some jQuery/PrototypeJS/whatever. Beautiful.

View the source of the page, navigate to public/javascripts/bundle/default.js and you’ll see the generated source:

(function(){
  var powers;
  powers = [1, 2, 3, 4].map(function(i) {
    return i * i;
  });
  alert(powers);
})();

The problem: Heroku doesn’t have CoffeeScript installed

Heroku is a great place to host apps. Though it doesn’t have CoffeeScript installed so it cannot dynamically convert the *.coffee files into JavaScript.

If you want to use Heroku I guess we need to perform the conversion locally and deploy it.

But. In development and integration testing I want bistro_car’s dynamically generated default.js. In production, I need a cached version.

In application.html.haml I use (I can’t keep pretending I use erb):

- if Rails.env.production?
  = javascript_include_tag "coffeescripts"
- else
  = coffee_script_bundle

Now we’re just left with the hassle of automatically generating public/javascripts/coffeescripts.js.

First, a rake task. Second, a git pre-commit hook.

Create lib/tasks/bistro_car.rake:

desc "Generate the cached bundle/default.js file from app/scripts/*.coffee files"
task :bistro_car => :environment do
  path = "public/javascripts/coffeescripts.js"
  puts "Building *.coffee -> #{path}"
  File.open(path, "w") { |file| file << BistroCar::Bundle.new('default').to_javascript }
end

file "public/javascripts/coffeescripts.js" => Dir[File.join(Rails.root, 'app/scripts/*.coffee')] do |t|
  Rake::Task["bistro_car"].invoke
end

Now you can create coffeescripts.js and add it to the repo with:

rake public/javascripts/coffeescripts.js
git add public/javascripts/coffeescripts.js
git commit -m "Initial bundled coffeescripts file"

Now create .git/hooks/pre-commit:

#!/bin/sh

exec rake public/javascripts/coffeescripts.js

And make it executable (and git commit will invoke it automatically):

chmod +x .git/hooks/pre-commit

Phew.

Now, whenever you change a *.coffee script and you are about to commit it, the cached-production-only coffeescripts.js is automatically updated and included in the same commit.

Seems like a clean hack.

Summary

Why not make a library to do this? Well I’m hoping there is a better, cleaner way. Perhaps bistro_car can include a rails generator to package these bits and pieces itself, if my approach happens to be the best way.

Nonetheless, let history record that CoffeeScript is very cool though in the world of Heroku living with it is non-trivial at the moment.

Customized Google Forms

Google Form Customized

Google Forms are a great, free way to collect information from anyone, stored directly into a Google Spreadsheet, and then have Google notify you each time a form is submitted (optionally). The downside is that you can only use one of their pre-packaged themes. You can’t have your company logo and corporate “look”.

Pooey to Google, we say. So we wrote custom_google_forms.

Want to truly customized Google Forms? Fork this repository, customize the CSS, DOM and images, and deploy to Heroku. You can then host/customize any number of Google Forms.

For example, here is an original bare Google Form and here is a fully customized version, including form validation and thank you page.

It’s fully a dynamic, thin layer on top of Google Forms. If you change your Google Form, your custom form application automatically changes.

How to use Google Forms?

Perhaps read this docco? Essentially if you can access Google Spreadsheets, you can create a Google Form (which automatically creates and updates a Google Spreadsheet based on the fields and form submissions).

Fork and Customize

It’s really simple to play with and customize Google Forms. Clone the GitHub project and fire up the Rails server:

gem install github
cd ~/Sites
gh clone mocra/custom-google-forms yourdomain-google-forms
cd yourdomain-google-forms
script/server

Go to http://localhost:3000/google_forms/new and add a Google Form:

My Google Forms - New

The “Slug” is the URL path people will follow. That is, a slug “railsdev” maps to http://forms.mocra.com/railsdev.

The “Form Key” field takes either the Form URL or just the formkey parameter (e.g. dFo0LXQyYmlEV2dXcVJ6WjRweW9vRnc6MA) from when you view the live form.

Press “Create” and follow the slug url to view your Google Form through your own customized style.

Well, initially you’ll see the Mocra style. Let’s fix that.

Default Theme

First, fork the github repository so that you can push your style changes to your own repo.

gh fork
mate public/stylesheets/style.css

Now, edit public/stylesheets/style.css to your tastes.

Please don’t reuse our style. Aside from you looking a bit silly having the :mocra logo at the top, it would be weird if your forms looked like our forms. I guess you might as well have used the default Google Form themes?

Heroku Deployment

Let’s not get fancy, let’s just deploy your fork to Heroku. It’s free. It’s simple. You’ll be done in two minutes.

To get your copy of the application deployed to heroku:

gem install heroku
heroku create yourdomain-google-forms
git push heroku master
heroku rake db:migrate

Two optional environment variables:

heroku config:add GOOGLE_ANALYTICS='YOURCODE'

If specified, Google Analytics will be included on all pages (including the custom Google Forms page).

heroku config:add EXPECTED_DOMAIN='some.yourdomain.com'

If specified, ‘yourdomain-google-forms.heroku.com/someform’ automatically redirects to ‘some.domain.com/someform’.

For example, for http://forms.mocra.com we used:

heroku config:add GOOGLE_ANALYTICS='UA-5370510-4'
heroku config:add EXPECTED_DOMAIN='forms.mocra.com'

Getting Started

Once deployed, go to the /google_forms/new URL and add your first form. Once it is validated and added, you can start using it using the links shown.

Summary

Yay for free, customized Google Forms! Yay for free Heroku hosting!

Bonus: you can configure your Google Forms/Spreadsheet to notify you when new forms are submitted. That’s handy.

Thanks to Odin Dutton, our resident designer at Mocra, who did a great job applying our new theme to the Google Forms DOM structure. It’s wonderful having him on the team!

First 5 Minutes of Stand Up Comedy

I thought you might be interested to see the fruits of my new hobby: stand up comedy.

It should be running in “HD” for 20% more laughs. Video taken by Greg Fairbrother, my awesome Mocra Off Railers co-driver.

I discovered a local Stand Up Comedy Course which started 6 weeks ago. The final “night” of the course was for the 8 of us to do a show for family and friends. I don’t remember reading about that on the sales brochure.

Nonetheless, knowing you had a 5 minute set to perform in front of your family and friends sets the expectation in your mind from day one that you don’t want to be shit. So we listened up, wrote as many jokes as we could think of, and hoped desperately we wouldn’t be a blubbering mess on the night.

It’s not all left to chance. Each week, the funny woman who ran the course, Fiona McGary, made us use the microphone on the stage. Either talk about our week, or list all the funny things you can think of about frogs. Or any other European people.

Each week we boldly attempted to make our other classmates laugh. At the start, they don’t. So I quickly learned to edit and then how to present comedy on stage. I tried to learn it fast because it’s weird telling a punch line, waiting for the laughs, and only being rewarded with a uncomfortable shared silence.

All my jokes started out crappy. So I attempted to edit them into “setup-punchline format”. Another phrase for “edit” is “delete half”. I’m a verbose writer. This turns out to suck awfully for stand up comedy. Or perhaps I should be a concise writer too. Oh the novelty of the idea.

Another way to edit a joke so it is ready for an audience is to delete all of it. Turns out, just because I thought of something funny doesn’t mean anyone else thinks it’s funny. Ewwww, that was an uncomfortable life lesson.

I don’t know anything else and the above is probably wrong too. The last six weeks have been a blur. Lots of practise, lots of editing, lots of writing, lots of testing ideas on Mocra staff when they aren’t expecting it, and weekly doses of disturbing reality at the Tuesday workshops when I realise I still have 10 years of more practise to go before David Letterman might ask me to come on his show. He’ll only be 112 years old by then, so fingers crossed.

I’m very appreciative of the 20+ family and friends who came along for the show. All the comedians were very appreciative of especially Lucas and Chendo who sat at the front and giggled like little girls all night.

Spending the last six weeks with the other noob comedians has been wonderful. It will be fun seeing everyone around the Open Mic rooms in Brisbane.

Finally, and most importantly, thanks to Fiona for running the course, and bumping us forward each week with the subtle phrase “that’s good; though it will need more editing.”