如何创建自定义 IRB 文件以加载 Ruby 项目的文件、gem 和依赖项?

How to create custom IRB file to load a Ruby project's files, gems and dependencies?

有谁知道如何从终端 运行 一个需要 N 个文件/gem 的 ruby 文件,并在 IRB 会话结束时将这些文件加载​​到内存中?

换句话说,我希望是这样的:

$ ruby project_console.rb

# project_console.rb
IRB.new do |config|
  require 'bundler/setup'
  require 'import_project_file'
  require_relative "spec/muffin_blog/app/models/random_file"
  Post.establish_connection({database: "spec/muffin_blog/db/development.sqlite3"})
end

# yay. I'm in my custom IRB session with all of the above already loaded
2.4.1 :001 >

 $ irb
     2.4.1 :001 > require 'bundler/setup'
     => true
    2.4.1 :002 > require 'import_project_file'
     => true
    2.4.1 :003 > require_relative "spec/muffin_blog/app/models/random_file"
     => true
    2.4.1 :004 > Post.establish_connection({database: "spec/muffin_blog/db/development.sqlite3"})
        # this makes me sad because its manual every time I want to play around with my project.

我正在开发一个 ruby 项目,在构建这个项目的过程中,我发现我需要类似 rails console 的东西,它将整个项目及其捆绑器依赖项加载到内存中,所以我不必手动进行。我认为如果我构建自己的超级东西 'rails console' 以便在构建它时调试/玩弄我的 ruby 会很棒。

另外我在某处读到有一个 .irbc 我可以使用,但这听起来像是我要在我的机器上全局更改 IRB - 我不想那样。我想为每个 ruby 项目加载特定文件、gem 和配置。

为了它的价值,我已经阅读了这些 SO 帖子:

然而 none 他们似乎为我的上述问题提供了答案。

很简单,其实:

#!/usr/bin/env ruby
require "bundler/setup"
# ...
# everything else you need
# ...
require "irb"
IRB.start

当您使用 IRB.start 启动 IRB 时,您将可以使用之前 loaded/initialised 的所有内容。