Rails 4 custom generator, revoke/invoke

702 Views Asked by At

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

There are 1 best solutions below

1
Pedram On

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