First step for upgrading to rails 3.

Check rake rails:upgrade:check for next steps.
This commit is contained in:
benni 2011-05-11 01:32:21 +02:00
parent a689bdd5f5
commit 4eba5fbc9c
45 changed files with 6139 additions and 2212 deletions

View file

@ -1,14 +1,14 @@
# A sample Gemfile
source "http://rubygems.org"
gem "rails", '2.3.11'
gem "rails", '3.0.7'
gem 'mysql'
gem "fastercsv"
gem "prawn", '<=0.6.3'
gem 'haml', '>=2.0.6'
gem 'routing-filter', '0.0.1', :require => 'routing_filter'
gem 'sqlite3-ruby'
#gem 'routing-filter', '0.0.1', :require => 'routing_filter'
#gem 'sqlite3-ruby'
group :development do
gem 'annotate'

View file

@ -1,21 +1,50 @@
GEM
remote: http://rubygems.org/
specs:
actionmailer (2.3.11)
actionpack (= 2.3.11)
actionpack (2.3.11)
activesupport (= 2.3.11)
rack (~> 1.1.0)
activerecord (2.3.11)
activesupport (= 2.3.11)
activeresource (2.3.11)
activesupport (= 2.3.11)
activesupport (2.3.11)
abstract (1.0.0)
actionmailer (3.0.7)
actionpack (= 3.0.7)
mail (~> 2.2.15)
actionpack (3.0.7)
activemodel (= 3.0.7)
activesupport (= 3.0.7)
builder (~> 2.1.2)
erubis (~> 2.6.6)
i18n (~> 0.5.0)
rack (~> 1.2.1)
rack-mount (~> 0.6.14)
rack-test (~> 0.5.7)
tzinfo (~> 0.3.23)
activemodel (3.0.7)
activesupport (= 3.0.7)
builder (~> 2.1.2)
i18n (~> 0.5.0)
activerecord (3.0.7)
activemodel (= 3.0.7)
activesupport (= 3.0.7)
arel (~> 2.0.2)
tzinfo (~> 0.3.23)
activeresource (3.0.7)
activemodel (= 3.0.7)
activesupport (= 3.0.7)
activesupport (3.0.7)
annotate (2.4.0)
arel (2.0.9)
builder (2.1.2)
erubis (2.6.6)
abstract (>= 1.0.0)
fastercsv (1.5.4)
haml (3.0.25)
hirb (0.3.4)
i18n (0.5.0)
mail (2.2.19)
activesupport (>= 2.3.6)
i18n (>= 0.4.0)
mime-types (~> 1.16)
treetop (~> 1.4.8)
mime-types (1.16)
mysql (2.8.1)
polyglot (0.3.1)
prawn (0.6.3)
prawn-core (< 0.7, >= 0.6.3)
prawn-format (< 0.3, >= 0.2.3)
@ -26,17 +55,29 @@ GEM
prawn-core
prawn-layout (0.3.2)
prawn-security (0.1.1)
rack (1.1.2)
rails (2.3.11)
actionmailer (= 2.3.11)
actionpack (= 2.3.11)
activerecord (= 2.3.11)
activeresource (= 2.3.11)
activesupport (= 2.3.11)
rake (>= 0.8.3)
rack (1.2.2)
rack-mount (0.6.14)
rack (>= 1.0.0)
rack-test (0.5.7)
rack (>= 1.0)
rails (3.0.7)
actionmailer (= 3.0.7)
actionpack (= 3.0.7)
activerecord (= 3.0.7)
activeresource (= 3.0.7)
activesupport (= 3.0.7)
bundler (~> 1.0)
railties (= 3.0.7)
railties (3.0.7)
actionpack (= 3.0.7)
activesupport (= 3.0.7)
rake (>= 0.8.7)
thor (~> 0.14.4)
rake (0.8.7)
routing-filter (0.0.1)
sqlite3-ruby (1.2.4)
thor (0.14.6)
treetop (1.4.9)
polyglot (>= 0.3.1)
tzinfo (0.3.27)
PLATFORMS
ruby
@ -48,6 +89,4 @@ DEPENDENCIES
hirb
mysql
prawn (<= 0.6.3)
rails (= 2.3.11)
routing-filter (= 0.0.1)
sqlite3-ruby
rails (= 3.0.7)

View file

@ -1,10 +1,7 @@
# Add your own tasks in files placed in lib/tasks ending in .rake,
# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
require(File.join(File.dirname(__FILE__), 'config', 'boot'))
require File.expand_path('../config/application', __FILE__)
require 'rake'
require 'rake/testtask'
require 'rake/rdoctask'
require 'tasks/rails'
Foodsoft::Application.load_tasks

View file

@ -0,0 +1,14 @@
<!DOCTYPE html>
<html>
<head>
<title>Foodsoft</title>
<%= stylesheet_link_tag :all %>
<%= javascript_include_tag :defaults %>
<%= csrf_meta_tag %>
</head>
<body>
<%= yield %>
</body>
</html>

4
config.ru Normal file
View file

@ -0,0 +1,4 @@
# This file is used by Rack-based servers to start the application.
require ::File.expand_path('../config/environment', __FILE__)
run Foodsoft::Application

42
config/application.rb Normal file
View file

