Over the last week I’ve been learning how to quickly develop simple applications in Rails without looking at API documentation. Each day I’ve been starting from scratch and seeing what I can create in an hour, only consulting documentation when I really need help. The first day I didn’t use scaffolds and I only got creating, reading, and deleting working with a single model. From the second day until today I’ve been using scaffolds. On Friday I got two models with a has_many association and image attachments (using paperclip) working. Each day I start from scratch, not copying or referencing the code from the previous day (though I do save the code). I think starting from scratch each time has helped me learn more quickly than I would if I were to use the last code each time.

Today I went back to working without scaffolds. Since I’ve been trying to read the documentation as little as possible while developing, I had to figure some things out for myself. One thing I had to think of was the list of actions to type when generating a controller. Here is what I came up with:

script/generate controller Planets index new show edit create update destroy

I’m obsessive-compulsive, so not only did I try to remember what actions are used in scaffolds, I tried to put them in an order that makes sense to me. I put index first because index is special. After that, there were two sensible approaches I could think of to order the remaining actions. I could either order by CRUD or order by whether or not the actions have views. Either way, I would use the other ordering technique within groups. I went with ordering first by whether or not actions have views, and then by CRUD. I started with the actions that have views because it’s nice to have them at the top when jumping from a view to its controller.

Here’s my thought process in a tabular format:

Create Read Update Delete
Has View new show edit *
No View create ** update destroy

Notice that there are a couple of holes in the table. The first one (*) is missing because the interface for deleting is built into the index. It doesn’t have to be this way, and in fact varies widely on the web. It could have its own page, or it could be on the show or even edit page (Side note: I think it’s bad UI to put the delete button on the edit page because the edit form doesn’t fit into the workflow of deleting an item. The user may want to look at an item before deleting it to make sure it’s something they don’t need, but they’re unlikely to want to edit an item). The second one (**) is missing because in the simple case reading is achieved entirely through GET requests.

One thing that’s convenient about having the ones without views at the end is that it makes it easy for me to remember which skeleton views to delete after running the generate command. It’s the last three.

It used to take me a minute or a few to remember what actions I need, but now that I have this mnemonic it should only take a few seconds.

Now, I place a certain level of importance on conventions. After I came up with this mnemonic I looked at a scaffold to see how rails orders things. The only difference between my ICRUDCRUD ordering (index, CRUD with views, CRUD without) or ICRUCUD ordering and the standard scaffold ordering is that the show and new actions are swapped. So rails uses the RCUD ordering. Fair enough. I have pontificated on whether the ordering in CRUD makes sense or is a bacronym. Create and read are pretty useless without eachother. Below is the table with the RCUD ordering. I threw index into the empty cell. If you read the first line left to right, then move down, like a book, the order is the same as it is in a scaffold:

The order of actions in a scaffold
index Read Create Update Delete
Has View show new edit *
No View ** create update destroy

Now, how to remember RCUD? Well, remembering to swap C and R is one way, but I prefer to think of a Rails cow chewing its CUD.

rcud

Original image from cerulean5000 on flickr. Used by Creative Commons license.

I just watched Corey Haines’ lightning talk from this year’s acts_as_conference:

He makes a lot of really good points in a short amount of time. One of the things he says is that if we have to look at documentation for a technique, we’re unlikely to use that technique when we’re in a time crunch. I think this is a very good point. Another time when I might not use the documentation is when I’m just dabbling.

To learn things, he suggests doing arbitrary tasks repetitively to get them engrained into our minds.

I spent a number of hours doing arbitrary tasks with vim, and I’ve gotten pretty good at using vim IMHO. I wish I could say I was as good at jQuery, but I haven’t got it down as well despite doing real projects in it. I think perhaps it’s best that I pick an arbitrary task, or at least do a real, but small, task repetitively, or keep trying to improve it, until I start to really get the hang of it.

On a side note, Corey Haines’ has quit working a regular job and started traveling around and pair programming with people in exchange for room and board. He calls himself a Software Journeyman. It will be interesting to hear what he learns from the experience. I hope his journey takes him to Arizona at some point!

I set up vim to use enter to get out of insert mode. This prevents frequently having to reach for the escape key or use a multi-key combination. To insert a new line while in insert mode, I now use shift-enter.

An idea I had this morning is to make shift-enter swap the shift-enter and enter bindings. This way, if I’m in the mode of writing something new without manipulating text, I can push shift-enter once to enter a newline, then push enter for each additional newline, and push shift-enter when I’m done to get out of insert mode.
shift-enter

