Articles about Rails

Active Record STI and eager loading

This week has been … interesting. Not because of obvious geopolitical events, but because a client application started throwing weird errors; background processes failed in ways that weren’t possible and otherwise reliable cronjobs just didn’t do what they were supposed to; no failures or anything, they just didn’t process the records they were meant to.

How to fix (some) UnknownError and InvalidArgumentError in Capybara

The other day, our headless system specs in a Ruby on Rails project started failing with a bunch of errors we hadn’t seen before. Mostly Selenium::WebDriver::Error::UnknownError: unknown error: failed to close window in 20 seconds but in some cases also Selenium::WebDriver::Error::InvalidArgumentError: invalid argument: 'handle' must be a string.

Usually random errors in browser tests can be fixed by upgrading selenium-webdriver, Chrome, chromedriver or any combination thereof, but not this time.

SimpleLocalize on Rails

When your application spans across multiple countries and languages, managing your translations using Rails’ default locale files in git becomes too cumbersome. We recently moved a clients Rails app to SimpleLocalize to give translators and developers a better workflow around translations. This is how we did it.

Failures

I’ve built stuff online pretty much since I figured out that I could. Join me on a tour through my the projects I have built where I planned on building a thriving side business - and failed.

The anatomy of a good commit

Commits are the DNA of your system. They describe the evolution of your system going back to when it was the most basic, automatically generated “Hello World” example. They contain the sum of all knowledge and history of your code.

In many cases they are the least changable part of your system, so you only really get one shot at getting them right. You’d better make it count.

Ember on Rails: Validations

In the previous episodes we’ve built a working Ember.js application to manage our growing collection of Books. It lives inside a Rails application which it uses for its backend.

We’re able to list all the books in our vast library, and also add new books to our collection. However, if we try to add a book without giving it a title, the backend gladly accepts it and saves it, which is probably not the optimal behavior.

It is time to add validations to our application.

Ember on Rails

I’ve been trying to get into Ember.js a few times by now, but I’ve always been dissuaded for various reasons.

This time around I’d like you all to learn with me - hopefully the act of me writing down what I do will make it stick better for me.

The plan here is to end up with an Ember application backed by a Rails JSON API - we’ll see if the future agrees with that goal.

Baruco 2013

I don’t go to many conferences - I am pleased that Baruco is one of them.

I really enjoyed the conference. It was well organized with a stellar lineup of speakers. I’ve returned home from Barcelona with things to ponder, things to try out, and a list of books to read.

I've taken up Exercising

I have been having fun participating in Exercism.io - a collaborative code improvement site started by Katrina Owen.

The rules are simple: You get an exercise with a README and a test suite. You make the test suite pass, submit your code and the other participants can nitpick the submitted code. It’s actually quite fun - even for us experienced developers.

Here are a few of my takeaways from having done a couple of exercises there.

Destroying anchovies

When ordering pizza from an unknown pizza joint, I used to order a number 7 without anchovies. I didn’t know what pizza number 7 was, but I knew I didn’t want anchovies.

The ensuing dialoge usually went like:

Them: “But… number 7 doesn’t have anchovies?”
Me: “Perfect!”
Them: “So… you want a number 7?”
Me: “Yes. Without anchovies.”
Them: “…“

I didn’t care about the pre-condition of my pizza; I only cared about the post-condition, where it should be without anchovies.

The pizza baker did care about the pre-condition; if the pizza did have anchovies, he’d have to remove them. In his mind, removing anchovies from a pizza without anchovies wasn’t a request he could handle. In my mind, if the pizza didn’t have anchovies, the request had already been fulfilled.

Rails 3, ActionMailer, and Google Apps for Domains

After upgrading my Redmine installation to Redmine 2 (the development branch) emails stopped being delivered.

I send emails through Google Apps for Domains, so I had the following in my configuration.yml (previously email.yml):

delivery_method: :smtp
smtp_settings:
  address: "smtp.gmail.com"
  port: 587
  domain: "substancelab.com"
  authentication: "login"
  user_name: "foobar@example.net"
  password: "passw0rd"
  tls: true

I am pretty sure it used to work before the upgrade, now; not so much.

Digging into Objective-C (again)

While the concept of writing native Mac apps in Ruby definitely appeals to me, I must say the experience isn’t quite as easy as I was looking for.

After writing my last post I realized that what I had thought to be the path of least resistance, wasn’t. And while I knew I’d run into resistance with XCode and Objective-C as well, at least I’d be doing things the “proper” way and learning new stuff.

So I fired up XCode once again and set out to write a Mac application. The following is a bunch of notes and stray thoughts I scribbled down during those first hours - my first (well, fourth) impressions of developing iApps coming from Ruby.

The state of Ruby in Denmark

Yesterday marked the 5 year anniversary of Copenhagen Ruby Brigade. Five years ago, I was part of founding that group. Five years, imagine that.

Back then, you could have heard me claim I knew all the Ruby developers in Denmark. While probably an exaggeration, it wasn’t far from the truth. Thankfully that is no longer the case. Yesterday, as I was sitting in the conference room at Podio looking at the other people present, I realized I didn’t know half of them. This got me thinking about how far we’ve come in the danish Ruby community over the last years.

Announcing r-conomic

If you have ever tried to integrate with e-conomic you’ll likely recognize that their API comes out pretty high on the How to make a crappy API checklist.

Luckily, if you’re using Ruby, you can now use the r-conomic gem to handle SOAP and the other tedious bits for you.

I’ll let the README do the talking while I head on over to my Working With Rails profile and finally check off the “Has published a Ruby gem” checkbox.

Ruby: How to check if a String is numeric

Finally, a technical article… This one caused by a seemingly simple question on Stack Overflow, asking how to Test if string is a number.

It turns out that it’s not entirely that simple to answer, and there are lot of apparently correct ideas, that all turn out to fail closer scrutiny.

For those who just want the answer: As far as I can tell, the best method is the one proposed on RosettaCode and in the Stack Overflow question above:

class String
  def numeric?
    Float(self) != nil rescue false
  end
end

