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.

1 Answers1

1

You can use the following piece of code (of course you can replace :scaffold with any other generator):

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
Pedram
  • 224
  • 1
  • 3
  • 12
  • I tested this inside of my custom generator, where I generate a model, and this pattern works. Thank you for providing this solution. – Jay Dorsey Sep 24 '19 at 12:49