Moving to brandon.dimcheff.com

I’ve drank the static site generation kool-aid and decided to move my blog to Jekyll-powered brandon.dimcheff.com. My new blog has all the content of this one, but this one will no longer receive new posts. This site will stay up for a while, but will eventually redirect to the new site.


About this entry

tasteb.in is up!

I’ve been working on a Merb-based recipe paste site for the past couple weeks called tasteb.in. It’s extremely simple for now. It lets you paste recipes in a very simple format and they show up on the site. You can access your recipes and all recipes on the site. And that’s about it.

I’ll be going into more details about how tasteb.in is built and where I’d like to take the site, but for now, just play with it if you like. Drop me a line with any problems you have, or features you would like to see.


About this entry

Play in the Sandbox

I needed to test some code that reads and writes files on the filesystem. I got sick of manually setting up a scratch area for my test files and cleaning them up when I was done, so I created Sandbox to keep my tests DRY.

See the Sandbox readme for more information, but the basic idea is this:

1
2
3
4
5
6
7
8
9
10
# inside a test somewhere

Sandbox.play do |path|
  file = File.join(path, 'foo')
  FileUtils.touch(file)  # build a sand castle

  assert File.exists?(file)  # test whatever you want in here
end

assert !File.exists?(file)  # path has been deleted

The project is currently only on github, but it will be on RubyForge once approved. If you want to use it now, you have to use the github gems source or install it from source.

Future plans

  • Optionally Dir.chdir to the temporary directory for even easier usage
  • Supply a template directory/archive to be used for the base state of the sandbox

About this entry

How to learn Ruby

Several people have asked me for tutorials, books, and other resources to help them learn Ruby, so I’ve attempted to compile a list of resources I feel are particularly valuable for beginning Rubyists. None of these resources are Rails-specific, but being a good Ruby programmer will obviously help you use Rails more effectively. If there is interest, I will compile a similar (and likely longer) list of Rails resources.

Also, if I’ve missed anything that helped you learn or teach Ruby, please leave a comment and I will add it to the page. I am especially interested in resources that beginning Rubyists have found useful.

For these resources, I assume you already have programming experience and are attempting to pick up Ruby to widen your skillset. If you’re new to programming entirely, check out Chris Pine’s Learn to Program online tutorial.

Online Resources

The following is a list of freely available online resources that I’ve found particularly helpful for new Rubyists.

Ruby Koans: The newest kid on the block (no pun intended) that’s taking github by storm is EdgeCase’s Ruby Koans. The Koans are essentially a series of failing test cases that you need to figure out how to fix in order to move on to the next step. The best way to learn anything is by doing, and this tutorial will get you programming in no time flat.

Note that the point in the exercise is not to fix all the tests as fast as possible. In order to get the benefit of this exercise, you must read and understand what the code is showing you. Complete each Koan one by one. Run your tests after each time you change your code.

I think the best way to use these Koans is to get in a small (2-3 person) group and take turns solving the problems. Discuss what you are doing with each other. Don’t take anything for granted.

Why’s Poignant Guide: Why the Lucky Stiff put together an extremely silly tutorial on Ruby. While it may seem a bit campy, it really is a good tutorial. And it’s a lot of fun!

Ruby Quiz: Once you get your feet wet, you might want to check out the Ruby Quiz archives. There are over 150 small programming challenges that you can try to solve using Ruby. Don’t cheat and look at the answers before you try it for yourself!

10 Things Every Java Programmer Should Know About Ruby: If you’re a Java programmer trying to learn ruby, you should check out Jim Weirich’s 10 things presentation. He goes over many important differences between Java and Ruby, and this can really help you avoid mistakes that many Java programmers make when transitioning to Ruby.

The Humble Little Ruby Book: Jeremy McAnally’s free introductory online Ruby book. Covers the basics about a lot of stuff that every Ruby programmer needs to know. Also available in print.

Books

The following books are, in my opinion, the best books for aspiring Rubists to check out. None of them are Rails specific.

Beginning Ruby: From Novice to Professional: Peter Cooper’s Beginning Ruby book has received rave reviews, and is specifically targeted at beginning Rubyists. I’m a bit ashamed that I didn’t pick it up on the first pass at this article. Sorry Peter!

