4

Given a simple custom generator:

# lib/generators/custom_model/custom_model_generator.rb

class CustomModelGenerator < Rails::Generators::NamedBase

  def rails_generate_model
    generate 'model', "#{file_name} #{args.join(' ')}"
  end

end

Which is used like so:

$ rails generate custom_model ModelName

How can i define the destroy behavior for this custom generator?

$ rails destroy custom_model ModelName

Actually, my problem is that this generator use the generate method to use an existing rails generator. But i couldn't find any method to reverse what this generate did.

I used to use this for my own generators (which doesn't call any existing generator), and write my own "destroy" routines:

  case self.behavior
    when :invoke
   # do that stuff
    when :revoke
   # undo it!
  end

I red a lot about this accross the web, but nothing relevant or up-to-date. So any advices are more than welcome.

Thanks for reading.

4

1 回答 1

1

您可以使用以下代码(当然您可以:scaffold用任何其他生成器替换):

case self.behavior
  when :invoke
    generate :scaffold, "#{file_name} #{attributes}"
    # Or equally:
    # Rails::Generators.invoke :scaffold, args, :behavior => :invoke
  when :revoke
    Rails::Generators.invoke :scaffold, [file_name], :behavior => :revoke
end
于 2015-09-27T21:22:10.070 回答