After you spend some time working in the same Rails project, being this project whatever project you are working for some time now, you probably use the Rails console a lot, many reasons:
- Testing code
- Seting up data
- Using “binding.pry” to “debug” some controller or model
- Put whatever you are doing in “rails c” now here
And doing it every day, there are tons of things you write there every day, and some times for security reasons your code starts to get more complicated, for example, in one of my projects, the username is encrypted, and I need to call “encrypt_username” before passing the parameter to “find_by”.
For example, in this project, every time I wanted to lookup a user, I had to write:
And as a lazy person that I am, I decided that there should be one easier way to do it, and after some lookup I found out that I could add methods do a “~/.irbrc” file, but that was not good enough, because I work with many projects, and those projects have different code, and many of the “helper methods” would work for one and not for the other.
So I kept digging, and found out that the awesome Rails team had already solved this problem for me, I just created an initializer in the file “config/initializers/console_methods.rb” and added the following code:
Rails.application.console do def find_user(name) User.find_by(username: User.encrypt_username(name)) end end
Now, every time I open the console in that project, I just type “find_user(‘my name’)” and my user is returned.
Of course this is kinda “hackish” solution, the best organization for this, would be to add all the methods I want in the console in a module, and then use the initializer to just include that module, for exemplo creating a “lib/console_utils.rb” with this code:
# These methods are included into the Rails console module ConsoleUtils # Find a user by username def find_user(username) User.find_by(username: User.encrypt_username(username)) end end
then use that initializer we’ve created before to include the module:
Rails.application.console do require 'console_utils' Rails::ConsoleMethods.send :include, ConsoleUtils end
Now, you just need to add the methods to scratch your own itch to the module in “lib/console_utils.rb” and be a lot happier with the tools that Rails already provides!
For example, in another project, I added a method to create easily a JWT token to send requests to a service that shares this authentication (wanna know more about using JWT with Rails?).
In another, a method to save a CSV report from some data that I use a lot;
Ok, but how do you use these methods?
Just open your rails console and type:
Now, if you have questions about these tips, or have more ideas of useful console methods, please leave a comment bellow!