If you want some more details, continue reading.

New Ruby and Rails apps in Denmark

The number of live, production Rails apps is ever increasing. Even though Denmark is still primarily living in a Microsoft and PHP bubble, great Rails applications are being built around the country.

Out of curiosity, I thought it interesting to compile a list of the newer ones added to the growing list of danish Rails applications, and thanks to my Twitter followers came up with the following list.

Localizable Rails 3 validators

Rails 3 introduced a new style of validators that allow us to group validations for each attribute into their own line. It also became easy to create our own, custom validators.

This a small tip, perhaps even a best practice, when doing so.

Most the examples I’ve seen around the web ends up adding errors to the errors array using something like

record.errors[attribute] << (options[:message] || "is not valid")

Unfortunately doing it this way means your validator doesn’t behave like the standard validators and the error message cannot be localized.

Instead, please use

record.errors.add(attribute, (options[:message] || :invalid))

Using a Symbol rather than a String lets you localize the validation message via your standard Rails I18n mechanism. It also lets you pass a proc to :message, allowing for things like Time.now to be used within an error message.

Thank you in advance from those of us who create non-English apps.

Tracking exceptions with Redmine

Staying on top of errors that happen in your production Rails applications is a must. Unfortunately trawling through log files get old really fast, and getting enough information about where the error happened can be hard.

That’s what services like Honeybadger or Airbrake solves. Whenever an error occurs in your application the details are sent to their service, where you are able to see when, where and how many times a given error has occurred.

However, if you’re uneasy about sending this level of details to a third party service – or if you’re simply a cheapskate like me, there is another way using Redmine.

Startup lessons from Rails Rumble

Rails Rumble is an annual, 48 hour web application programming competion. This year around 300 teams attempted to build and launch a web application over the course of a weekend, 180 succeeded.

Participating in the Rails Rumble is a lot like being in a startup, just a heck of a lot more focused. A small group of people with nothing but an idea, passion, and a tight deadline. As such. there are some lessons that apply equally well to Rails Rumble as to launching a new startup.

Humor driven development

Happy developers are productive developers. Having fun makes people happy. So sayeth the Chief Happiness Officer.

This should come as no surprise to noone in the Rails community – after all, Rails is “optimized for developer happiness” and DHH has touted this on numerous occasions.

And the Ruby community in general seems to be a life-loving bunch. _why didn’t rise to fame solely because he was a good programmer. His code was fun and quirky, his documentation and presentations even more so.

Rails 3: Responding with Excel

The following is a short code snippet from my Rails 3 presentation at Community Day last week. I’m putting it here, because it’s such a nifty little piece of code.

It answers an feature request I seem to get fairly often; “please make it possible to download an Excel file of data”. Traditionally I’ve relied on good ole CSV for that, but it’s a bit tricky to get just right with Excel. Besides, the customer explicitly said Excel file, so let’s give her that.

Heroku, Rails 3, and Sass

Heroku is a great way to host your Rails apps. Rails 3 is the new hotness. Sass is a decent way to write your stylesheets. Unfortunately combining the three isn’t as straight forward as it could be, but it can be done.

Update: While these instructions are still correct, you should use the Hassle fork from jasoncodes instead of my fork. Alternatively, you can roll your own following Herokus instructions.

Suppress warnings from Ruby

We Ruby programmers routinely do things that other programmers frown upon, and – in many cases – won’t even be allowed to do by their interpreter/compiler.

Case in point for this article, is redefining constants. In Ruby a constant isn’t constant. Creating a constant is merely a way for the programmer to indicate a value that really isn’t supposed to be changed – but if you do anyways, you’re on your own.

Introducing Progress Wars

Today, I am stoked to bring you Progress Wars – the ultimate game of progression.

If you enjoy spending time on Facebook “games” like Mafia/Pirate/Ninja/Viking Wars/Clan/whatever you’ll most certainly be thrilled by Progress Wars!

  • Unique gameplay experience
  • Unlimited amount of missions
  • Play as much as you want, when you want
  • No need to invest time you don’t have
  • Super simple learning curve – anyone can join
  • Advanced algorithms tailors missions to your playing style (patent pending)
  • It is absolutely free to play
  • Progressive, automated difficulty levels

I have analyzed popular Facebook games and distilled their enticing gameplay into their core game mechanics. What’s left is only the stuff that makes a game like Mafia Wars tick – none of the fluff. The result is Progress Wars.

Freelancing lessons learned

A long long time ago, I quit my great job at BiQ to live primarily of my freelance Ruby on Rails development work.

It’s one of the best decisions I’ve ever made.

Being directly responsible for my own income has been fun, empowering, fulfilling, and pretty damn scary. I’ve met lots of great people, worked with great customers on great projects, and I’ve learned a lot of lessons in the process. Allow me to share a few of those lessons with you.

Your network is important

I am a geek. I am not particularly outgoing. Small talk is not a forté of mine.

However, as a freelancer, entrepreneur, or anyone running a business you cannot isolate yourself in a dark basement producing high quality work. You need to get out of your chair and meet people – partly in order to stay sane and get outside influences, but definitely also because your network is very important to your business.

I have gotten the majority of my customers through my network. If you provide a great service, your previous customers will happily recommend you and your coworkers will happily refer clients you. If you’re a great person, your friends are going to talk about you.

Leverage your network, and don’t forget to make yourself available for them as well.

Running a business will consume you

One of the things I have been most surprised by, is how much I think about the company.

There are always a ton of things to think about; processes that could be improved, ideas that might be worth pursuing, people to get in touch with.

Whenever I have some downtime; doing the dishes, walking the dog, watching television or in some other way allow my mind to wander, it tends to wander towards Substance Lab.

You won’t bill out as many hours as you think

Many other people have written about this point in length, but it is important enough to bear repeating.

If you plan on working reasonable hours – and you should – you cannot expect to work 8 billable hours per day. There are so many other tasks that you need to take care of, that a part of running the business. Admin, taxes, sales, marketing – Jon Hicks have a longer list-.

I have, on rare occasions been able to work 6-7 billable hours in a day, but more realistically, I count on around 3-4 billable hours on any given day.