Programming Ruby: The Pragmatic Programmers’ Guide, Second Edition (aka. The Pickaxe): This book has been the gold standard of Ruby books for years, and is a must have for ruby programmers. It has both a descriptive section and a reference section. The 2nd edition is from 2004, however, and does not cover Ruby 1.9 at all. The 3rd edition is available in beta, and the final version will be available in March.

The Ruby Way: Hal Fulton’s book is full of solutions to common problems, plus it really helps you learn many of the Ruby idioms that are used by experienced Ruby programmers. Ruby 1.8 only.

The Ruby Programming Language: Written by the creator of Ruby himself, this book covers ruby 1.8 and 1.9. It’s not a tutorial-style book, nor a complete reference, but more of description of the important parts of the Ruby programming language. It’s a great second book (after the Pickaxe) to help you understand more details about how Ruby works.

The Well Grounded Rubyist: David Black’s newest book The Well Grounded Rubyist is available in pre-release form. It’s in tutorial form, which is generally good for beginners. I have not had a chance to read it yet, but his last book was great and I hear this one’s even better.

Note: This is a work in progress. I will be updating it over the next few days as I get feedback and do more research. I also don’t necessarily want an exhaustive list of every ruby resource. I’m looking for resources that are helpful for beginners. Too many choices may be overwhelming.


About this entry

Sinatra block parameters!

The latest master Sinatra now supports optional block parameters. It captures any parameters in the URL and passes them into the block that defines the action:

1
2
3
get '/hello/:name' do |n|
  "Hello #{n}!"
end

The params hash is still available as before, so this should not break any existing applications. It will also work with regular expressions. Any captures are yielded in order:

1
2
3
get %r{/hello/([\w]+)/([\w]+)} do |a, b|
  "Hello, #{a} and #{b}!"
end

Big thanks to rtomayko for accepting my patch, and working with me to get this solid enough to put into Sinatra!

One final note: this feature behaves slightly differently in ruby 1.8 and 1.9. Ruby 1.9 is much stricter about block arity than 1.8 is. If the number of captures in the URL and the arity of the block do not match, 1.9 will raise an exception. 1.8 will likely just ignore the extra parameters and throw up a warning. If you write code that is compatible with 1.9, it will also work with 1.8, as ruby 1.9 is simply more strict.


About this entry

Run specs with autotest, er, autospec!

It seems that it’s not well publicized, but if you want to run your RSpec files with autotest try autospec instead. It looks inside the spec/ directory for files named “*_spec.rb” by default for specs. autospec is part of the RSpec gem, and basically just sets up the proper environment and then shells out to autotest.

Also, if your files in lib/ match up with specs in spec/, autospec will automatically re-run your specs for changed files in lib/ on save. So if you have lib/foo/bar.rb, autospec will re-run lib/foo/bar_spec.rb when you save bar.rb.


About this entry

Gearing up for CodeMash

I’m getting all packed for CodeMash! Hope too see a lot of you there. I’m a little bit disappointed by the dearth of Ruby sessions, but there are enough of us that the open sessions will be rockin’. And the ever popular scotch track always helps.

CodeMash


About this entry

Commit a linear git history to subversion

Update: Deskin points out that there is a commit to git that fixes this problem by adding a --root option to rebase --onto. So when you get a new build of git, you can probably ignore everything here.

The other day I needed to commit a plain old (git-svn free) git repository to subversion. Why, you ask? I had been working on a small project at work in my own little git repository and needed to get it into our official version control. I could, of course, just commit the latest version that I had, but that would not record any of my git commit history in subversion. I needed a better option. git-svn can save each individual commit of a linear commit history to subversion, so I figured I could just apply git-svn metadata to my repository and go from there.

This post is a bit long, as I explain the whole process for the solution. If you’re interested in just the solution, scroll to the bottom.

I’m going to create a small git repository for illustrative purposes:

    $ git init
    Initialized empty Git repository in /Users/bdimchef/testgit/.git/
    $ touch foo
    $ git add foo
    $ git commit -m "added foo"
    Created initial commit 95d1297: added foo
     0 files changed, 0 insertions(+), 0 deletions(-)
     create mode 100644 foo
    $ touch bar
    $ git add bar
    $ git commit -m "added bar"
    Created commit 202b5c7: added bar
     0 files changed, 0 insertions(+), 0 deletions(-)
     create mode 100644 bar
    $ touch baz
    $ git add baz
    $ git commit -m "added baz"
    Created commit 58d6331: added baz
     0 files changed, 0 insertions(+), 0 deletions(-)
     create mode 100644 baz

