Skip to content

Instantly share code, notes, and snippets.

@dennisreimann
Created February 28, 2011 22:37
Show Gist options
  • Save dennisreimann/848195 to your computer and use it in GitHub Desktop.
Save dennisreimann/848195 to your computer and use it in GitHub Desktop.
My template for generating new rails apps
# Helpers
def git_update(message)
git :add => ".", :commit => "-m '#{message}'"
end
def git_remove(file)
git :rm => file
end
# Flags
devise_flag = yes?("Do you want to use Devise?")
if devise_flag
devise_class = ask("What is the name of your Devise class? (i.e. 'User')")
devise_class_underscored = devise_class.underscore
end
# Git
say "Git setup", :yellow
append_file '.gitignore' do
<<-RUBY
.DS_Store
.autotest
.sass-cache
config/database.yml
log/*.log
coverage
*.pid
public/system
public/uploads
rerun.txt
capybara*.html
vendor/cache/*
RUBY
end
git :init
git_update "Initial commit with basic rails app"
# Crap
say "removing unneccessary files...", :yellow
git_remove 'public/index.html'
git_remove 'public/favicon.ico'
git_remove 'public/images/rails.png'
git_remove 'README'
run 'touch README.md'
git_update "Removed unneccessary files"
# RVMRC
say ".rvmrc setup", :yellow
rvm_lib_path = "#{`echo $rvm_path`.strip}/lib"
$LOAD_PATH.unshift(rvm_lib_path) unless $LOAD_PATH.include?(rvm_lib_path)
require 'rvm'
rvm_env = RVM::Environment.current
create_file ".rvmrc" do
"rvm use #{rvm_env.environment_name} --create\nrvm wrapper #{rvm_env.environment_name} textmate"
end
git_update "Added .rvmrc"
# Gems
say "Gemfile setup", :yellow
remove_file "Gemfile"
create_file "Gemfile" do
<<-RUBY
source "http://rubygems.org"
# Essentials
gem 'mysql2', '0.2.6'
#{"gem 'devise'" if devise_flag}
gem 'simple_form'
gem 'responders'
# Frontend
gem 'jquery-rails'
gem 'haml-rails'
gem 'compass'
gem 'compass-colors'
gem 'settingslogic'
group :development do
gem 'awesome_print'
gem 'rails3-generators'
# html2haml
gem 'hpricot'
gem 'ruby_parser'
end
group :development, :test do
# deployment (in test group so that our CI can deploy on green)
gem 'vlad'
gem 'vlad-git'
gem 'vlad-extras'
# for generating seeds we also need these in the development group
gem 'factory_girl_rails', :require => nil
gem 'faker'
end
group :test do
gem 'rspec'
gem 'rspec-rails'
gem 'cucumber-rails'
gem 'fuubar'
gem 'fuubar-cucumber'
gem 'spork', '~> 0.9.0.rc4'
gem 'infinity_test'
gem 'launchy'
gem 'pickle'
gem 'capybara'
gem 'database_cleaner'
end
RUBY
end
run 'bundle install'
git_update "Added some gems"
# Gem setup
say "Vlad setup", :yellow
create_file "config/deploy.rb" do
<<-RUBY
# If Vlad does not find some commands, try the following:
#
# To enable per user PATH environments for ssh logins you
# need to add to your sshd_config:
# PermitUserEnvironment yes
#
# After that, restart sshd!
#
# Then in your "users" ssh home directory (~/.ssh/environment),
# add something to this effect (your mileage will vary):
# PATH=/opt/ruby-1.8.7/bin:/usr/local/bin:/bin:/usr/bin
#
# For details on that, see:
# http://zerobearing.com/2009/04/27/capistrano-rake-command-not-found
#
# Maybe you also need to configure SSH Agent Forwarding:
#
# $ ssh-add ~/.ssh/<private_keyname>
#
# Edit your ~/.ssh/config file and add something like this:
# Host <name>
# HostName <ip or host>
# User <username>
# IdentityFile ~/.ssh/<filename>
# ForwardAgent yes
#
# For details on that, see:
# http://jordanelver.co.uk/articles/2008/07/10/rails-deployment-with-git-vlad-and-ssh-agent-forwarding/
set :user, "deploy"
set :application, "webapplication"
set :domain, "\#{application}.com"
set :deploy_to, "/var/www/\#{application}"
set :repository, "PLEASE_SET_THE_REPOSITORY_LOCATION"
# Revision defaults to master
# set :revision, "origin/develop"
set :web_command, "/etc/init.d/nginx"
set :symlinks, { 'config/database.yml' => 'config/database.yml' }
role :app, domain
role :web, domain
role :db, domain, :primary => true
require 'bundler/vlad'
namespace :vlad do
desc "Full deployment cycle: Update, install bundle, migrate, restart, cleanup"
remote_task :deploy, :roles => :app do
%w(update symlink bundle:install migrate start_app cleanup).each do |task|
Rake::Task["vlad:\#{task}"].invoke
end
end
end
RUBY
end
inject_into_file "Rakefile", :after => "require 'rake'\n" do
<<-RUBY
begin
require 'vlad'
require 'vlad-extras'
Vlad.load(:scm => :git, :web => :nginx, :app => :passenger, :type => :rails)
rescue LoadError
puts 'Could not load Vlad'
end
RUBY
end
git_update "Setup vlad"
say "Settingslogic setup", :yellow
create_file "app/models/settings.rb" do
<<-RUBY
class Settings < Settingslogic
source "\#{Rails.root}/config/application.yml"
namespace Rails.env
end
RUBY
end
create_file "config/application.yml" do
<<-RUBY
defaults: &defaults
app_name: 'Web Application'
development:
<<: *defaults
test:
<<: *defaults
production:
<<: *defaults
RUBY
end
git_update "Setup settingslogic"
say "jQuery setup", :yellow
generate 'jquery:install'
git_update "Setup jquery"
say "compass setup", :yellow
run "compass init rails ."
git_update "Setup compass"
say "responders setup", :yellow
generate "responders:install"
git_update "Setup responsers"
say "simple_form setup", :yellow
generate "simple_form:install"
git_update "Setup simple_form"
say "RSpec setup", :yellow
generate 'rspec:install'
append_file ".rspec" do
<<-RUBY
--format Fuubar
--tty
--drb
RUBY
end
git_update "Setup rspec"
say "Cucumber setup", :yellow
generate 'cucumber:install', '--rspec --capybara --spork'
gsub_file 'config/cucumber.yml', /'progress'/, "'Cucumber::Formatter::Fuubar'"
gsub_file 'features/support/env.rb', /require 'rubygems'\n/, ""
inject_into_file "features/support/env.rb", :after => "Spork.each_run do\n" do
<<-RUBY
require 'factory_girl_rails'
RUBY
end
git_update "Setup cucumber"
say "Pickle setup", :yellow
generate 'pickle --paths --email'
git_update "Setup pickle"
say "Spork setup", :yellow
run 'spork rspec --bootstrap'
gsub_file 'spec/spec_helper.rb', /require 'rubygems'\n/, ""
inject_into_file "spec/spec_helper.rb", :after => "# This code will be run each time you run your specs.\n" do
<<-RUBY
require 'factory_girl_rails'
RUBY
end
rspec_setup = %q{
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
RSpec.configure do |config|
# == Mock Framework
#
# If you prefer to use mocha, flexmock or RR, uncomment the appropriate line:
#
# config.mock_with :mocha
# config.mock_with :flexmock
# config.mock_with :rr
config.mock_with :rspec
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_path = "#{::Rails.root}/spec/fixtures"
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = true
end
}
# Remove instructions
gsub_file 'spec/spec_helper.rb', /# --- Instructions ---.*# free to delete them\.\s+# This file is copied to spec\/ when you run 'rails generate rspec:install'/m, ''
# Move rest into prefork block
gsub_file 'spec/spec_helper.rb', /ENV\["RAILS_ENV"\] \|\|= 'test'(.*?)end/m, ''
gsub_file 'spec/spec_helper.rb', /Spork.prefork do(.*?)end/m, "Spork.prefork do#{rspec_setup}end"
git_update "Setup spork"
# Generators
initializer 'generators.rb', <<-RUBY
Rails.application.config.generators do |g|
g.template_engine :haml
g.test_framework :rspec
g.fixture_replacement :factory_girl, :dir => "spec/factories"
g.view_specs false
g.helper_specs false
g.routing_specs false
g.controller_specs false
g.stylesheets false
g.helper false
g.integration_tool false
end
RUBY
git_update "Added generators initializer"
# Database
say "Database setup", :yellow
database_config = "defaults: &defaults
adapter: mysql2
encoding: utf8
reconnect: false
pool: 5
username: root
password:
socket:
development:
<<: *defaults
database: #{app_name}_development
test:
<<: *defaults
database: #{app_name}_test
production:
<<: *defaults"
remove_file "config/database.yml"
create_file "config/database.yml", database_config
create_file "config/database.example.yml", database_config
run 'rake db:setup'
git_update "Setup database"
# Layout
devise_layout_stuff = ""
if devise_flag
devise_layout_stuff = <<-RUBY
#account
- if user_signed_in?
= "\#{t('hello')} \#{current_#{devise_class_underscored}.email}"
= link_to t('sign_out'), destroy_#{devise_class_underscored}_session_path
- else
= link_to t('sign_in'), new_#{devise_class_underscored}_session_path
|
= link_to t('sign_up'), new_#{devise_class_underscored}_registration_path
RUBY
end
create_file "app/views/layouts/application.html.haml", "!!!
%html
%head
%title= page_title
= stylesheet_link_tag 'screen', :media => 'screen, projection'
= stylesheet_link_tag 'print', :media => 'print'
/[if IE]
= stylesheet_link_tag 'ie', :media => 'screen, projection'
= javascript_include_tag :defaults
= csrf_meta_tag
= yield(:head)
%body
%header
%h1= yield :title
#{devise_layout_stuff}
%nav
= link_to 'Home', root_url
%content
= render :partial => 'shared/flash', :object => flash
= yield
"
create_file "app/helpers/layout_helper.rb", %q{module LayoutHelper
def title(page_title)
content_for :title do
page_title.to_s
end
end
def page_title
app_name = Settings.app_name
content_for(:title).blank? ? app_name : "#{app_name} - #{content_for(:title)}"
end
def errors_for(*objects)
render "shared/error_messages", :objects => objects.flatten
end
end}
create_file "app/views/shared/_flash.html.haml", %q{- flash.each_pair do |key, value|
%div{ :class => "flash #{key}" }= value}
create_file "app/views/shared/_error_messages.html.haml", %q{- errors = objects.sum { |object| object.errors.full_messages.map { |msg| msg } }
- if errors.any?
#error_explanation
%h2
= pluralize(errors.count, "error")
occured:
%ul
- errors.each do |msg|
%li= msg}
git_remove "app/views/layouts/application.html.erb"
git_update "Added layout and helpers"
# Devise
if devise_flag
say "Devise setup", :yellow
generate 'devise:install'
puts "modifying environment configuration files for Devise..."
gsub_file 'config/environments/development.rb', /# Don't care if the mailer can't send/, '# ActionMailer'
gsub_file 'config/environments/development.rb', /config.action_mailer.raise_delivery_errors = false/ do
<<-RUBY
config.action_mailer.default_url_options = { :host => 'localhost:3000' }
config.action_mailer.delivery_method = :smtp
config.action_mailer.perform_deliveries = false
config.action_mailer.raise_delivery_errors = true
config.action_mailer.default :charset => "utf-8"
RUBY
end
gsub_file 'config/environments/production.rb', /config.i18n.fallbacks = true/ do
<<-RUBY
config.i18n.fallbacks = true
# ActionMailer
config.action_mailer.default_url_options = { :host => 'yourhost.com' }
config.action_mailer.delivery_method = :smtp
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = false
config.action_mailer.default :charset => "utf-8"
RUBY
end
git_update "Setup devise"
puts "creating a #{devise_class} model w/ added ame string, modifying routes for Devise..."
run "rails generate devise #{devise_class}"
gsub_file "app/models/#{devise_class_underscored}.rb", /attr_accessible :email, :password, :password_confirmation, :remember_me/ do
<<-RUBY
validates_uniqueness_of :email, :case_sensitive => false
attr_accessible :email, :password, :password_confirmation, :remember_me
RUBY
end
run 'rake db:migrate'
git_update "Added #{devise_class} model"
end
# i18n
gsub_file 'config/application.rb', /# config.i18n.default_locale = :de/, "config.i18n.default_locale = :de"
gsub_file 'config/application.rb', /config.action_view.javascript_expansions[:defaults] = %w()/, "# config.action_view.javascript_expansions[:defaults] = %w()"
get "https://github.com/svenfuchs/rails-i18n/raw/master/rails/locale/de.yml", "config/locales/rails.de.yml"
get "https://gist.github.com/raw/848021/responders.de.yml", "config/locales/responders.de.yml"
get "https://gist.github.com/raw/848017/simple_form.de.yml", "config/locales/simple_form.de.yml"
get "https://gist.github.com/raw/848028/devise.de.yml", "config/locales/devise.de.yml" if devise_flag
git_remove 'config/locales/en.yml'
create_file "config/locales/app.de.yml" do
<<-RUBY
de:
hello: "Hallo"
show: "Anzeigen"
back: "Zurück"
save: "Speichern"
edit: "Bearbeiten"
create: "Anlegen"
update: "Bearbeiten"
destroy: "Löschen"
confirm: "Sind Sie sicher?"
# Layout
sign_up: "Anmelden"
sign_in: "Login"
sign_out: "Logout"
RUBY
end
git_update "Setup locale"
# Homepage
say "Homepage setup", :yellow
generate(:controller, "pages index")
gsub_file 'config/routes.rb', /get \"pages\/index\"/, 'root :to => "pages#index"'
git_update "Added homepage"
# JavaScript
create_file 'public/javascripts/application.js' do
%q{var App = {
init: function() {
}
};
$(function() {
App.init();
});
}
end
git_update "Added basic javascript application"
#!/usr/bin/env ruby
rvm_ruby = ARGV[0]
app_name = ARGV[1]
template = ARGV[2] || "https://gist.github.com/raw/848195/rails-app-template.rb"
unless rvm_ruby && app_name && template
puts "\nYou need to:\n"
puts "- specify which rvm ruby to use\n" unless rvm_ruby
puts "- specify the name of your app\n" unless app_name
puts "\n"
exit
end
rvm_lib_path = "#{`echo $rvm_path`.strip}/lib"
$LOAD_PATH.unshift(rvm_lib_path) unless $LOAD_PATH.include?(rvm_lib_path)
require 'rvm'
@env = RVM::Environment.new(rvm_ruby)
puts "Creating gemset #{app_name} in #{rvm_ruby}"
@env.gemset_create(app_name)
@env = RVM::Environment.new("#{rvm_ruby}@#{app_name}")
puts "Installing bundler and rails."
puts "Successfully installed bundler" if @env.system("gem", "install", "bundler")
puts "Successfully installed rails" if @env.system("gem", "install", "rails")
system("rvm #{rvm_ruby}@#{app_name} exec rails new #{app_name} -JT -d mysql -m #{template}")
@dennisreimann
Copy link
Author

This is the template I use for generating new rails applications. It contains stuff I copied from various other templates all over the places. There is also a shell script for wrapping it all up in a rvm gemset, which was inspired by this great blog post: http://blog.madebydna.com/all/code/2010/10/11/cooking-up-a-custom-rails3-template.html

@arbovm
Copy link

arbovm commented Mar 1, 2011

This is great stuff! Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment