Rails Generators with Command Line Args

It took me a little while to figure out how to do this correctly so I figured I would share.

Rails generators can be easily modified to accept custom command line arguments which can be helpful if you’re building a more complicated generator. This functionality actually comes right from Thor:

class_option :scope, type: :string, default: 'read_products'

Now our generator can be invoked as follows:

rails generate initializer --scope write_products

The command line arguments are accessed through the options method inside the generator class. e.g:

@scope = options['scope']

I submitted these docs upstream rails#27386 for my first PR to Rails!

Kevin Hughes's Picture

About Kevin Hughes

Developer @Shopify, Traveller and Ultimate Player

Ottawa, Canada http://kevinhughes.ca