每次rails控制台启动时执行命令

时间:2016-06-30 18:06:03

标签: ruby-on-rails ruby-on-rails-4 rails-console

我有一个设置命令,我想每次执行 我开始rails console -

MyClass.some_method()

每次启动时我都厌倦了重新输入rails c - 有没有办法让它在每次启动新控制台时自动运行?

谢谢!

3 个答案:

答案 0 :(得分:3)

我们这样做是为了在每次控制台启动时要求租户。我们进行了一些调查,但我们的工作相当顺利。请注意,这适用于Rails 5.2,但自Rails 4以来,其工作方式基本上相同。

要注意的另一件事是,这是专门编写的,因为我们希望能够在启动时运行一次该方法,然后在使用控制台时再次运行该方法,例如是否要在会话期间切换租户

第一步是在lib文件中创建一组模块和类。这是一个摘录自我们的示例:

# lib/console_extension.rb
module ConsoleExtension
  # This module provides methods that are only available in the console
  module ConsoleHelpers
    def do_someting
      puts "doing something"
    end
  end

  # This is a simple class that allows us access to the ConsoleHelpers before
  # we get into the console
  class ConsoleRunner
    include ConsoleExtension::ConsoleHelpers
  end

  # This is specifically to patch into the startup behavior for the console.
  #
  # In the console_command.rb file, it does this right before start:
  #
  # if defined?(console::ExtendCommandBundle)
  #   console::ExtendCommandBundle.include(Rails::ConsoleMethods)
  # end
  #
  # This is a little tricky. We're defining an included method on this module
  # so that the Rails::ConsoleMethods module gets a self.included method.
  #
  # This causes the Rails::ConsoleMethods to run this code when it's included
  # in the console::ExtendCommandBundle at the last step before the console
  # starts, instead of during the earlier load_console stage.
  module ConsoleMethods
    def included(_klass)
      ConsoleExtension::ConsoleRunner.new.do_someting
    end
  end
end

下一步是将以下内容添加到application.rb文件中:

module MyApp
  class Application < Rails::Application
    ...

    console do
      require 'console_extension' # lib/console_extension.rb
      Rails::ConsoleMethods.send :include, ConsoleExtension::ConsoleHelpers
      Rails::ConsoleMethods.send :extend, ConsoleExtension::ConsoleMethods
    end
  end
end

现在,每次您运行Rails控制台时,它都会执行以下操作:

enter image description here

如果您只是想在每次启动控制台时运行一次,这比需要的操作复杂得多。相反,您可以仅在MyApp :: Application中使用console()方法,它将作为the load_console step的一部分运行您想要的任何代码。

module MyApp
  class Application < Rails::Application
    ...

    console do
      puts "do something"
    end
  end
end

我们遇到的一个问题是,它在打印出环境之前就运行了代码,因此,如果您要进行任何打印或交互操作,那会感觉有些奇怪:

enter image description here

您可能不像我们现在那样挑剔。做任何使您和您的团队最快乐的事情。

答案 1 :(得分:1)

我不知道这是一个好习惯,但你可以检查服务器是否在控制台上运行,如Aditya awnsered

if defined?(Rails::Console)
  MyClass.some_method()
end

请注意,在Swartz运行Spring时,这在Rails初始化期间不起作用,如Swartz所说。

答案 2 :(得分:0)

我会尝试为它创建一个Rake任务,并使用after_initialize调用它:

config.after_initialize do
  IndividualProject::Application.load_tasks
  Rake::Task[ 'foo:bar' ].invoke
end