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
The above creates 18 columns, all integers, named
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