Scheduling is really hard

Things will take longer than you think. Period. Couple that with the fact that you probably won’t be able to work as many hours as you figure, and you have a scheduling problem on your hands.

You want to minimize the amount of time without client work. But at the same time you need to leave buffers in place for when your estimates are flat out wrong or when something goes wrong and needs to be dealt with.

I wish I had any words of wisdom to dish out that would instantly transform you – well, myself – into a scheduling demi-god. Unfortunately, I don’t. For now, I am relying on optimism and a lot of running really fast when things get tight – hardly optimal.

I’ve shown you mine…

That’s just a few of the lessons I’ve learned over the last years of freelancing. If you do any freelancing or run your own business, what have you learned? What would you tell someone who’s thinking about starting out on their own?

mentalized.net in 2009

A new year has arrived — what better time is there to look back at the year that passed?

The decline of blog readers

The number of visitors to mentalized.net keeps declining. This is hardly surprising; I don’t write as much as I used to here (I have a feeling Twitter is eating up a bunch of potential articles), and a lot of content is probably being consumed off the site in news readers and other aggregators.

Still, I am quite happy having more than 125000 people visit my humble website and I owe each one of you my thanks.

What people came for

My collection of totally free, animated GIFs for showing Ajax activity continues to reign supreme as the most popular content on mentalized.net. It is followed by my satirical web 2.0 webdesign tutorial.

Both of those were published back in 2005 over 4 years ago, yet they still continue to draw readers to the website. The only article on the content top 10 that’s actually published in 2009 is my response to a Java developer spreading some FUD (which unfortunately detoriated into more FUD and mud-slinging).

Top content on mentalized.net in 2009

  1. AJAX Activity indicators
  2. Building your very own web 2.0 layout
  3. No such file to load — mkmf
  4. Java kicks Ruby in the what now?
  5. Hello Ruby on Rails World
  6. Rails 2.0 deprecations
  7. Browser size does matter – Actual numbers
  8. Hunting down VBScript error codes
  9. Setting the request content type in Rails
  10. AJAX activity indicators ":https://mentalized.net/journal/2005/11/29/ajax-activity-indicators/

How people got here

Google is still, hands down, the biggest source of traffic for mentalized.net. Almost half of all visits have been referred by Google. For comparison, the next search engine on the list is Bing with less than 1% of Googles referrals.

Social media sites like Digg, Twitter, and Facebook still aren’t providing me with a lot of traffic. I must be “old media” – or perhaps my content simply isn’t the kind of content that cries out for immediate attention.

The only post I’ve made in 2009 that was in relation to “current events” (link) did in fact get some traction on the social sites with roughly half the visitors coming from various social sites.

2010?

I am looking forward to redoing the above stats for mentalized.net when 2010 is over. I signed up for Project52 fully intent on accomplishing the goal (“to write at least 1 new article per week for 1 year”). Hopefully, getting back into the thrill of writing regular content should provide for better content that can at least break the decline of visits. Time will tell.

The death of an idea

I pulled the plug on a project today. The project was the first Rails project I ever built, and my first, feeble attempt at getting some of all those free money I’ve heard is floating around the internet.

4 years ago, when I was still thinking PHP was a great language, I needed a real project to use for my experiments into Rails. At the time, I was getting into playing World of Warcraft along with a bunch of friends, and we needed a website where we could discuss tactics, organize events, and all the other small tidbits that go into running a guild.

I figured I could use Rails for that website, and hey, I might even be able to make a little money on the side by letting other guilds use the same application on a pay-per-month basis. Step 1: Build it – Step 2: ? – Step 3: Profit! As it turns out, step 2 is actually pretty important and harder than I thought.

Things I did wrong

Over the last course of the project, I’m sure I’ve made a lot of mistake. Following are a few of them, the ones, I think are most important. Writing them out here, shaming myself publicly, will hopefully result in me not forgetting the lessons learned.

Perhaps someone else might even learn from my mistakes.

I was not passionate enough

Probably the number one reason for the failure of Guildspace, was the fact that I did not take the project seriously enough. All the other problems can be traced back to this.

I built the application for myself and some friends, and the business part was just a stray idea. As long as we used the application, I was motivated to improve it. Consequently, when we stopped using the application, I lost the motivation to build the application.

Certainly, if the application had customers and was generating revenue at that point, I might have been motivated enough to keep it running, but the reality was different. Which isn’t surprising, because no one knew about Guildspace.

I didn’t tell anyone

I launched Guildspace with no real plan for how to market it. I invited a few friends and members of my family who used the application and were reasonably pleased with it, but other than that, I never really told anyone about it.

To this day, I am surprised by that fact. I have a weblog with thousands of visitors every month, yet I’d be very surprised if any of the readers of this blog knew about Guildspace. To be fair, I’ve never claimed to know the first thing about marketing. Yet, I could easily have done better than what I did.

I wasn’t prepared to invest

My lackluster attitude towards the project also resulted in my not wanting to invest any money in it. Sure, I could pay for a few domains, but that was pretty much my upper limit when it came to hosting. You know what? If you want to turn a project idea into a profitable business you need to invest money in proper infrastructure. And no, the cheapest hosting plan you can find will not cut it.

Hosting wasn’t the only piece of infrastructure I skimped on. I didn’t want to spend money on proper payment processing. I figured, as soon as the customers start flowing in and I actually have some payments to process, I can just use PayPal. They only charge a transaction fee, so if I don’t make money, I don’t pay them anything. Big mistake!

In order for PayPal subscription payments to work, the customer needs to create an account on PayPal – or if they already have one, log in there. This totally messed up the signup process, but I was too much of a scrooge to care. Not only would a potential customer have to sign up for Guildspace, she’d also have to sign up on a seemingly unrelated website.

Not surprisingly, the majority of new signups never got past the PayPal step.

Post-mortem

The net result of all of the above is that Guildspace is no more. The life-support-system keeping it alive has been turned off. I’ve had fun building the application and I learned a lot in the process.

Rest in peace, Guildspace, we hardly knew you.