To implement it, I created a function that toggles the bindings, and added a call to the function to my bindings for <S-Enter>.

function ToggleEnterMappings()
  if mapcheck("<CR>", "i") == "<Esc>"
    iunmap <CR>
    inoremap <S-Enter> <C-o>:call ToggleEnterMappings()<CR><Esc>
  else
    inoremap <CR> <Esc>
    inoremap <S-Enter> <C-o>:call ToggleEnterMappings()<CR><CR>
  endif
endfunction
call ToggleEnterMappings()

Time will tell whether this is a good setup for me. I think if I do single-line inserts much more often than I do multi-line inserts it might.

The other day I went back to an old branch that had about five files that were changed and I only wanted to incorporate two of them into my master branch. In order to just merge in a couple, I used git merge with the –no-commit option.

git merge --no-commit planner

This merges in all changes but doesn’t commit it. Since it isn’t committed, it’s easy to roll back individual files. I ran git status to get a list of files and rolled back several files with git checkout. When I was done, I had only the two files I wanted to merge showing up when I ran git status.

Yesterday I started trying out Vimperator, and so far I’m impressed. It’s a Firefox extension that puts a vim-like keyboard interface on top of Firefox.

After using it for a while, I wanted to turn the bell off, because I find it to be distracting. I turned to the documentation. I quickly found a visual bell option, but I find visual bells to be even more distracting. Then I saw the visual bell CSS style option, which can be set to an empty string for no bell at all. Bingo! Or so I thought.

It turns out that the page flickers when the bell is triggered. This is not the desired effect. So after searching the docs one more time, I unpacked a jar and poked around in the source code of Vimperator.

There’s a beep function in there. I changed the beep function to return false and Voila! It did nothing when you scrolled past the bottom or top of the page.

Rather than keep the code patched, though, I figured out how to implement my change in my ~/.vimperatorrc file. There’s a javascript command for executing a line of javascript. Vimperator’s beep function is in a global “liberator” object. Combining these two bits of knowledge, I came up with the following line which can be added to ~/.vimperatorrc:

javascript liberator.beep = function() { return false; }

It’s simple but it works. It would be nice if completely disabling the bell (including any visual artifacts) were built into Vimperator, but being able to fix it with a one-liner in the configuration file is the next best thing! Kudos to the Vimperator developers for writing code that’s easy to modify.

I’m not sure how often I’ll use Vimperator. I need to learn how easy it is to pass the input through to the current web page first. But it certainly seems to do a difficult job remarkably well!

Update: I started a Silencing and Disabling Bells WikiBook and put instructions for disabling bells in Vimperator, MacVim, and iTerm in it. Contributions welcome!

After watching the Meet Emacs screencast on Peepcode and talking to a few local developers who use emacs, I’ve started using emacs again. Since I started playing around with it several weeks ago, I’ve learned about a number of useful features I either hadn’t used before or had just barely scratched the surface of. These include the following:

  • ido-mode – A tool for quickly finding files that uses a combination of history and intelligent name searching.
  • hippie-expand – Intelligently completes part of a word to match another word in the current buffer.
  • text macros – I’d seen this before but didn’t realize how often it can be done in place of a regex search-and-replace. Much more intuitive, too.
  • C-x C-v – Unlike the more commonly used C-x C-f, which loads a file in a new buffer, visit-file (C-x C-v) loads a file in the current buffer. This solves a common annoyance for me of opening the wrong file in the right directory, and having to choose between leaving the wrong file open or navigating back to the right directory after closing the wrong file.

These are things I wouldn’t have noticed if I had still been blindly following the Pragmatic Programmer tip, Use a Single Editor Well. The problem with picking an editor and sticking to it is that there really isn’t a way to learn how good an editor is without actually using it.

I’m also starting to think that maybe, even after I’ve gained a pretty good understanding of most editors, I still won’t want to pick a single editor. Maybe I’ll use emacs for some things and TextMate for others. Using more than one editor might not be for everybody, but for people who take a serious interest in editors, it might be a good idea.

I put my emacs dotfiles directory up on GitHub, if anyone is curious about the customizations I’ve made to it.

So far I like my new setup, and I’m using Emacs most of the time. I’m getting to be quite comfortable in it. I’ve dealt with a couple of things that used to annoy me most about emacs, which are confusing indentation and inaccurate syntax highlighting. I dealt with the former by setting the tab key to go to the next tab key, rather than use the current mode’s indentation code. To deal with the latter, I just turned off syntax highlighting. I’m actually quite comfortable without it most of the time, and if I really want pretty syntax highlighting, I can always fire up TextMate.

