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!