at.*_*at. 9 ruby ruby-on-rails rails-console ruby-on-rails-4 ruby-on-rails-4.2
假设每次 Rails 控制台出现时我都想要一个问候语:
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 >
Run Code Online (Sandbox Code Playgroud)
我该把puts 'Hello there! I\'m a custom greeting'声明放在哪里?
另一个 Stackoverflow 答案建议,我也在其他地方读过这篇文章,我可以将其放入初始化程序中,如下所示:
# config/initializers/console_greeting.rb
if defined?(Rails::Console)
puts 'Hello there! I\'m a custom greeting'
end
Run Code Online (Sandbox Code Playgroud)
但这对我不起作用:(。即使没有,if defined?(Rails::Console)我仍然没有得到输出。当我进入控制台时,似乎初始化程序没有运行,尽管其他人建议了。
以下内容将在Rails 6中运行:
只需将一个块传递给Rails.application.console,例如
# config/initializers/custom_console_message.rb
if Rails.env.production?
Rails.application.console do
puts "Custom message here"
end
end
Run Code Online (Sandbox Code Playgroud)
现在,当启动 Rails 生产控制台时,将打印自定义消息。当你启动rails服务器时,这段代码不会被执行。
if Rails.env.production?如果您希望它在所有环境中运行,请删除。
我将 ~/.irbrc 用于类似的目的(我需要在每个控制台会话中使用 gem)。例如,我的 .irbrc
if (defined? Rails)
# Rails specific
end
# common for all irb sessions
Run Code Online (Sandbox Code Playgroud)
您可以使用项目名称将执行代码限制为仅在一个项目的控制台上执行:
if (defined? Rails) && (defined? YourProject)
# code goes here
end
Run Code Online (Sandbox Code Playgroud)