Software dev, tech, mind hacks and the occasional personal bit

Category: Technical Page 7 of 14

Review: “Deploying Rails Applications” by Ezra Zygmuntowicz et al.

Deploying Rails Applications: A Step-by-Step Guide by Ezra Zygmuntowicz, Bruce Tate and Clinton Begin is a good read, if a little dated. It was published in May 2008, and you can see that things have moved on a little in the Rails world since then. None the less, quite a lot of the information is still relevant and useful.

The book covers some basic Rails and version control concerns at the start, then rapidly launches into chapters devoted to Rails hosting options available from shared hosts to virtual and dedicated servers. The advice given is good and is in line with my experiences. Unix configuration is given in depth which would be very handy if you had not set up a server before. Next is a good discussion of Capistrano and automating deployments. The examples all use subversion. However, these days I expect the majority of Rails source code is pulled with Git. There is also a chapter on managing mongrels and setting up monitoring solutions. This is still relevant if you want to use mongrels, however these days Passenger is probably the best choice, and it does not have such complex management and configuration requirements. The scaling out chapter is useful and pulls together handy information including details on MySql replication/clustering. There’s a chapter on deploying on Windows and also some suggestions around performance and profiling.

I haven’t come across another book that brings together a structured collection of useful information to help you move from running rails locally to having a cluster of scalable production servers and the automated deployment process required to support it. Despite being too old to cover Git and Passenger, I’d still recommend having a read of this book if you’re at the stage of planning to launch a Rails site or looking to scale your VPS up to a cluster.

Linux VirtualBox vs Windows for Rails Dev

So yes, everyone has heard that Mac OS X and TextMate is the epitome of Rails development, and that it is so awesome that it brings tears of joy to developers eyes, &c. However, for those of us who either don’t have a Mac, or get to work on client provided hardware (often running Windows), there are a few options available.

Developing on Windows XP, with InstantRails is workable. It is easy to get everything you need and have your apps up and running quickly. However, performance is, well, quite frankly, terrible for anything you do on the command line. Mainly, this bites when running tests, doing migrations, generating files etc. Performance running Mongrel is good enough for development.

What about Cygwin? Subjectively, I found it provided similar speed to Windows Ruby/Rails.

So this brings us to virtualisation. Recently, I’ve been testing out VirtualBox running Ubuntu on top of Windows XP. This has had surprisingly good results. On the same machine, the virtual Ubuntu running Rails tasks has about 4 times (!!!) faster performance, even though it has less memory and system resources!

Here are some stats to give you and idea of the advantage.

Machine is a 2.4ghz quad core, 4gig of memory running Windows XP. Using VirtualBox 2.1.4 for virtualized Ubuntu Intrepid 64 bit, with 1.5gig of memory allocated. Figures are in seconds and approximate (taken with a wrist watch).

  generate scaffold db:migrate with no changes run tests for medium sized rails app
Windows XP & Instant Rails 7 7 25
VirtualBox Ubuntu on same Windows XP 1.5 1.5 6

Some of these commands / tests rely on hitting a MySQL database. However, I’m interested in overall development speed for both platforms, not in Ruby speed in particular, so I think it is fair game to include these in the results.

So if you want to do Rails Dev on Windows, I highly recommend trying a virtual machine running Linux!

Vim with find file for Rails (like TextMate)

In a fit of TextMate jealousy, several months ago, I scoured the web for a way to get find-file functionality info my favourite Ruby/Rails editor, vim. I was very happy to find that Jamis Buck had developed an aweseome plugin do to this. It is a little fiddly to install, but worth the trouble. Here’s some simplified steps to get you going.

  • Install Jamis’s ruby gem
    sudo gem install jamis-fuzzy_file_finder --source=http://gems.github.com
  • Download this fuzzyfinder script and pop it in your ‘~/.vim/plugin’ directory. Note that the most recent versions of this script are incompatible with Jamis’s plugin.
  • Grab the latest version of ‘fuzzyfinder_textmate.vim’ from http://github.com/jamis/fuzzyfinder_textmate/tree/master and pop it in your ‘~/.vim/plugin’ directory

