If you are not using the Rails console while your developing then now is the time to start! I learn best by example, so that’s how I am going to structure this.
Here’s the scenario:
You are writing code against a class and need to determine which attributes you have available to you. In Rails, your attributes are largely driven by the database schema, so you will not see them in the class definition. At this point most developers will take a look at the table in the database and find the column they need, then determine the type of data stored there. There is a better way…
Let’s use the command line.
We start by firing up our Rails application in console mode:
You must be in your Rails application directory to issue this command.
So now what? Well now you have command line access to your entire Rails application! For example, let’s say you have a class named Person (which would map to a people table in the database). You want a new instance of this class? Then issue the following:
p = Person.new
Perhaps you want to view a Person from the database:
p = Person.find(1)
By default the results are displayed below each command and they are not very friendly, so let’s output them in YAML as it will be much more readable:
‘y’ is like calling ‘puts p.to_yaml’ on the resulting value that follows it. There is also a ‘p’ shortcut that is the equivalent of issuing ‘puts’ on the value.
So how does this help with determining attributes? At first glance you may think you have to look at the list of values returned in your YAML command and find what your looking for… no… it gets better. Remember that all Ruby objects inherit certain methods, watch this:
You want to get the methods associated with your object:
You can also get the private, public, and protected methods using the following commands:
1 2 3
y p.public_methods y p.private_methods y p.protected_methods
So this class could return a huge YAML result which may not seem as efficient as scanning the schema in the database, and you’re right. So let’s get to what we are really looking for using ‘grep':
y p.methods.grep /method_name/
This will return any method which contains method_name. You can write pass any regular expression you like into this command and really drill into your class methods, and for help putting those regular expressions together I really like using Rubular a web-based Ruby regular expression editor.
And what about the type of an object?
This is just a taste of what you can do with the console… I use the console everyday as I develop. I will post some more console tips in future posts!