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

Author: James Page 9 of 20

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.

An Island to Oneself by Tom Neale

While in the Cook Islands, we went to the National Museum and it was there that I first heard about Tom Neale and saw reference to him on a census of island populations from the 1950s (“Suvarov: population 1” with a footnote saying “Tom Neale”!). He was the only inhabitant of Suvarov, an atoll in the Cook Islands, having done what many people only dream of. He left civilisation and moved to a beautiful, deserted island in the Pacific, replete with coconut trees, jungle, and an azure lagoon. Not only that, but he survived and prospered there and wrote an amazing autobiography of the time, called “An Island to Oneself”.

I tried to borrow “An Island to Oneself” from the National Library on Rarotonga (there is only one library on Rarotonga!) but unfortunately all copies were out. So, I turned to Amazon (the long tail poster child), and was very happy to find they could source me a copy. I don’t want to spoil the tale, but recommend you have a read if you have ever thought about what life would be like on a desert island, surviving only by your own wit and skills, hundreds of miles from civilisation!

UPDATE (6 Jul 2016): Thanks to Don Hirst for this link to the full book online.

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.

Wing Chun Notes

Stance

  • Lift up through body. Imagine your body is hanging from a thread from the middle of the top of your head
  • Shoulders should be relaxed and down
  • Knees springy (ie very slightly bent so you can bounce up and down)
  • Tie gung on – tensing core muscles and rotating pelvis up slightly (bottom of pelvis goes forward)
  • core muscles tensed, rest of body relaxed

Moving

  • Get into stance
  • Move with weight centred between legs, not on one foot or the other
  • When you move forward, your core/waist should move forward in time with the leg. Ie, leg should NOT lead and then pull body forward.
  • Waist should be driving the leg movement, which means your weight still stays balanced between your legs
  • Legs should be light and relaxed, body is being drawn up by the stance

Speed
When punching or kicking, you arms and legs should be completely relaxed, although tie gung should be on. If completely relaxed can move faster. Imagine swatting a fly.

When moving in, trust your wing chun. Moving in should be almost like getting pushed from your waist from behind. Legs relaxed, high acceleration, full weight moving forward, taking the space they currently occupy.

Pivoting
Pivot so that both feet finish moving at the same time. Move from the waist.

Guard
Guard should be with arms relaxed and fingers pointing forward towards your opponent’s centre line where the neck meets the trunk, to give even time for high and low attacks.

Defending against head punches
Think primarily of hitting the opponent with your punch/strike, as this will cripple the attack. The dai sau is secondary. Dia sau should keep sheering upwards on contact. It should be a rotation in the shoulder joint, your angles should not collapse. Your shoulder should always be down and the ball of the joint rotating at the back of the joint. Dia sau should be inscribing an even circle of your space. Contact should be shearing with the hard side bones of your arm against the inside of their wrist. Wrist should always stay on centre. Your fingers may be pointing towards the opponent’s head near the end of the move, or your hand may be above your head, depending on strength and hookedness of the attack.

Hook Kick
You really need to swing your hip into a good hook kick. Your leg should go up quite high as it swings around and then drive down into your opponent’s thigh / leg. In close, you may contact with your knee, with more distance, you should be contacting with the front of your lower leg (above ankle, but below knee).

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

Cook Islands Holiday

The Cook Islands are an awesome place to visit to chill out and relax. We stayed there for two weeks and had a great time, coming back much refreshed. We only visited Rarotonga, the largest island which has about 14,000 people, and a coast line of around 32km. Basically it is a volcanic island surrounded by a large, shallow reef with bath-water warm water and lots of little uninhabited motu (islands) to explore. Around the edge of the island are beaches and flat land where people live, usually in houses with large gardens, lots of coconut and mango trees, and vivid tropical plants. In the middle of the island are tall mountains covered in jungle. It is a great place for water-sports such as kayaking, fishing, swimming and snorkelling, and there’s also some fairly hard core walking tracks to explore in the jungle. Prices are reasonable, though food tends to be quite expensive as most of it comes in from New Zealand. The Cook Islanders maintain their culture very strongly and put on enjoyable performances and feasts that you can attend (often called “Island Nights”).

Cook Islands Fruits of Rarotonga

Cook Islands Water

Cook Islands Motu

Cook Islands Sunrise

Cook Islands

Our Feet

Cook Islands Jungle

Soosun of the Jungle

Cook Islands traditional dancing

Cook Islands beach at sunset

Also, more Cook Islands photos here.

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.

Page 9 of 20

Powered by WordPress & Theme by Anders Norén