Cromwell version 0.4 is out!

•2010-02-01 • Leave a Comment

While you weren’t looking, Cromwell — Lord Protector of your scripts turned 0.4. The new features include:

  • logger support,
  • inspect and change Cromwell’s state,
  • restore original traps after protection end,
  • custom traps support.

…and I have run out of To Do list items. So if you use Cromwell (the gem has been downloaded 165 times from Gemcutter as the time of this writing and the github project has 22 watchers so I assume there are some users of it) and you miss some feature or you found some bug or incompatibility, let me know. Otherwise, happy protecting!

Exploiting obscure Ruby quirks for fun and profit

•2010-01-26 • Leave a Comment

Here’s one quirk I accidentally discovered in Ruby. Check this out (this is copied from my irb session):

>> defined? x
=> nil
>> x
NameError: undefined local variable or method `x' for main:Object
	from (irb):2
>> if false
>>   x = 3
>> end
=> nil
>> defined? x
=> "local-variable"
>> x
=> nil

What’s going on here?

Continue reading ‘Exploiting obscure Ruby quirks for fun and profit’

You can’t always do less

•2010-01-18 • Leave a Comment

David Heinemeier Hansson seems to be very fond of his philosophy Less is More. Recently he wrote about it again: You can always do less. I mostly agree with the spirit of the article. Some of my concerns have been already voiced by the commenters (about things being not so sweet in the customer-is-always-right world). I also particularly like this sentence:

Most software has a tiny essence that justifies its existence, everything after that is wants and desires mistaken for needs and necessities.

But I just couldn’t leave without a comment the last paragraph of it:

For every 1 day estimates of a task, there’s a simpler version of that you can do in 3 hours, and an even simpler still you can do in 30 minutes. Back yourself into a corner and these versions will vividly appear before your eye. You can always do less.

Continue reading ‘You can’t always do less’

Introducing Cromwell — Lord Protector of your scripts

•2010-01-04 • Leave a Comment

I’m back after a few months hiatus to present you a shiny new gem of Ruby technology: Cromwell — Lord Protector of your scripts. From the README:

[Cromwell] allows you to easily protect your scripts from being killed while they are doing something that should not be interrupted (e.g. interacting with some non-transactional service) or is too costly to restart (e.g. long computations).

More info and examples can be found on Cromwell’s github page. Gem is hosted on Gemcutter, so installation should be as easy as sudo gem install cromwell.

The API and code are minimalistic for now, but I have some features planned for upcoming versions. While signal handling isn’t rocket science, I haven’t yet seen a gem to do it in a more convenient way than Ruby’s Signal.trap. It would also be good if the gem provided compatibility layer over some OS’s quirks if possible.

Comments, suggestions, bug reports and bug fixes welcome. If you find it useful, I’d be glad to hear it. If you think it’s a piece of crap, I’d like to hear that, too :)

And, last but not least, I wish you a Happy New Year 2010!

The simplest way to set-up a “we’ll be back shortly” page

•2009-07-10 • 2 Comments

If you’re going to have to stop your site for a maintenance or deploy break and care about your users (and SEO!), you should setup a custom 503 page. AskApache provides some documentation on this, but the examples require creating a PHP page. One of the commenters proposed a non-PHP version, but it’s complicated and didn’t work for me.

So, this is the simplest way to set-up a custom “we’ll be back shortly” error page in Apache 2 that also tells Googlebots to retry after 1 hour:

ErrorDocument 503 /503.html
RewriteEngine On
RewriteCond %{REQUEST_URI} !^/503.html$
Header always set Retry-After "3600"
RewriteRule .* - [R=503]

Read on for explanation and a more advanced example.

Continue reading ‘The simplest way to set-up a “we’ll be back shortly” page’

A very simple persistent consumer-producer queue

•2009-06-17 • Leave a Comment

This is my take on implementing a very simple persistent consumer-producer style queue using database table. The producers insert records to the table and consumers process them. There can be many producers and/or consumers working simultaneously. They can be separate processes or threads. There is no explicit locking.

Continue reading ‘A very simple persistent consumer-producer queue’

Finally getting GetText to work with Rails 2.2

•2009-03-07 • 11 Comments

I18n layer, introduced in Rails 2.2, is said to be “the simplest thing that ever could work”. Too bad they didn’t go for “the simplest thing that could be practical to use”. These two can be very far apart. I have a hard time imagining a real-world app using only bare Rails’ I18n engine.

Another unpleasant thing is that Rails 2.2 broke GetText compatibility, which prevents many projects from migrating to Rails 2.2 or later versions.

Well, not anymore. Thanks to clever guys Masao Mutoh and Michael Grosser, it’s finally possible to get Rails 2.2 running with GetText. Read on for details.
Continue reading ‘Finally getting GetText to work with Rails 2.2′

Error while installing Postgresql 8.3 on Windows XP

•2009-02-22 • 6 Comments

I tried to install PostgreSQL on Windows XP using “PostgreSQL One-Click Installer” and got a cryptic message box telling about “error.installing.runtimes”. Googling for this message yielded nothing helpful so I thought I’d post my solution of this problem. I checked Windows’ Event Log and under System tab found a failure event from Windows Scripting Host telling that, basically, I tried to run a script but the host is inactive.

Well, to tell the truth, I inactivated it myself, using the xp-antispy proggy. The solution is to run xp-antispy, find “Deactivate Scripting Host” under “Misceallaneous Settings” and turn it off (make it red). After that PostgreSQL installs without errors.

After installation you can deactivate Scripting Host again, it looks that it’s not needed once PostgreSQL is installed.

How to: turn off ANSI codes in Rails console

•2009-02-02 • 1 Comment

Small tip: when you happen to be running Rails in a console that doesn’t understand ANSI codes (those pesky ←[4;36;1m and ←[0;1m that clutter your display), like for example Windows’ cmd, you can turn them off with:

if RUBY_PLATFORM =~ /mswin32/
  ActiveRecord::Base.colorize_logging = false
end

Put this in config/environments/development.rb and restart script/server.

Took me a while to find it, so I thought I’d post it for posterity :)

Launch first, audit later

•2008-11-07 • Leave a Comment

Some time ago my boss told me that two of his colleagues are building their top secret, Next-Big-Thing site in Rails. They asked him if we (the company) could audit their code. This struck me as a really strange thing to do, given they are nowhere near launching their site. I told my boss: “Sure, we can audit their code, but do they really want to waste their money on this right now?”

Don’t get me wrong, I do care about code quality more than most programmers. I’m all for automated unit testing, high test coverage, using code metrics, profiling, automating builds with continuous integration and so on. We practice most of these things here at Jarorcon. And I would be more than happy to examine someone’s code and point the problems in it (and get paid for it).

Continue reading ‘Launch first, audit later’

Relation from RailsConf Europe, day 3

•2008-09-14 • Leave a Comment

Welcome to the final part of my RailsConf Europe 2008 coverage. On the third day I attended Ruby and Rails Symposium: Versions, Implementations, and the Future, Genomes on Rails and Small Things, Loosely Joined and Written Fast. The keynote was a little bit disappointing, but the other talks were both inspiring, albeit in different ways.

Continue reading ‘Relation from RailsConf Europe, day 3′

Relation from RailsConf Europe 2008, day 2

•2008-09-07 • 3 Comments

It seems that I got too carried away writing about DHH keynote and forgot to mention other session I’ve been to that day. The first one was Hacking the Mid-End: Unobtrusive Scripting and Advanced UI Techniques in Rails, then Rails Software Metrics and Modeling Denormalization – The Speed You Need, the Order You Crave. I’m going to cover each one below.

Continue reading ‘Relation from RailsConf Europe 2008, day 2′

Relation from RailsConf Europe 2008, DHH keynote

•2008-09-04 • 3 Comments

The second day of RailsConf Europe 2008 started with David Heinemeier Hansson’s keynote on legacy software and was by far the most interesting and enlightening of the talks that I attended yesterday. DHH was mainly talking about legacy but I think the main message he was trying to get through was that a programmer should never stop learning, and I totally agree with that. I really regret I haven’t written about this before because now it will look like another DHH fanboy desperately trying to get to the me-too camp. Nonetheless, a couple of my own thoughts first and then on with the show.

Continue reading ‘Relation from RailsConf Europe 2008, DHH keynote’

Relation from RailsConf Europe 2008, day 1

•2008-09-03 • 1 Comment

Panel discussion with DHH and Rails Core Team members

Panel discussion with DHH and Rails Core Team members

The first day was a registration and tutorial day. The registration went smoothly, there was no gigantic queue that people waited in for half an hour like last year. My feeling is that there is less people this year but probably the organization is also better. Read on for a relation on the tutorials I attended and evening’s panel discussion.

Continue reading ‘Relation from RailsConf Europe 2008, day 1′

I will be at RailsConf Europe 2008

•2008-08-31 • 1 Comment

Thanks to my employer Jarorcon, I will be attending RailsConf Europe 2008 in Berlin, Germany. Hopefully it will be at least as good as last year. I also hope to get some more t-shirts than last year (only one).

I’m especially looking forward to attending the tutorials: Better Living Through Resourceful Plugins and Meta-programming Ruby for Fun & Profit. The Object Databases with Ruby on Rails and Extending Ruby with Class talks also look very interesting. There is of course plenty of other interesting talks but I’m still undecided which ones to attend.

I will be also present at Bratwurst on Rails for some serious beer quaffing. I hope the wurst will be better than last time. Don’t hesitate to come up and chat with me if you want.

Breadcrumbs II: the Internationalization

•2008-07-23 • Leave a Comment

This is a quick followup to my breadcrumb solution. If your application is internationalized, I think you might be interested in the code presented below. If not, stick with the original version.

Continue reading ‘Breadcrumbs II: the Internationalization’

Blast from the past: Compaq commercials with John Cleese

•2008-07-09 • 4 Comments

Being a long time Monty Python fan, I couldn’t resist to share these hilarious mid-80’s Compaq commercials with John Cleese.

I Wouldn’t Watch This Commercial

…made from 386 chips and 32 bits of a bus!

Continue reading ‘Blast from the past: Compaq commercials with John Cleese’

Easy and flexible breadcrumbs for Rails

•2008-06-13 • 31 Comments

Most projects I work on require some implementation of breadcrumbs. Unfortunately most solutions that I found take the very simplistic approach: they split the URL and present each part as a link. I really have a hard time imagining that this can be sufficient for any non-trivial app.

I also found session-based implementation, but according to the above mentioned Wikipedia article classification these are path-style breadcrumbs, while I need location-style with a little bit of attribute-style mixed in where needed. That is, the breadcrumbs should normally reflect the page’s location in some (virtual) website hierarchy. Sometimes, while browsing things that are naturally hierarchical (like forum threads/posts, category trees and so on), the breadcrumb trail should also reflect this hierarchy. Read on to see my take on this problem.

Continue reading ‘Easy and flexible breadcrumbs for Rails’

Eliminating code duplication with metaprogramming

•2008-06-05 • 6 Comments

Duplication of code is one of the worst code smells. It should be refactored in order to keep DRY if only possible. This is generally easy. But what if the code itself is not duplicated, but its structure is? That could be a little bit more difficult, but with Ruby’s metaprogamming facilities it’s not that hard. Read on to see how.

Continue reading ‘Eliminating code duplication with metaprogramming’

Small TextMate tip

•2008-05-20 • 5 Comments

Here’s a small TextMate tip I discovered today. Normally, some TextMate functions don’t work too well with Ruby code. Word selection and keyword completion ignore Ruby-specific characters like : or ? or !. For example, if you used somewhere method like blank? and then you type bl and press Esc, TextMate will complete it as blank, ignoring the ? at the end. And don’t even get me started about when you double click blank? and the ? is not selected.

To change it, go to the Preferences (CMD-,) and select Text Editing tab. At the bottom, there’s an editbox labeled Word characters containing a single _ by default. Add characters :?! to this editbox, close the window and you’re done. Enjoy!

There’s one caveat, however. This setting is global and affects word selection and keyword completion in all files. If you edit many other types of files, that could be a problem.

Who do you want to be when you grow up?

•2008-03-25 • 8 Comments

So, you’re young and you’re a programmer. Maybe even a successful one. You have a cool job: the salary is good, the tasks are challenging and your coworkers are both intelligent and funny. Perhaps you’re not “just” a programmer, maybe your job title is something like “developer/designer” or “leading programmer”. I bet your parents are proud of you and most of your non-geek friends envy you. You have probably already created something you’re proud of: some cool app or a web framework. But…

Continue reading ‘Who do you want to be when you grow up?’

Tales from the WTF company, part II

•2008-03-20 • 29 Comments

Welcome to the followup of my Tales from the WTF company. If you haven’t read the first part yet, I’d suggest you do. Otherwise you’ll miss important background info and a really funny story, too. This part starts where the last part ended, around noon of the second day.

Continue reading ‘Tales from the WTF company, part II’

Tales from the WTF company, part I

•2008-02-28 • 17 Comments

Some time ago I had a short episode of working for a Polish branch of a Germany based software company. In this entry (and probably a few following) I’m going to share with you a couple of WTF moments, so if you’re in for a few good laughs, read on! There is also part II of this story.

Continue reading ‘Tales from the WTF company, part I’

Multilingual page caching in Ruby on Rails

•2008-02-02 • 4 Comments

There is plenty of stuff written about caching in Ruby on Rails. You can easily cache anything from objects returned by a query to fragments or even whole pages. Especially storing full pages (known as page caching) in a directory when Apache1 can grab them is really efficient. And there are quite decent tutorials about it.

Sadly, most of the tutorials assume that you live in a small, cozy, speak-english-or-die type of world and your only contact with foreign languages is when you order “pommes frites” at MacDonald’s.2 The rest of us, working on multilingual applications, might have a lot of problems with implementing page caching. Fortunately, it’s not that difficult. Read on to see for yourself.

Continue reading ‘Multilingual page caching in Ruby on Rails’

Teh worstest answer on a job interview ever

•2008-01-23 • 4 Comments

I was asked by our company’s HR guy to take part in a job interview with a candidate and ask a few “technical” questions. The candidate was final year undergraduate at the Technical University and hasn’t worked anywhere yet (at least his CV was silent about it), so I prepared really easy questions for him. The interview started like this:

Me: Can you tell us about some of your bigger projects? What were they about? What technologies did you use?

Candidate: Well… I haven’t done anything bigger. Only the tasks they gave me at the university. And some examples from the books.

Continue reading ‘Teh worstest answer on a job interview ever’

Cookie handling in multi-domain applications in Ruby on Rails

•2008-01-21 • 16 Comments

My team is working on a multilingual multinational application in Rails (I know this sounds incredibly pushy but bear with me). The application is at susuh.de if you want to have a look at it, but it’s still alpha version.

In practice, this multi-multi-blah-blah means that we want to use both various national domains (like susuh.at, susuh.pl — those links don’t function yet, they are only examples) and various subdomains (like pl.susuh.de or en.susuh.pl). The national domains will filter content only to respective country (so susuh.de will only have content from Germany) and the subdomains will be used to change the default language for the national domain (so if you are an English-speaking person living in Germany, en.susuh.de is your place to go). The subdomain will also be important in multilingual countries like Switzerland.

Trying to implement this scheme we’ve run into problems with cookie domain handling in Rails. And cookie problems lead to session problems for users, like being erroneously logged out or loosing other settings.

Cookie Monster
Mandatory Cookie-monster reference (you wouldn’t believe how many hits from Google this provides).

It seems that there are two official (normal) ways of handling this — at least that’s what Google says. Either you set your default session options in environment.rb like this:

ActionController::CgiRequest::DEFAULT_SESSION_OPTIONS[:session_domain] =
  '.susuh.de'

Or you don’t set it at all.

The former lets you set cookies for any subdomain of susuh.de, like pl.susuh.de, but no other domain. The latter sets cookie independently for each subdomain, causing different cookies for pl.susuh.de, en.susuh.de and susuh.pl. Neither is what we really want.

Spice Girls
So tell me what you want, what you really really want?

What we really want is to have the same cookie for any subdomain of susuh.eu and a different one for any subdomain of susuh.pl and so on. Nota bene, I’m not talking about a Single Sign-On problem, this is on much more basic level. We tried experimenting with setting DEFAULT_SESSION_OPTIONS “on the fly” in before_filter, but found out that this is too late (basically, this sets cookie domain for next request).

Fortunately, all is not lost. If all else fails, start reading code. And that’s what I did. The “entry point” for Rails is defined in dispatcher.rb file. Glancing over the code, I noticed something new for me: a before_dispatch callback. Google agreed that this may be a way to go, giving us link to http://m.onkey.org/2007/10/16/dispatcher-callbacks, among others.

Here’s our solution:

require 'dispatcher'
module ActionController
  class Dispatcher
    def set_session_domain
      ApplicationController.session_options.update(
        :session_domain => "#{@request.host.gsub(/^[^.]*/, '')}"
      )
    end

    before_dispatch :set_session_domain
  end
end

Does stubbing make your tests brittle?

•2008-01-07 • 9 Comments

Stubbing and mocking in unit tests is generally considered a Good Thing. It can make your tests run faster, it helps you not to cross boundaries. But it also makes your tests more brittle.

The reason for this is simple. If you want to stub out some method, you have to do it very precisely. You have to know the underlying implementation and choose a very concrete instance and method for stubbing. This makes your test very tightly coupled to the implementation details of tested class. And tightly coupled is brittle. Let’s look at some trivial example:

Continue reading ‘Does stubbing make your tests brittle?’

Learn a new programming language

•2008-01-03 • 10 Comments

As many of the luminaries of programming say, you should learn a new programming language every new year. That’s what I’ve been doing for several years now. Maybe not that strictly to start on January 1st with a completely new language and lose all interest in it on December 31st, but learning new things (including new languages) is one of my favorite things to do. And since I can probably list more languages that I think I “know” than I have spent years as a professional programmer (whatever that means), I think I’ve been true to above mentioned rule.

Continue reading ‘Learn a new programming language’

Too much intuitiveness will kill you

•2007-11-30 • Leave a Comment

Recently I wanted to export some of my snippets from Textmate, so my teammates could use them too. I tried everything: right-clicking on snippets and bundles, clicking various buttons in Bundle editor, searching through menus and options, but I couldn’t any command for doing so. After several minutes of frantic clicking, I resorted to reading help file. To my surprise, exporting and importing bundle items is very simple, almost too simple.

If you want to share a bundle or particular bundle item then you can drag it directly from the bundle editor (from the list in the left side of the window) to the Finder.

This item can then be sent to other people and they will be able to double-click it to install it. Note: this also works for single items, like a snippet or a command.

TextMate manual

Moral of the story: too much intuitiveness will kill you. Or: if you make something too simple, some people may overlook it. Maybe you should add a less intuitive option for them too (like right-click menu item).

Unstubbing methods in Mocha

•2007-11-09 • 3 Comments

Recently I needed to ‘unstub’ a method in Mocha. Browsing Mocha documentation and googling yielded no results. Apparently, Mocha doesn’t support a concept of ‘unstubbing’, i.e. recovering original implementation of a method that has been stubbed. After a little hacking, I found out that it’s quite easy (though not necessarily elegant) to call original implementation.

Continue reading ‘Unstubbing methods in Mocha’