如何以编程方式生成自定义 Rails 应用程序

How to generate a custom Rails application programmatically

我想在 Ruby 中以编程方式创建自定义 Rails 5.x 应用程序。给定应用程序的规范,我想生成一个 Rails 应用程序文件夹,其中包含该应用程序。我可以想到几种方法来做到这一点,但我不确定哪种是惯用的 Rails 方法。

理想情况下,我想要下面 (5) 中描述的方法。 1-4 是我尝试过的解决方法,但如果可用的话,我更喜欢编程方法。

这里的例子是著名的博客应用程序:

  1. 使用系统命令:

    `# my_app_maker.rb`
    `rails new blog`
    `cd blog`
    `rails generate resource Post title:string body:text`
    `rails db:migrate`
    `# <use a previously created template to modify the controller, layouts and views based on the app specification>`
    
  2. 或者,我可以做类似的事情,但使用脚手架,然后根据需要修改模板。

  3. 使用发电机或发动机。我不知道该怎么做。

  4. 预先创建并模板化 Rails 应用程序,然后使用它来生成 Rails 应用程序。

  5. 理想情况下,我希望 API 完全以编程方式执行此操作。类似于:

    app = Rails::App.new('blog', 'path/to/save/app')
    post = app.resources.add('Post')
    post.controllers.add_actions(['index', 'new']
    # ...
    

执行此操作最惯用的方法是什么?

根据我的经验,rails 应用程序模板 非常适合这个特定的工作。
我认为这正是您所需要的:一个特殊的 API,包装常见的系统命令,以编程方式创建新的 rails 应用程序。

Rails 申请模板

它们是生成整个 rails 应用程序的生成器。

您只需将命令放入 ruby 文件,然后使用以下方法创建应用程序:

$ rails new blog -m ~/template.rb

这是指南中的示例:

# template.rb
generate(:scaffold, "person name:string")
route "root to: 'people#index'"
rails_command("db:migrate")

after_bundle do
  git :init
  git add: "."
  git commit: %Q{ -m 'Initial commit' }
end

资源

Creating and Customizing Rails Generators & Templates guide comes with a lot of explanation on how generators in general work, and the Rails Application Templates guide 详细说明了可用于应用程序模板的 API。

另一个很好的资源是查看 Thoughtbot 的 suspenders gem 的实现。它是 Thoughbot 用于 bootstrap 新项目的 rails 模板。

我自己为 bootstrap 新应用程序创建了一个 rails 生成器,其中包含我在所有项目和通用配置中需要的 gem。它在创建新项目时为我节省了大量时间。