Twelve Tips of Christmas - 9 Custom Generators
With an application template and the assistance of a gem, bootstrapping a brand new Rails app is very easy for us these days. I hadn't realised how spoilt we had become until I had to create one from scratch recently.
One of the nice things in our bootstrap process, is that I have a few generators running to install some custom templates for our application to utilise. Creating a generator command is pretty easy and can be done within a gem or within your own Rails app
We'll use our basic example which is to copy our usual Capistrano configuration templates over to our application folder:
Firstly, you'll need to extend Rails::Generators::Base
and give it the root directory of your templates to copy over
class CapistranoConfigGenerator < Rails::Generators::Base
source_root File.expand_path("../../templates", __FILE__)
end
Then its as simple as creating your methods and using the Thor API to start moving your files over:
class CapistranoConfigGenerator < Rails::Generators::Base
source_root File.expand_path("../../templates", __FILE__)
def copy_config_files
copy_file "config/deploy.rb", "config/deploy.rb"
directory "config/deploy", "config/deploy"
end
end
Passing in an additional description, will help new users determine what your generator actually does if they dont happen to look at your code
class CapistranoConfigGenerator < Rails::Generators::Base
source_root File.expand_path("../../templates", __FILE__)
desc 'Copies over Capistrano templates'
def copy_config_files
copy_file "config/deploy.rb", "config/deploy.rb"
directory "config/deploy", "config/deploy"
end
end
The help can be viewed by running (assuming your generator is housed in your Rails application):
bin/rails generate capistrano_config --help
Following that, just running the generate command and it'll safely start moving over those files for you
`bin/rails generate capistrano_config`
The flexibility and scope of Thor makes it really easy to accomplish any bootstrapping you may need to do, I highly recommend checking out the documentation
No comments:
Post a Comment