Find missing translations in your Rails application

I am currently wrapping up a client-project where I am preparing a Rails application for internationalization. The application is currently in English and I am translating it to Danish as a proof of concept.

I am using the I18n::Simple backend and the resulting Danish locale file is now at 2100 lines. That’s a bit much for me to keep in my head at once, so I created a small Rake task that takes all locales in your Rails application and reports back all the keys that are missing from one or more locales. Works wonders for finding those typos or oversights that would otherwise result in ‘missing translation data’ messages.

Using Google Page Speed to optimize websites

Back when Yahoo! released their YSlow add-on for Firebug, I took it for a spin and optimized biq.dk using it.

Google recently released their variant of YSlow called Page Speed. Like YSlow, it’s an add-on for Firebug and it provides a bunch of recommendations for optimizing the clientside performance of your websites. This time, I’ll let it loose on the homepage of Lokalebasen.

Java kicks Ruby in the what now?

When I first read the Java Kicks Ruby on Rails in the Butt article by Javier Paniza, I brushed it aside as something from the time when Rails was just getting traction and people using related, established technologies started feeling threatened.

I then noticed the date – turns out the article is only a few days old! Color me confused, could that article really have been written in 2009? I thought we had left the FUD-spreading behind us.

In an effort to educate Javier – and hopefully others – I decided to rewrite the Rails part of his article the way he would have written it had he had more knowledge and experience with Rails.

Testing HTML emails with Rails and Litmus

Every so often, a client wants their web application to send out emails that could benefit from a bit richer styling than what’s provided with your basic text emails. Occasionally, they’re right, and you find yourself walking down the path of HTML emails. But beware! That path is perilous and behind every corner lurks the big, all-consuming monsters of HTML emails; Email clients.

Rails Camp DK 2008

Take 12 attendees (one from Italy, way to go, Fransesco!), 11 Apple laptops (and one Windows one, I believe), 1 wifi hotspot, mix it all together in a cottage in the middle of nowhere, sprinkle it with a tad of Ruby, Git, and *jour and let is stew for 2 days and 2 nights.

What you get is a Rails Camp, and the above recipe was cooked with great success last weekend. Thomas Watson has a bunch of pictures from the event.

Rails Rumble 2008

Rails Rumble 2008 is in full effect. Rails Rumble is a 48 hour Rails development contest, and I and two others from the Copenhagen Ruby Brigade have decided to enter the fray.

2 hours to go

The time is getting close to midnight and my eyelids are getting to close to the floor – or so it feels. We’re done, there’s no way we can manage any more improvements.

The last hour we’ve been doing bugfixes by deleting the stuff that’s not working. When something is buggy with no time (or energy) to fix it, and you refuse to deploy low quality stuff, that’s the way to go about it. Oh well.

Rails Rumble 2008 is over for us, looking forward to going through all the apps – some of them are looking really amazing.

3.5 hours to go

Fatigue is definitely setting in now. We’re doing stupid mistakes and things aren’t moving nearly as quickly as it has been. But, we’ve been able to check off some of the items on the “nice to have” list, which is… well… nice. Looks like my ability to blog doesn’t increase the more tired I get, either.

Anyways, the site has been deployed, and we don’t want to risk doing anything major to it for the remainder of the contest – we’re bound to break something if we do.

So without further ado I give you Quotagious – the most awesome way to store and find quotes.

7 hours to go

Uh oh, less than a regular day of work left. Actually, a lot less as it’s highly unlikely we’ll stay awake until the deadline, it being at 2AM our time and tomorrow being a work day.

Funny how tons of small things crop up as we get closer to the deadline. Luckily we have the features we aimed for done. And they would’ve been deployed had it not been for the fact that something took the server down. Oh well, with no staging environment stuff like that happens.

Thomas has been working on Twitter integration for the last few hours. We didn’t want to be the only Rails Rumble app not hooked up to Twitter somehow… Performance optimizations and even more usability improvements have been my focus for the last few hours – our beta testers are ruthless, thanks guys :)