Then, if you want to have a similar sort of light-weight Rails ‘IDE’ I enjoy coding with, see my config files below:

.vimrc

source $VIMRUNTIME/vimrc_example.vim
behave xterm
set nu
set tabstop=2
set shiftwidth=2
set softtabstop=2
set ai
set expandtab
set smarttab
let g:rubycomplete_rails = 1

map f :FuzzyFinderTextMate<CR>
map n :tabnew<CR>
map c :tabclose<CR>
map m :tabnext<CR>

let g:fuzzy_ignore = "*.svn"
let g:fuzzy_ignore = "*.swp"
let g:fuzzy_ignore = "*.jpg"
let g:fuzzy_ignore = "*.gif"
let g:fuzzy_ignore = "*~"

set nobackup

.gvimrc

source ~/.vimrc
set selectmode=mouse
set columns=100
set lines=50

In this set up, there are no chords etc. Instead, when not in edit mode, ‘n’ will open a new tab. ‘f’ will let you find a new file to open in the current tab. ‘c’ will close the current tab and ‘m’ will move between tabs. So in a normal workflow, you might decide to swap the file in the current tab for a new one (simply press ‘f’), or if you need another file open, hit ‘n’ for new tab, and then ‘f’ to load the relevant file. My text description doesn’t do it justice, but I find this works very well to get you to the file you want quickly, and let you have the files you’re interested in open all at the same time.

One last note, remember to start vim/gVim in the root of your rails directory.

Happy Vimming 🙂

UPDATE
These files are now available from my github dotfiles repository, including the gem inside of the vim/gems_required directory.

Slides from REST Talk at St George Bank

Thanks very much to Nigel for inviting me to present on REST at St George Bank in Kogarah, and to ThoughtWorks for the time in the middle of the day to give the talk. It was a fun session and the people attending asked quite a number of good questions. Here are the slides. Please note that they are about 10mb (thanks to all the images). There’s some extra information in the “Notes” pane as well.

Review: RESTful PHP Web Services by Samisa Abeysinghe

Packt Publishing kindly sent me a copy of RESTful PHP Web Services by Samisa Abeysinghe to review. The book’s cover claims that it will help you “Learn the basic architectural concepts and steps through examples of consuming and creating RESTful web services in PHP”. The book succeeds in providing simple steps and examples of creating and consuming web services, but falls short on REST architectural concepts and design principles.

The book starts with a very brief introduction to the principles of REST, and rapidly moves on to a discussion of PHP tools frameworks. The introduction misses some important REST / RESTful web service concepts such as hypermedia, application vs resource state and the relevance of utilising HTTP headers and status codes. Some of the information in the introduction is confusing. For example, on page 12, it says “Resources can have multiple representations that reflect different application states”. This does sound a little odd – resources can have multiple representations, for example, for different requested content types. Representations should reflect resource state, not application state. Also, the coverage of HTTP verbs is misleading, especially when POST and PUT are discussed.

The next couple of chapters discuss PHP support for HTTP, using libraries such as CURL, and XML parsing strategies. The author chooses realistic examples for code samples, such as Flickr and Yahoo Maps clients. The last example given is quite cool – using earthquake latitudes and longitudes from an Australian government site to plot points on Yahoo maps. The example code is generally simple and easy to follow. However, it would have been nice to see some sort of separation between view and data access logic.

The following chapter is a worked example of building RESTful services for a library lending books. It is a good example, and becomes the basis for most future chapters. The resource design and URLs are reasonable, although it may have been nice to have “loans” as resources in their own right. Using links between resources, rather than just relying on known URLs would also benefit the design.

Later chapters cover alternative frameworks such as Zend and WSO2 using the library lending system as an example for code samples. These chapters are useful as they give an idea how the frameworks look when put in practice. It does look as though PHP and frameworks still have significant limitations around routing flexibility from the examples (eg, the .php extension seems to mandatory in URLs). There is also a chapter on debugging with tips around tools and troubleshooting XML parsing issues.

