启动 Rails 控制台时如何自动运行代码? [英] How to run code automatically when launching a Rails console?
问题描述
假设每次 Rails 控制台出现时我都想打个招呼:
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 >
我该把 放在哪里,你好!我是自定义问候语'
声明?
建议了另一个 Stackoverflow 答案,我也在别处读过这个,我可以把它放在这样的初始化程序中:
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
虽然这对我不起作用:(.即使没有 if 定义?(Rails::Console)
我仍然没有得到输出.似乎当我输入时没有运行初始化程序控制台,尽管其他人建议.
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.
推荐答案
我将 ~/.irbrc 用于类似目的(我在每个控制台会话中都需要一个 gem).例如,我的 .irbrc
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
这篇关于启动 Rails 控制台时如何自动运行代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!