In related news, we’re now down to 99% Ruby code, 1% Javascript :(

12 hours to go

75% through the competition. So far I have been focused on usability and making the site look nice. Thomas has started on one of the fancier features, and my wife has been doing beta-testing for us.

Having someone outside the team look over the application is invaluable, even if done remotely. We’ve already implemented some changes, primarily in relation to wording and program flow in order to make it clearer what the application is and how it works.

The application is pretty solid, and we’ve added a “stable” tag to it. So if we end up messing it totally up the last twelve hours, at least we’ll have something to deploy. We’ve also started working purely in feature branches (yay Git) to lessen the risk that we end up deploying something half-implemented and broken.

Day 2 – 17 hours to go

Good morning, time to dive back into the code after a short nights sleep. Unfortunately, the more interesting stuff will have to wait, as the nights beta-testing revealed a few serious issues that needs to be fixed; primarily usability-wise. I have a feeling that we won’t get many favourable votes if people cannot sign up or log in.

26 hours to go

Yawn, tiredness is definitely setting in, but we’ve come a long way by now. The core functionality is working and seems solid – although I am sure it’s all an illusion that shatters the moment a real user gets involved. We’ve even got around to adding the majority of the UI theme.

UI-wise we had originally decided on just buying a stock theme somewhere, but we ended up doing it ourselves. I had some visual ideas I wanted to try out, and most the themes we could find in the short time we’d put aside for it, didn’t feel right and/or would need too much modification after the fact. So we’re rolling our now – support for IE6? Yeah, right.

For the last couple of hours we’ve been mainly doing minor stuff, none of us really feel like tackling the bigger ToDo items. Looking at the bright side, this means we’ve got a fairly complete’ish application now not even halfways through the competion.

The plan for tomorrow is to dig into the more interesting stuff; the features that move the application away from “meh, this is just a script/generate scaffold job” and into Championship belt status – or at least, that’s the plan.

The plan for right now: Sleeping.

32 hours to go

The first long workday (and then some) has passed – and we’re still going strong. However fatigue is becoming noticeable and I suspect we’ll be heading away from the computers to do something different very soon.

The application is really shaping up. We’re dealing with a bunch of fairly intricate edge cases we discover as we learn more about data model, and Test Driven Development is really helping us out here.

Our To Do list for today is growing thin, and it looks like we might be able to start working on polish and cool stuff already today.

37 hours to go

5 hours in, and we’ve started questioning our data model. It’s not even that it’s that complex. We’ve got 5 models, but it should probably be just 4. Too bad we can’t figure out if it’ll make things easier or harder cutting the one model.

Another thing we’ve been running into is the desire to make things too good. When you’re facing a 48 hour deadline you have to settle for good enough. There’s simply no time to go “Hrm, that URL doesn’t like exactly like I’d like it to, let’s just tweak it a liiiiiiittle bit…” – before you know it, you look at the clock and it’s an hour later.

42 hours to go

Due to the competition starting at 1AM our time we figured we’d be wiser to start the competition by sleeping, so by now we’ve only been at it for roughly 3 hours. Progress so far: Breakfast has been eaten, and a basic application skeleton has been deployed to our server, running a very, very, very basic version of our core functionality.

We’ve used Bort (as I am sure a ton of other teams has as well) as the base for the application, and I am sure we’ve have saved some time doing just that.

Next time around I’ll probably take a look at the base application before actually basing an application on it, though. Not that there has been any issues, but we did waste some time figuring out some Bort details. Luckily, it’s time to dig into the meat of the application now.

change:healthcare on CNN

My longest running client, change:healthcare, has been featured on the CNN website and is scheduled to appear on air this weekend – what a great achievement.

I’ve worked with Christopher, one of the founders, and the rest of the team for the last few years, going from a static website with just 5 pages to an increasingly complex Ruby on Rails application helping people make sense of their medical bills and providers.

These guys (and gals) are the real deal. They are in this to change healthcare for the better – publishing a free PDF book and getting on CNN are just a few of the steps on the way.

Congratulations.

Podcast recommendations

I am a big fan of podcasts. I have roughly one hour of daily bicycling to and from work, and roughly the same amount of walking the dog, both of which are perfect time to listen to podcasts.

My brother recently asked me for podcast recommendations and I figured I might as well share my podcast playlist with him, you, and the rest of the world.

Audio only

General tech

Business stuff

Development/programming

Humour

Video

Some time ago we bought a Mac Mini for our living room, and since then, video podcasts have been one of – if not the – main source of media intake in our daily lives. The stuff we see:

Your recommendations

Please, let me know in the comments if there are any obvious podcasts I am missing.

Launch: Børn i byen

This is probably one of those posts, that I ought to in Danish, oh well…

The recent weekend marked the launch of Børn i byen (that’s “Children in the city” for you danishly-challenged readers) – a user-driven guide to Copenhagen focusing solely on parents and their children.

Børn i byen frontpage

People are already blogging about it and judging by the comments, people are liking it.

Since December I have been part of the Børn i byen team. Even though I have no kids, I was added to the project – on recommendation from Lars to assist the original developer and the rest of the team get a launchable product out the virtual door.

On the technical side of things, it’s all Ruby on Rails, using Blueprint for the CSS, Capistrano for deployment, Comatose for a lightweight CMS, Geokit for the Google Map stuff, and Carolines espresso machine for fuel.

Looking for patch +1's

During his keynote today, and now on the Rails blog, David explained the new policy for getting patches into Rails.

Basically the new policy requires every patch to have documentation, tests and 3 supporters. It’s a welcome change, especially if it means the core team have to do less legwork and apply higher quality patches.

Therefore, I am now looking for a few supporters for some of my patches. If there’s anything of the below you’d like to see included in Rails, please comment on the patch, saying +1.

I have a few other patches sitting idle, but they might need a bit more work (read: tests) before getting supporters.

Happy birthday, Copenhagen.rb

I’m a bit late on this, but nevertheless: Last Friday marked the one year anniversary of the first gathering of Ruby and Rails geeks in Copenhagen, that which should later be formalized as the Copenhagen Ruby Brigade.

That initial meeting has been well documented online, both in words and in pictures.

A year, really?

So what has happened since then, I can hear the masses of inquisitive readers ask.

  • We have hosted around 10 official meetings – initially in offices around Copenhagen, but lately we have settled in at our gracious hosts, PROSA. The topics covered have been many and varied, from technologies like Puppet over building Gems to question likewhat CMS’s to choose for your Rails applications. And every meeting continues to feature new people.
  • We have held informal meetings in bars, hosted a free-for-all hackday, and a 14 hour night of contributing patches to Rails.
  • We have been visited by prominent Rubyists like Obie Fernandez, David Black, and David Heinemeier Hansson.
  • The pool of Copenhagen.rb images on Flickr has grown a fair deal.
  • The mailing list – which is our primary mean of communication – is up to 89 subscribed members.

Ruby adoption in Copenhagen

At the initial meeting, we did a quick poll asking what programming language the crowd present wrote for a living.

  1. Java, 7 (35%)
  2. .NET, 7 (35%)
  3. PHP, 4 (20%)
  4. Other, 2 (10%)
  5. Ruby, 0 (0%)

Recently I posted a poll asking not entirely the same question, but rather what language is the primary language of the people on the mailing list. The results paint a quite different now, a year later:

  1. Ruby, 17 (44%)
  2. Java, 8 (22%)
  3. Other, 6 (17%)
  4. .NET, 3 (8%)
  5. PHP, 2 (6%)

While this is hardly scientific in any way, or any indication that 44% of all programmers in Copenhagen use Ruby, the numbers are sweet music to my ears. I am thrilled that so many people in our small group have been able to go from wanting to do Ruby to actually naming Ruby their primary programming language (it obviously helps that I am one of them). Being able to work on stuff you like in the language you love is a great motivator.

To infinity and beyond?

I am sure the coming year is going to be even more interesting and prove an even higher adoption rate of Ruby in Copenhagen – and Denmark in general. The number of publicly available, danish Ruby-based projects is steadily increasing and is bound to continue to rise.

Rails 2.0 deprecations

The Rails core team is cleaning up. That’s obviously a good thing, however it does leave us facing a kabillion deprecation warnings when running tests and whatnot.

Unfortunately the official deprecations page appears to have been thrown together quickly after someone noticed that Rails 1.2 had been pushed out without anyone finishing the page that all deprecation warnings were referring to.

So what does a smart Rails developer who wants to be ready for Rails 2.0 when that time comes around do? She reads on…

Online payments are still a mess

This is a followup to my previous rant about the state of accepting online subscriptions.

A few things happened after my post. Most importantly the client met with a focus group of potential users, and – among other things – talked pricing with them. Every single one stated they’d much rather prefer paying a one-off yearly fee instead of automated monthly subscriptions.

Launch: MedBillManager

MedBillManager makes dealing with medical bills easier and allows you to compare what you’re paying with what others are paying.

MedBillManager is a little (well not quite that small) something that I’ve been working on over the last couple of months. I did most of the backend stuff together with Wilkes Joiner and Matthew Beale, while Matt Mueller dealt with the front end.

It’s the first Rails application developed primarily by Substance Lab and I’ve been working with Christopher on it since the beginning so it feels really good getting it out the door.

Simplifying my Rails views

Rails views are powerful creatures. You have the full power of Ruby right at your fingertips, which makes it easy to write too much Ruby code in your view making them become cluttered and hard to read.

The following is the tale of how I cleaned up a small part of a single view in BiQ after having made a dirty mess of it.

Copenhagen.rb August meeting

Last Wednesday the Copenhagen Ruby Brigade crowd got together for our first “real” meeting. Approximately 22 people showed up, proving that it wasn’t only the sponsor beer that lured people last time.

Stuff that happened

Jesper introduced his Localization Simplified plugin, which aims to be a dead easy way to alter the default English messages that Rails uses pretty much everywhere. It has since then been added to RubyForge, and support for pirate talk has been added. :)

