Rails for Villains

Before We Start

Ok, now, let’s do something useful, and talk about the rails console. I’ve created a very simple Rails application, using ruby version 2.5.1, and rails 5.2.4.3. This shouldn’t matter, because I’m not doing anything special, but who knows.. maybe these commands won’t work for you, and knowing the versions will help. rails new rails_for_villains cd rails_for_villains rails g migration createEnemies I edited the generated file, so that the model I create would contain only the ‘updated_at’ and ‘created_at’ timestamps, like so:

Metaprogramming Monologue

Rails has a concept called ‘convention over configuration’. In theory, this means that, by following conventions, we can accomplish a lot of work, without having to spend very much time configuring very much at all. In practice, it means that, generally, it’s not obvious what’s happening, especially to a Rails newbie. This can be confusing, but it works through a concept called metaprogramming. Metaprogramming means that, rather than creating a lot of boilerplate code, rails will follow general conventions to automatically create a lot of functionality for us, in the form of methods that are created at runtime, and so only exist in active memory, in a running Rails application.

Metaprogramming Exploration

Here, we are going to create a situation where we can see what new methods are created in Rails, when a new field is added to a table. To accomplish this, we can use two consoles. One will be a simple command line, and the other will be a rails console. In the first console, it’s important to stay logged in; we’re going to capture the list of methods on the ‘enemy’ table, before and after a migration, so that we can easily see the difference, and run a migration in the second console, to actually add a field to the database.