For this howto, I’m using a blank subversion repository, but you can use this method with any subversion repository that has an empty directory to put your new project.

    $ svnadmin create /Users/bdimchef/testsvn
    $ svn mkdir file:///Users/bdimchef/testsvn/trunk
    $ svn mkdir file:///Users/bdimchef/testsvn/branches
    $ svn mkdir file:///Users/bdimchef/testsvn/tags

Then, I added my svn metadata to my git repository and fetched the contents of svn:

    $ git svn init -s file:///Users/bdimchef/testsvn
    $ git svn fetch

Now I was ready to commit:

    $ git svn dcommit
    Can't call method "full_url" on an undefined value at /opt/local/libexec/git-core/git-svn line 425.

What this error means (in our case) is that it can’t figure out where to dcommit. If we try to rebase, it’s clearer what the problem is:

    $ git svn rebase
    Unable to determine upstream SVN information from working tree history

Our problem is that we have two disjoint histories in our git repository: The history that we made in git, and the history from our svn repository. Since they share no common ancestors, git svn can’t figure out where to commit its changes. Take a look at gitk to see what’s going on here.

It turns out that this problem is pretty easy to fix with svn rebase. But there is one little trick that will get you if you’re not careful. And before we get carried away doing too many rebases, lets just make a backup branch of master just in case.

    $ git branch master.bak master

Lets try one approach. git rebase --onto A B C takes the commit range B..C and puts it onto A. In this case, we want to take all our commits and put them on to trunk:

    $ git rebase --onto trunk master~2 master
    Applying: added bar
    Applying: added baz

Oops! That only applied bar and baz. It forgot about our first commit, foo. Lets go back one more.

    $ git rebase --onto trunk master~3 master
    fatal: Needed a single revision
    invalid upstream master~3

Well, that didn’t work either. The problem is that git rebase --onto rebases the range beginning after commit B. In this case, the commit after foo, which is bar. And there is no commit before foo, so there’s no way to rebase a range starting with foo included. The simple solution to this problem is to git cherry-pick foo first, then do the rebase. First we’ll create a named branch for our rebase.

The Solution

    $ git co -b svnrebase trunk                    # create a temporary branch
    $ git cherry-pick master~2                     # cherry pick the first commit
    $ git rebase --onto svnrebase master~2 master  # rebase the 2nd through current commit
    $ git svn dcommit                              # finally commit the results to svn

And that worked! So, generally, the secret to joining two separate histories together is to cherry-pick the first commit, and then rebase the rest on top of it.

Thanks to charon on #git for the cherry-pick idea.


About this entry

Use Capistrano to set your production database password

This is a Capistrano recipe I use to configure my production database.yml. Before deploy:setup executes, this recipe will prompt for a database password and save a new database.yml file to the shared directory on your server. After each deploy, the database.yml file will be symlinked from the shared directory. You can reconfigure your database by executing cap db:configure.

Here are the goods. I’m pretty sure I got this from Jeremy Voorhis a while back, and modified it to work with Capistrano 2.


About this entry

Resolutions

I generally think that new year resolutions are silly, but since it’s the new year and I have some goals I’d like to set, I guess I might as well call them resolutions.

Since goals, like technical requirements, are meaningless if you can’t measure them, I’ll be as specific as possible even if it means that I’ll have to adjust them later. So here we go:

Resolved:

  • I will blog at least once a week. Corollary: I will blog within one day of saying to myself “Hey, I should blog about this”
  • I will contribute a patch to an open source project at least once a month
  • I will start a useful open source project by April
  • I will write my blog from scratch by July so I can do it just the way I want
  • I will do Project 365. Seriously this time.

and perhaps most importantly:

  • I will have my next form of gainful employment arranged by January 23rd.

This blog post does not count towards resolution #1, and I’ve got a decent backlog of items to write about, so you’ll be hearing from me soon.

Happy new year!


About this entry

Ruby Hoedown Videos Online

Ruby Hoedown 2008 videos are now live. There are a lot of good talks. I highly recommend checking them out. I’ve set up a torrent of all the videos for your convenience.