I gave a brief presentation titled “Legacy stinks” in which I more or less concluded that while it can be tedious and timeconsuming to put legacy database schemas on Rails, it is not as impossible as it used to be.

Finally Casper gave a quick rundown of his experiences and the major topics from RailsConf in Chicago.

The whole shebang took place in the offices of Nordija, who (I think?) also kindly sponsored the pizza for the evening.

About the website

At the meeting I more than alluded that I’d try and get a website up and running last week. Unfortunately the place I registered the domain with apparently hadn’t seen my order until I emailed them to get them to cancel it. Here’s hoping the new registrar has a better sales system. Basically I guess this means the website will be there eventually.

Next meeting

Next meeting of Copenhagen.rb is going to take place September 19th at 17:30. We still need a venue and preferably some topics/demos/presentations, so do sound off on the mailing list if you can provide either.

Copenhagen Ruby/Rails Brigade

Thursday marked the first, casual gathering of what is hopefully going to become the Copenhagen Rails User Group or something like it. We had a great evening with great people, and spent most the time presenting ourselves and discussing what came to mind.

As promised, I’ve set up a mailing list so we can figure out where we go from here, and generally keep in touch etc. Head over here to sign up.

Jesper has posted images from the evening, Olle live-blogged the event, and Kasper has posted his thoughts on the evening and the format.

Plug: Pluggd pluggs in

This weekend Pluggd launched. Pluggd is a podcasting directory/community combining podcast listening with social networking and recommendations built on the belief that many people listen to podcasts online when at work or school, and not just offline while commuting.

Through Substance Lab I have built most of their AJAX interaction, and done Ruby on Rails work helping their permanent team get ready for public launch. The initial visual design was done by me as well, although it’s been somewhat modified over the development process.

Phew, Rails Day is over

After 24 hours of insane, non-stop coding, designing, talking, and general tom-foolery, Rails Day 2006 is over. Nearly 200 teams competed, committing over 5000 total changesets to the official SVN server.

My team

Even though I got a team fairly late, and our initial design/concept wasn’t fully fleshed out, I reckon we got fairly far. The application was inspired by Dan Russells post on Creating Passionate Users about visualizing your life as dots.

The application got almost feature complete, although it got far from as usable as I would have liked it to. We’ll have it deployed to a webserver near you soon. Our team stats are here, for those who care.

Is Rails Day 2007 coming soon?

Rails Day was a really cool (and tough) experience, and I had a lot of fun. Thanks should go to my teammates and our “manager” (yes, Johannes, that’s you ;) ), and to the Rails Day crew. The spectate function, SVN bots, and generally everything has been running pretty smootly, cheers! Also huge thanks to my lovely girlfriend who took good care of me all day, and didn’t even once call me crazy or roll her eyes – at least not while I noticed.

Next year, I am hoping the danish Rails community will be crawling with people so we can field a team all sitting together. That’d be extremely cool in my book. So, see you next year?

Railsday is acoming

This coming Saturday will bring about 24 hours of Rails programming mayhem. Participating would be extremely cool and fun to boot, but I have no team or no really good ideas for a killer application.

So uhm, anyone need a Rails developer with a flair for UI design?

Update: That didn’t take long, looks like I’ll be competing in Rails day for the first time. Cool, looking forward to this.

Benchmarking Ruby, DBI, and ODBC

Also known as “The blog post where Jakob publically ridicules himself pretending to know squat about benchmarking”

As part of our investigation into changing platforms, we’ll be looking for ways to make Rails or Ruby break down and cry. We’ll be kicking groins, pinching nipples and generally be meanies. Todays target is Rubys DBI/DBD connection to a remote Microsoft SQL Server.

Watch out for those return values

For the first time a Rubyism has bit me using Rails. I needed to make sure a field was set to false and not null. So I added af before_save callback to my ActiveRecord model:

before_save :set_defaults
def set_defaults
  self.signup_completed = false if self.signup_completed.nil?
end

This worked great and the testcase passed. Alas, a ton of other testcases failed. Somehow adding the above prevented objects from being saved for no apparent reason. They were valid, .errors were empty, but .save still returned false.

