[英]Rails: How to run code when server starts up, but not when running a rake task or the console?
[英]How to run code automatically when launching a Rails console?
假设每次 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 >
我会把puts 'Hello there! I\\'ma custom greeting'
哪里puts 'Hello there! I\\'ma custom greeting'
puts 'Hello there! I\\'ma custom greeting'
?
建议的另一个 Stackoverflow 答案,我也在其他地方读过这个,我可以把它放在这样的初始化程序中:
# config/initializers/console_greeting.rb
if defined?(Rails::Console)
puts 'Hello there! I\'m a custom greeting'
end
虽然这对我不起作用 :(。即使没有if defined?(Rails::Console)
我仍然没有得到输出。似乎当我进入控制台时初始化程序没有运行,尽管其他人建议。
我将 ~/.irbrc 用于类似目的(我在每个控制台会话中都需要一个 gem)。 例如,我的 .irbrc
if (defined? Rails)
# Rails specific
end
# common for all irb sessions
您可以使用项目名称将执行代码限制在一个项目的控制台:
if (defined? Rails) && (defined? YourProject)
# code goes here
end
以下将在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
现在,当启动 rails 生产控制台时,将打印自定义消息。 启动 rails 服务器时不会执行此代码。
删除if Rails.env.production?
如果您希望它在所有环境中运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.