如何使用自定义生成器覆盖rails中的文件

时间:2016-05-11 09:15:32

标签: ruby-on-rails-4 generator

我有一个名为Datatable的自定义生成器,文件结构如下:

 lib/generators/datatable/templates
 lib/generators/datatable/templates/datatables.rb
/lib/generators/datatable/datatable_generator.rb

这些是我的文件夹结构,我的datatable_generator.rb包含:

 class DatatableGenerator < ::Rails::Generators::Base
  desc 'Creates a *_datatable model in the app/datatables directory.'
  source_root File.expand_path('../templates', __FILE__)
  # argument :name, :type => :string
   argument :name, :type => :string
   argument :name1, type: :array, default: [], banner: "action"
  def generate_datatable
    file_prefix = set_filename(name)
    @datatable_name = set_datatable_name(name)
    template 'datatable.rb', File.join(
      'app/datatables', "#{file_prefix}_datatable.rb"
    )
  copy_file "stylesheet.css", "public/stylesheets/#{file_name}.css"
  template  "layout.html.erb", "app/views/#{file_name}s/index.html.erb"
  end

  private
 def file_name
   name.underscore
 end
  def set_filename(name)
    name.include?('_') ? name : name.to_s.underscore
  end

  def set_datatable_name(name)
    name.include?('_') ? build_name(name) : capitalize(name)
  end

  def build_name(name)
    pieces = name.split('_')
    pieces.map(&:titleize).join
  end

  def capitalize(name)
    return name if name[0] == name[0].upcase
    name.capitalize
  end
end

我正在尝试找到一种方法,我需要更改控制器的索引操作,例如我正在为demo生成datatable我将运行此命令生成datatable Demo cbc cbdd cbse here demo是一个脚手架并且在它的索引动作我只需要覆盖我想要的索引动作:

  def index
@dis_additive_frequencies = DisAdditiveFrequency.all
 end

是这样的:

def index
 respond_to do |format|
   format.html
   format.json { render    json:DisAdditiveFrequencieDatatable.new(view_context) }
 end
 end

是否有任何方法可以编辑某个文件的索引操作。

1 个答案:

答案 0 :(得分:1)

您可以使用诸如gsub_file或insert_into_file之类的Thor函数来检查thor的文档:http://www.rubydoc.info/github/wycats/thor/Thor%2FActions%3Agsub_file

我认为您想要替换以前的索引操作,并且您希望将其替换为新的索引操作,因为您可以使用此代码:

 # Start ---this logic is to comment default index action querly example @ankurs = Ankur.all
   path = "app/controllers/#{file_name}s_controller.rb"
   line = "@#{file_name}s = #{@datatable_name}.all"
   gsub_file(path, /^(\s*)([^#|\n]*#{line})/, '\1# \2', *args)
   # End ---this logic is to comment default index action querly example @ankurs = Ankur.all

 # Start ---this logic is to append content in index action
  content = "
   respond_to do |format|
     format.html
     format.json { render json:#{@datatable_name}Datatable.new(view_context) }
    end"
  insert_into_file path, content, :after => "@#{file_name}s = #{@datatable_name}.all\n"
  end
 # Start ---this logic is to append content in index action

这将注释您要替换的代码,并在下面添加新代码。