Category Archives: ruby

Java and Ruby: how language principles influence users’ mindsets

I’ve been doing some Java development lately and Java’s verboseness sent me looking for a way to shorten some of the monstrous generic type declarations. I know there is no typedef or similar concept in Java, but hoped that maybe some Java or Design Patterns gurus invented some clever trick or pattern to do something similar. It’s better to use a ThreeLevelHashMapOfStrings type instead of HashMap<String, HashMap<String, HashMap<String, String>>>, right?

Continue reading


Using assert’s message to boost your unit testing productivity

Here’s a quick tip for enhancing your test writing productivity: use assert‘s last parameter, the message. Virtually all assert_... methods accept it. You may have noticed in the docs that the last parameter is always message = nil or message = "". Too bad the docs don’t give examples on how to use this message. So, let me fix that.
Continue reading


TextMate shortcuts you should be using

This is my list of TextMate‘s keyboard shortcuts that are very useful for Ruby and Rails developers, but are not used as widely as they should (according to my very scientific observation on a very representative sample, i.e. my colleagues). I skipped all the obvious ones (like “open file”, “save file”, “go to next window”, “close window” etc.) that most people use anyway. My list includes shortcuts that are very useful but sometimes might be hard to grasp at first or might require a little explanation.
Continue reading


Cromwell version 0.4 is out!

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

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


Introducing Cromwell — Lord Protector of your scripts

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!


Eliminating code duplication with metaprogramming

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


Small TextMate tip

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.


Learn a new programming language

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


Unstubbing methods in Mocha

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


Looping in a no man’s land

…or: how to put class scope to use

The class scope, i.e. the space inside class declaration, but outside method definitions, is a no man’s land in many languages (particularly in Java). By this I mean that you can define methods, variables, and other classes there and you can even execute some code (in variable initializations) but nothing more. Fortunately, in Ruby empty space between method definitions can be filled with all kinds of useful, executable code. Let’s check a few examples.

Continue reading


Subversion updates notification with growlnotify

Here’s another cool use for growlnotify: informing about incoming SVN updates. For me this is crucial when working with TextMate, as it doesn’t have ‘Synchronization view’ like Eclipse has. And keeping up to date with files modified by your teammates helps minimize the number of SVN conflicts you’ll have to resolve.

Continue reading


Way beyond cool: autotest + growl + Doomguy

Here’s something that will amaze your friends to no end. Your male geek friends, that is. Type some code in your editor, save file and… a smiling Doom Marine tells you that all your tests passed. Or, if there were some errors, the Marine is bleeding. The more errors, the more blood. Is it cool or is it cool?

Just look at the screenshots. First: Marine is happy that your tests passed.

The Doom Marine is happy that your tests passed.

Next: there were some failures. The blood starts to flow!

The blood starts to flow.

Even more failures, even more blood.

Even more failures, even more blood.

Oh my, it looks like we killed him, we bastards!

Oh my, it looks like we killed him, we bastards!

How to do this? Read on.
Continue reading


Extending Rails’ magic finders

One of the many cool things of Ruby on Rails are magic finders, or Dynamic attribute-based finders as the documentation calls them. Thanks to them we can write:

User.find_by_login_and_status(some_login, 1)

instead of:

User.find(:first, ['login = ? and status = ?', some_login, 1])

The first form is shorter and easier for human to parse.

Unfortunately, we can only combine attributes using and operator, but the possibility to use or and not operators would also be nice. And, as always when using Ruby on Rails, when we find that library is lacking some feature, we can easily add it. Let’s see how to do it.
Continue reading


each-require anti-pattern

This is going to be a little rant. This little anti-pattern I see all over in Ruby code by various people:

%w{yaml fileutils}.each { |lib| require lib }

I cannot understand why do people write it like this. This is neither shorter nor easier to read than the ‘normal’ version:

require 'yaml' 
require 'fileutils'

Continue reading


A simple shuffle that proved not so simple after all

Yesterday I found following snippet of Ruby magic to shuffle an array:

class Array 
  def shuffle 
    sort { rand(3) - 1 } 
  end 
end                                                      

arr = (1..10).to_a 
# => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]                                                     

arr.shuffle 
# => [1, 8, 6, 10, 9, 3, 7, 2, 5, 4]                                                     

arr.shuffle 
# => [3, 7, 10, 4, 5, 8, 2, 6, 9, 1]

There is one thing wrong with it, but the original site no longer permits commenting on this entry, so I thought I’d share my thoughts here.
Continue reading


Follow

Get every new post delivered to your Inbox.