Archive for the ‘Ruby’ Category

Always index your tables. Always

Saturday, August 9th, 2008


This is going to be brief one: iRead.ro, one of the projects I’m working on during my spare time, was giving me major headaches lately – 2 weeks ago, it took like 15 seconds to render a page. In the last couple of days, it was taking somewhere around 100 seconds to render it; obviously too much for the nginx server that was running my two mongrels.

I *had* indexed my tables, by id, url and several other fields. Turns out, they weren’t indexed with the right columns.

(more…)

10 Ruby programming tips you should already know

Wednesday, July 2nd, 2008

Other blogs about Ruby or Rails have already touched some of the tips I’m going to show, but it never hurts to remind you these small recipes aimed at Ruby novices:

(more…)

Enumerable iterators (why I love Ruby part 2)

Wednesday, January 16th, 2008

Got myself a sleepless night recently and killed some time reading the Rubyisms in Rails book. The chapter about Iterators was particularly pleasant, reminding me the beauty of Ruby’s Enumerable class – feels so Lisp-ish and Scheme-ish to write stuff like col.select{..}.collect{..}.join(“, “)

For the curious, here’s a cool excerpt from the book, with Enumerable’s most important methods:

Examples of Enumerable’s Higher-Level Iterators

Selection
common = bird.select {|bird, count| count > 5 }
rare = bird.reject { |bird, count| count > 5 }

Accumulation (summing up values)
sightings = birds.inject {|total, bird| total += b.count}

Detection
indie = jukebox.any? {|x| x.artist.hip? }

Searching
Winner = contestants.find {|p| p.has_answer? }

Reordering
titles = jukebox.sort_by {|x| x.title }

Partitioning
quick, dead = people.partition {|p| p.can_outrun? :bear }

Recombination
blind_dates = restaurants.zip(men, women)

Go ahead, read the docs and use Enumerable without restraints – your code will look much more beautiful and, well.. Rubyish.

Ruby Metaprogramming part 2

Wednesday, November 7th, 2007

Last time I discussed Ruby and metaprogramming, I was trying to stay DRY (Don’t Repeat Yourself) while coding some very similar-looking methods. The solution, then was to use class_eval to dynamically add methods into the current class, the way attr_accessor and it’s peers already do.

Today I was having a similar, yet more difficult problem: the architecture of my app includes two controllers: IncomeController and ExpenseController, two identical twins, each saving, updating and listing it’s associated models (Income/Expense), where Income has_many income_attributes and.. you guessed it, Expense has_many expense_attributes. And the list can go on, since they have some more relationships, all of them being identical but for the names and associations.

I know, perhaps such thing might have been avoided if, in the first place, we would have used single-table inheritance and such. But for various reasons we didn’t, and I was getting tired of keeping in sync all the changes in Income* to Expense* and vice-versa.

So.. what could the solution be? Namely, I wanted both IncomeController and ExpenseController to share the same codebase, the only difference being the names; I wanted a… replace_all to be run on the fly.

Luckily for me, I remembered Camping, a Ruby Microframework for web apps(kinda like Rails, but more simplistic), which uses some intense metaprogramming-kung-fu to keep its code to less than 4kb. For instance, in the homepage example, we see that

A skeletal Camping blog could look like this:
require ‘camping’
Camping.goes :Blog

The .goes method returns a class duplicate of the Camping one, where all occurences of Camping have been changed with Blog.

(more…)

Ruby: create your code on the fly

Saturday, September 8th, 2007

Ruby is so powerful it scares me. I’m far from even grasping how powerful it is. Whenever I discover something cool to do with it, I have the urge to tell it to the world.

First, here’s the context:
I’m currently working my way through building a Rails browser game in the style of these ones. For simplicity’s sake, think of it as a RPG-style game.
I have an Avatar object that belongs_to Race and Occupation.
The avatar, race and occupation have several common properties: mana, health, reactivity, initiative, etc. The avatar has its own health, mana or reflexes value, but when I access them I want to sum them up with the corresponding values stored in the Race and Occupation; this means that the race and occupation you chose when creating the avatar will impact the character’s features throughout the game.

