Remember, Ruby Is Everywhere

ruby

Ruby is fantastic for creating domain-specific languages. This means ruby (& therefore rails) development tools are full of domain specific languages - things like ActiveRecord’s Migration syntax, Rspec’s expect() syntax, and so on.

When working with these domain-specific languages, it is easy to forget that you still have the full power of Ruby at your disposal. Case in point: I am currently working on rails application that involves tracking golf scores. Ergo, there is a scores table that stores a player’s results for an outing. Storing a score for a round of golf means inputting 18 integers - one for each hole that the player played. I wanted to just have 18 columns in the database, instead of having some sort of HoleScore class and then expanding it - certainly this might change later, but starting with the simplest answer is usually the right way to go.

How to create the migration? It’s easy to forget that you can use plain old Ruby in your ActiveRecord Migrations! This solution works splendidly:

1
2
3
4
5
create_table :scores do |t|
  18.times do |n|
    t.integer "hole_#{n+1}_score"
  end
end

The above creates 18 columns, all integers, named hole_1_score through hole_18_score. Great!

This can be extended to writing specs as well - although needing to write specs like this is probably a code smell, sometimes it is easiest to just put your spec in a loop:

1
2
3
  [:one, :two, :three].each do |arg|
    expect(a_method(arg)).to eq(a_value)
  end

Happy coding!


I'm looking for better ways to build software businesses. Find out if I find something.