Archive for 'Coding'
Deploy a specific revision with Capistrano
Posted on August 6, 2010, under Coding.
Just about every website that I release, be it at work or at home, is stored in a Git repository, and deployed using Capistrano.
I’ve been debugging this PHP application at work that was written by a 3rd-party. After cleaning up the XSS and SQL injection vulnerabilities in it, we found a new bug. It’s minor, yet important.
While tracking down the offending line, I needed to deploy various revisions of the website. It turns out that it’s really easy to do this with Capistrano:
$ cap -S revision=3f30b6de3c55a8347e5f3de3b43193591e6c7322 beta deploy
One thing I noticed was the need to provide the full SHA-1 object name (AKA revision ID, commit ID). Normally with Git, you can provide the first few characters of a commit ID. For example:
$ git checkout 3f30b6de
instead of
$ git checkout 3f30b6de3c55a8347e5f3de3b43193591e6c7322
I guess Capistrano’s a bit more picky!
Matching Printable Characters
Posted on November 30, 2009, under Coding, GNU/Linux, Uncategorized.
Who doesn’t love regular expressions? They’re fucking awesome. I use’em at least 10 times per day.
Sometimes, there’re restrictions on what patterns you can use. I wanted to change a regex for validating passwords. Originally, it allowed letters, numbers, and a seemingly random collection of special characters. How lame is this?:
^[A-Za-z0-9]{1}[A-Za-z0-9_\\.\\!\@\#\-]{0,255}$
Not only are the allowed special characters arbitrary, but they’re escaping characters in a character class, and using “{1}”.
I tried changing the regex to this:
^[[:print:]]{0,255}$
Unfortunately, that wasn’t considered “valid” by the system in question. Luckily, there’s a fairly concise alternative:
^[\x20-\x7E]{0,255}$
If you find a system that lacks support for POSIX character classes, check out this Wikipedia article.
Hashes and Frozen Keys
The hash class freezes keys that are strings:
This can be a problem if you want to use those keys later on…more specifically, if you want to extract and edit those strings:
Unfortunately, those strings will have to be duped or cloned:
Sinatra and Passenger/mod_rails
If you want Apache to serve up a Sinatra app, your best bet is to use Passenger (AKA mod_rails).
All your app needs is the usual Rackup config file (config.ru) in the app’s root directory, and the directory public/ .
There’s one caveat, though: if you have a file named environment.rb , do not put it in config/ .
If mod_rails finds config/environment.rb , it’ll think your app runs on Rails:
Ruby in Etch
As some of you may know, Ruby and Debian’s ways of packaging software go together like Darwin and religious zealots…as in, they don’t. So how should you install Ruby when using Debian Stable? How do you stay up-to-date with new versions of Ruby and gems?
By using Backports, and not worrying so much.
First, setup your box to be able to install backports of packages. Next, uninstall any Ruby-related packages. Yeah, that’s right. Do you know why? Because, if you’re running Etch, you’re using Ruby 1.8.5! Egad! That’s almost medieval. Make sure to uninstall irb and rdoc, too.
Now it’s time to install shinier versions…1.8.7, to be exact:
$ sudo aptitude install -t etch-backports libruby1.8 ruby1.8 rdoc1.8 irb1.8
All of that should be on one line.
There you have it. Now you’ve got Ruby 1.8.7 on Debian Stable (AKA “Etch”). Ruby’s not complete without RubyGems, though. Download the latest version to /usr/src/ , and extract it:
$ cd /usr/src/$ wget http://rubyforge.org/frs/download.php/45905/rubygems-1.3.1.tgz$ tar zxf rubygems-1.3.1.tgz
Then run the setup utility:
$ cd rubygems-1.3.1/$ sudo ruby setup.rb
Let’s do one last thing to make life easier. The RubyGems setup script installed the “gem” command as /usr/bin/gem1.8 . I don’t want to have to type that “1.8″ every time.
$ cd /usr/local/bin/$ sudo ln -v -s /usr/bin/gem1.8 gem
There. Now we can run “gem” like the rest of the world.
Easy? Yar.
Default stegosaurses
Ever heard of Jonathan Viney’s active_record_defaults plugin? It’s fantastic. In a nutshell, it enables you to specify default values for model attributes. If an attribute isn’t set when initialising a new instance, the attribute’s set to whatever the default value is.
For example, let’s rebuild that Stegosaurus class from a previous post:
class Stegosaurus < ActiveRecord::Base attr_accessible :tail_spikes, :back_plates validates_numericality_of :tail_spikes,nly_integer => true, :greater_than_or_equal_to => 0 validates_numericality_of :back_plates,
nly_integer => true, :greater_than_or_equal_to => 0end
With that, if we created a new Stegosaurus and didn’t specify any attributes, not only would it have no tail spikes or back plates, but the model instance wouldn’t be valid.
To fix that, all we need to do is add two lines:
class Stegosaurus < ActiveRecord::Base attr_accessible :tail_spikes, :back_plates default :tail_spikes => 4 default :back_plates => 6 validates_numericality_of :tail_spikes,nly_integer => true, :greater_than_or_equal_to => 0 validates_numericality_of :back_plates,
nly_integer => true, :greater_than_or_equal_to => 0end
And voila, new Stegosaurus objects will automatically have 4 tail spikes and 6 back plates:
>> s = Stegosaurus.new=> #<Stegosaurus tail_spikes: 4, back_plates: 6>>> ?> s.tail_spikes=> 4>> s.back_plates=> 6
However, if used improperly, this can lead to several hours of pounding your head on your desk. Note that that the default values we used above, 4 and 6, are immutable objects. You can’t change them. You can perform operations on them, such as addition (4 + 1), but that never changes the object.
Say we want our Stegosaurus class to have an array specifying its diet that defaults to “fern” and “cycad”:
class Stegosaurus < ActiveRecord::Base attr_accessible :tail_spikes, :back_plates, :diet default :tail_spikes => 4 default :back_plates => 6 default :diet => %w(fern cycad) validates_numericality_of :tail_spikes,nly_integer => true, :greater_than_or_equal_to => 0 validates_numericality_of :back_plates,
nly_integer => true, :greater_than_or_equal_to => 0end
That looks right. But watch this:
=> charles = Stegosaurus.new=> #<Stegosaurus tail_spikes: 4, back_plates: 6, diet: ["fern", "cycad"]>>> ?> arnold = Stegosaurus.new=> #<Stegosaurus tail_spikes: 4, back_plates: 6, diet: ["fern", "cycad"]>>> ?> charles.diet < < 'moss'=> ["fern", "cycad", "moss"]>> ?> arnold.diet=> ["fern", "cycad", "moss"]
We didn’t mean to do that…Arnold doesn’t want to eat moss!
At the moment, when the Stegosaurus class is initialised, it creates one Array for the default “diet” attribute of all future Stegosaurus objects. In other words, Charles’ and Arnolds’ “diet” attributes were references to the same object:
>> charles.diet.object_id=> 19103090>> ?> arnold.diet.object_id=> 19103090
How do we fix that? We tell the Stegosaurus class to create a new Array for each model instance. Simply change this:
default :diet => %w(fern cycad)
to this:
default :diet => Proc.new { %w(fern cycad) }
Now each time we create a new Stegosaurus, that Proc will fire, and create a new “diet” Array:
=> charles = Stegosaurus.new=> #<Stegosaurus tail_spikes: 4, back_plates: 6, diet: ["fern", "cycad"]>>> ?> arnold = Stegosaurus.new=> #<Stegosaurus tail_spikes: 4, back_plates: 6, diet: ["fern", "cycad"]>>> ?> charles.diet < < 'moss'=> ["fern", "cycad", "moss"]>> ?> arnold.diet=> ["fern", "cycad"]
I highly recommend giving active_record_defaults a try. It’s very handy, and very easy to use.
And by the way, yes, I was bitten by this problem. Why else would I be writing about it! Can you guess how I discovered it, though? … My tests picked it up!
Friends don’t let friends code without tests
But what if your friends don’t write tests? Or what if you’re just lazy? Well, if the latter applies, that’s your own damn fault. But if nobody around you tests their code, you’re probably not going to be motivated to test your own code. But, fear not! RSpec is here!
RSpec is a really awesome testing framework. By “awesome”, I mean that it:
- makes it easy to write tests;
- makes your tests easy to read;
- gives you an easy development path to follow.
It accomplishes this by following behaviour-driven development (BDD). If you’re not a keener, don’t bother following that link. Just read on for the stegosaurus.
With BDD, you write specs that describe your application’s behaviour in terms of what it should and shouldn’t do.
Let’s write an app to mimic one of my favourite dinosaurs. And while we’re at it, we’ll do some testing. But first, install RSpec:
sudo gem install rspec
Stegosauruses are known for 2 things. Let’s start with those awesome tail spikes:
class Stegosaurus attr_accessor :tail_spikesend
That’s pretty simple. So how do we spec this? We start off by describing what we want our application to do. In this case, we should be able to grab the “tail_spikes” attribute:
require 'stegosaurus' describe Stegosaurus doit 'should have tail spikes' do steggie = Stegosaurus.new steggie.should respond_to :tail_spikes steggie.should respond_to :tail_spikes=endend
Run the spec, and we’re off to the races!
$ spec stegosaurus_spec.rb. Finished in 0.015328 seconds 1 example, 0 failures
We should also spec setting the number of tail spikes, so let’s update the spec:
require 'stegosaurus' describe Stegosaurus doit 'should have tail spikes' do steggie = Stegosaurus.new steggie.should respond_to :tail_spikes steggie.should respond_to :tail_spikes= steggie.tail_spikes = 4 steggie.tail_spikes.should equal 4endend
That’s one of the most readable and easy-to-understand tests you’ve ever seen, eh?
Stegosauruses are also known for the huge plates on their backs:
class Stegosaurusattr_accessor :tail_spikesattr_accessor :platesend
The spec should be pretty obvious:
require 'stegosaurus' describe Stegosaurus doit 'should have tail spikes' do steggie = Stegosaurus.new steggie.should respond_to :tail_spikes steggie.should respond_to :tail_spikes= steggie.tail_spikes = 4 steggie.tail_spikes.should equal 4end it 'should have plates' do steggie = Stegosaurus.new steggie.should respond_to :plates steggie.should respond_to :plates= steggie.plates = 12 steggie.plates.should equal 12endend
Notice, though, that we’re beginning to repeat ourselves. In both of those examples (#it blocks), we create a new Stegosaurus. Let’s tidy that up a bit:
require 'stegosaurus' describe Stegosaurus dobefore :each do @steggie = Stegosaurus.newend it 'should have tail spikes' do @steggie.should respond_to :tail_spikes @steggie.should respond_to :tail_spikes= @steggie.tail_spikes = 4 @steggie.tail_spikes.should equal 4end it 'should have plates' do @steggie.should respond_to :plates @steggie.should respond_to :plates= @steggie.plates = 12 @steggie.plates.should equal 12endend
What we did there is tell RSpec to create a new Stegosaurus before each example is run. To make the stegosaurus available to the examples, it simply needs to be an instance variable.
When running your specs, there are a few different ways to format the output. I tend to use the default and “specdoc” formats. Currently, our spec’s output looks like this:
$ spec stegosaurus_spec.rb.. Finished in 0.01591 seconds 2 examples, 0 failures
But we can also tell RSpec to spit out a summary of our specs:
$ spec stegosaurus_spec.rb --format specdoc Stegosaurus- should have tail spikes- should have plates Finished in 0.057443 seconds 2 examples, 0 failures
Our Stegosaurus class is feeling a bit weird, though..technically, we can set the “tail_spikes” and “plates” attributes to any object:
$ irb>> require 'stegosaurus'=> true>>?> steggie = Stegosaurus.new=> #<Stegosaurus:0x602afc>>>?> steggie.tail_spikes = "we don't want to be able to do this!"=> "we don't want to be able to do this!"
So we need to restrict those two attributes to integers:
class Stegosaurusattr_reader :tail_spikesattr_reader :plates def tail_spikes=(number_of_tail_spikes) raise ArgumentError, 'The first argument (number_of_tail_spikes) must be a Fixnum.' unless number_of_tail_spikes.is_a? Fixnum @tail_spikes = number_of_tail_spikesend def plates=(number_of_plates) raise ArgumentError, 'The first argument (number_of_plates) must be a Fixnum.' unless number_of_plates.is_a? Fixnum @plates = number_of_platesendend
With that done, what do we need to change in our specs? We need to spec the behaviour of the 2 new setter methods:
require 'stegosaurus' describe Stegosaurus dobefore :each do @steggie = Stegosaurus.newend describe '"tail_spikes" attribute' do it 'can only be set to an integer' do Proc.new { @steggie.tail_spikes = 'asdf' }.should raise_error ArgumentError, 'The first argument (number_of_tail_spikes) must be a Fixnum.' @steggie.tail_spikes = 4 @steggie.tail_spikes.should equal 4 endend describe '"plates" attribute' do it 'can only be set to an integer' do Proc.new { @steggie.plates = 'asdf' }.should raise_error ArgumentError, 'The first argument (number_of_plates) must be a Fixnum.' @steggie.plates = 12 @steggie.plates.should equal 12 endendend
Most of that is pretty self-explanatory. However, notice that we’ve just nested #describe inside of the original #describe…twice! We do this because it makes are specs read more fluidly, and it groups examples (#it blocks) together. And inside these inner-#describes, we can do anything we talked about earlier, like setup a before-block.
Let’s add one more attribute…a name:
class Stegosaurusattr_reader :tail_spikes, :plates, :name def tail_spikes=(number_of_tail_spikes) raise ArgumentError, 'The first argument (number_of_tail_spikes) must be a Fixnum.' unless number_of_tail_spikes.is_a? Fixnum @tail_spikes = number_of_tail_spikesend def plates=(number_of_plates) raise ArgumentError, 'The first argument (number_of_plates) must be a Fixnum.' unless number_of_plates.is_a? Fixnum @plates = number_of_platesend def name=(name) raise ArgumentError, 'The first argument (name) must be a String.' unless name.is_a? String @name = nameendend
And now the specs look like:
require 'stegosaurus' describe Stegosaurus dobefore :each do @steggie = Stegosaurus.newend describe '"tail_spikes" attribute' do it 'can only be set to an integer' do Proc.new { @steggie.tail_spikes = 'asdf' }.should raise_error ArgumentError, 'The first argument (number_of_tail_spikes) must be a Fixnum.' @steggie.tail_spikes = 4 @steggie.tail_spikes.should equal 4 endend describe '"plates" attribute' do it 'can only be set to an integer' do Proc.new { @steggie.plates = 'asdf' }.should raise_error ArgumentError, 'The first argument (number_of_plates) must be a Fixnum.' @steggie.plates = 12 @steggie.plates.should equal 12 endend describe '"name" attribute' do it 'can only be set to a string' do Proc.new { @steggie.name = ['not valid'] }.should raise_error ArgumentError, 'The first argument (name) must be a String.' @steggie.name = 'Rupert' @steggie.name.should equal 'Rupert' endendend
Let’s run that spec now:
$ spec stegosaurus_spec.rb..F 1)'Stegosaurus "name" attribute can only be set to a string' FAILEDexpected "Rupert", got "Rupert" (using .equal?)./stegosaurus_spec.rb:37: Finished in 0.02225 seconds 3 examples, 1 failure
Hrmmm, that’s no good. But that’s a fairly useful error message, eh?…well, sort of. It’s telling us what it expected, and what it received. The thing is, it expected “Rupert” and got “Rupert”, so what’s going on? The problem lies in the fact that you can’t use #equal? to compare strings, and that’s exactly what we’re doing. If you don’t believe me, try it for yourself:
$ irb>> 'Rupert'.equal? 'Rupert'=> false
BTW, did you notice the “(using .equal?)” hint that RSpec gave us?
Enough banter. All we need to do is change this:
@steggie.name.should equal 'Rupert'
to this:
@steggie.name.should == 'Rupert'
Shall we view our specs in all their glory now?
$ spec stegosaurus_spec.rb --format specdoc Stegosaurus "tail_spikes" attribute- can only be set to an integer Stegosaurus "plates" attribute- can only be set to an integer Stegosaurus "name" attribute- can only be set to a string Finished in 0.018755 seconds 3 examples, 0 failures
Those’re the absolute basics of RSpec. If you’re thirsty for more, check out the RSpec website.
Testing…it’s what life’s all about
I just read a great call to action by John Nunemaker. He wants to see everyone writing tests for their code, and has decided to “post like a superhuman fiend until everyone is testing”. He’s on to something!
With that said, I’m joining in. I primarily use RSpec, so I’ll be focussing on that, but we’ll give Cucumber and other tools a go, and we’ll be starting with the basics.
So subscribe to our feeds, and stay tuned!
Rails Resources: :as vs :controller
As you may or may not know, when configuring routes and resources in config/routes.rb , you can pass the :as or :controller options to map.resources . When I first read about these two options in the Rails Routing From The Outside In Rails Guide, they seemed to do the exact same thing.
However, that’s not the case at all.
map.resources :photos, :as => 'images'
This allows you to request the “photos” resource using the word “images”. IE: http://localhost:3000/images/ would route to the “photos” controller.
On the other hand,
map.resources :photos, :controller => 'images'
This allows you to request the “images” resource using the word “photos”. IE: http://localhost:3000/photos/ would route to the “images” controller.
Simple? Yes. Subtle? Yes.
Convention and reasoning
When coding in the past, I rarely used the switch/select/case-conditional. However, since I started using Ruby, I’ve found it to be quite useful in some situations.
Vim formats them like this:
case foobarwhen 'something' # Do something.when 'another thing' # Do another thing.else # Do this if the above "when"s don't match.end
That indentation scheme doesn’t feel right to me. The “when” and “else” clauses are pretty much children of the “case” clause. In my opinion, “when” and “else” should be indented +1, like this:
case foobar when 'something' # Do something. when 'another thing' # Do another thing. else # Do this if the above "when"s don't match.end
But now the code within each “when” and “else” is indented +2! That’s a lot of indentation.
I brought this up in #ruby-lang on Freenode. A couple of people agreed with me, a couple didn’t care, and the rest disagreed. There was one poignant comment though:
<quix> litage: why doesn't your reasoning for if/elsif apply to case/when?
I haven’t been able to answer that yet. quix’s reasoning is sound, but I can’t shake the dirtiness that I feel when indenting “when” and “else” to the same level as “case”. It just feels wrong…