【问题标题】:Rails generator not removing newly created folders on destroyRails 生成器不会在销毁时删除新创建的文件夹
【发布时间】:2018-10-18 19:36:21
【问题描述】:

我正在编写一个 Rails 生成器,它将文件/文件夹从我的 gem 的模板目录复制到应用程序的目录中。当我运行 rails generate mygem:install 时,它按预期工作,但是当我尝试使用 rails destroy mygem:install 反转它时,它不会删除新创建的子文件夹。

模板文件夹

├── templates
│   ├── views
│   │   ├── about
│   │   │   ├── index.html.erb
│   │   ├── contact
│   │   │   ├── index.html.erb 

app 文件夹(生成后)

├── app
│   ├── views
│   │   ├── about
│   │   │   ├── index.html.erb
│   │   ├── contact
│   │   │   ├── index.html.erb 

app 文件夹(销毁后)

├── app
│   ├── views
│   │   ├── about
│   │   ├── contact

期望的结果

├── app
│   ├── views

我的 gem 的安装生成器

module Mygem
  module Generators
    class InstallGenerator < Rails::Generators::Base

      source_root File.expand_path('../templates', __FILE__)

      def copy_templates
        templates = Dir.glob("#{source_paths[0]}/*")
        directory(templates[0], "app/views/")
      end

    end
  end
end

【问题讨论】:

    标签: ruby-on-rails rails-generators


    【解决方案1】:

    我遇到了同样的问题 - 通过将以下内容添加到我的 generator.rb 文件来解决

    def clean_up
      case self.behavior
        when :revoke then `rm -rf path/to/directory/`
      end
    end
    

    您还可以使用:invoke 选项来指定仅在生成时发生的操作:

    case self.behavior
      when :invoke then do_something
    end
    

    所以

    # something_generator.rb
    
    def generate_directory
      case self.behavior
      when :invoke
        `mkdir path/to/directory`
      when :revoke
        `rm -rf path/to/directory`
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-01
      • 2021-07-12
      • 1970-01-01
      • 2016-10-28
      • 2012-04-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多