About this entry

Make RubyMate work with MacPorts Ruby

To make TextMate’s RubyMate work with MacPorts (or any other non-default ruby install) just set TM_RUBY environment variable to be the path to your custom ruby interpreter in TextMate’s preferences. Custom environmental variable settings are located under ‘Advanced’->’Shell Variables’ in TM’s prefs.


About this entry

Test behavior, not implementation!

This is a based on a comment I made on a post on thoughtbot’s blog. I suggest you read the original post for some background on what I’m talking about.

If you’re too lazy to read, here’s the basic gist: You could potentially test your associations or plugins (such as acts_as_solr) by simply checking whether or not your object responds to the messages that the plugins generate when their class methods are called.

The problem is, we should be trying to test behavior, not simply whether or not acts_as_solr or has_many are being called. The problem with the approach described above is that it assumes too much about implementation details and doesn’t actually make sure your app is doing what it’s supposed to be doing.

In this case, I think that find_by_solr should be called find_by_content or something, since it doesn’t really matter that it’s solr that’s doing the lookup. All the developer using the API cares about is that when they pass a particular query into the method, the proper results are returned. And that is what our tests should test.

I am not convinced that (as many test/rspec examples show) simply checking for association methods (has_many, belongs_to, etc.) or plugin methods (acts_as_solr) are sufficient, or even a good idea at all. Nor do I think that those sorts of tests qualify as BDD. For instance, I have something resembling the following in an application per someone’s suggestion:


Person.reflect_on_association(:addresses).should_not be_nil

I really don’t like this, though. I don’t care one bit that there’s an association called “addresses” on my Person object. What I care about is that Person responds to addresses and that addresses returns an array of the proper addresses. This is the whole point in BDD. Care about the behavior of your objects, not their implementation.

To explore this further, I’ll use a slightly more complicated example. Say I have the following in my Person class:

1
2
3
# app/models/person.rb
has_many :addresses
has_many :cool_addresses, :foreign_key => "address_id", :conditions => ["foo = ? AND bar = ?", foo, bar], :order => :zipcode

And the corresponding test case:


Person.reflect_on_association(:cool_addresses).should_not be_nil

Well, guess what. This association exists. Our tests pass. But it’s wrong. That :foreign_key is supposed to be person_id and not address_id. Well, we can solve that! Just test to make sure the has_many receives the appropriate parameters. Something like this (made up) helper would work:


Person.reflect_on_association(:cool_addresses).should have_foreign_key("person_id"))

And we could go about our business, basically duplicating all the parameters supplied to has_many in our tests. But in the end, this is just going to make our tests horribly brittle and is not actually testing anything useful. It’s not testing behavior at all.

The whole point in BDD is to make our tests poke and prod our application in a certain way and have them spit back the correct output. Yes, the plugins/associations are well tested and I shouldn’t be testing them again. I know that if my has_many call supplies the correct parameters, I will get the objects I expect to get. But I still need to make sure that I’m calling has_many properly. It’s simply not sufficient for me to know that has_many is called, I need to know that when it’s called, the proper “stuff” happens. I need to make sure the association does what I expect it to do. Here’s what I think my tests should do to ensure cool_addresses is working properly (no real code this time):

  • Add a few objects to the Addresses table, either using fixtures or in some kind of before callback. (Yes, fixtures suck, etc.)
  • Make sure cool_addresses returns addresses that correspond to the ‘foo’ and ‘bar’ conditions above.
  • Make sure that cool_addresses returns the addresses ordered by zipcode.

And that’s it. Yes, it will take the tests slightly longer to run, since they’re using the database (and maybe fixtures). Yes, I’m partially testing ActiveRecord. But I’m testing that my object behaves like I want it to. That’s the point in BDD, right?

As an added benefit, the tests are much more flexible now. Check it out:

1
2
3
4
5
6
7
# app/models/person.rb
has_many :addresses
#has_many :cool_addresses, :foreign_key => "address_id", :conditions => ["foo = ? AND bar = ?", foo, bar], :order => :zipcode

def cool_addresses
  addresses.find_all do {|a| a.foo == foo && a.bar == bar}.sort(&:zipcode)
end

That passes my tests, too. And it should. But my previous example where I used association introspection would fail miserably.

