Rails Generator and Gem
Recently i created two emberjs-rails projects.(money,food-ntpc).
Everytime i have to create a new rails project and add gems(ember-rails,twitter-bootstrap,thin…) repeatedly. Based on DRY principle i try to write a gem to solve trivials.
Finally, my first gem railsone is out and push to RubyGems. There are many Rail proper nouns like Generator,Template,Plugins,Engine. In the beginning it’s very confuse to me but i have solved them luckly :)
How to make gem and generator?
Use bundler to create gem structure. railsone is my gem name.
It create structure like below
1 2 3 4 5 6
Edit railsone.gemspec. We should finish
1 2 3 4
Then create a file in lib/railsone/generators/install_generator.rb. It’s better to put my custom generator in a generators folder.
Next the default auto generated file is in lib/railsone.rb. We should modify it to require my generator file.
1 2 3 4 5 6
Now continue to finish our install_generator.rb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
Your generator may use external files and they should be searched by
source_paths. I create a templates folder to place files. It’s under root folder.
Any public method in your generator will be executed automatically. It means
example_cmd will be executed when you execute generator.
gem 'ember-rails' means add gem ‘ember-rails’ into Gemfile. All commands can be found in RubyGuides and Thor:Action.
How to test?
Before push to RubyGems, we should do a minimal testing. Create a new rails project.
Assume your myrails and railsone are in the same folder
Add railsone to your myrails’s Gemfile
1 2 3
Execute railsone generator. railsone is our namespace and install is our generator name.
Then your will find your myrails Gemfile and application.js are changed.
How to publish?
Push to RubyGems is incrediblely simple. Refer to RubyGems. Don’t forget to create your account first.
1 2 3 4 5