In the future, I may continue to use emacs as my primary editor, or I may not. If not, I don’t think my time learning Emacs will have gone to waste, as I’ll have learned new editor features and I’ll know what to look for when I explore the advanced features of whichever editor I’m using.

Update: I was wrong about the popup preference not working. I had forgotten to turn off popup balloons on one of my computers, and missed a return statement while reading the source code. So my changes are unnecessary.

I am a big fan of twitter. I use it all the time. I follow a lot of people. Some I know personally, some I’ve only met online, and some I have never met. I like to interact with people on twitter in real time.

Of course, the benefits of twitter come at the cost of time. The little bits of time here and there spent reading and posting tweets add up. It can also cause interruptions, making it hard to focus.

twitter.com and twhirl

I used twitter.com at first, then twhirl, and twitter.com again before I discovered TwitterFox.

The biggest problem with using twitter.com is that I have to load twitter.com to check for new tweets, whether or not there are any new tweets. It takes a while to load a web page. Usually that is an interruption in itself. Usually I either miss the action on twitter or I obsessively check twitter.com to see if there are any new tweets. On days when I’m feeling less motivated or more curious about what’s happening on twitter it is usually the latter.

For a month or two I used twhirl to access twitter. There are two different ways of using it, each of which has its own problems. One way is the default, where it pops up new messages in the lower-right corner of the screen. This is the way most desktop twitter clients work. The problem with this is obvious: it’s an interruption, plain and simple. If I’m in the zone, I will likely get distracted. The other way of using twhirl is to turn off pop-up messages, and to either give the window some space on the screen or to switch to it using Alt-Tab to check tweets. The problem with this is it quickly devolves into a glancing or Alt-Tab frenzy, as at any time when I’m even slightly curious about what’s happening on twitter, I can check in an instant. Often times when I would check I would find no new tweets.

the twitter urge

Every so often I get the urge to check twitter. It’s perfectly natural for anyone who has discovered the joy of using twitter. What matters is what I do with those urges. If every urge turns into reading a list of twitter messages, it can turn into a real productivity killer.

For a while I’ve known the way that I would like to be able to use twitter. I would like a number of new messages on the screen. Then, if I got the twitter urge and there weren’t any new messages, it would only cause a split-second of interruption. If there were any new messages, I would know, and if I didn’t check even though there were new messages, I could give myself a pat on the back for staying productive, and know that once I got more work done I would have something to read.

After a week of being frustrated with twitter, I decided to do something about it. So I looked at the list of twitter clients again and tried a couple out. I wanted one that was open source and easy to customize.

TwitterFox

I spend enough time in Firefox, both at work and on my laptop, that having something in the Firefox status bar is pretty much as good as having something in the taskbar, if not better. Firefox extensions are also easy to customize (unless the code is a mess), so I gave it a try. When I saw the number of new tweets in the lower-right corner of my Firefox window, I was elated. This is exactly what I wanted!

It worked really well for me, once I figured out how to turn off popup balloons, where it would show the latest tweet(s) in the bottom-right corner, much like twhirl. At first, I thought the preference wasn’t working, so I made changes to the source code. I found tinkering with the source code to be relatively easy. Since I’m a web developer, I’m very comfortable working in JavaScript.

The tiny difference between TwitterFox and twhirl that makes it work for me is that the number of messages appears on a part of the screen that I see regularly. The information I need is there, and presented in a way that is not distracting. This is also the way I keep tabs on my e-mail (GMail) and my RSS Feeds (Google Reader), though I like the way TwitterFox shows the number better. GMail and Google Reader have the number of new items in their titles, which appear in the Firefox tab bar. Sometime I’d like to find or make extensions that will show the number of new items in those two web apps in the Firefox status bar.

Since I love FireBug, and CouchDB has a JSON API, I attempted to combine the two. My goal was to find a way to use jQuery‘s AJAX functions to create, read, and update CouchDB documents.

Getting Started

The first thing I tried was creating a merb project with a single page referencing jQuery, and accessing CouchDB from there. The browser’s security model got in my way, however. A page on one port on localhost can’t access another port with AJAX. I searched for ways to give a page special permission, but my search turned up empty and I figured that I’d rather not go against the browser anyway, if I could help it.

The next thing I tried was getting a page that references jQuery to be served by CouchDB’s web server. That way the page and jQuery’s JSON API would be on the same port and Firefox would be happy. I opened up CouchDB’s Futon Utility Client at http://localhost:5984/_utils/ and found that it already had the latest version of jQuery included! Problem solved.

