I’ve always found writing and testing custom ActiveRecord validations to be a straightforward process. In your model, add a private validation method and hook in to the validation callbacks using the validate class method. In your tests, build a model with invalid data, and assert its validity (or lack thereof).
But more and more, I find myself writing validations that I’d like to share between models. The Active Record Validations and Callbacks Rails Guide (and the Rails API docs) suggest that the best way to create a reusable validation for individual attributes is by creating a subclass of ActiveModel::EachValidator. This even integrates with the Rails 3 ActiveModel validates method for easy-to read validations. Cool stuff.
But what do you do when you want to test these validators in isolation from the business logic of your models? Here’s a pretty sweet solution I found, using Rspec and the with_model gem.
In this example, I’ve written an excitement validator. A string attribute will pass validation if it ends with an exclamation point, and fail if it does not. Here’s my ActiveModel::EachValidator subclass:
And, using with_model, here’s my spec:
I placed these files in app/validations and spec/validations, respectively – Rails 3 and higher will include any directories in app/ on your load path automatically.
An alternative way of testing the validation would be to instantiate the ExcitementValidator class directly and test the results of the validate_each method. I like this with_model approach, however, because it tests both the validation code itself
and that the class complies with ActiveModel::EachValidator’s interface.
I’ve found myself working on a static HTML website recently (hosted on GitHub Pages), and I wanted to test the site without going through the effort of configuring Apache. This one-liner is a combination of twoideas that use Ruby’s built-in WEBrick web server to serve the files in the current working directory.
I added this as an alias to my bash profile, so I can type servhere and host any directory I want. Cool!
A few months ago, I woke up one day to discover hundreds of little white-and-blue Smart cars scattered all over Portland. I wondered: who owns all of these cars, and why have they come to my city? It turns out that they all belonged to car2go, a car sharing service in town. Intrigued, I looked into car2go, and what I’ve found is pretty interesting.
Unlike Zipcar, the dominant player in Portland’s car-sharing world, which requires you to a) reserve a car in advance and b) return a car to the location you picked it up, car2go’s model is designed for on-demand, one-way rentals. It works like this. Walk up to a car, tap your member card on the windshield, get in, and drive off. When you’re finished, just park the car in any normal street parking spot, anywhere in the city, tap your card again, and walk away. That’s right — return it anywhere, and don’t even bother paying for parking. Your credit card gets charged later based on how long you drive.
Of course, it isn’t quite that simple. You can’t park in parking spaces designated for less than an hour. You can’t rent cars that have been reserved by other users. There is a “Home Area” that restricts where you can end your rental. And then, of course, there’s the price: 35 cents per minute, including gas and insurance.
I joined car2go shortly after it launched in April and have been testing out the service since. And I’ve been using the service more than I ever thought I would. It’s been a lifesaver on those dreary mornings when I just don’t have it in me to ride my bike to work. I use it for runnings errands for the office, and when I go grocery shopping and just have too much stuff with me to carry easily.
Now, keep in mind that I’m coming from a somewhat unusual perspective: I don’t own a car, I live in a close-in neighborhood, and my primary mode of transportation is a bicycle. For me, car2go has been a super useful addition to my transportation options. I love that I can combine car2go’s one-way trips with other kinds of transportation without much trouble. I never joined Zipcar because it felt too rigid — I don’t plan my trips in advance, I take multiple stops, and don’t end up in the place where I started. car2go feels more like a self-drive taxi than a traditional car rental, but cheaper and more convenient.
There are some downsides, though. Car availability can be spotty. It’s getting more and more common for there to be no cars within reasonable walking distance from my house in SE Portland. I am reluctant to rely on car2go because I just don’t know whether a car will be available when I need one. So using car2go is always an impulsive decision, and this does not appeal to the planner part of my brain. And the price adds up quickly. Even with hourly and daily caps, if you want to drive a car for more than a few minutes, it may actually be cheaper to rent a car from a traditional rental company.
Although the customer service has been friendly and helpful, it seems to take 3-4 business days for any changes to be made for my account. Smart cars are cute and easy to park, but there are times I’ve wished I could drive more than one one passenger. The car2go website is slow and confusing (I’ve been using the C2G app for iPhone, which is definitely worth the cost). Finally, there’s the thinly-veiled fact that car2go is owned by Daimler — If you think you’re helping out some scrappy startup, think again.
I’d definitely recommend giving car2go a try if you live in one of its service areas. Its model may very well be the future of private car transportation: ubiquitous vehicles, available when you need them, without the stresses of pumping gas or maintenance.
Have you used car2go? What do you think about it? I’d love to hear about it on Twitter.
What is there to say that hasn’talreadybeensaid? The man was visionary, obstinate, and decisive. He made his mark on the world in ways that few people have the opportunity to do. He did so in his own way, on his own terms, yet managed to consistently bring joy and wonder into others' loves. We should all be so lucky.
It’s commencement season, and I loved this speech at Harvard Medical School given by Atul Gawande of the New Yorker. Gawande has written a number of excellentarticles on heath care over the last few years. As a practicing surgeon, he has an insider’s knowledge of the heath care system – and some interesting ideas for how to improve it. He believes that doctors should act less like maverick cowboys and more like systematized pit crews:
Recently, you might be interested to know, I met an actual cowboy. He described to me how cowboys do their job today, herding thousands of cattle. They have tightly organized teams, with everyone assigned specific positions and communicating with each other constantly. They have protocols and checklists for bad weather, emergencies, the inoculations they must dispense. Even the cowboys, it turns out, function like pit crews now. It may be time for us to join them.
Anyway, you might want to keep this in mind the next time you call someone a “cowboy coder.”
There’s been a lot of blog chatter recently (beginning, it seems, with Brent Simmons' “A Plea for Baked Weblogs”) about so-called “baked” blogs. The concept is simple: in a time when CPU cycles are cheap and bandwidth is seemingly limitless, why do so many bloggers use dynamic blogging frameworks that crumble when traffic spikes? Instead of relying on full-stack, database-backed web applications, why not just generate static files whenever content changes and upload to any run-of-the-mill web server?
There are strong arguments to be made for this “baked” approach. The performance of static files just can’t be beat: Apache was hosting static files long before WordPress was a twinkle in Matt Mullenweg’s eye. When you host static files, you can forget all about that time you spend looking for the MySQL password you made up three years ago, or trying to remember which WordPress cache plugin you’re supposed to use this week. Baking your blog gives you access to all of your content in plain text – and you don’t need to worry about TumblBeasts eating your hard drives.
But there are tradeoffs. (Marco Arment and Dan Benjamin cover many of the isses on Episode 18 of Build and Analyze.) Configuring software to bake your blog takes a fair amount of technological proficiency: not problem for most web developers, but a serious obstacle for average bloggers. Worse, using client-side software means that you’re now tethered to a computer – good luck posting from a mobile device. (Yes, you could follow Marco’s example and build your own Dropbox-backed baked blogging system, but then you’re stuck with yet another service to depend on.)
In short: baked blogs make sense if you are technically proficient, plan to write posts on a computer (not a mobile device), and already have a place to host host static files.
After thinking through these tradeoffs, I settled on a solution for this blog that’s become moreandmorepopular.
To generate the static HTML for my blog, I’m using Jekyll, an easy-to-use, command-line Ruby application. Getting it set up was super straightforward. I first created a liquid template for each page type, along with all the usual CSS. Each blog post and static page is a Markdown file with some extra metadata at the top. To generate the site, I run jekyll on the command line (Protip: jekyll --server --auto is a great way to test and preview your posts and designs).
The final piece of the puzzle is GitHub Pages, which makes it incredibly easy to update and deploy a static site. I’m storing this blog in a repository on GitHub, and every time I push, GitHub automatically builds the site with Jekyll and hosts it for free. Thanks, guys!
All in all, I think I ended up with a pretty slick solution – from a developer’s perspective, at least.