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:
class CreateEnemies < ActiveRecord::Migration[5.2]
def change
create_table :enemies do |t|
t.timestamps
end
end
end
and created an empty model, like so:
class Enemy < ApplicationRecord
end
Then a couple more commands, in order to create a database, and build the ‘enemies’ database table:
rails db:create
rails db:migrate
Now, at last, I’m ready to open a Rails repl (which is conveniently called a console, go figure) with the command ‘rails c’. Rails ‘helps’ us by allowing partial commands, although the command ‘rails console’ would work just as well.
rails c
Enemy.new.save
So, when I run Enemy.first.methods
, the repl prints an array of all the methods;
we will save those into a variable to work with, but I want to take a moment
to talk about the massive amount of data that just printed to the screen;
When working with Rails classes, sometimes whatever is returned is going to
be pages long, and can really mess with your ability to scroll up and down,
to keep track of what you’re doing. I like to clean up the screen output, by
taking advantage of the ability to run two commands sequentially. When I do this,
only the output of the last command will be printed.
Running the command:
enemy_methods = Enemy.first.methods ; nil
cleans up the returned information, by returning nil
. Here are a couple other
fun things you can do with this:
enemy_methods = Enemy.first.methods ; "done"
# If I run something from the console that's going to take a while,
# it might be cool if my computer could tell me when it's done!
enemy_methods = Enemy.first.methods ; system('say done') #mac-only, I think!