I opened the FireBug console (which was already enabled on localhost from when I was trying to get it working with my Merb project) and started trying out jQuery’s AJAX functions on CouchDB.

The GET request returned successfully! However, FireBug doesn’t retain the response, so I have to click Load Response to get it.

OK, there’s CouchDB’s welcome message! Expanding the GET request and clicking Load Response is tedious, though, so a better technique is needed. The first thing that comes to mind is doing a synchronous request. I find that get() doesn’t support this option, so I need to use ajax().

Aside from FireBug’s quoting FAIL, it works nicely. What I’d really like, though, is for FireBug to pretty-print the JSON. So I throw an eval() statement around it, and add the left side of an assignment statement because otherwise I would get an error (another way to get it working is to throw square brackets around the expression).

The output is quite a bit nicer, in my opinion.

Creating a Database

To create a database I use the HttpDatabaseApi page on the CouchDB wiki. Creating a database requires use of a PUT request, which can be made with jQuery’s ajax() function if the browser supports it (and Firefox does).

CouchDB returns a simple OK message to let me know it worked.

Creating a Document

Now that I have a database, I can create a document using the HttpDocumentApi. I opt to take the cavalier approach of having the server generate an ID rather than supplying an ID of my own. To do this, I send a POST with the database’s URL for the address and the document’s contents for the POST data. To send the POST data, I call ajax() with the document’s contents (as a JSON expression) for the data option and the string ‘json’ for the dataType option.

It didn’t work. I expand the POST and look at the data sent to find out why.

The ajax() function didn’t serialize the data! It’s not built into jQuery. It makes sense, given that one of jQuery’s features is its small footprint. I remember that when I viewed the source of the main page of CouchDB’s Futon Utility Client I saw a JSON include. It’s in http://localhost:5984/_utils/script/json2.js. It’s not a jQuery plug-in, but its interface is fairly simple. To serialize data, you call JSON.stringify() with an object as the first parameter. I add this to my statement and try again.

It worked! Or, at least, it didn’t error. It returned a globally unique ID (GUID) generated by the server. Now I use the ID to GET the document’s contents.

Only a summary of the object is shown. If I click the object it expands to a full view.

The data is there. The revision number is also present. One of CouchDB’s coolest features is built-in versioning.

After I realized that I was given only a summary of the object, I tried creating a document again and seeing if I missed any info that was supplied in the response to the POST request. It turns out that I did. The revision (_rev) was given. I’d like to have Firebug print out the whole response (and not a short summary), but I don’t see any way of doing so.

Updating a Document

Documents can be updated by sending a PUT request with the document’s URL as the address and the new contents as the data. The new contents must include the revision number upon which the update is based. This is to prevent conflicts. If a revision number other than that of the latest revision is supplied, it means that another client updated it first.

I update the document by getting the latest copy, storing it in a variable, removing the ID (since it’s already in the URL), changing the radius, and sending a PUT request with the new database contents.

The document is updated. If I expand the object I can see the new revision number.

Pretty cool, huh?

Conclusion & Next Steps

Before I tried using CouchDB with Firebug, I tried using the Futon Utility Client. I felt that I learned more and better retained what I learned when I used Firebug. Firebug as it is right now has a couple of issues that will keep me from using it as an environment in which to try doing different things with CouchDB. The first issue is that the pretty-print doesn’t show the full object in the console view, and there’s no option in the UI to make it do so. The second issue is that I find the editor to be insufficient. When the editor is in vertical mode, there’s no way to go through the history of commands entered. When the editor is in horizontal mode, it can’t expand beyond one line. When I switch between tabs, the text in the editor is often lost.

Firebug is, however, being actively worked on, and will hopefully get some features that will make it easier and more fun to use to play with JavaScript API’s and web services.

I would like to get the custom JavaScript environment mentioned at the top of this post set up and working with CouchDB. One way to get it working might be to set up a proxy of sorts to CouchDB. I could have any requests starting with /couchdb be forwarded to the CouchDB port with the /couchdb part stripped off.

This was fun. I think the next thing I’ll do with CouchDB is try writing a simple wiki using CouchDB and Merb.

I’ve been trying to find clever Ubiquity commands in the Herd. I want to see things that use the preview functionality in interesting ways, like the built-in map command does. What I’ve wound up doing so far, though, is sifting through dozens of commands that do nothing more than what could be done with a custom entry in the Firefox Search Bar, or commands that are nothing but links to another page.

While I think it’s useful to be able to search and go to websites from a command line, it’s not what I have in mind when I search for new commands.