“Jakob”, I asked to myself, “what can prevent an ActiveRecord object from saving?” “Oh, many things”, came the swift reply, “for example callbacks returning false, but that’s certainly not the case here.”

However, that is exactly the case here: Ruby methods return the last evaluated result. Since self.signup_completed = false returns false, my callback was returning false as well, which cancels the save. Doh!

The solution

def set_defaults
  self.signup_completed = false if self.signup_completed.nil?
  return true
end

Ugly, but working.

My little black book of ideas

I carry a Moleskine notebook with me pretty much wherever I go. I use it to jot down ideas and thoughts, usually for websites and -services. At the time of writing I have 10-12 different ideas floating around in my head and/or notebook.

My problem: I have no clue how to monetize these, nor do I know if they are actually good ideas – most probably aren’t.

I could build the core of most of those ideas easily enough. I should probably follow Paul Scrivens idea of taking a weekend and do nothing but hack away at the core functionality of an application and simply get stuff out there, worry about monetization later. Harness the power of Ruby on Rails prototyping, getting real and all that jazz.

Come to think of it, I’ll probably have a bunch of time over Easter to hack away on something. And seeing how I have no pressing client work at the moment, I should probably pick an idea and just go with it.

Hm, it actually sounds like a plan.

Running Rails tests on SQL Server

Quick tip: If you want to run your Rails test suite through Rake on Windows using SQL Server, you need to have the scptxfr.exe utility in your path. On our development server, which is a pretty standard Microsoft SQL Server 2000 install, it’s located in C:\Program Files\Microsoft SQL Server\MSSQL\Upgrade.

And for the sake of completness, on Windows 2000 you change your path variable on My Computer > Properties > Advanced > Environment variables > System Variables. Only command prompts created after the fact will reflect that change.

Kill the Rails pluralization

One of the oft-ranted about features of Rails, is the Inflector – also known as that f***** pluralizer. To turn it off, put this in your config/environment.rb, below the line that says “Include your application configuration below”:

ActiveRecord::Base.pluralize_table_names = false

This works in Rails 1.0, and counters seemingly weird issues where Rails can’t find your tables (like the “Before updating scaffolding from new DB schema, try creating a table for your model” message from the scaffold generator).

To figure out what the pluralizer does and expects, do check out Geoffrey Grosenbach’s Pluralizer Tool.

Fare well David

Last night a bunch of people said goodbye to David, all while trying to prive whatever information we could from that impressive (and loud) mind of his.

Selected highlights from David’s emigration speech/presentation/keynote/whachamacallit:

  • Danish mediocricy-loving and taxes pushed him towards the states.
  • Open sourcing Rails was a fantastic idea.
  • “Reality PR” requires a thick hide and bombastic opinions.
  • We ain’t seen the best of Rails yet.

Thanks bundles to Lars Pind, Thomas Madsen-Mygdal, Martin von Haller, Nikolaj Nyholm, and Guan Yang for organizing that little shindig. Oh, and thanks to Gert from "

Setting the request content type in Rails

To set the content type and character set of your responses of your Rails application, add this to your Application Controller (/app/controllers/application.rb):

class ApplicationController < ActionController::Base
  before_filter :set_content_type
  def set_content_type
    @headers["Content-Type"] = "text/html; charset=utf-8"
  en
end

This can obviously be set in any other controller if you need special contenttypes, for example for a feeds controller:

class FeedsController < ApplicationController
  before_filter :set_content_type
  def set_content_type
    @headers["Content-Type"] = "text/xml; charset=utf-8"
  end
end

How to stay on Rails 0.13.1

In these times where Rails 1.0 Release Candidates introduce memory leaks, bugs, and whatnot, you might want to lock your Rails application to a tried and tested version.

In your config/environment.rb, change your require_gem lines from

require 'active_support'
require 'active_record'
require 'action_controller'
require 'action_mailer'
require 'action_web_service'

to

require_gem 'activesupport', '= 1.1.1'
require_gem 'activerecord', '= 1.11.1'
require_gem 'actionpack', '= 1.9.1'
require_gem 'actionmailer', '= 1.0.1'
require_gem 'actionwebservice', '= 0.8.1'
require_gem 'rails', '= 0.13.1'

and you’ll be rolling on Rails 0.13.1 until you decide not to. Best way to make sure breakage doesn’t happen when your host decides to upgrade without warning you.

My stages of Ruby on Rails acceptance

Andy Budd has posted a about the stages of technological acceptance. They seem to mirror my acceptance of Ruby and Rails quite well.

I remember back when David showed me Ruby for the first time. Come to think of it, he was probably showing me Rails, but I was blissfully unaware of this. David was as excited and enthusiastic as a kid in a candystore, going “Look! You can do this! Open declarations! Ducktyping! Full Object Orientation! Blocks!”.

I looked at him going “Yes, that’s all very fine, but I can do websites in PHP or ASP too, what’s the big deal?”. Heh, kinda fun thinking about that. Obvious denial, eh?

Next phase is supposed to be anger. I don’t recall actually going through anything close to that. My anger phase came as part of my acceptance phase, while trying to install Ruby and Rails on Debian

My acceptance phase came when I kept hearing David rave about Rails and seeing him and everybody else release one kickass application after the other. I figured I’d look into it. It was about time to learn a new language anyways, and it couldn’t hurt.

From that point, understanding wasn’t far away. I think my Point of Understanding was right after Routes was added to Rails. I changed a route around and blam – all my links changed accordingly. I swear, I was clapping my hands with glee.

Leading to enthusiasm, which is definatly the phase I am still in. I am sure everyone in my nearest surroundings can attest to this. And I imagine this very weblog shows proof of this too.

I do wonder, though, what’s the next stage? Saturation? Boredom? Ignorant Bliss?

has_and_belongs_to_one_self

This little Ruby on Rails snippet solves a problem I’ve seen some people get confused by. I figured I’d share my way of doing it.

The trick to behind creating a has_and_belongs_to_many association that associates rows in the same table is to specify more options than you’re used to. Rails can’t figure out how to work it’s magic when associationg 2 classes named the same, so you have to guide it by hand. From a current project in the works:

class ClassDescription < Description
  has_and_belongs_to_many :included_modules, :class_name => 'ModuleDescription', :join_table => 'includes_modules', :foreign_key => 'description_id', :association_foreign_key => 'module_id'
end

Note that this also adds Single Table Inheritance (STI) into the mix, which makes the above less clear. The simplest thing you have to do is:

has_and_belongs_to_many :models, :association_foreign_key => 'other_model_id'

You may want to specify more options to make your tables more readable. The above assumes a table called model_model with the fields model_id and other_model_id.

Slow Lighttpd on redirect_to

This seems to be an issue that pops up every so often on the Ruby on Rails mailing list and IRC channel and probably elsewhere. When using Lighttpd proxypassed behind Apache (this might also be true if you’re not behind Apache, I’m too lazy to check) the redirect_to function will take roughly 30 seconds to complete.

To get around this, you can disable Keep Alive in Lighttpd by adding the following line to your config:

server.max-keep-alive-requests = 0

According to the Lighttpd Trac this has been fixed earlier today, so expect this to go away with the next Lighttpd release.

Update: Seems you can also get around this by hacking ActionController. Personally I prefer disabling KeepAlive.

Lighttpd mod_cgi slowdown issue

My first Ruby on Rails project is currently being tested by some friends. Today one of them told me that it was running REAL slow for him; around 15 seconds per request! Needless to say, that’s bad (and weird, since I saw nothing of the kind). Thus began the hunt.

The application is running Ruby on Rails on MySQL on Lighttpd with FastCGI proxypassed behind Apache, which frankly makes it kinda hard to pinpoint a problem like this.

After a bunch of debugging back and forth it became clear that Lighttpd was screwing something up, even Webrick was serving pages quicker to him. However, I had no clue exactly what was going on, so I started trimming the config.

One item removed at a time, restarting Lighttpd, trying to access a bunch of pages, rinse and repeat.

Heureka! Turns out that removing mod_cgi from the list of loaded modules completely removed the problems. Why? Beats me, but there is no doubt that the entire application is running faster now. Even the logfile shows improvement (4-8 times increase in the amount of guesstimated requests per second). Apparently I wasn’t even using mod_cgi for anything except slowing Lighttpd down.

In the future I should probably configure servers using the same policy as when designing websites: Only include the necessary elements, simple, with less cruft. Lesson learned.

Respect my table name prefix

What’s wrong with this line of Ruby on Rails code?

Car.find(:all, :conditions => ['cars.year = ?', @year])

If you’re doing your own, internal application, nothing major is wrong. However if your application is meant for distribution and end-user-deployment, you’re making dangerous assumptions about the database by hardcoding the table name.

Readable Rails code

Man, I love how humanly readable Ruby on Rails code can be. I mean, I reckon even my mother could guess what this line of actual code does:

redirect_to login_url unless current_user.has_permission_to(MANAGE_USERS)

Ruby on Rails site on Stylegala

Whoa, the Ruby on Rails site got featured on Stylegala. That’s pretty cool and the first site of mine (getting ever harder to call it mine, though, read on for more on that) to get featured on any site-gallery.

The Stylegala entry had an interesting side effect: In the comments, Mike Rundle complained about the sites header – which I’ll be the first to admit was pretty sucky (insert long-winded excuse here). Constructive criticism is always great ofcourse, but in Mikes case, there wasn’t far from words to action and he created a new header for us to use. Very cool stuff!

Thanks Mike, the header now looks just like it always should’ve done.

I've been ripped off

… Well, not really.

The guy behind RailFrog emailed and asked if I was cool with him using the Ruby on Rails design.

For a project like Ruby on Rails it makes a whole lot of sense letting users of the framework use the website design, and it’s kind of funky seeing your work evolve/mutate/adapt.

So yes, I was cool with it and I wish him the best of luck with the project. Oh, and I dig the frog.

Notetagger - Summing up

The previous installments cover roughly 4 hours of development, research and taking notes for these posts. That is 4 hours from doing the initial

rails notetagger

to having an application that works. It’s not perfect in any way, but it does most of what I initially aimed for. Not too shabby for a slowpoke like me, I say.

Notetagger - Adding tags

Onwards to implementing tagging, taking advantage of a whole bunch of Ruby on Rails features: Helpers, assocations, partials, and filters.

I wasn’t entirely sure how to go about the whole tagging business, and I initially went for keeping all the tags separated by spaces in a string. While that’s a perfectly fine way to display and enter tags, it has a whole bunch of flaws when you actually want to store and use the tags.

(You might want to read the previous installment before this one.)

Notetagger - The introduction

I want to get into using Ajax. I want to get more Ruby on Rails experience. I want an online place to post my thoughts and notes since my memory isn’t quite reliable.

If you think the above sounds like something that should be combined into a project, you are right, and I did just that. To make it even more interesting, I’ve decided to share my progress with you and the rest of the world.

Ruby on Rails hurts developer productivity

Gah, using Ruby on Rails is seriously influencing my productivity at work in a negative way. I take longer doing simple stuff, my code has more errors and never works the first time anymore.

“Why? How? Everybody else praise Rails to the skies, why are you different, Jakob?”, I hear the masses cry out. I’ll tell you why!

After having gotten used to RoR for a private project or 2, all the web development stuff I do at work feels ugly, clunky and unproductive, simply because I am not using Ruby on Rails for it.

Now my if statements are all wrong, I try to create objects that don’t exist, I think in terms of before- and after-filters, I expect everything handed to me on a gold platter, but it just doesn’t happen like it does in RoR!

So take my advice: If you are stuck doing legacy work on a legacy system, don’t think about learning RoR – you might never want to go back to work if you do.

Putting Debian on Ruby rails

David keeps yapping about his Ruby on Rails framework, and I have to admit it looks interesting.

So I decided to give it a shot, and see what all the fuzz was about. After all I only had to install 3 things:

  • Ruby
  • RubyGems
  • Rails

But oh boy, had I known the difficulties I was setting myself up for and I probably wouldn’t have…