The writing style is generally clear and easy to read. There are occasionally some odd turns of phrase, such as on page 10: “AJAX makes Web applications to become more interactive, faster, and more user-friendly”.

Overall, I would recommend this book to people wanting to write simple URI template based web services or clients in PHP, and also to people interested in getting an overview of libraries and frameworks currently available in the PHP ecosystem. To gain an understanding of the REST architectural constraints and designing good RESTful systems, I would recommend RESTful Web Services, and if you wanted to take it further, digging into Roy Fielding’s thesis and the HTTP 1.1 Spec.

Review: JavaScript – The Good Parts by Douglas Crockford

“JavaScript: The Good Parts” was kindly lent to me by my friend and colleague Dave Cameron. It was a highly informative read, and a good length at just under 150 pages. The aim of the book is to define an elegant, recommended subset of JavaScript that allows you to do everything you need, and work around problems in the language. The book is aimed at people who already have a good grasp of programming in other languages.

I learnt quite a bit from the book. Here are a few of the most important parts that come to mind:

  • JavaScript has function scope, not block scope so it is best to declare variables at the top of functions.
  • It is important to put { on the same line as the block opening keyword (eg, function, if etc) rather than on the next line. Otherwise, you may run into problems with some JavaScript implementations auto-adding ; in the wrong place.
  • Using the === and !== operators are safer and better than the == and != operators as they do no coerce types.
  • The ‘new’ operator is a bad way to make new objects in JavaScript and should be avoided. Functions starting with a capital letter should always be called with the new operator by convention. Failing to do this will add all the functionality of the object you are trying to create to the global object (thanks to the this references)!
  • You can always pass any number of arguments to a function. Extra arguments are not bound to function parameters, missing arguments will be undefined. Inside the function all arguments are accessible using the ‘arguments’ variable which is an array-like object.
  • Lots of things are false. Eg, 0, NaN, empty string, null, and undefined.
  • hasOwnProperty(name) is great in for(property in object) loops to find members of your object rather inherited members.
  • Object.beget(someOtherObject) allows prototypal inheritance from someOtherObject.
  • JavaScript arrays are really just objects with numerical property names and the length property, so if you use a for in loop, you’ll get indices in random order.
  • It is a good idea to ‘namespace’ your code in a single global variable for your application to avoid conflicts with other libraries. Eg, myApp = {}; myApp.myVariable = 5;
  • If you don’t used var, a global variable is created.
  • Closures let you make information private and give you encapsulation.
  • Inner functions have access to the variables defined in an outer function.

Creating objects with private data:

var incrementer = function() {
  var value = 0;
  
  return {
    increment: function (inc) {
      value += typeof inc === 'number' ? inc : 1;
    },
    getValue: function() {
      return value;
    }
  };
};

var myIncrementer = incrementer();
 

Functional inheritance

var mammal = function(spec) {
  var that = {};
  
  that.getName = function() {
    return spec.name;
  };

  return that;
};

var myMammal = mammal({name: 'Fred'});
myMammal.getName() === 'Fred'

var cat = function(spec) {
  var that = mammal(spec);
  var super_getName = that.superior('getName');

  that.purr = function { /* new catty stuff */ };

  that.getName = function { 
    return super_getName() + ' the Cat!';
  };

  return that;
};

var myCat = cat({name: 'Kitty'});
myCat.getName() === 'Kitty the Cat!'

// Helpers

Object.method('superior', function(name) {
  var that = this, method = that[name];
  return function() { return method.apply(that, arguments); };
});

Function.prototype.method = function(name, func) {
  this.prototype[name] = func;
  return this;
};

There were a few things that I thought could be improved in the book. First of all, although the structure was adequate, it did lend itself to repetition. For example, scope is covered on p36 (in Functions section) and p102 (Awful parts), with very similar words. Secondly, I did not find the frequent syntax diagrams added much to the narrative.

Despite these small blemishes, I’m glad to have read Crockford’s book. I now understand much better which parts of JavaScript to use, and how to build good object oriented code in JavaScript.

XML: When to attribute and when to element?

When defining an XML document, when are attributes most appropriate, and when are elements best? This is something that I’ve generally decided based more on intuition than a good set of rules.

Recently, at work, the need has arisen to define quite a few XML message payloads. I’ve also had the good fortune to work with Erik Doernenburg and we had a chat about attributes vs. elements. Largely thanks to Erik, here are some guidelines that could come in handy when making such a decision.

An attribute is best used to represent:

  • an id
  • metadata (eg, like rel and class in HTML)
  • a value from a small, closed set of values which interpreting programs rely on (eg, values that end up as application constants)

If none of the above apply, an element would likely be the best choice.

Green & Red Local Builds (adding colour to the local build process)

build.JPGWell, who doesn’t write tests and do continuous integration (CI) these days? Whether you use one of the many Cruise Control variants, or Team City or some other tool, you most likely get a handy colour coding of builds as either green or red (ie, good, or bad). But, you can take this a step further!

redbuild.JPGOften on .NET projects, we have a little batch file that we run before checking in (often with a pause at the end so it can be run from a shortcut), to confirm that no tests are broken locally. Well, it’s not much fun peering at the ugly Nant output (or whatever build system you use). Instead, it is quite easy to add a couple of lines to your batch file and change the colour of the console to bright Red or bright Green depending on the success of the local build. It is great for telling what the result was at a glance. I can’t claim credit the idea – it was something we used at EDI for our custom build system, but here’s some batch file code I whipped up which I can claim is all mine, every last GOTO of it! Enjoy 🙂

The following code uses NAnt, but you can replace it with MsBuild or any other build tool that returns a status code.

@echo off

color 07

tools\\nant\\NAnt.exe -buildfile:mybuild.build %*

IF ERRORLEVEL 1 goto RedBuild
IF ERRORLEVEL 0 goto GreenBuild

:RedBuild
color 4F
goto TheEnd

:GreenBuild
color 2F

:TheEnd
pause

Slides from ACS REST Talk

Thanks to everyone who came along to the REST talk at ACS tonight. Here are the slides. They are quite a big download (10mb) as a result of all the images. When you review them, you might want to turn on the “Notes” view as I’ve added some text to go along with the image based slides.

Sydney ALT.NET Launched & Ruby Slides

This evening we had the first Sydney Alt.Net meeting. It went really well. Our venue at the ThoughtWorks offices was pretty packed with about 35 interested people coming along. We started with a discussion of news in the .NET space, and then broke for food. After that we had my presentation on Ruby & Rails from a .NET perspective, followed by Richard’s presentation on Rhino Mocks. We ended with a retrospective to gather feedback and thoughts for future meetings. Thanks to everyone for coming along and making it such a great night! And also a big thank you to ThoughtWorks for the venue, food and drink.

Here’s the slides from “Ruby and Rails from a .NET perspective”. It’s a bit hard to give you a transcript of the demos but here is a taste of some of the ruby commands we looked at today.

Basic IronRuby Console demo

4+4
"hello".class
$friends = ["James", "Richard", "Bill"]
$friends.find_all { |f| f.include? "a" }
$friends.collect { |f| f.length }
"-" * 100
$person_type = Struct.new(:name, :age, :sex)
$j = person_type.new("James", 27, "m") 

Iron Ruby Calling WinForms

require 'System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' 
Form = System::Windows::Forms::Form  
MessageBox = System::Windows::Forms::MessageBox  
Button = System::Windows::Forms::Button 

$b = Button.new
$b.text = "Hello Button"
$f = Form.new
$f.controls << $b
$f.show_dialog 

Simple Rails App Demo

rails myapp
ruby script/generate scaffold Person name:string age:integer
rake db:migrate
ruby script/server

Page 7 of 14

Powered by WordPress & Theme by Anders Norén