How to get generators call other generators in rails 3

前端 未结 4 682
攒了一身酷
攒了一身酷 2021-02-05 16:58

I am experimenting with gem development, right now specifically generators. So far I have successfully created two generators that do their job just perfectly. These two generat

4条回答
  •  温柔的废话
    2021-02-05 17:03

    Another possibility is to use something like

    invoke 'active_record:model', 'foo bar:string baz:float'
    

    which is not as clean as generate, but has one advantage: When your generator gets called via rails destroy, this call -- like may other of Thors actions -- will try to revoke the action of the generator you invoke.

    There's a catch however: Probably due to Thors dependency management, this only works once per generator you want to call, meaning that a second invoke of the same generator will do nothing. This can be circumvented by using a statement like

    Rails::Generators.invoke 'active_record:model', '...', behavior: behavior
    

    instead. In this case you have to explicitly pass through the behavior of your generator (which is a method returning values like :invoke, :revoke and possibly others, depending on which command -- rails generate, rails destroy, rails update, etc. -- called your generator) to achieve the same result as above. If you don't do this, the generator you call with Rails::Generators.invoke will also be executed when running your generator with rails destroy.

    Alternatively you could stick to invoke and try to tamper with Thors invocation system. See also here for example.

提交回复
热议问题