What I could do was to define accessor methods for each property:


  def get_mana
    mana+race.mana+occupation.mana
  end

  def get_health
    health+race.health+occupation.health
  end

While it works just fine, the problem of this approach is that it’s not DRY(Don’t Repeat Yourself) – if I have tens of such common properties, I end up having tens of similar methods which differ only by the name of the property. So what I wanted to do was to have a method similar to the attr_reader one, with my own body instead.

(more…)

Ruby for daily chores: Extracting most frequent loto numbers

Sunday, August 19th, 2007

Here’s the quick story: I was hoping to win the Romanian lottery (6 winning numbers out of 49). On the website, they were having the list of the winning numbers from 1998 to now. So I copy-pasted them all into a text file, and wrote a quick and dirty script to count their appearances and sort them – thus getting the lists of the most frequent numbers and the least frequent ones.

First, the input text file – I’ll show you a brief excerpt:

(more…)

Setting up Rails and SQLITE

Wednesday, April 25th, 2007

If you are interested in web, databases and the like then you probably already heard of SQLITE. If not, here’s a quick intro
SQLITE is a database engine that uses just one file per database. It’s tiny, simple to use and, most importantly, very easy to use with Ruby on Rails. All you need is the sqlite ruby gem, which is already included in most Ruby installations.

What is sqlite3? Nothing much than a newer and better version of sqlite. You should use it instead of sqlite if you have the chance.

How do you set it up in Rails?
Let’s say you want to make your own database-driven Rails application. Mysql is a big download, a bit difficult to install, etc. Plus, you don’t really need it; you just want a tiny sql database engine that works with Rails, so you can develop and test your application.
Nothing easier: if not already installed on your machine, then you download and install sqlite3.
Then you make sure you have the latest sqlite bindings in place : gem install sqlite3 .

Hmm.. what else?

(more…)

TwitterYM – tiny ruby Yahoo Messenger status Twitter updater

Wednesday, April 4th, 2007

Challenged by a commenter on my website, I spent the last half an hour coding a tiny application that updates your Yahoo Messenger status with your latest Twitter status. It’s Windows only (I’m a Mac user myself, and twitterific does a good job for it).

The reason why it’s a Ruby script and not a self executable is because I’m in a rush and have to go out of town for Easter. I’ll improve things when I get back, if you want me to.

Download it from here: http://alexbrie.net/files/twitterym.rbw and leave your feedback in the comments.

PS. you need to be on windows and have a ruby installation on your system. Extra instructions are below:

# to make it work:

# 1. install ruby on your machine;

# 2. install the gems specified here http://addictedtonew.com/archives/187/ruby-twitter-gem/ :

# gem install hpricot --source http://code.whytheluckystiff.net -v 0.4.86

# gem install twitter

# 3. change the line s = Twitter::Base.new('my_email', 'my_password').timeline(:user)[0]

# by entering your login credentials for the twitter account

# 4. start yahoo messenger

# 5. run the script

Enjoy!

Grepping in Ruby

Tuesday, April 3rd, 2007

You can’t call yourself a programmer if you never used Grep (or diff, or wget, or regular expressions for the matter). I couldn’t call myself a programmer till the fourth year of college, btw.. :)

Still, grep has a pretty big manual page, and being a casual grep user I never see the need to memorize it. The one and only grep command I use and abuse is
grep -Rn "my pattern" . which, for people not familiar with it, means “search my pattern in all files under the current dir, recursively, and if find then print out also the line number”. Seriously, this might be the one and only use I have for grep now.

What about more complicated tasks, involving regular expressions and the like?

Since my job involves Ruby and Rails, there’s basically no need for me to use grep anymore. I mean, my tasks don’t involve real-time text line extractions; from time to time, though, they involve writing scripts that extract specific patterns from some log file.

Here’s where Ruby is my best friend. And given that I’ve had a bit of trouble putting together the bits and pieces found on the internet, I’m sticking it all together here:

(more…)