Programmable Generators on Rails

Kadu Diógenes
1 min readAug 2, 2019

--

Have you ever though about calling rails generators from ruby code? If you’re willing to get your hands dirty, it’s not that hard!

Typing the code above in rails console will generate controller, helper and views for the User resource. As you can see, it’s easy to use command line arguments.

The require is needed because Rails don’t load these files, but thanks to ruby exploring different ways isn’t only easy, but pleasant.

After sometime to discover how to instantiate the generator:

Wow! Nice!!! 🎉

Pry console is really nice to explore an object, now it’s only a question of patience and determination to discover all the possibilities. Ow, it’s helps to know that Ruby don’t prevent you to call private methods.

When exploring the options in this level it’s cool to keep the code open (https://github.com/rails/rails/blob/master/railties/lib/rails/generators/rails/scaffold_controller/scaffold_controller_generator.rb) and use send (https://ruby-doc.org/core-2.6.3/Object.html#method-i-send) to call private methods and instance_variable_set and instance_variable_get to play with the object variables (https://ruby-doc.org/core-2.6.3/Object.html#method-i-instance_variable_get).

Happy hacking!

--

--