Using an application's name in Rails 3.1 application templates
CodeSponge — billychamp
c: 2011-10-05 16:10:50 UTC
u: 2011-10-07 14:25:57 UTC
Create more powerful rails app generators
When I want to try something new like a heroku addon, I generally like to try it out in a dummy app, to make sure it does what I expect and know how to configure it before I muck around in a working production app.
So to begin I make a new rails app, do some config stuff, create my local databases on postgresql (since I frequently deploy to heroku I use postgresql locally so my development and test environments are as close to production as I can get, for this reason I also use the thin server.) I almost always also install ActiveAdmin and track the AdminUser as an ActiveAdmin resource.
I realized that I tend to create these dummy apps quite frequently and got tired of repeating all the steps above. A rails app template seemed the logical choice. I had used simple templates in older versions of rails to do things like remove public/index.html and to use jquery.
In order to automate the database creation and config I needed the application name however I had some trouble figuring a variable that points to the application’s in my template files and the
Rails Application Templates guide provided a bunch of information but not the info I was looking for. The proposed solutions I found from web searches on the topic didn’t work. I found what I was looking for in the source docs for Rails::Generators::AppGenerator, namely the following variables
[app_const, app_const_base, app_name, app_secret, camelized]
So for a simple example if I have the following file
file: basic_template_info.rb
puts "----------"
%w(app_const app_const_base app_name app_secret camelized).each do |v|
puts "#{v} => #{eval v}"
end
puts "----------"
If if run
prompt$> rails new great_application -m basic_template_info.rb
Then I get the following (truncated) output.
...
create vendor/plugins
create vendor/plugins/.gitkeep
apply /Users/billy/Rails/utils/templates/basic.rb
--------------------
app_const => MyGreatApplication::Application
app_const_base => MyGreatApplication
app_name => my_great_application
app_secret => 2c10...f5c211
camelized => MyGreatApplication
--------------------
run bundle install
Fetching source index for http://rubygems.org/
Using rake (0.9.2)
Using multi_json (1.0.3)
Using activesupport (3.1.0)
Using bcrypt-ruby (3.0.1)
...
Here is a gist of a simplified and commented version of a script I actually use. It is provided mainly as an example but you could edit the
lines that are marked with “# <= EDIT” and put it to work for you.
Hope this quickie helped you to write more powerful rails 3.1 application templates.
Articles List