@ -0,0 +1,42 @@
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# If you have a Gemfile, require the gems listed there, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env) if defined?(Bundler)
module Foodsoft
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W(#{config.root}/extras)
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# JavaScript files you want as :defaults (application.js is always included).
# config.action_view.javascript_expansions[:defaults] = %w(jquery rails)
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
end
end

View file

@ -1,129 +1,6 @@
# Don't change this file!
# Configure your app in config/environment.rb and config/environments/*.rb
RAILS_ROOT = "#{File.dirname(__FILE__)}/.." unless defined?(RAILS_ROOT)
module Rails
class << self
def boot!
unless booted?
preinitialize
pick_boot.run
end
end
def booted?
defined? Rails::Initializer
end
def pick_boot
(vendor_rails? ? VendorBoot : GemBoot).new
end
def vendor_rails?
File.exist?("#{RAILS_ROOT}/vendor/rails")
end
def preinitialize
load(preinitializer_path) if File.exist?(preinitializer_path)
end
def preinitializer_path
"#{RAILS_ROOT}/config/preinitializer.rb"
end
end
class Boot
def run
load_initializer
Rails::Initializer.run(:set_load_path)
end
end
class VendorBoot < Boot
def load_initializer
require "#{RAILS_ROOT}/vendor/rails/railties/lib/initializer"
Rails::Initializer.run(:install_gem_spec_stubs)
Rails::GemDependency.add_frozen_gem_path
end
end
class GemBoot < Boot
def load_initializer
self.class.load_rubygems
load_rails_gem
require 'initializer'
end
def load_rails_gem
if version = self.class.gem_version
gem 'rails', version
else
gem 'rails'
end
rescue Gem::LoadError => load_error
if load_error.message =~ /Could not find RubyGem rails/
STDERR.puts %(Missing the Rails #{version} gem. Please `gem install -v=#{version} rails`, update your RAILS_GEM_VERSION setting in config/environment.rb for the Rails version you do have installed, or comment out RAILS_GEM_VERSION to use the latest version installed.)
exit 1
else
raise
end
end
class << self
def rubygems_version
Gem::RubyGemsVersion rescue nil
end
def gem_version
if defined? RAILS_GEM_VERSION
RAILS_GEM_VERSION
elsif ENV.include?('RAILS_GEM_VERSION')
ENV['RAILS_GEM_VERSION']
else
parse_gem_version(read_environment_rb)
end
end
def load_rubygems
min_version = '1.3.2'
require 'rubygems'
unless rubygems_version >= min_version
$stderr.puts %Q(Rails requires RubyGems >= #{min_version} (you have #{rubygems_version}). Please `gem update --system` and try again.)
exit 1
end
rescue LoadError
$stderr.puts %Q(Rails requires RubyGems >= #{min_version}. Please install RubyGems and try again: http://rubygems.rubyforge.org)
exit 1
end
# Set up gems listed in the Gemfile.
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
def parse_gem_version(text)
$1 if text =~ /^[^#]*RAILS_GEM_VERSION\s*=\s*["']([!~<>=]*\s*[\d.]+)["']/
end
private
def read_environment_rb
File.read("#{RAILS_ROOT}/config/environment.rb")
end
end
end
end
# Bundler requirements
class Rails::Boot
def run
load_initializer
Rails::Initializer.class_eval do
def load_gems
@bundler_loaded ||= Bundler.require :default, Rails.env
end
end
Rails::Initializer.run(:set_load_path)
end
end
# All that for this:
Rails.boot!
require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE'])

View file

@ -1,70 +1,5 @@
# Be sure to restart your web server when you modify this file.
# Load the rails application
require File.expand_path('../application', __FILE__)
# Uncomment below to force Rails into production mode when
# you don't control web/app server and can't set it the proper way
# ENV['RAILS_ENV'] ||= 'production'
# Specifies gem version of Rails to use when vendor/rails is not present
RAILS_GEM_VERSION = '2.3.11' unless defined? RAILS_GEM_VERSION
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
Rails::Initializer.run do |config|
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# See Rails::Configuration for more options.
# Skip frameworks you're not going to use (only works if using vendor/rails)
# config.frameworks -= [ :action_web_service, :action_mailer ]
# Only load the plugins named here, by default all plugins in vendor/plugins are loaded
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Add additional load paths for your own custom dirs
# config.load_paths += %W( #{RAILS_ROOT}/extras )
# Force all environments to use the same logger level
# (by default production uses :info, the others :debug)
# config.log_level = :debug
# Disable colorized logging output for ActiveRecord:
config.active_record.colorize_logging = false
# Use the database for sessions instead of the file system
# (create the session table with 'rake db:sessions:create')
# config.action_controller.session_store = :active_record_store
# Use SQL instead of Active Record's schema dumper when creating the test database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
# Activate observers that should always be running
# config.active_record.observers = :cacher, :garbage_collector
# Make Active Record use UTC-base instead of local time
config.time_zone = 'Berlin'
# Specify gems that this application depends on.
# They can then be installed with "rake gems:install" on new installations.
# You have to specify the :lib option for libraries, where the Gem name (sqlite3-ruby) differs from the file itself (sqlite3)
# config.gem "bj"
# config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net"
# config.gem "sqlite3-ruby", :lib => "sqlite3"
# config.gem "aws-s3", :lib => "aws/s3"
#
# config.gem "fastercsv"
# config.gem "prawn", :version => '<=0.6.3'
# config.gem "haml", :version => '>=2.0.6'
# config.gem "routing-filter", :lib => "routing_filter"
# The internationalization framework can be changed to have another default locale (standard is :en) or more load paths.
# library for parsing/writing files from/to csv-file
# All files from config/locales/*.rb,yml are added automatically.
# config.i18n.load_path << Dir[File.join(RAILS_ROOT, 'my', 'locales', '*.{rb,yml}')]
config.i18n.default_locale = :de
# See Rails::Configuration for more options
end
# Initialize the rails application
Foodsoft::Application.initialize!

View file

@ -1,25 +1,49 @@
# Settings specified here will take precedence over those in config/environment.rb
Foodsoft::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# The production environment is meant for finished, "live" apps.
# Code is not reloaded between requests
config.cache_classes = true
# Enable threaded mode
# config.threadsafe!
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Specifies the header that your server uses for sending files
config.action_dispatch.x_sendfile_header = "X-Sendfile"
# For nginx:
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect'
# If you have no front-end server that supports something like X-Sendfile,
# just comment this out and Rails will serve the files
# See everything in the log (default is :info)
# config.log_level = :debug
# Use a different logger for distributed setups
# config.logger = SyslogLogger.new
config.log_level = :warn
# Full error reports are disabled and caching is turned on
config.action_controller.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Disable Rails's static asset server
# In production, Apache or nginx will already do this
config.serve_static_assets = false
# Enable serving of images, stylesheets, and javascripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Disable delivery errors if you bad email addresses should just be ignored
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
end

View file

@ -1,4 +1,5 @@
# Settings specified here will take precedence over those in config/environment.rb
Foodsoft::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
@ -10,10 +11,25 @@ config.cache_classes = true
config.whiny_nils = true
# Show full error reports and disable caching
config.action_controller.consider_all_requests_local = true
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Raise exceptions instead of rendering exception templates
config.action_dispatch.show_exceptions = false
# Disable request forgery protection in test environment
config.action_controller.allow_forgery_protection = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
# Use SQL instead of Active Record's schema dumper when creating the test database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
# Print deprecation notices to the stderr
config.active_support.deprecation = :stderr
end

View file

@ -0,0 +1,7 @@
# Be sure to restart your server when you modify this file.
# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code.
# Rails.backtrace_cleaner.remove_silencers!

View file

@ -0,0 +1,7 @@
# Be sure to restart your server when you modify this file.
# Your secret key for verifying the integrity of signed cookies.
# If you change this key, all old signed cookies will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
Foodsoft::Application.config.secret_token = '2be5574568ff4d270b108399078a8e485b363af84d441d02d2a6fd3fc51a8c015065790b7e414134e6d97ffc40da898a5a12f66f9de6b992b7ea96e7a34839b8'

0
lib/tasks/.gitkeep Normal file
View file

26
public/422.html Normal file
View file

@ -0,0 +1,26 @@
<!DOCTYPE html>
<html>
<head>
<title>The change you wanted was rejected (422)</title>
<style type="text/css">
body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
div.dialog {
width: 25em;
padding: 0 4em;
margin: 4em auto 0 auto;
border: 1px solid #ccc;
border-right-color: #999;
border-bottom-color: #999;
}
h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
</style>
</head>
<body>
<!-- This file lives in public/422.html -->
<div class="dialog">
<h1>The change you wanted was rejected.</h1>
<p>Maybe you tried to change something you didn't have access to.</p>
</div>
</body>
</html>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.7 KiB

After

Width:  |  Height:  |  Size: 6.5 KiB

239
public/index.html Normal file
View file

@ -0,0 +1,239 @@
<!DOCTYPE html>
<html>
<head>
<title>Ruby on Rails: Welcome aboard</title>
<style type="text/css" media="screen">
body {
margin: 0;
margin-bottom: 25px;
padding: 0;
background-color: #f0f0f0;
font-family: "Lucida Grande", "Bitstream Vera Sans", "Verdana";
font-size: 13px;
color: #333;
}
h1 {
font-size: 28px;
color: #000;
}
a {color: #03c}
a:hover {
background-color: #03c;
color: white;
text-decoration: none;
}
#page {
background-color: #f0f0f0;
width: 750px;
margin: 0;
margin-left: auto;
margin-right: auto;
}
#content {
float: left;
background-color: white;
border: 3px solid #aaa;
border-top: none;
padding: 25px;
width: 500px;
}
#sidebar {
float: right;
width: 175px;
}
#footer {
clear: both;
}
#header, #about, #getting-started {
padding-left: 75px;
padding-right: 30px;
}
#header {
background-image: url("images/rails.png");
background-repeat: no-repeat;
background-position: top left;
height: 64px;
}
#header h1, #header h2 {margin: 0}
#header h2 {
color: #888;
font-weight: normal;
font-size: 16px;
}
#about h3 {
margin: 0;
margin-bottom: 10px;
font-size: 14px;
}
#about-content {
background-color: #ffd;
border: 1px solid #fc0;
margin-left: -55px;
margin-right: -10px;
}
#about-content table {
margin-top: 10px;
margin-bottom: 10px;
font-size: 11px;
border-collapse: collapse;
}
#about-content td {
padding: 10px;
padding-top: 3px;
padding-bottom: 3px;
}
#about-content td.name {color: #555}
#about-content td.value {color: #000}
#about-content ul {
padding: 0;
list-style-type: none;
}
#about-content.failure {
background-color: #fcc;
border: 1px solid #f00;
}
#about-content.failure p {
margin: 0;
padding: 10px;
}
#getting-started {
border-top: 1px solid #ccc;
margin-top: 25px;
padding-top: 15px;
}
#getting-started h1 {
margin: 0;
font-size: 20px;
}
#getting-started h2 {
margin: 0;
font-size: 14px;
font-weight: normal;
color: #333;
margin-bottom: 25px;
}
#getting-started ol {
margin-left: 0;
padding-left: 0;
}
#getting-started li {
font-size: 18px;
color: #888;
margin-bottom: 25px;
}
#getting-started li h2 {
margin: 0;
font-weight: normal;
font-size: 18px;
color: #333;
}
#getting-started li p {
color: #555;
font-size: 13px;
}
#sidebar ul {
margin-left: 0;
padding-left: 0;
}
#sidebar ul h3 {
margin-top: 25px;
font-size: 16px;
padding-bottom: 10px;
border-bottom: 1px solid #ccc;
}
#sidebar li {
list-style-type: none;
}
#sidebar ul.links li {
margin-bottom: 5px;
}
</style>
<script type="text/javascript">
function about() {
info = document.getElementById('about-content');
if (window.XMLHttpRequest)
{ xhr = new XMLHttpRequest(); }
else
{ xhr = new ActiveXObject("Microsoft.XMLHTTP"); }
xhr.open("GET","rails/info/properties",false);
xhr.send("");
info.innerHTML = xhr.responseText;
info.style.display = 'block'
}
</script>
</head>
<body>
<div id="page">
<div id="sidebar">
<ul id="sidebar-items">
<li>
<h3>Browse the documentation</h3>
<ul class="links">
<li><a href="http://api.rubyonrails.org/">Rails API</a></li>
<li><a href="http://stdlib.rubyonrails.org/">Ruby standard library</a></li>
<li><a href="http://corelib.rubyonrails.org/">Ruby core</a></li>
<li><a href="http://guides.rubyonrails.org/">Rails Guides</a></li>
</ul>
</li>
</ul>
</div>
<div id="content">
<div id="header">
<h1>Welcome aboard</h1>
<h2>You&rsquo;re riding Ruby on Rails!</h2>
</div>
<div id="about">
<h3><a href="rails/info/properties" onclick="about(); return false">About your application&rsquo;s environment</a></h3>
<div id="about-content" style="display: none"></div>
</div>
<div id="getting-started">
<h1>Getting started</h1>
<h2>Here&rsquo;s how to get rolling:</h2>
<ol>
<li>
<h2>Use <code>rails generate</code> to create your models and controllers</h2>
<p>To see all available options, run it without parameters.</p>
</li>
<li>
<h2>Set up a default route and remove or rename this file</h2>
<p>Routes are set up in config/routes.rb.</p>
</li>
<li>
<h2>Create your database</h2>
<p>Run <code>rake db:migrate</code> to create your database. If you're not using SQLite (the default), edit <code>config/database.yml</code> with your username and password.</p>
</li>
</ol>
</div>
</div>
<div id="footer">&nbsp;</div>
</div>
</body>
</html>

View file

@ -1,6 +1,8 @@
// Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
// (c) 2005-2008 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
// (c) 2005-2008 Jon Tirsen (http://www.tirsen.com)
// script.aculo.us controls.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009
// Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
// (c) 2005-2009 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
// (c) 2005-2009 Jon Tirsen (http://www.tirsen.com)
// Contributors:
// Richard Livsey
// Rahul Bhargava

View file

