How to add custom methods to Rails console

Juraj Kostolanský November 13, 2021

Sometimes we all need to do something in the Rails console. Did you know you can easily extend the Rails console with your own methods?

To do so, just create the following module:

# lib/core_extensions/console_methods

module CoreExtensions
  module ConsoleMethods
    def hello_world
      puts "Hello world!"
    end
  end
end

Edit the development environment config file and use this new module:

# config/environments/development.rb

require "core_extensions/console_methods"

Rails.application.configure do
  # ...

  module Rails::ConsoleMethods
    include CoreExtensions::ConsoleMethods
  end
end

Alternatively, you can also create an initializer if you want to use this method in all environments:

# config/initializers/console_methods.rb

Rails.configuration.to_prepare do
  require "core_extensions/console_methods"
  
  module Rails::ConsoleMethods
    include CoreExtensions::ConsoleMethods
  end
end

Done! You can now use your new hello_world method in the console:

$ bin/rails c

irb(main):001:0> hello_world
Hello world!

Let's stay in touch

Do you like what you read? Subscribe to get my content on web development, programming, system administration, side projects and more. No spam, unsubscribe at any time.