This is a major complaint about a lot of the test code examples I see floating around. Everybody seems to be mocking and stubbing and introspecting to their heart’s content, but all they seem to be doing in the end is writing the same code twice: once in their implementation, and once in their tests. And so when they change the way their application is implemented (NOTE: I did not say their application’s behavior) their tests break.

There are two sides to this BDD thing. First, your tests need to ensure that if you change the behavior of your code, they will fail. Second, your tests need to still work when your application still behaves the right way, even if you change every single line of code in your application. Of course, this is nearly impossible to achieve, but at least we can try.

Thoughts?


About this entry

Predefined models? No different than any others.

Earlier today I was trying to figure out how to make a list of potential models to be created. For example: I have some Users and some Groups. I have a many-to-many Membership join model with some has_many :throughs. The fundamental goal is to provide the user an interface to add Membership models that link a User to a Group. I could use a bunch of checkboxes, but I’d rather pull up a list of possible Groups with little “add” links next to them.

Since I’m using RESTful controllers, we have a MembershipsController that implements all the standard methods. We’re also nesting our routes such that MembershipsController nested beneath the UsersController. In order to create the Membership, we need to POST to /users/1/memberships. But how do we get a list of Memberships that we can quickly add?

How about modifying MembershipsController.new? We don’t need the normal definition of new, since we’re never going to be manually creating a new Membership.

1
2
3
4
5
6
# controllers/memberships_controller.rb
def new
  @memberships = Groups.find(:all).collect do |group|
    Membership.new(:user_id => params[:user_id], :group_id => group.id)
  end
end

Now we have a list of potential Membership objects available to our view. Remember, the Memberships haven’t been saved yet. They’re just there for convenience for holding attributes. We are doing object-oriented programming after all.

1
2
3
4
5
6
7
8
# views/memberships/new.html.erb
<% @memberships.each do |membership| %>
  <% form_for :membership, membership, :url => memberships_path do |f| %>
    <%= f.hidden_field :user_id %>
    <%= f.hidden_field :group_id %>
    <%= f.submit membership.group.name %>
  <% end %>
<% end %>

Basically what we have here is a big list of predefined join models wrapped up in form tags. When you click on one of them, you’ll end up submitting the form that actually creates the model. Eventually, we could make this into an AJAX widget that uses form_remote_for with very little effort.

Nothing I have described here is particularly revolutionary. Rather than just returning a single new Membership in the new method, we return a list of objects. Rather than rendering one form with editable fields, we render multiple forms with predefined, hidden fields. Whichever you submit creates the corresponding object. These two very simple changes to the standard REST actions allow us to easily and elegantly create our join models.


About this entry

Installing a Rails stack on Mac OS X with MacPorts

I have a clean install of OS X on which I need to install Rails. I’ve done this maybe 3 or 4 times in the past year with minor variations each time which inevitably come back to bite me later. This post is an effort to document and standardize all the details to get a Rails stack going with MacPorts.

Installing Xcode Tools

You need the latest version of Xcode tools to be able to compile all the packages necessary for Ruby and Rails. They’re a free download from Apple.

Installing MacPorts

First thing’s first: Install MacPorts! Be sure to follow the directions closely. Especially the bit about setting your PATH appropriately. The /opt paths must be before your standard path so when you type ruby, you use the ruby interpreter from MacPorts rather than the old one that came with OS X.

Installing Rails Prerequisites with MacPorts

$ sudo port install mysql5 +server
$ sudo port install ruby
$ sudo port install rb-rubygems
$ sudo port install rb-mysql
$ sudo port install rb-termios
$ sudo port install subversion +tools

Configure MySQL

First, add /opt/local/lib/mysql5/bin/ to your PATH as you did in the instructions to install MacPorts.

$ sudo mysql_install_db5 --user=mysql

Install Gems

$ sudo gem install -y rake
$ sudo gem install -y rails
$ sudo gem install -y capistrano
$ sudo gem install -y mongrel
$ sudo gem install -y mongrel_cluster
$ sudo gem install -y piston

Install Optional Packages

The above ports and gems are the minimum you’ll need to get rails running successfully. The ones below, while not required, are often useful when developing rails apps.

Other Databases

Try postgres or sqlite3 for some database variety (port install postgresql82-server && port install rb-postgres or port install rb-sqlite3, respectively).

Testing

Misc


About this entry