How to run code automatically when launching a Rails console?

偶尔善良 提交于 2019-12-11 03:52:35

问题


Let's say I wanted a greeting every time the Rails console comes up:

Scotts-MBP-4:ucode scott$ rails c
Loading development environment (Rails 4.2.1)
Hello there! I'm a custom greeting
2.1.5 :001 >

Where would I put the puts 'Hello there! I\'m a custom greeting' statement?

Another Stackoverflow answer suggested, and I've read this elsewhere too, that I can put that in an initializer like this:

# config/initializers/console_greeting.rb
if defined?(Rails::Console)
  puts 'Hello there! I\'m a custom greeting'
end

That doesn't work for me though :(. Even without the if defined?(Rails::Console) I still don't get output. Seems like initializers are not run when I enter a console, despite what others suggest.


回答1:


I use ~/.irbrc for similar purposes (I require a gem in each console session). For example, my .irbrc

if (defined? Rails)
  # Rails specific
end

# common for all irb sessions

You could use your project name to limit executing code to only one project's console:

if (defined? Rails) && (defined? YourProject)
  # code goes here
end


来源:https://stackoverflow.com/questions/29686658/how-to-run-code-automatically-when-launching-a-rails-console

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!