@ -1,5 +1,6 @@
// Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
// (c) 2005-2008 Sammi Williams (http://www.oriontransfer.co.nz, sammi@oriontransfer.co.nz)
// script.aculo.us dragdrop.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009
// Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/
@ -311,7 +312,7 @@ var Draggable = Class.create({
tag_name=='TEXTAREA')) return;
var pointer = [Event.pointerX(event), Event.pointerY(event)];
var pos = Position.cumulativeOffset(this.element);
var pos = this.element.cumulativeOffset();
this.offset = [0,1].map( function(i) { return (pointer[i] - pos[i]) });
Draggables.activate(this);
@ -454,7 +455,7 @@ var Draggable = Class.create({
},
draw: function(point) {
var pos = Position.cumulativeOffset(this.element);
var pos = this.element.cumulativeOffset();
if(this.options.ghosting) {
var r = Position.realOffset(this.element);
pos[0] += r[0] - Position.deltaX; pos[1] += r[1] - Position.deltaY;
@ -730,7 +731,7 @@ var Sortable = {
}
// keep reference
this.sortables[element.id] = options;
this.sortables[element.identify()] = options;
// for onupdate
Draggables.addObserver(new SortableObserver(element, options.onUpdate));
@ -825,7 +826,7 @@ var Sortable = {
hide().addClassName('dropmarker').setStyle({position:'absolute'});
document.getElementsByTagName("body").item(0).appendChild(Sortable._marker);
}
var offsets = Position.cumulativeOffset(dropon);
var offsets = dropon.cumulativeOffset();
Sortable._marker.setStyle({left: offsets[0]+'px', top: offsets[1] + 'px'});
if(position=='after')

View file

@ -1,4 +1,6 @@
// Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
// script.aculo.us effects.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009
// Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
// Contributors:
// Justin Palmer (http://encytemedia.com/)
// Mark Pilgrim (http://diveintomark.org/)
@ -145,14 +147,13 @@ var Effect = {
'blind': ['BlindDown','BlindUp'],
'appear': ['Appear','Fade']
},
toggle: function(element, effect) {
toggle: function(element, effect, options) {
element = $(element);
effect = (effect || 'appear').toLowerCase();
var options = Object.extend({
return Effect[ Effect.PAIRS[ effect ][ element.visible() ? 1 : 0 ] ](element, Object.extend({
queue: { position:'end', scope:(element.id || 'global'), limit: 1 }
}, arguments[2] || { });
Effect[element.visible() ?
Effect.PAIRS[effect][1] : Effect.PAIRS[effect][0]](element, options);
}, options || {}));
}
};
@ -228,12 +229,6 @@ Effect.Queue = Effect.Queues.get('global');
Effect.Base = Class.create({
position: null,
start: function(options) {
function codeForEvent(options,eventName){
return (
(options[eventName+'Internal'] ? 'this.options.'+eventName+'Internal(this);' : '') +
(options[eventName] ? 'this.options.'+eventName+'(this);' : '')
);
}
if (options && options.transition === false) options.transition = Effect.Transitions.linear;
this.options = Object.extend(Object.extend({ },Effect.DefaultOptions), options || { });
this.currentFrame = 0;

File diff suppressed because it is too large Load diff

191
public/javascripts/rails.js Normal file
View file

@ -0,0 +1,191 @@
(function() {
// Technique from Juriy Zaytsev
// http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/
function isEventSupported(eventName) {
var el = document.createElement('div');
eventName = 'on' + eventName;
var isSupported = (eventName in el);
if (!isSupported) {
el.setAttribute(eventName, 'return;');
isSupported = typeof el[eventName] == 'function';
}
el = null;
return isSupported;
}
function isForm(element) {
return Object.isElement(element) && element.nodeName.toUpperCase() == 'FORM'
}
function isInput(element) {
if (Object.isElement(element)) {
var name = element.nodeName.toUpperCase()
return name == 'INPUT' || name == 'SELECT' || name == 'TEXTAREA'
}
else return false
}
var submitBubbles = isEventSupported('submit'),
changeBubbles = isEventSupported('change')
if (!submitBubbles || !changeBubbles) {
// augment the Event.Handler class to observe custom events when needed
Event.Handler.prototype.initialize = Event.Handler.prototype.initialize.wrap(
function(init, element, eventName, selector, callback) {
init(element, eventName, selector, callback)
// is the handler being attached to an element that doesn't support this event?
if ( (!submitBubbles && this.eventName == 'submit' && !isForm(this.element)) ||
(!changeBubbles && this.eventName == 'change' && !isInput(this.element)) ) {
// "submit" => "emulated:submit"
this.eventName = 'emulated:' + this.eventName
}
}
)
}
if (!submitBubbles) {
// discover forms on the page by observing focus events which always bubble
document.on('focusin', 'form', function(focusEvent, form) {
// special handler for the real "submit" event (one-time operation)
if (!form.retrieve('emulated:submit')) {
form.on('submit', function(submitEvent) {
var emulated = form.fire('emulated:submit', submitEvent, true)
// if custom event received preventDefault, cancel the real one too
if (emulated.returnValue === false) submitEvent.preventDefault()
})
form.store('emulated:submit', true)
}
})
}
if (!changeBubbles) {
// discover form inputs on the page
document.on('focusin', 'input, select, texarea', function(focusEvent, input) {
// special handler for real "change" events
if (!input.retrieve('emulated:change')) {
input.on('change', function(changeEvent) {
input.fire('emulated:change', changeEvent, true)
})
input.store('emulated:change', true)
}
})
}
function handleRemote(element) {
var method, url, params;
var event = element.fire("ajax:before");
if (event.stopped) return false;
if (element.tagName.toLowerCase() === 'form') {
method = element.readAttribute('method') || 'post';
url = element.readAttribute('action');
params = element.serialize();
} else {
method = element.readAttribute('data-method') || 'get';
url = element.readAttribute('href');
params = {};
}
new Ajax.Request(url, {
method: method,
parameters: params,
evalScripts: true,
onComplete: function(request) { element.fire("ajax:complete", request); },
onSuccess: function(request) { element.fire("ajax:success", request); },
onFailure: function(request) { element.fire("ajax:failure", request); }
});
element.fire("ajax:after");
}
function handleMethod(element) {
var method = element.readAttribute('data-method'),
url = element.readAttribute('href'),
csrf_param = $$('meta[name=csrf-param]')[0],
csrf_token = $$('meta[name=csrf-token]')[0];
var form = new Element('form', { method: "POST", action: url, style: "display: none;" });
element.parentNode.insert(form);
if (method !== 'post') {
var field = new Element('input', { type: 'hidden', name: '_method', value: method });
form.insert(field);
}
if (csrf_param) {
var param = csrf_param.readAttribute('content'),
token = csrf_token.readAttribute('content'),
field = new Element('input', { type: 'hidden', name: param, value: token });
form.insert(field);
}
form.submit();
}
document.on("click", "*[data-confirm]", function(event, element) {
var message = element.readAttribute('data-confirm');
if (!confirm(message)) event.stop();
});
document.on("click", "a[data-remote]", function(event, element) {
if (event.stopped) return;
handleRemote(element);
event.stop();
});
document.on("click", "a[data-method]", function(event, element) {
if (event.stopped) return;
handleMethod(element);
event.stop();
});
document.on("submit", function(event) {
var element = event.findElement(),
message = element.readAttribute('data-confirm');
if (message && !confirm(message)) {
event.stop();
return false;
}
var inputs = element.select("input[type=submit][data-disable-with]");
inputs.each(function(input) {
input.disabled = true;
input.writeAttribute('data-original-value', input.value);
input.value = input.readAttribute('data-disable-with');
});
var element = event.findElement("form[data-remote]");
if (element) {
handleRemote(element);
event.stop();
}
});
document.on("ajax:after", "form", function(event, element) {
var inputs = element.select("input[type=submit][disabled=true][data-disable-with]");
inputs.each(function(input) {
input.value = input.readAttribute('data-original-value');
input.removeAttribute('data-original-value');
input.disabled = false;
});
});
Ajax.Responders.register({
onCreate: function(request) {
var csrf_meta_tag = $$('meta[name=csrf-token]')[0];
if (csrf_meta_tag) {
var header = 'X-CSRF-Token',
token = csrf_meta_tag.readAttribute('content');
if (!request.options.requestHeaders) {
request.options.requestHeaders = {};
}
request.options.requestHeaders[header] = token;
}
}
});
})();

View file

6
script/rails Executable file
View file

@ -0,0 +1,6 @@
#!/usr/bin/env ruby
# This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application.
APP_PATH = File.expand_path('../../config/application', __FILE__)
require File.expand_path('../../config/boot', __FILE__)
require 'rails/commands'

View file

@ -0,0 +1,9 @@
require 'test_helper'
require 'rails/performance_test_help'
# Profiling results for each test method are written to tmp/performance.
class BrowsingTest < ActionDispatch::PerformanceTest
def test_homepage
get '/'
end
end

View file

@ -1,28 +1,13 @@
ENV["RAILS_ENV"] = "test"
require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
require 'test_help'
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
class Test::Unit::TestCase
# Transactional fixtures accelerate your tests by wrapping each test method
# in a transaction that's rolled back on completion. This ensures that the
# test database remains unchanged so your fixtures don't have to be reloaded
# between every test method. Fewer database queries means faster tests.
class ActiveSupport::TestCase
# Setup all fixtures in test/fixtures/*.(yml|csv) for all tests in alphabetical order.
#
# Read Mike Clark's excellent walkthrough at
# http://clarkware.com/cgi/blosxom/2005/10/24#Rails10FastTesting
#
# Every Active Record database supports transactions except MyISAM tables
# in MySQL. Turn off transactional fixtures in this case; however, if you
# don't care one way or the other, switching from MyISAM to InnoDB tables
# is recommended.
self.use_transactional_fixtures = true
# Instantiated fixtures are slow, but give you @david where otherwise you
# would need people(:david). If you don't want to migrate your existing
# test cases which use the @david style and don't mind the speed hit (each
# instantiated fixtures translates to a database query per test method),
# then set this back to true.
self.use_instantiated_fixtures = false
# Note: You'll currently still have to declare fixtures explicitly in integration tests
# -- they do not yet inherit this setting
fixtures :all
# Add more helper methods to be used by all tests here...
end

0
vendor/plugins/.gitkeep vendored Normal file
View file

View file

@ -0,0 +1,20 @@
Copyright (c) 2010 Jeremy McAnally
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

26
vendor/plugins/rails_upgrade/README vendored Normal file
View file

@ -0,0 +1,26 @@
= rails-upgrade
A simple battery of scripts for upgrading Rails app/checking them for required updates. This application should work on Rails 2.x and 3.0, with a focus on upgrading to 3.0.
== Usage
You need to install this plugin first:
script/plugin install git://github.com/rails/rails_upgrade.git
Then you can run its rake tasks to check your application:
# Check your app for required upgrades
rake rails:upgrade:check
# Backup your likely modified files that might be overwritten by the generator
rake rails:upgrade:backup
# Generate a new route file
rake rails:upgrade:routes
# Generate a Gemfile from your config.gem directives
rake rails:upgrade:gems
# Generate code for a new config/application.rb from your environment.rb
rake rails:upgrade:configuration

22
vendor/plugins/rails_upgrade/Rakefile vendored Normal file
View file

@ -0,0 +1,22 @@
require 'rake'
require 'rake/testtask'
require 'rake/rdoctask'
desc 'Default: run unit tests.'
task :default => :test
Rake::TestTask.new do |t|
t.libs << 'lib'
t.libs << 'test'
t.test_files = FileList['test/*_test.rb']
t.verbose = true
end
desc 'Generate documentation for the rails_upgrade plugin.'
Rake::RDocTask.new(:rdoc) do |rdoc|
rdoc.rdoc_dir = 'rdoc'
rdoc.title = 'Rails-upgrade'
rdoc.options << '--line-numbers' << '--inline-source'
rdoc.rdoc_files.include('README')
rdoc.rdoc_files.include('lib/**/*.rb')
end

2
vendor/plugins/rails_upgrade/init.rb vendored Normal file
View file

@ -0,0 +1,2 @@
# Get long stack traces for easier debugging; you'll thank me later.
Rails.backtrace_cleaner.remove_silencers!

38
vendor/plugins/rails_upgrade/install.rb vendored Normal file
View file

@ -0,0 +1,38 @@
puts "Thanks for installing the Rails upgrade plugin. This is a set of generators and analysis tools to help you upgrade your application to Rails 3. It consists of three tasks...
To get a feel for what you'll need to change to get your app running, run the application analysis:
rake rails:upgrade:check
This should give you an idea of the manual changes that need to be done, but you'll probably want to upgrade some of those automatically. The fastest way to do this is to run 'rails .', which will simply generate a new app on top of your existing code. But this generation also has the effect of replacing some existing files, some of which you might not want to replace. To back those up, first run:
rake rails:upgrade:backup
That will backup files you've probably edited that will be replaced in the upgrade; if you finish the upgrade and find that you don't need the old copies, just delete them. Otherwise, copy their contents back into the new files or run one of the following upgraders...
Routes upgrader
===============
To generate a new routes file from your existing routes file, simply run the following Rake task:
rake rails:upgrade:routes
This will output a new routes file that you can copy and paste or pipe into a new, Rails 3 compatible config/routes.rb.
Gemfile generator
=================
Creating a new Gemfile is as simple as running:
rake rails:upgrade:gems
This task will extract your config.gem calls and generate code you can put into a bundler compatible Gemfile.
Configuration generator
=======================
Much of the configuration information that lived in environment.rb now belongs in a new file named config/application.rb; use the following task to generate code you can put into config/application.rb from your existing config/environment.rb:
rake rails:upgrade:configuration
"

View file

@ -0,0 +1,477 @@
require 'open3'
module Rails
module Upgrading
class ApplicationChecker
def initialize
@issues = []
raise NotInRailsAppError unless in_rails_app?
end
def in_rails_app?
File.exist?("config/environment.rb")
end
# Run all the check methods
def run
# Ruby 1.8 returns method names as strings whereas 1.9 uses symbols
the_methods = (self.public_methods - Object.methods) - [:run, :initialize, "run", "initialize"]
the_methods.each {|m| send m }
end
# Check for deprecated ActiveRecord calls
def check_ar_methods
files = []
["find(:all", "find(:first", "find.*:conditions =>", ":joins =>"].each do |v|
lines = grep_for(v, "app/")
files += extract_filenames(lines) || []
end
unless files.empty?
alert(
"Soon-to-be-deprecated ActiveRecord calls",
"Methods such as find(:all), find(:first), finds with conditions, and the :joins option will soon be deprecated.",
"http://m.onkey.org/2010/1/22/active-record-query-interface",
files
)
end
lines = grep_for("named_scope", "app/models/")
files = extract_filenames(lines)
unless files.empty?
alert(
"named_scope is now just scope",
"The named_scope method has been renamed to just scope.",
"http://github.com/rails/rails/commit/d60bb0a9e4be2ac0a9de9a69041a4ddc2e0cc914",
files
)
end
end
def check_validation_on_methods
files = []
["validate_on_create", "validate_on_update"].each do |v|
lines = grep_for(v, "app/models/")
files += extract_filenames(lines) || []
end
unless files.empty?
alert(
"Updated syntax for validate_on_* methods",
"Validate-on-callback methods (validate_on_create/validate_on_destroy) have been changed to validate :x, :on => :create",
"https://rails.lighthouseapp.com/projects/8994/tickets/3880-validate_on_create-and-validate_on_update-no-longer-seem-to-exist",
files
)
end
end
def check_before_validation_on_methods
files = []
%w(before_validation_on_create before_validation_on_update).each do |v|
lines = grep_for(v, "app/models/")
files += extract_filenames(lines) || []
end
unless files.empty?
alert(
"Updated syntax for before_validation_on_* methods",
"before_validation_on_* methods have been changed to before_validation(:on => :create/:update) { ... }",
"https://rails.lighthouseapp.com/projects/8994/tickets/4699-before_validation_on_create-and-before_validation_on_update-doesnt-exist",
files
)
end
end
# Check for deprecated router syntax
def check_routes
lines = ["map\\.", "ActionController::Routing::Routes", "\\.resources"].map do |v|
grep_for(v, "config/routes.rb").empty? ? nil : true
end.compact
unless lines.empty?
alert(
"Old router API",
"The router API has totally changed.",
"http://yehudakatz.com/2009/12/26/the-rails-3-router-rack-it-up/",
"config/routes.rb"
)
end
end
# Check for deprecated test_help require
def check_test_help
files = []
# Hate to duplicate code, but we have to double quote this one...
lines = grep_for("\'test_help\'", "test/", true)
files += extract_filenames(lines) || []
lines = grep_for("\"test_help\"", "test/")
files += extract_filenames(lines) || []
files.uniq!
unless files.empty?
alert(
"Deprecated test_help path",
"You now must require 'rails/test_help' not just 'test_help'.",
"http://weblog.rubyonrails.org/2009/9/1/gem-packaging-best-practices",
files
)
end
end
# Check for old (pre-application.rb) environment.rb file
def check_environment
unless File.exist?("config/application.rb")
alert(
"New file needed: config/application.rb",
"You need to add a config/application.rb.",
"http://omgbloglol.com/post/353978923/the-path-to-rails-3-approaching-the-upgrade",
"config/application.rb"
)
end
lines = grep_for("config.", "config/environment.rb")
unless lines.empty?
alert(
"Old environment.rb",
"environment.rb doesn't do what it used to; you'll need to move some of that into application.rb.",
"http://omgbloglol.com/post/353978923/the-path-to-rails-3-approaching-the-upgrade",
"config/environment.rb"
)
end
end
# Check for deprecated constants
def check_deprecated_constants
files = []
["RAILS_ENV", "RAILS_ROOT", "RAILS_DEFAULT_LOGGER"].each do |v|
lines = grep_for(v, "app/")
files += extract_filenames(lines) || []
lines = grep_for(v, "lib/")
files += extract_filenames(lines) || []
end
unless files.empty?
alert(
"Deprecated constant(s)",
"Constants like RAILS_ENV, RAILS_ROOT, and RAILS_DEFAULT_LOGGER are now deprecated.",
"http://litanyagainstfear.com/blog/2010/02/03/the-rails-module/",
files.uniq
)
end
end
# Check for old-style config.gem calls
def check_gems
lines = grep_for("config.gem ", "config/*.rb")
lines += grep_for("config.gem ", "config/**/*.rb")
files = extract_filenames(lines)
unless files.empty?
alert(
"Old gem bundling (config.gems)",
"The old way of bundling is gone now. You need a Gemfile for bundler.",
"http://omgbloglol.com/post/353978923/the-path-to-rails-3-approaching-the-upgrade",
files
)
end
end
# Checks for old mailer syntax in both mailer classes and those
# classes utilizing the mailers
def check_mailers
lines = grep_for("deliver_", "app/models/ #{base_path}app/controllers/ #{base_path}app/observers/")
files = extract_filenames(lines)
unless files.empty?
alert(
"Deprecated ActionMailer API",
"You're using the old ActionMailer API to send e-mails in a controller, model, or observer.",
"http://lindsaar.net/2010/1/26/new-actionmailer-api-in-rails-3",
files
)
end
files = []
["recipients ", "attachment(?!s) ", "(?<!:)subject ", "(?<!:)from "].each do |v|
lines = grep_for_with_perl_regex(v, "app/models/")
files += extract_filenames(lines) || []
end
unless files.empty?
alert(
"Old ActionMailer class API",
"You're using the old API in a mailer class.",
"http://lindsaar.net/2010/1/26/new-actionmailer-api-in-rails-3",
files
)
end
end
# Checks for old-style generators
def check_generators
generators = Dir.glob(base_path + "vendor/plugins/**/generators/**/")
unless generators.empty?
files = generators.reject do |g|
grep_for("def manifest", g).empty?
end.compact
unless files.empty?
alert(
"Old Rails generator API",
"A plugin in the app is using the old generator API (a new one may be available at http://github.com/trydionel/rails3-generators).",
"http://blog.plataformatec.com.br/2010/01/discovering-rails-3-generators/",
files
)
end
end
end
# Checks a list of known broken plugins and gems
def check_plugins
# This list is off the wiki; will need to be updated often, esp. since RSpec is working on it
bad_plugins = ["rspec", "rspec-rails", "hoptoad", "authlogic", "nifty-generators",
"restful_authentication", "searchlogic", "cucumber", "cucumber-rails", "devise",
"inherited_resources"]
bad_plugins = bad_plugins.map do |p|
p if File.exist?("#{base_path}vendor/plugins/#{p}") || !Dir.glob("#{base_path}vendor/gems/#{p}-*").empty?
end.compact
unless bad_plugins.empty?
alert(
"Known broken plugins",
"At least one plugin in your app is broken (according to the wiki). Most of project maintainers are rapidly working towards compatability, but do be aware you may encounter issues.",
"http://wiki.rubyonrails.org/rails/version3/plugins_and_gems",
bad_plugins
)
end
end
# Checks for old-style ERb helpers
def check_old_helpers
lines = grep_for("<% .*content_tag.* do.*%>", "app/views/**/*")
lines += grep_for("<% .*javascript_tag.* do.*%>", "app/views/**/*")
lines += grep_for("<% .*form_for.* do.*%>", "app/views/**/*")
lines += grep_for("<% .*form_tag.* do.*%>", "app/views/**/*")
lines += grep_for("<% .*fields_for.* do.*%>", "app/views/**/*")
lines += grep_for("<% .*field_set_tag.* do.*%>", "app/views/**/*")
files = extract_filenames(lines)
if !files.blank?
alert(
"Deprecated ERb helper calls",
"Block helpers that use concat (e.g., form_for) should use <%= instead of <%. The current form will continue to work for now, but you will get deprecation warnings since this form will go away in the future.",
"http://weblog.rubyonrails.org/",
files
)
end
end
# Checks for old-style AJAX helpers
def check_old_ajax_helpers
files = []
['link_to_remote','form_remote_tag','remote_form_for'].each do |type|
lines = grep_for(type, "app/views/**/*")
inner_files = extract_filenames(lines)
files += inner_files unless inner_files.nil?
end
unless files.empty?
alert(
"Deprecated AJAX helper calls",
"AJAX javascript helpers have been switched to be unobtrusive and use :remote => true instead of having a seperate function to handle remote requests.",
"http://www.themodestrubyist.com/2010/02/24/rails-3-ujs-and-csrf-meta-tags/",
files
)
end
end
# Checks for old cookie secret settings
def check_old_cookie_secret
lines = grep_for("ActionController::Base.cookie_verifier_secret = ", "config/**/*")
files = extract_filenames(lines)
unless files.empty?
alert(
"Deprecated cookie secret setting",
"Previously, cookie secret was set directly on ActionController::Base; it's now config.secret_token.",
"http://lindsaar.net/2010/4/7/rails_3_session_secret_and_session_store",
files
)
end
end
def check_old_session_secret
lines = grep_for("ActionController::Base.session = {", "config/**/*")
files = extract_filenames(lines)
unless files.empty?
alert(
"Deprecated session secret setting",
"Previously, session secret was set directly on ActionController::Base; it's now config.secret_token.",
"http://lindsaar.net/2010/4/7/rails_3_session_secret_and_session_store",
files
)
end
end
# Checks for old session settings
def check_old_session_setting
lines = grep_for("ActionController::Base.session_store", "config/**/*")
files = extract_filenames(lines)
unless files.empty?
alert(
"Old session store setting",
"Previously, session store was set directly on ActionController::Base; it's now config.session_store :whatever.",
"http://lindsaar.net/2010/4/7/rails_3_session_secret_and_session_store",
files
)
end
end
private
def grep_for_with_perl_regex(text, where = "./", double_quote = false)
grep_for(text, where, double_quote, true)
end
# Find a string in a set of files; calls +find_with_grep+ and +find_with_rak+
# depending on platform.
#
# TODO: Figure out if this works on Windows.
def grep_for(text, where = "./", double_quote = false, perl_regex = false)
# If they're on Windows, they probably don't have grep.
@probably_has_grep ||= (Config::CONFIG['host_os'].downcase =~ /mswin|windows|mingw/).nil?
# protect against double root paths in Rails 3
where.gsub!(Regexp.new(base_path),'')
lines = if @probably_has_grep
find_with_grep(text, base_path + where, double_quote, perl_regex)
else
find_with_rak(text, base_path + where, double_quote)
end
# ignore comments
lines.gsub /^(\/[^:]+:)?\s*#.+$/m, ""
end
# Sets a base path for finding files; mostly for testing
def base_path
Dir.pwd + "/"
end
# Use the grep utility to find a string in a set of files
def find_with_grep(text, where, double_quote, perl_regex = false)
value = ""
# Specifically double quote for finding 'test_help'
command = if double_quote
"grep -rH #{"-P" if perl_regex} \"#{text}\" #{where} | grep -v \.svn"
else
"grep -rH #{"-P" if perl_regex} '#{text}' #{where} | grep -v \.svn"
end
Open3.popen3(command) do |stdin, stdout, stderr|
value = stdout.read
end
value
end
# Use the rak gem to grep the files (not yet implemented)
def find_with_rak(text, where, double_quote)
value = ""
Open3.popen3("rak --nogroup -l '#{Regexp.escape(text)}' #{where}") do |stdin, stdout, stderr|
value = stdout.read
end
value
end
# Extract the filenames from the grep output
def extract_filenames(output)
if @probably_has_grep
filenames = extract_filenames_from_grep(output)
else
filenames = extract_filenames_from_rak(output)
end
filenames.compact.map do |f|
f.gsub(base_path, "")
end
end
def extract_filenames_from_grep(output)
return [] if output.empty?
output.split("\n").map do |fn|
if m = fn.match(/^(.+?):/)
m[1]
end
end.compact.uniq
end
def extract_filenames_from_rak(output)
return [] if output.empty?
output.split("\n").uniq
end
# Terminal colors, borrowed from Thor
CLEAR = "\e[0m"
BOLD = "\e[1m"
RED = "\e[31m"
YELLOW = "\e[33m"
CYAN = "\e[36m"
WHITE = "\e[37m"
# Show an upgrade alert to the user
def alert(title, text, more_info_url, culprits)
if Config::CONFIG['host_os'].downcase =~ /mswin|windows|mingw/
basic_alert(title, text, more_info_url, culprits)
else
color_alert(title, text, more_info_url, culprits)
end
end
# Show an upgrade alert to the user. If we're on Windows, we can't
# use terminal colors, hence this method.
def basic_alert(title, text, more_info_url, culprits)
puts "** " + title
puts text
puts "More information: #{more_info_url}"
puts
puts "The culprits: "
Array(culprits).each do |c|
puts "\t- #{c}"
end
puts
end
# Show a colorful alert to the user
def color_alert(title, text, more_info_url, culprits)
puts "#{RED}#{BOLD}#{title}#{CLEAR}"
puts "#{WHITE}#{text}"
puts "#{BOLD}More information:#{CLEAR} #{CYAN}#{more_info_url}"
puts
puts "#{WHITE}The culprits: "
Array(culprits).each do |c|
puts "#{YELLOW}\t- #{c}"
end
ensure
puts "#{CLEAR}"
end
end
end
end

View file

@ -0,0 +1,95 @@
module Rails
module Upgrading
class GemfileGenerator
def generate_new_gemfile
if has_environment?
generate_gemfile
else
raise FileNotFoundError, "Can't find environment.rb [config/environment.rb]!"
end
end
def has_environment?
File.exists?("config/environment.rb")
end
def environment_code
File.open("config/environment.rb").read
end
def generate_gemfile
environment_file = environment_code
# Get each line that starts with config.gem
gem_lines = environment_file.split("\n").select {|l| l =~ /^\s*config\.gem/}
# Toss those lines to a generator class; the lines are evaluated in the
# context of that instance.
config = GemfileGenerator.new
config.instance_eval(gem_lines.join("\n"))
config.output
end
end
class GemfileGenerator
# Creates a target for the config.gem calls
def config
self
end
def initialize
@gems = []
end
# Receive a call to add a gem to the list
def gem(name, options={})
data = {}
# Add new keys from old keys
data[:require] = options[:lib] if options[:lib]
data[:source] = options[:source] if options[:source]
version = options[:version]
@gems << [name, version, data]
end
# Generate the Gemfile output
def output
# Generic preamble, taken from Yehuda Katz's blog
preamble = <<STR
# Edit this Gemfile to bundle your application's dependencies.
# This preamble is the current preamble for Rails 3 apps; edit as needed.
source 'http://rubygems.org'
gem 'rails', '3.0.6'
STR
preamble + generate_upgraded_code
end
# Get Gemfile call for all the gems
def generate_upgraded_code
code = @gems.map do |name, version, data|
version_string = (version ? "'#{version}'" : nil)
source = data.delete(:source)
data_string = nil
unless data.empty?
data_string = data.to_a.map {|k, v| ":#{k} => '#{v}'"}.join(", ")
end
# If we have a source, generate a call to +source+ then output the
# gem call. Otherwise, just generate the gem requirement.
if source
str = ["'#{name}'", version_string, data_string].compact.join(", ")
"source '#{source}'\ngem #{str}"
else
str = ["'#{name}'", version_string, data_string].compact.join(", ")
"gem #{str}"
end
end.join("\n")
end
end
end
end

View file

@ -0,0 +1,51 @@
module Rails
module Upgrading
class NewConfigurationGenerator
def generate_new_configurations
if has_environment?
generate_new_application_rb
else
raise FileNotFoundError, "Can't find environment.rb [config/environment.rb]!"
end
end
def has_environment?
File.exists?("config/environment.rb")
end
def environment_code
File.open("config/environment.rb").read
end
def generate_new_application_rb
environment_file = environment_code
initializer_code = ""
if matches = environment_file.match(/Rails\:\:Initializer\.run do \|config\|\n(.*)\nend/m)
initializer_code = matches[1]
else
raise "There doesn't seem to be a real environment.rb in your app. Are you sure config/environment.rb has the right contents?"
end
frame = "# Put this in config/application.rb
require File.expand_path('../boot', __FILE__)
module #{app_name.classify}
class Application < Rails::Application
%s
end
end"
frame % [indent(initializer_code)]
end
def indent(text)
text.split("\n").map {|l| " #{l}"}.join("\n")
end
def app_name
File.basename(Dir.pwd)
end
end
end
end

View file

View file

@ -0,0 +1,366 @@
# TODO: Fix formatting on member/collection methods
module Rails
module Upgrading
module FakeRouter
module ActionController
module Routing
class Routes
def self.setup
@redrawer = Rails::Upgrading::RouteRedrawer.new
end
def self.redrawer
@redrawer
end
def self.draw
yield @redrawer
end
end
end
end
end
class RoutesUpgrader
def generate_new_routes
if has_routes_file?
upgrade_routes
else
raise FileNotFoundError, "Can't find your routes file [config/routes.rb]!"
end
end
def has_routes_file?
File.exists?("config/routes.rb")
end
def routes_code
File.read("config/routes.rb")
end
def upgrade_routes
FakeRouter::ActionController::Routing::Routes.setup
# Read and eval the file; our fake route mapper will capture
# the calls to draw routes and generate new route code
FakeRouter.module_eval(routes_code)
# Give the route set to the code generator and get its output
generator = RouteGenerator.new(FakeRouter::ActionController::Routing::Routes.redrawer.routes)
generator.generate
end
end
class RouteRedrawer
attr_accessor :routes
def self.stack
@stack
end
def self.stack=(val)
@stack = val
end
def initialize
@routes = []
# The old default route was actually two routes; we generate the new style
# one only if we haven't generated it for the first old default route.
@default_route_generated = false
# Setup the stack for parents; used use proper indentation
self.class.stack = [@routes]
end
def root(options)
debug "mapping root"
@routes << FakeRoute.new("/", options)
end
def connect(path, options={})
debug "connecting #{path}"
if (path == ":controller/:action/:id.:format" || path == ":controller/:action/:id")
if !@default_route_generated
current_parent << FakeRoute.new("/:controller(/:action(/:id))", {:default_route => true})
@default_route_generated = true
end
else
current_parent << FakeRoute.new(path, options)
end
end
def resources(*args)
if block_given?
parent = FakeResourceRoute.new(args.shift)
debug "mapping resources #{parent.name} with block"
parent = stack(parent) do
yield(self)
end
current_parent << parent
else
if args.last.is_a?(Hash)
current_parent << FakeResourceRoute.new(args.shift, args.pop)
debug "mapping resources #{current_parent.last.name} w/o block with args"
else
args.each do |a|
current_parent << FakeResourceRoute.new(a)
debug "mapping resources #{current_parent.last.name}"
end
end
end
end
def resource(*args)
if block_given?
parent = FakeSingletonResourceRoute.new(args.shift)
debug "mapping resource #{parent.name} with block"
parent = stack(parent) do
yield(self)
end
current_parent << parent
else
if args.last.is_a?(Hash)
current_parent << FakeSingletonResourceRoute.new(args.shift, args.pop)
debug "mapping resources #{current_parent.last.name} w/o block with args"
else
args.each do |a|
current_parent << FakeSingletonResourceRoute.new(a)
debug "mapping resources #{current_parent.last.name}"
end
end
end
end
def namespace(name, options = {})
debug "mapping namespace #{name}"
namespace = FakeNamespace.new(name, options)
namespace = stack(namespace) do
yield(self)
end
current_parent << namespace
end
def method_missing(m, *args)
debug "named route: #{m}"
current_parent << FakeRoute.new(args.shift, args.pop, m.to_s)
end
def self.indent
' ' * ((stack.length) * 2)
end
private
def debug(txt)
puts txt if ENV['DEBUG']
end
def stack(obj)
self.class.stack << obj
yield
self.class.stack.pop
end
def current_parent
self.class.stack.last
end
end
class RouteObject
def indent_lines(code_lines)
if code_lines.length > 1
code_lines.flatten.map {|l| "#{@indent}#{l.chomp}"}.join("\n") + "\n"
else
"#{@indent}#{code_lines.shift}"
end
end
def opts_to_string(opts)
opts.is_a?(Hash) ? opts.map {|k, v|
":#{k} => " + (v.is_a?(Hash) ? ('{ ' + opts_to_string(v) + ' }') : "#{value_to_string(v)}")
}.join(", ") : opts.to_s
end
def value_to_string(value)
case value
when Regexp then value.inspect
when String then "'" + value.to_s + "'"
else value.to_s
end
end
end
class FakeNamespace < RouteObject
attr_accessor :routes, :name, :options
def initialize(name, options = {})
@routes = []
@name, @options = name, options
@indent = RouteRedrawer.indent
end
def to_route_code
if !@options.empty?
options = ', ' + opts_to_string(@options)
else
options = ''
end
lines = ["namespace :#{@name}#{options} do", @routes.map {|r| r.to_route_code}, "end"]
indent_lines(lines)
end
def <<(val)
@routes << val
end
def last
@routes.last
end
end
class FakeRoute < RouteObject
attr_accessor :name, :path, :options
def initialize(path, options, name = "")
@path = path
@options = options || {}
@name = name
@indent = RouteRedrawer.indent
end
def to_route_code
if @options[:default_route]
indent_lines ["match '#{@path}'"]
else
base = "match '%s' => '%s#%s'"
extra_options = []
if not name.empty?
extra_options << ":as => :#{name}"
end
if @options[:requirements]
@options[:constraints] = @options.delete(:requirements)
end
if @options[:conditions]
@options[:via] = @options.delete(:conditions).delete(:method)
end
if @options[:method]
@options[:via] = @options.delete(:method).to_s
end
@options ||= {}
base = (base % [@path, @options.delete(:controller), (@options.delete(:action) || "index")])
opts = opts_to_string(@options)
route_pieces = ([base] + extra_options + [opts])
route_pieces.delete("")
indent_lines [route_pieces.join(", ")]
end
end
end
class FakeResourceRoute < RouteObject
attr_accessor :name, :children
def initialize(name, options = {})
@name = name
@children = []
@options = options
@indent = RouteRedrawer.indent
end
def to_route_code
# preserve :only & :except options
copied_options = @options.reject { |k,v| ![:only, :except].member?(k) }
unless copied_options.empty?
copied_options_str = ", " + copied_options.map { |k, v| "#{k.inspect} => #{v.inspect}" }.join(",")
end
if !@children.empty? || @options.has_key?(:collection) || @options.has_key?(:member)
prefix = ["#{route_method} :#{@name}#{copied_options_str} do"]
lines = prefix + custom_methods + [@children.map {|r| r.to_route_code}.join("\n"), "end"]
indent_lines(lines)
else
base = "#{route_method} :%s#{copied_options_str}"
indent_lines [base % [@name]]
end
end
def custom_methods
collection_code = generate_custom_methods_for(:collection)
member_code = generate_custom_methods_for(:member)
[collection_code, member_code]
end
def generate_custom_methods_for(group)
return "" unless @options[group]
method_code = []
RouteRedrawer.stack << self
@options[group].each do |name, methods|
[*methods].each do |method|
method_code << "#{method} :#{name}"
end
end
RouteRedrawer.stack.pop
indent_lines ["#{group} do", method_code, "end"].flatten
end
def route_method
"resources"
end
def <<(val)
@children << val
end
def last
@children.last
end
end
class FakeSingletonResourceRoute < FakeResourceRoute
def route_method
"resource"
end
end
class RouteGenerator
def initialize(routes)
@routes = routes
@new_code = ""
end
def generate
@new_code = @routes.map do |r|
r.to_route_code
end.join("\n")
"#{app_name.underscore.classify}::Application.routes.draw do\n#{@new_code}\nend\n"
end
private
def app_name
File.basename(Dir.pwd)
end
end
end
end

View file

@ -0,0 +1,78 @@
$:.unshift(File.dirname(__FILE__) + "/../../lib")
require 'routes_upgrader'
require 'gemfile_generator'
require 'application_checker'
require 'new_configuration_generator'
require 'fileutils'
namespace :rails do
namespace :upgrade do
desc "Runs a battery of checks on your Rails 2.x app and generates a report on required upgrades for Rails 3"
task :check do
checker = Rails::Upgrading::ApplicationChecker.new
checker.run
end
desc "Generates a Gemfile for your Rails 3 app out of your config.gem directives"
task :gems do
generator = Rails::Upgrading::GemfileGenerator.new
new_gemfile = generator.generate_new_gemfile
puts new_gemfile
end
desc "Create a new, upgraded route file from your current routes.rb"
task :routes do
upgrader = Rails::Upgrading::RoutesUpgrader.new
new_routes = upgrader.generate_new_routes
puts new_routes
end
desc "Extracts your configuration code so you can create a new config/application.rb"
task :configuration do
upgrader = Rails::Upgrading::NewConfigurationGenerator.new
new_config = upgrader.generate_new_application_rb
puts new_config
end
CLEAR = "\e[0m"
CYAN = "\e[36m"
WHITE = "\e[37m"
desc "Backs up your likely modified files so you can run the Rails 3 generator on your app with little risk"
task :backup do
files = [".gitignore",
"app/controllers/application_controller.rb",
"app/helpers/application_helper.rb",
"config/routes.rb",
"config/environment.rb",
"config/environments/development.rb",
"config/environments/production.rb",
"config/environments/staging.rb",
"config/database.yml",
"config.ru",
"doc/README_FOR_APP",
"test/test_helper.rb"]
puts
files.each do |f|
if File.exist?(f)
puts "#{CYAN}* #{CLEAR}backing up #{WHITE}#{f}#{CLEAR} to #{WHITE}#{f}.rails2#{CLEAR}"
FileUtils.cp(f, "#{f}.rails2")
end
end
puts
puts "This is a list of the files analyzed and backed up (if they existed);\nyou will probably not want the generator to replace them since\nyou probably modified them (but now they're safe if you accidentally do!)."
puts
files.each do |f|
puts "#{CYAN}- #{CLEAR}#{f}"
end
puts
end
end
end

View file

@ -0,0 +1,330 @@
require 'test_helper'
require 'application_checker'
require 'fileutils'
tmp_dir = File.expand_path("#{File.dirname(__FILE__)}/fixtures/tmp")
if defined? BASE_ROOT
BASE_ROOT.replace tmp_dir
else
BASE_ROOT = tmp_dir
end
FileUtils.mkdir_p BASE_ROOT
# Stub out methods on upgrader class
module Rails
module Upgrading
class ApplicationChecker
attr_reader :alerts, :culprits
def base_path
BASE_ROOT + "/"
end
def in_rails_app?
true
end
def initialize
@alerts = {}
@culprits = {}
end
def alert(title, text, more_info_url, culprits)
@alerts[title] = [text, more_info_url]
@culprits[title] = culprits
end
end
end
end
class ApplicationCheckerTest < ActiveSupport::TestCase
def setup
@checker = Rails::Upgrading::ApplicationChecker.new
@old_dir = Dir.pwd
Dir.chdir(BASE_ROOT)
end
def test_check_ar_methods_in_controller
make_file("app/controllers", "post_controller.rb", "Post.find(:all)")
@checker.check_ar_methods
assert @checker.alerts.has_key?("Soon-to-be-deprecated ActiveRecord calls")
end
def test_check_ar_methods_in_models
make_file("app/models", "post.rb", "Post.find(:all)")
@checker.check_ar_methods
key = "Soon-to-be-deprecated ActiveRecord calls"
assert @checker.alerts.has_key?(key)
assert_equal "app/models/post.rb", @checker.culprits[key].first
end
def test_check_svn_subdirs_are_not_included
make_file("app/models/.svn/text-base", "foo.rb.tmp", "Post.find(:all)")
@checker.check_ar_methods
assert @checker.alerts.empty?
end
def test_check_validation_on_methods
make_file("app/models", "post.rb", "validate_on_create :comments_valid?")
@checker.check_validation_on_methods
assert @checker.alerts.has_key?("Updated syntax for validate_on_* methods")
end
def test_check_before_validation_on_methods
make_file("app/models", "post.rb", "before_validation_on_create :comments_valid?")
@checker.check_before_validation_on_methods
assert @checker.alerts.has_key?("Updated syntax for before_validation_on_* methods")
end
def test_named_scope_left_over
make_file("app/models", "post.rb", "named_scope :failure")
@checker.check_ar_methods
assert @checker.alerts.has_key?("named_scope is now just scope")
end
def test_check_routes
make_file("config/", "routes.rb", " map.connect 'fail'")
@checker.check_routes
assert @checker.alerts.has_key?("Old router API")
end
def test_check_for_old_test_help
make_file("test/", "test_helper.rb", " require 'test_help'")
@checker.check_test_help
assert @checker.alerts.has_key?("Deprecated test_help path")
end
def test_check_for_old_test_help_with_double_quotes
make_file("test/", "test_helper.rb", " require \"test_help\"")
@checker.check_test_help
assert @checker.alerts.has_key?("Deprecated test_help path")
end
def test_check_for_old_test_help_doesnt_see_test_helper
make_file("test/", "test_helper.rb", " require 'test_helper'")
@checker.check_test_help
assert !@checker.alerts.has_key?("Deprecated test_help path")
end
def test_check_lack_of_app_dot_rb
@checker.check_environment
assert @checker.alerts.has_key?("New file needed: config/application.rb")
end
def test_check_environment_syntax
make_file("config/", "environment.rb", "config.frameworks = []")
@checker.check_environment
assert @checker.alerts.has_key?("Old environment.rb")
end
def test_check_gems
make_file("config/", "environment.rb", "config.gem 'rails'")
@checker.check_gems
assert @checker.alerts.has_key?("Old gem bundling (config.gems)")
end
def test_check_gems_finds_nothing
@checker.check_gems
assert_equal false, @checker.alerts.has_key?("Old gem bundling (config.gems)")
end
def test_check_mailer_finds_nothing
@checker.check_mailers
assert_equal false, @checker.alerts.has_key?("Old ActionMailer class API")
end
def test_check_mailer_syntax
make_file("app/models/", "notifications.rb", "def signup\nrecipients @users\n end")
@checker.check_mailers
assert @checker.alerts.has_key?("Old ActionMailer class API")
end
def test_check_mailer_syntax_from
make_file("app/models/", "notifications.rb", "def signup\nfrom @user\n end")
@checker.check_mailers
assert @checker.alerts.has_key?("Old ActionMailer class API")
end
def test_check_mailer_syntax_subject
make_file("app/models/", "notifications.rb", "def signup\nsubject @subject\n end")
@checker.check_mailers
assert @checker.alerts.has_key?("Old ActionMailer class API")
end
def test_check_mailer_syntax_attachment
make_file("app/models/", "notifications.rb", "def signup\nattachment 'application/pdf' do |a|\n end")
@checker.check_mailers
assert @checker.alerts.has_key?("Old ActionMailer class API")
end
def test_new_check_mailer_syntax_from
make_file("app/models/", "notifications.rb", "def signup\n:from => @users\n end")
@checker.check_mailers
assert ! @checker.alerts.has_key?("Old ActionMailer class API")
end
def test_new_check_mailer_syntax_subject
make_file("app/models/", "notifications.rb", "def signup\n:subject => @users\n end")
@checker.check_mailers
assert ! @checker.alerts.has_key?("Old ActionMailer class API")
end
def test_new_check_mailer_syntax_attachments
make_file("app/models/", "notifications.rb", "def signup\nattachments['an-image.jp'] = File.read('an-image.jpg')\n end")
@checker.check_mailers
assert ! @checker.alerts.has_key?("Old ActionMailer class API")
end
def test_check_mailer_api
make_file("app/controllers/", "thing_controller.rb", "def signup\n Notifications.deliver_signup\n end")
@checker.check_mailers
assert @checker.alerts.has_key?("Deprecated ActionMailer API")
end
def test_check_generators
make_file("vendor/plugins/thing/generators/thing/", "thing_generator.rb", "def manifest\n m.whatever\n end")
@checker.check_generators
assert @checker.alerts.has_key?("Old Rails generator API")
end
def test_check_plugins
make_file("vendor/plugins/rspec-rails/", "whatever.rb", "def rspec; end")
@checker.check_plugins
assert @checker.alerts.has_key?("Known broken plugins")
end
def test_ignoring_comments
make_file("config/", "routes.rb", "# map.connect 'fail'")
@checker.check_routes
assert !@checker.alerts.has_key?("Old router API")
end
def test_check_deprecated_constants_in_app_code
make_file("app/controllers/", "thing_controller.rb", "class ThingController; THING = RAILS_ENV; end;")
@checker.check_deprecated_constants
assert @checker.alerts.has_key?("Deprecated constant(s)")
end
def test_check_deprecated_constants_in_lib
make_file("lib/", "extra_thing.rb", "class ExtraThing; THING = RAILS_ENV; end;")
@checker.check_deprecated_constants
assert @checker.alerts.has_key?("Deprecated constant(s)")
end
def test_check_deprecated_cookie_finds_nothing
@checker.check_old_cookie_secret
assert_equal false, @checker.alerts.has_key?("Deprecated cookie secret setting")
end
def test_check_deprecated_cookie_settings
make_file("config/initializers/", "more_settings.rb", "ActionController::Base.cookie_verifier_secret = 'OMG'")
@checker.check_old_cookie_secret
assert @checker.alerts.has_key?("Deprecated cookie secret setting")
end
def test_check_deprecated_session_finds_nothing
@checker.check_old_session_secret
assert_equal false, @checker.alerts.has_key?("Deprecated session secret setting")
end
def test_check_deprecated_session_secret
make_file("config/initializers/", "more_settings.rb", "ActionController::Base.session = {\n:whatever => 'woot'\n}")
@checker.check_old_session_secret
assert @checker.alerts.has_key?("Deprecated session secret setting")
end
def test_check_old_session_setting_finds_nothing
@checker.check_old_session_setting
assert_equal false, @checker.alerts.has_key?("Old session store setting")
end
def test_check_deprecated_session_settings
make_file("config/initializers/", "more_settings.rb", "ActionController::Base.session_store = :cookie\nthings.awesome(:whatever)")
@checker.check_old_session_setting
assert @checker.alerts.has_key?("Old session store setting")
end
def test_check_helpers
make_file("app/views/users/", "test.html.erb", "<b>blah blah blah</b><% form_for(:thing) do |f| %> <label>doo dah</label> <%= f.whatever %> <% end %>")
@checker.check_old_helpers
assert @checker.alerts.has_key?("Deprecated ERb helper calls")
end
def test_check_old_helpers_lets_regular_blocks_pass
make_file("app/views/users/", "another_test.html.erb", "<b>blah blah blah</b><% @some_items.each do |item| %> <label>doo dah</label> <%= item %> <% end %>")
@checker.check_old_helpers
assert_equal @checker.alerts.has_key?("Deprecated ERb helper calls"), false
end
def test_check_old_helpers_lets_regular_blocks_pass
make_file("app/views/users/", "another_test.html.erb", "<b>blah blah blah</b><% @some_items.each do |item| %> <label>doo dah</label> <%= item %> <% end %>")
@checker.check_old_helpers
assert_equal false, @checker.alerts.has_key?("Deprecated ERb helper calls")
end
def test_check_old_ajax_helpers
make_file("app/views/sections", "section.js", "<%= link_to_remote 'section-', :update => 'sections', :url => {:action => :destroy, :controller => 'sections', :id => @section.id } %>")
@checker.check_old_ajax_helpers
assert @checker.alerts.has_key?("Deprecated AJAX helper calls")
end
def test_check_old_ajax_helpers_empty
@checker.check_old_ajax_helpers
assert ! @checker.alerts.has_key?("Deprecated AJAX helper calls")
end
def teardown
clear_files
Dir.chdir(@old_dir)
end
def make_file(where, name=nil, contents=nil)
FileUtils.mkdir_p "#{BASE_ROOT}/#{where}"
File.open("#{BASE_ROOT}/#{where}/#{name}", "w+") do |f|
f.write(contents)
end if name
end
def clear_files
FileUtils.rm_rf(Dir.glob("#{BASE_ROOT}/*"))
end
end

View file

@ -0,0 +1,72 @@
require 'test_helper'
require 'gemfile_generator'
# Stub out methods on upgrader class
module Rails
module Upgrading
class GemfileGenerator
attr_writer :environment_code
def has_environment?
true
end
def environment_code
@environment_code
end
end
end
end
class GemfileGeneratorTest < ActiveSupport::TestCase
PREAMBLE = <<STR
# Edit this Gemfile to bundle your application's dependencies.
# This preamble is the current preamble for Rails 3 apps; edit as needed.
source 'http://rubygems.org'
gem 'rails', '3.0.6'
STR
def test_generates_with_no_gems
generator = Rails::Upgrading::GemfileGenerator.new
generator.environment_code = ""
assert_equal PREAMBLE, generator.generate_gemfile
end
def test_generates_with_gem
generator = Rails::Upgrading::GemfileGenerator.new
generator.environment_code = "config.gem 'camping'"
assert_equal PREAMBLE + "gem 'camping'", generator.generate_gemfile
end
def test_generates_with_version
generator = Rails::Upgrading::GemfileGenerator.new
generator.environment_code = "config.gem 'camping', :version => '2.1.1'"
assert_equal PREAMBLE + "gem 'camping', '2.1.1'", generator.generate_gemfile
end
def test_can_add_sources
generator = Rails::Upgrading::GemfileGenerator.new
generator.environment_code = "config.gem 'camping', :source => 'http://code.whytheluckystiff.net'"
assert_equal PREAMBLE + "source 'http://code.whytheluckystiff.net'\ngem 'camping'", generator.generate_gemfile
end
def test_changes_lib_to_new_key
generator = Rails::Upgrading::GemfileGenerator.new
generator.environment_code = "config.gem 'camping', :lib => 'kamping'"
assert_equal PREAMBLE + "gem 'camping', :require => 'kamping'", generator.generate_gemfile
end
def test_generates_with_all_options
generator = Rails::Upgrading::GemfileGenerator.new
generator.environment_code = "config.gem 'camping', :lib => 'kamping', :source => 'http://code.whytheluckystiff.net', :version => '2.1.1'"
assert_equal PREAMBLE + "source 'http://code.whytheluckystiff.net'\ngem 'camping', '2.1.1', :require => 'kamping'", generator.generate_gemfile
end
end

View file

@ -0,0 +1,63 @@
require 'test_helper'
require 'new_configuration_generator'
# Stub out methods on upgrader class
module Rails
module Upgrading
class NewConfigurationGenerator
attr_writer :environment_code
def has_environment?
true
end
def environment_code
@environment_code
end
def app_name
"my_application"
end
end
end
end
class NewConfigurationGeneratorTest < ActiveSupport::TestCase
FRAME = "# Put this in config/application.rb
require File.expand_path('../boot', __FILE__)
module MyApplication
class Application < Rails::Application
%s
end
end"
CONFIG = " config.what_have_you = 'thing'
config.action_controller = 'what'"
CODE = "require 'w/e'
this_happens_before_the(code)
more_before_the_code!
Rails::Initializer.run do |config|
%s
end
this_is_after_the_code
"
def test_raises_error_with_no_code
generator = Rails::Upgrading::NewConfigurationGenerator.new
generator.environment_code = ""
assert_raises(RuntimeError) { generator.generate_new_application_rb }
end
def test_generates_with_code
generator = Rails::Upgrading::NewConfigurationGenerator.new
generator.environment_code = CODE % [CONFIG]
assert_equal FRAME % [generator.indent(CONFIG)], generator.generate_new_application_rb
end
end

View file

@ -0,0 +1,184 @@
require 'test_helper'
require 'routes_upgrader'
# Stub out methods on upgrader class
module Rails
module Upgrading
class RoutesUpgrader
attr_writer :routes_code
def has_routes_file?
true
end
def routes_code
@routes_code
end
end
class RouteGenerator
def app_name
"MyApplication"
end
end
end
end
class RoutesUpgraderTest < ActiveSupport::TestCase
def setup
Rails::Upgrading::RouteRedrawer.stack = []
end
def test_generates_routes_file
routes_code = "
ActionController::Routing::Routes.draw do |map|
map.connect '/home', :controller => 'home', :action => 'index'
map.login '/login', :controller => 'sessions', :action => 'new'
map.resources :hats
map.resource :store
end
"
new_routes_code = "MyApplication::Application.routes.draw do
match '/home' => 'home#index'
match '/login' => 'sessions#new', :as => :login
resources :hats
resource :store
end
"
upgrader = Rails::Upgrading::RoutesUpgrader.new
upgrader.routes_code = routes_code
result = upgrader.generate_new_routes
assert_equal new_routes_code, result
end
def test_generates_code_for_regular_route
route = Rails::Upgrading::FakeRoute.new("/about", {:controller => 'static', :action => 'about'})
assert_equal "match '/about' => 'static#about'", route.to_route_code
end
def test_generates_code_for_named_route
route = Rails::Upgrading::FakeRoute.new("/about", {:controller => 'static', :action => 'about'}, "about")
assert_equal "match '/about' => 'static#about', :as => :about", route.to_route_code
end
def test_generates_code_for_namespace
ns = Rails::Upgrading::FakeNamespace.new("static")
# Add a route to the namespace
ns << Rails::Upgrading::FakeRoute.new("/about", {:controller => 'static', :action => 'about'})
assert_equal "namespace :static do\nmatch '/about' => 'static#about'\nend\n", ns.to_route_code
end
def test_generates_code_for_namespace_with_options
ns = Rails::Upgrading::FakeNamespace.new("static", { :path_prefix => 'prefix' })
# Add a route to the namespace
ns << Rails::Upgrading::FakeRoute.new("/about", {:controller => 'static', :action => 'about'})
assert_equal "namespace :static, :path_prefix => 'prefix' do\nmatch '/about' => 'static#about'\nend\n", ns.to_route_code
end
def test_generates_code_for_resources
route = Rails::Upgrading::FakeResourceRoute.new("hats")
assert_equal "resources :hats", route.to_route_code
end
def test_generates_code_for_resources
route = Rails::Upgrading::FakeSingletonResourceRoute.new("hat")
assert_equal "resource :hat", route.to_route_code
end
def test_generates_code_for_resources_with_special_methods
route = Rails::Upgrading::FakeResourceRoute.new("hats", {:member => {:wear => :get}, :collection => {:toss => :post}})
assert_equal "resources :hats do\ncollection do\npost :toss\nend\nmember do\nget :wear\nend\n\nend\n", route.to_route_code
end
def test_generates_code_for_resources_with_multiple_special_methods_per_name
route = Rails::Upgrading::FakeResourceRoute.new("hats", {:member => {:wear => [:get, :put]}, :collection => {:toss => [:get, :post]}})
assert_equal "resources :hats do\ncollection do\nget :toss\npost :toss\nend\nmember do\nget :wear\nput :wear\nend\n\nend\n", route.to_route_code
end
def test_generates_code_for_route_with_extra_params
route = Rails::Upgrading::FakeRoute.new("/about", {:controller => 'static', :action => 'about', :something => 'extra'})
assert_equal "match '/about' => 'static#about', :something => 'extra'", route.to_route_code
end
def test_generates_code_for_route_with_requirements
route = Rails::Upgrading::FakeRoute.new("/foo", {:controller => 'foo', :action => 'bar', :requirements => {:digit => /%d/}})
assert_equal "match '/foo' => 'foo#bar', :constraints => { :digit => /%d/ }", route.to_route_code
end
def test_generates_code_for_root
routes_code = "
ActionController::Routing::Routes.draw do |map|
map.root :controller => 'home', :action => 'index'
end
"
new_routes_code = "MyApplication::Application.routes.draw do
match '/' => 'home#index'
end
"
upgrader = Rails::Upgrading::RoutesUpgrader.new
upgrader.routes_code = routes_code
result = upgrader.generate_new_routes
assert_equal new_routes_code, result
end
def test_generates_code_for_default_route
routes_code = "
ActionController::Routing::Routes.draw do |map|
map.connect ':controller/:action/:id.:format'
map.connect ':controller/:action/:id'
end
"
new_routes_code = "MyApplication::Application.routes.draw do
match '/:controller(/:action(/:id))'
end
"
upgrader = Rails::Upgrading::RoutesUpgrader.new
upgrader.routes_code = routes_code
result = upgrader.generate_new_routes
assert_equal new_routes_code, result
end
def test_preserves_resources_except_option
route = Rails::Upgrading::FakeResourceRoute.new("hats", :except => [:index])
assert_equal "resources :hats, :except => [:index]", route.to_route_code
end
def test_preserves_resources_only_option
route = Rails::Upgrading::FakeResourceRoute.new("hats", :only => :show)
assert_equal "resources :hats, :only => :show", route.to_route_code
end
def test_generates_code_for_delete_route
routes_code = %Q{
ActionController::Routing::Routes.draw do |map|
map.sign_out '/sign_out', :controller => 'sessions', :action => 'destroy', :method => :delete
end
}
new_routes_code = %Q{
MyApplication::Application.routes.draw do
match '/sign_out' => 'sessions#destroy', :as => :sign_out, :via => 'delete'
end
}
upgrader = Rails::Upgrading::RoutesUpgrader.new
upgrader.routes_code = routes_code
assert_equal new_routes_code.strip, upgrader.generate_new_routes.strip
end
end

View file

@ -0,0 +1,5 @@
require 'test/unit'
require 'rubygems'
require 'active_support'
require 'active_support/test_case'

View file

@ -0,0 +1 @@
# Uninstall hook code here