How to execute code after Rails console has loaded?
Asked Answered
C

3

6

How does one go about running code specifically after a console has loaded in Rails? All other answers and questions appear to revolve around running a hook at some point, but not necessarily after as I am seeking.

Desired Result:

> rails console
Loading development environment (Rails 5.1.1)
pry(main)>
Welcome

I have attempted to use both the console hook and initializer hook with no success. e.g.

Attempt 1:

# config/application.rb

console do
  puts "Welcome"
end

Result:

> rails console
Welcome # Too early                                                              
Loading development environment (Rails 5.1.1)
pry(main)>

Attempt 2:

# config/application.rb

initializer "welcome", after: :disable_dependency_loading do |app|
  puts "Welcome"
end

Result:

> rails console
Welcome # Too early                                                              
Loading development environment (Rails 5.1.1)
pry(main)>
Cartesian answered 16/10, 2017 at 23:22 Comment(1)
I am not certain of your desired result, but have you considered rails runner, i.e. "rails runner 'p Rails.env' "?Bartolemo
C
5

When Using with IRB

Create a .irbrc file (it should be root of your project) you should set conf for IRB_RC. Below is the file

#.irbrc
IRB.conf[:IRB_RC] = Proc.new do
  puts "Welcome"
end

Output

~/D/p/p/s/console_test> rc
Running via Spring preloader in process 60648
Loading development environment (Rails 5.1.4)
Welcome #<======= Desired Result
irb(main):001:0>

When Using with PRY

Create a .pryrc file (it should be root of your project) you should set conf for exec_string. Below is the file

#.pryrc
class WelcomeClass

  def self.greet
    puts "Welcome"
  end
end

Pry.config.exec_string = WelcomeClass.greet

Output

 ~/D/p/p/s/console_test> rails console
Running via Spring preloader in process 61794
Loading development environment (Rails 5.1.4)
Welcome #<======= Desired Result
[1] pry(main)>
Carpic answered 17/10, 2017 at 5:8 Comment(0)
B
1

Create an ".irbrc" in your root. This is simply a regular Ruby script file where you can run code on IRB startup. For examples, see Tweaking IRB.

Bartolemo answered 17/10, 2017 at 1:31 Comment(0)
W
0

You can create a config/initializers like this:

# config/initializers/001_test_console.rb
module Rails::ConsoleMethods
  def self.included(base)
    puts "Welcome!"
  end
end

Note: I've not tried this with pry, just standard irb.

Wallas answered 17/10, 2017 at 1:50 Comment(1)
Should still work as of Rails 6, but monkey patching like this could break in future versions.Ivette

© 2022 - 2024 — McMap. All rights reserved.