I think that search engines and bookmarks should be separated from the rest of the commands, and that posting search engines or bookmarks as commands to the command part of the Herd should be discouraged. This will help in several ways:

  • Users who don’t know JavaScript will have an easy time adding bookmarks and search engines to Ubiquity and assigning them strings
  • I’ll be able to add search engines and bookmarks from websites without having to look at the code or decide whether I can trust the people who write the code
  • If I provide a bookmark or search engine on my website I won’t have to worry about convincing my users to trust me enough to install it, since it won’t be able to send any information from their browser to my website except for a search query
  • I won’t have to sift through bookmarks and search engines to find commands that provide advanced functionality
  • It will encourage website owners to create more powerful Ubiquity commands

Ubiquity is at an early stage, so I won’t be surprised if someone’s already working on separating simple commands from more complex ones. I hope so. I really want to see Ubiquity catch on, and for that to happen I think it needs to be easier for users to customize their commands.

Today I got a chance to try out Ubiquity. What a neat concept! It’s a GUI command line like QuickSilver, only it’s implemented as a Firefox extension instead of a desktop application.

The demo movie is impressive.


Ubiquity for Firefox from Aza Raskin on Vimeo.

I like how it shows information based on the text typed as I’m typing it. This functionality, called preview, is used extensively in the map command. In fact, most of the time the map command doesn’t even need to be executed, because a small map can be viewed and added to documents without executing a command. I think the preview functionality will be especially useful for looking up programming documentation.

The preview functionality is also used in the built-in twitter command, which posts an update to the microblogging site Twitter. It shows how many characters are left before you hit twitter’s limit. The built-in twitter command, however, uses 160 characters for the limit instead of the 140 character limit on twitter’s website. The 160 character limit for API’s is provided in case a long URL is included in the tweet, which twitter will auto-shorten using tinyurl.

I often post long tweets and don’t want to guess at whether one is going to be too long, so I created my own command, tweet, which uses is.gd for URL shortening. It uses the longest length of is.gd URLs to calculate what the size of URL will be, and bases the number of characters left on that. It replaces any occurrence of the string isgd with an is.gd link to the current page.

It was very easy to write, in large part due to being integrated into Firefox, and having Firefox’s JavaScript environment. It also is written with JQuery and command writers have jQuery available to them.

Ubiquity might not be the embodiment of a totally new concept, but I find that since it’s a Firefox extension, as opposed to being a desktop application, it’s a lot more convenient for me to use and develop for.

When installing Merb on my laptop, which runs Ubuntu Linux, I ran into a compiler error with hpricot, one of Merb’s dependencies. Before bothering to see what might be causing it, I checked to see if there was a precompiled apt-get package available. There was! I installed it and tried installing Merb again.

It still tried to install hpricot, however, and when I said to skip it, it said it could not install Merb because it was missing hpricot. I could have used force, or “pretty please”, but I wanted to instead tell the packaging system that I have hpricot installed.

I seem to remember a UNIX packaging system having an inject command — which tells the packaging system a program is already installed. I may have got the terminology wrong. I searched for such a command for rubygems but couldn’t find one. I did, however, find another way to convince rubygems that I already had hpricot.

I decided to do some digging in the gems directory. To find the gems directory, I typed:

ben@magicthise:~$ gem environment
RubyGems Environment:
  - VERSION: 0.9.4 (0.9.4)
  - INSTALLATION DIRECTORY: /var/lib/gems/1.8
  - GEM PATH:
     - /var/lib/gems/1.8
  - REMOTE SOURCES:
     - http://gems.rubyforge.org
ben@magicthise:~$ cd /var/lib/gems/1.8/
ben@magicthise:/var/lib/gems/1.8$ ls
bin  cache  doc  gems  source_cache  specifications
ben@magicthise:/var/lib/gems/1.8$ cd specifications/
ben@magicthise:/var/lib/gems/1.8/specifications$ ls
abstract-1.0.0.gemspec          merb-cache-0.9.2.gemspec
actionmailer-2.0.2.gemspec      merb-core-0.9.2.gemspec
...
ben@magicthise:/var/lib/gems/1.8/specifications$

I took a look at the gemspec files and found that they contained the name and version of the library. I copied the smallest of the files to hpricot-0.6.gemspec and used the gemspec documentation to find out which parameters are required. I wound up with the following in /var/lib/gems/1.8/specifications/hpricot-1.6.rb.

Gem::Specification.new do |s|
  s.name = %q{hpricot}
  s.version = "0.6"
end

I tried running:

ben@magicthise:~$ gem install merb --include-dependencies

And it worked!

It might not be everything that’s needed to get it working — but now I at least know how to inject a package.