fix all upgrade warnings from the rails_upgrade plugin

This commit is contained in:
Reinier Balt 2012-04-18 14:22:58 +02:00
parent fd4fb6df9e
commit fd433d76d8
47 changed files with 288 additions and 2284 deletions

View file

@ -41,14 +41,13 @@ GEM
coffee-script-source
execjs
coffee-script-source (1.3.1)
daemons (1.0.10)
erubis (2.7.0)
execjs (1.3.0)
multi_json (~> 1.0)
gem_plugin (0.2.3)
highline (1.5.2)
hike (1.2.1)
htmlentities (4.3.1)
httpclient (2.2.4)
i18n (0.6.0)
journey (1.0.3)
jquery-rails (2.0.2)
@ -60,9 +59,6 @@ GEM
mime-types (~> 1.16)
treetop (~> 1.4.8)
mime-types (1.18)
mongrel (1.2.0.pre2)
daemons (~> 1.0.10)
gem_plugin (~> 0.2.3)
multi_json (1.2.0)
mysql2 (0.3.11)
nokogiri (1.4.7)
@ -101,7 +97,8 @@ GEM
railties (~> 3.2.0)
sass (>= 3.1.10)
tilt (~> 1.3)
soap4r-ruby1.9 (2.0.5)
soap4r (1.5.8)
httpclient (>= 2.1.1)
sprockets (2.1.2)
hike (~> 1.2)
rack (~> 1.0)
@ -135,13 +132,12 @@ DEPENDENCIES
htmlentities (~> 4.3.0)
jquery-rails
mail
mongrel (= 1.2.0.pre2)
mysql2
rails (= 3.2.3)
rails_autolink
sanitize (~> 1.2.1)
sass-rails (~> 3.2.3)
soap4r-ruby1.9
soap4r (~> 1.5.8)
sqlite3
swf_fu
uglifier (>= 1.0.3)

View file

@ -18,9 +18,9 @@ class DataController < ApplicationController
def yaml_export
all_tables = {}
all_tables['todos'] = current_user.todos.find(:all, :include => [:tags])
all_tables['contexts'] = current_user.contexts.find(:all)
all_tables['projects'] = current_user.projects.find(:all)
all_tables['todos'] = current_user.todos.includes(:tags)
all_tables['contexts'] = current_user.contexts.all
all_tables['projects'] = current_user.projects.all
todo_tag_ids = Tag.find_by_sql([
"SELECT DISTINCT tags.id "+
@ -34,13 +34,13 @@ class DataController < ApplicationController
"WHERE recurring_todos.user_id=? "+
"AND tags.id = taggings.tag_id " +
"AND taggings.taggable_id = recurring_todos.id ", current_user.id])
tags = Tag.find(:all, :conditions => ["id IN (?) OR id IN (?)", todo_tag_ids, rec_todo_tag_ids])
taggings = Tagging.find(:all, :conditions => ["tag_id IN (?) OR tag_id IN(?)", todo_tag_ids, rec_todo_tag_ids])
tags = Tag.where("id IN (?) OR id IN (?)", todo_tag_ids, rec_todo_tag_ids)
taggings = Tagging.where("tag_id IN (?) OR tag_id IN(?)", todo_tag_ids, rec_todo_tag_ids)
all_tables['tags'] = tags
all_tables['taggings'] = taggings
all_tables['notes'] = current_user.notes.find(:all)
all_tables['recurring_todos'] = current_user.recurring_todos.find(:all)
all_tables['notes'] = current_user.notes
all_tables['recurring_todos'] = current_user.recurring_todos
result = all_tables.to_yaml
result.gsub!(/\n/, "\r\n") # TODO: general functionality for line endings
@ -53,7 +53,7 @@ class DataController < ApplicationController
csv << ["id", "Context", "Project", "Description", "Notes", "Tags",
"Created at", "Due", "Completed at", "User ID", "Show from",
"state"]
current_user.todos.find(:all, :include => [:context, :project]).each do |todo|
current_user.todos.include(:context, :project).all.each do |todo|
csv << [todo.id, todo.context.name,
todo.project_id.nil? ? "" : todo.project.name,
todo.description,
@ -78,13 +78,13 @@ class DataController < ApplicationController
# had to remove project include because it's association order is leaking
# through and causing an ambiguous column ref even with_exclusive_scope
# didn't seem to help -JamesKebinger
current_user.notes.find(:all,:order=>"notes.created_at").each do |note|
current_user.notes.order("notes.created_at").each do |note|
# Format dates in ISO format for easy sorting in spreadsheet Print
# context and project names for easy viewing
csv << [note.id, note.user_id,
csv << [note.id, note.user_id,
note.project_id = note.project_id.nil? ? "" : note.project.name,
note.body, note.created_at.to_formatted_s(:db),
note.updated_at.to_formatted_s(:db)]
note.updated_at.to_formatted_s(:db)]
end
end
send_data(result, :filename => "notes.csv", :type => content_type)
@ -103,17 +103,17 @@ class DataController < ApplicationController
"WHERE recurring_todos.user_id=? "+
"AND tags.id = taggings.tag_id " +
"AND taggings.taggable_id = recurring_todos.id ", current_user.id])
tags = Tag.find(:all, :conditions => ["id IN (?) OR id IN (?)", todo_tag_ids, rec_todo_tag_ids])
taggings = Tagging.find(:all, :conditions => ["tag_id IN (?) OR tag_id IN(?)", todo_tag_ids, rec_todo_tag_ids])
tags = Tag.where("id IN (?) OR id IN (?)", todo_tag_ids, rec_todo_tag_ids)
taggings = Tagging.where("tag_id IN (?) OR tag_id IN(?)", todo_tag_ids, rec_todo_tag_ids)
result = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><tracks_data>"
result << current_user.todos.find(:all).to_xml(:skip_instruct => true)
result << current_user.contexts.find(:all).to_xml(:skip_instruct => true)
result << current_user.projects.find(:all).to_xml(:skip_instruct => true)
result << current_user.todos.to_xml(:skip_instruct => true)
result << current_user.contexts.to_xml(:skip_instruct => true)
result << current_user.projects.to_xml(:skip_instruct => true)
result << tags.to_xml(:skip_instruct => true)
result << taggings.to_xml(:skip_instruct => true)
result << current_user.notes.find(:all).to_xml(:skip_instruct => true)
result << current_user.recurring_todos.find(:all).to_xml(:skip_instruct => true)
result << current_user.notes.to_xml(:skip_instruct => true)
result << current_user.recurring_todos.to_xml(:skip_instruct => true)
result << "</tracks_data>"
send_data(result, :filename => "tracks_data.xml", :type => 'text/xml')
end
@ -126,7 +126,7 @@ class DataController < ApplicationController
def adjust_time(timestring)
if (timestring=='') or ( timestring == nil)
return nil
else
else
return Time.parse(timestring + 'UTC')
end
end
@ -186,7 +186,7 @@ class DataController < ApplicationController
case item.ivars['attributes']['state']
when 'active' then newitem.activate!
when 'project_hidden' then newitem.hide!
when 'completed'
when 'completed'
newitem.complete!
newitem.completed_at = adjust_time(item.ivars['attributes']['completed_at'])
when 'deferred' then newitem.defer!

View file

@ -27,7 +27,8 @@ class IntegrationsController < ApplicationController
end
def search_plugin
@icon_data = [File.open(RAILS_ROOT + '/public/images/done.png').read].
# TODO: ASSET PATH!!
@icon_data = [File.open(Rails.root + '/public/images/done.png').read].
pack('m').gsub(/\n/, '')
render :layout => false
@ -52,7 +53,7 @@ class IntegrationsController < ApplicationController
message = Mail.new(params[:message])
# find user
user = User.find(:first, :include => [:preference], :conditions => ["preferences.sms_email = ?", message.from])
user = User.where("preferences.sms_email = ?", message.from).includes(:preferences).first
if user.nil?
render :text => "No user found", :status => 404
return false

View file

@ -13,13 +13,13 @@ class ProjectsController < ApplicationController
if params[:projects_and_actions]
projects_and_actions
else
@contexts = current_user.contexts.all
@contexts = current_user.contexts
init_not_done_counts(['project'])
init_project_hidden_todo_counts(['project'])
if params[:only_active_with_no_next_actions]
@projects = current_user.projects.active.select { |p| count_undone_todos(p) == 0 }
else
@projects = current_user.projects.all
@projects = current_user.projects
end
respond_to do |format|
format.html &render_projects_html
@ -101,15 +101,15 @@ class ProjectsController < ApplicationController
init_data_for_sidebar unless mobile?
@page_title = t('projects.page_title', :project => @project.name)
@not_done = @project.todos.active_or_hidden(:include => Todo::DEFAULT_INCLUDES)
@deferred = @project.todos.deferred(:include => Todo::DEFAULT_INCLUDES)
@pending = @project.todos.pending(:include => Todo::DEFAULT_INCLUDES)
@not_done = @project.todos.active_or_hidden.includes(Todo::DEFAULT_INCLUDES)
@deferred = @project.todos.deferred.includes(Todo::DEFAULT_INCLUDES)
@pending = @project.todos.pending.includes(Todo::DEFAULT_INCLUDES)
@done = {}
@done = @project.todos.find_in_state(:all, :completed,
:order => "todos.completed_at DESC",
:limit => current_user.prefs.show_number_completed,
:include => Todo::DEFAULT_INCLUDES) unless current_user.prefs.show_number_completed == 0
@done = @project.todos.completed.
order("todos.completed_at DESC").
limit(current_user.prefs.show_number_completed).
includes(Todo::DEFAULT_INCLUDES) unless current_user.prefs.show_number_completed == 0
@count = @not_done.size
@down_count = @count + @deferred.size + @pending.size
@ -318,7 +318,7 @@ class ProjectsController < ApplicationController
@count = current_user.projects.count
@active_projects = current_user.projects.active
@hidden_projects = current_user.projects.hidden
@completed_projects = current_user.projects.completed.find(:all, :limit => 10)
@completed_projects = current_user.projects.completed.limit(10)
@completed_count = current_user.projects.completed.count
@no_projects = current_user.projects.empty?
current_user.projects.cache_note_counts

View file

@ -9,12 +9,12 @@ class RecurringTodosController < ApplicationController
@page_title = t('todos.recurring_actions_title')
@source_view = params['_source_view'] || 'recurring_todo'
find_and_inactivate
@recurring_todos = current_user.recurring_todos.active.find(:all, :include => [:tags, :taggings])
@completed_recurring_todos = current_user.recurring_todos.completed.find(:all, :limit => 10, :include => [:tags, :taggings])
@recurring_todos = current_user.recurring_todos.active.includes(:tags, :taggings)
@completed_recurring_todos = current_user.recurring_todos.completed.limit(10).includes(:tags, :taggings)
@no_recurring_todos = @recurring_todos.size == 0
@no_completed_recurring_todos = @completed_recurring_todos.size == 0
@count = @recurring_todos.size
@no_recurring_todos = @recurring_todos.count == 0
@no_completed_recurring_todos = @completed_recurring_todos.count == 0
@count = @recurring_todos.count
@new_recurring_todo = RecurringTodo.new
end
@ -271,8 +271,8 @@ class RecurringTodosController < ApplicationController
end
@xth_day = [[t('common.first'),1],[t('common.second'),2],[t('common.third'),3],[t('common.fourth'),4],[t('common.last'),5]]
@projects = current_user.projects.find(:all, :include => [:default_context])
@contexts = current_user.contexts.find(:all)
@projects = current_user.projects.includes(:default_context)
@contexts = current_user.contexts
end
def get_recurring_todo_from_param
@ -282,10 +282,11 @@ class RecurringTodosController < ApplicationController
def find_and_inactivate
# find active recurring todos without active todos and inactivate them
current_user.recurring_todos.active.all(
:select => "recurring_todos.id, recurring_todos.state",
:joins => "LEFT JOIN todos fai_todos ON (recurring_todos.id = fai_todos.recurring_todo_id) AND (NOT fai_todos.state='completed')",
:conditions => "fai_todos.id IS NULL").each { |rt| current_user.recurring_todos.find(rt.id).toggle_completion! }
current_user.recurring_todos.active.
select("recurring_todos.id, recurring_todos.state").
joins("LEFT JOIN todos fai_todos ON (recurring_todos.id = fai_todos.recurring_todo_id) AND (NOT fai_todos.state='completed')").
where("fai_todos.id IS NULL").
each { |rt| current_user.recurring_todos.find(rt.id).toggle_completion! }
end
end

View file

@ -7,19 +7,22 @@ class SearchController < ApplicationController
@page_title = "TRACKS::Search Results for #{params[:search]}"
terms = '%' + params[:search] + '%'
@found_not_complete_todos = current_user.todos.find(:all,
:conditions => ["(todos.description LIKE ? OR todos.notes LIKE ?) AND todos.completed_at IS NULL", terms, terms],
:include => Todo::DEFAULT_INCLUDES,
:order => "todos.due IS NULL, todos.due ASC, todos.created_at ASC")
@found_complete_todos = current_user.todos.find(:all,
:conditions => ["(todos.description LIKE ? OR todos.notes LIKE ?) AND NOT (todos.completed_at IS NULL)", terms, terms],
:include => Todo::DEFAULT_INCLUDES,
:order => "todos.completed_at DESC")
@found_not_complete_todos = current_user.todos.
where("(todos.description LIKE ? OR todos.notes LIKE ?) AND todos.completed_at IS NULL", terms, terms).
includes(Todo::DEFAULT_INCLUDES).
order("todos.due IS NULL, todos.due ASC, todos.created_at ASC")
@found_complete_todos = current_user.todos.
where("(todos.description LIKE ? OR todos.notes LIKE ?) AND NOT (todos.completed_at IS NULL)", terms, terms).
includes(Todo::DEFAULT_INCLUDES).
order("todos.completed_at DESC")
@found_todos = @found_not_complete_todos + @found_complete_todos
@found_projects = current_user.projects.find(:all, :conditions => ["name LIKE ? OR description LIKE ?", terms, terms])
@found_notes = current_user.notes.find(:all, :conditions => ["body LIKE ?", terms])
@found_contexts = current_user.contexts.find(:all, :conditions => ["name LIKE ?", terms])
@found_projects = current_user.projects.where("name LIKE ? OR description LIKE ?", terms, terms)
@found_notes = current_user.notes.where("body LIKE ?", terms)
@found_contexts = current_user.contexts.where("name LIKE ?", terms)
# TODO: limit search to tags on todos
@found_tags = Tagging.find_by_sql([
"SELECT DISTINCT tags.name as name "+

View file

@ -1,8 +1,7 @@
class StatsController < ApplicationController
helper :todos, :projects, :recurring_todos
append_before_filter :init, :exclude => []
append_before_filter :init
def index
@page_title = t('stats.index_title')
@ -10,7 +9,7 @@ class StatsController < ApplicationController
@tags_count = get_total_number_of_tags_of_user
@unique_tags_count = get_unique_tags_of_user.size
@hidden_contexts = current_user.contexts.hidden
@first_action = current_user.todos.find(:first, :order => "created_at ASC")
@first_action = current_user.todos.order("created_at ASC").first
get_stats_actions
get_stats_contexts
@ -23,10 +22,10 @@ class StatsController < ApplicationController
def actions_done_last12months_data
# get actions created and completed in the past 12+3 months. +3 for running
# average
@actions_done_last12months = current_user.todos.completed_after(@cut_off_year).find(:all, { :select => "completed_at" })
@actions_created_last12months = current_user.todos.created_after(@cut_off_year).find(:all, { :select => "created_at"})
@actions_done_last12monthsPlus3 = current_user.todos.completed_after(@cut_off_year_plus3).find(:all, { :select => "completed_at" })
@actions_created_last12monthsPlus3 = current_user.todos.created_after(@cut_off_year_plus3).find(:all, { :select => "created_at"})
@actions_done_last12months = current_user.todos.completed_after(@cut_off_year).select("completed_at" )
@actions_created_last12months = current_user.todos.created_after(@cut_off_year).select("created_at")
@actions_done_last12monthsPlus3 = current_user.todos.completed_after(@cut_off_year_plus3).select("completed_at" )
@actions_created_last12monthsPlus3 = current_user.todos.created_after(@cut_off_year_plus3).select("created_at")
# convert to array and fill in non-existing months
@actions_done_last12months_array = convert_to_months_from_today_array(@actions_done_last12months, 13, :completed_at)
@ -56,8 +55,8 @@ class StatsController < ApplicationController
end
def actions_done_lastyears_data
@actions_done_last_months = current_user.todos.completed.find(:all, { :select => "completed_at", :order => "completed_at DESC" })
@actions_created_last_months = current_user.todos.find(:all, { :select => "created_at", :order => "created_at DESC" })
@actions_done_last_months = current_user.todos.completed.select("completed_at").order("completed_at DESC")
@actions_created_last_months = current_user.todos.select("created_at").order("created_at DESC" )
# query is sorted, so use last todo to calculate number of months
@month_count = [difference_in_months(@today, @actions_created_last_months.last.created_at),
@ -88,8 +87,8 @@ class StatsController < ApplicationController
def actions_done_last30days_data
# get actions created and completed in the past 30 days.
@actions_done_last30days = current_user.todos.completed_after(@cut_off_month).find(:all, { :select => "completed_at" })
@actions_created_last30days = current_user.todos.created_after(@cut_off_month).find(:all, { :select => "created_at" })
@actions_done_last30days = current_user.todos.completed_after(@cut_off_month).select("completed_at")
@actions_created_last30days = current_user.todos.created_after(@cut_off_month).select("created_at")
# convert to array. 30+1 to have 30 complete days and one current day [0]
@actions_done_last30days_array = convert_to_days_from_today_array(@actions_done_last30days, 31, :completed_at)
@ -102,7 +101,7 @@ class StatsController < ApplicationController
end
def actions_completion_time_data
@actions_completion_time = current_user.todos.completed.find(:all, { :select => "completed_at, created_at", :order => "completed_at DESC" })
@actions_completion_time = current_user.todos.completed.select("completed_at, created_at").order("completed_at DESC" )
# convert to array and fill in non-existing weeks with 0
@max_weeks = difference_in_weeks(@today, @actions_completion_time.last.completed_at)
@ -122,7 +121,7 @@ class StatsController < ApplicationController
end
def actions_running_time_data
@actions_running_time = current_user.todos.not_completed.find(:all, { :select => "created_at", :order => "created_at DESC" })
@actions_running_time = current_user.todos.not_completed.select("created_at").order("created_at DESC")
# convert to array and fill in non-existing weeks with 0
@max_weeks = difference_in_weeks(@today, @actions_running_time.last.created_at)
@ -150,8 +149,9 @@ class StatsController < ApplicationController
# - actions not deferred (show_from must be null)
# - actions not pending/blocked
@actions_running_time = current_user.todos.not_completed.not_hidden.not_deferred_or_blocked.find(
:all, :select => "todos.created_at", :order => "todos.created_at DESC")
@actions_running_time = current_user.todos.not_completed.not_hidden.not_deferred_or_blocked.
select("todos.created_at").
order("todos.created_at DESC")
@max_weeks = difference_in_weeks(@today, @actions_running_time.last.created_at)
@actions_running_per_week_array = convert_to_weeks_from_today_array(@actions_running_time, @max_weeks+1, :created_at)
@ -170,8 +170,9 @@ class StatsController < ApplicationController
end
def actions_open_per_week_data
@actions_started = current_user.todos.created_after(@today-53.weeks).find(:all,
:select => "todos.created_at, todos.completed_at",:order => "todos.created_at DESC")
@actions_started = current_user.todos.created_after(@today-53.weeks).
select("todos.created_at, todos.completed_at").
order("todos.created_at DESC")
@max_weeks = difference_in_weeks(@today, @actions_started.last.created_at)
@ -259,8 +260,8 @@ class StatsController < ApplicationController
end
def actions_day_of_week_all_data
@actions_creation_day = current_user.todos.find(:all, { :select => "created_at" })
@actions_completion_day = current_user.todos.completed.find(:all, { :select => "completed_at" })
@actions_creation_day = current_user.todos.select("created_at")
@actions_completion_day = current_user.todos.completed.select("completed_at")
# convert to array and fill in non-existing days
@actions_creation_day_array = Array.new(7) { |i| 0}
@ -276,8 +277,8 @@ class StatsController < ApplicationController
end
def actions_day_of_week_30days_data
@actions_creation_day = current_user.todos.created_after(@cut_off_month).find(:all, { :select => "created_at" })
@actions_completion_day = current_user.todos.completed_after(@cut_off_month).find(:all, { :select => "completed_at" })
@actions_creation_day = current_user.todos.created_after(@cut_off_month).select("created_at")
@actions_completion_day = current_user.todos.completed_after(@cut_off_month).select("completed_at")
# convert to hash to be able to fill in non-existing days
@max=0
@ -294,8 +295,8 @@ class StatsController < ApplicationController
end
def actions_time_of_day_all_data
@actions_creation_hour = current_user.todos.find(:all, { :select => "created_at" })
@actions_completion_hour = current_user.todos.completed.find(:all, { :select => "completed_at" })
@actions_creation_hour = current_user.todos.select("created_at")
@actions_completion_hour = current_user.todos.completed.select("completed_at")
# convert to hash to be able to fill in non-existing days
@actions_creation_hour_array = Array.new(24) { |i| 0}
@ -311,8 +312,8 @@ class StatsController < ApplicationController
end
def actions_time_of_day_30days_data
@actions_creation_hour = current_user.todos.created_after(@cut_off_month).find(:all, { :select => "created_at" })
@actions_completion_hour = current_user.todos.completed_after(@cut_off_month).find(:all, { :select => "completed_at" })
@actions_creation_hour = current_user.todos.created_after(@cut_off_month).select("created_at")
@actions_completion_hour = current_user.todos.completed_after(@cut_off_month).select("completed_at")
# convert to hash to be able to fill in non-existing days
@actions_creation_hour_array = Array.new(24) { |i| 0}
@ -355,11 +356,12 @@ class StatsController < ApplicationController
end
# get all running actions that are visible
@actions_running_time = current_user.todos.not_completed.not_hidden.not_deferred_or_blocked.find(
:all, :select => "todos.id, todos.created_at", :order => "todos.created_at DESC")
@actions_running_time = current_user.todos.not_completed.not_hidden.not_deferred_or_blocked.
select("todos.id, todos.created_at").
order("todos.created_at DESC")
selected_todo_ids = get_ids_from(@actions_running_time, week_from, week_to, params['id']== 'avrt_end')
@selected_actions = selected_todo_ids.size == 0 ? [] : current_user.todos.find(:all, { :conditions => "id in (" + selected_todo_ids.join(",") + ")" })
@selected_actions = selected_todo_ids.size == 0 ? [] : current_user.todos.where("id in (" + selected_todo_ids.join(",") + ")")
@count = @selected_actions.size
render :action => "show_selection_from_chart"
@ -379,10 +381,10 @@ class StatsController < ApplicationController
end
# get all running actions
@actions_running_time = current_user.todos.not_completed.find(:all, { :select => "id, created_at" })
@actions_running_time = current_user.todos.not_completed.select("id, created_at")
selected_todo_ids = get_ids_from(@actions_running_time, week_from, week_to, params['id']=='art_end')
@selected_actions = selected_todo_ids.size == 0 ? [] : current_user.todos.find(:all, { :conditions => "id in (" + selected_todo_ids.join(",") + ")" })
@selected_actions = selected_todo_ids.size == 0 ? [] : current_user.todos.where("id in (#{selected_todo_ids.join(",")})")
@count = @selected_actions.size
render :action => "show_selection_from_chart"
@ -397,10 +399,10 @@ class StatsController < ApplicationController
init_not_done_counts
@done_recently = current_user.todos.completed.all(:limit => 10, :order => 'completed_at DESC', :include => Todo::DEFAULT_INCLUDES)
@last_completed_projects = current_user.projects.completed.all(:limit => 10, :order => 'completed_at DESC', :include => [:todos, :notes])
@done_recently = current_user.todos.completed.limit(10).order('completed_at DESC').includes(Todo::DEFAULT_INCLUDES)
@last_completed_projects = current_user.projects.completed.limit(10).order('completed_at DESC').includes(:todos, :notes)
@last_completed_contexts = []
@last_completed_recurring_todos = current_user.recurring_todos.completed.all(:limit => 10, :order => 'completed_at DESC', :include => [:tags, :taggings])
@last_completed_recurring_todos = current_user.recurring_todos.completed.limit(10).order('completed_at DESC').includes(:tags, :taggings)
#TODO: @last_completed_contexts = current_user.contexts.completed.all(:limit => 10, :order => 'completed_at DESC')
end
@ -415,7 +417,7 @@ class StatsController < ApplicationController
"AND todos.user_id = #{current_user.id}"])
tags_ids_s = tag_ids.map(&:id).sort.join(",")
return {} if tags_ids_s.blank? # return empty hash for .size to work
return Tag.find(:all, :conditions => "id in (" + tags_ids_s + ")")
return Tag.where("id in (#{tags_ids_s})")
end
def get_total_number_of_tags_of_user
@ -452,7 +454,7 @@ class StatsController < ApplicationController
def get_stats_actions
# time to complete
@completed_actions = current_user.todos.completed.find(:all, { :select => "completed_at, created_at" })
@completed_actions = current_user.todos.completed.select("completed_at, created_at")
actions_sum, actions_max = 0,0
actions_min = @completed_actions.first ? @completed_actions.first.completed_at - @completed_actions.first.created_at : 0
@ -475,12 +477,12 @@ class StatsController < ApplicationController
@actions_min_ttc_sec = (actions_min / @seconds_per_day).round.to_s + " days " + @actions_min_ttc_sec if actions_min > @seconds_per_day
# get count of actions created and actions done in the past 30 days.
@sum_actions_done_last30days = current_user.todos.completed.completed_after(@cut_off_month).count(:all)
@sum_actions_created_last30days = current_user.todos.created_after(@cut_off_month).count(:all)
@sum_actions_done_last30days = current_user.todos.completed.completed_after(@cut_off_month).count
@sum_actions_created_last30days = current_user.todos.created_after(@cut_off_month).count
# get count of actions done in the past 12 months.
@sum_actions_done_last12months = current_user.todos.completed.completed_after(@cut_off_year).count(:all)
@sum_actions_created_last12months = current_user.todos.created_after(@cut_off_year).count(:all)
@sum_actions_done_last12months = current_user.todos.completed.completed_after(@cut_off_year).count
@sum_actions_created_last12months = current_user.todos.created_after(@cut_off_year).count
end
def get_stats_contexts

View file

@ -18,7 +18,7 @@ class TodosController < ApplicationController
extend ActionView::Helpers::SanitizeHelper::ClassMethods
def index
@projects = current_user.projects.all(:include => [:default_context])
@projects = current_user.projects.includes(:default_context)
@contexts = current_user.contexts
@contexts_to_show = current_user.contexts.active
@ -36,7 +36,7 @@ class TodosController < ApplicationController
def new
@projects = current_user.projects.active
@contexts = current_user.contexts.find(:all)
@contexts = current_user.contexts
respond_to do |format|
format.m {
@new_mobile = true
@ -126,16 +126,16 @@ class TodosController < ApplicationController
if @saved
redirect_to @return_path
else
@projects = current_user.projects.find(:all)
@contexts = current_user.contexts.find(:all)
@projects = current_user.projects
@contexts = current_user.contexts
render :action => "new"
end
end
format.js do
if @saved
determine_down_count
@contexts = current_user.contexts.find(:all) if @new_context_created
@projects = current_user.projects.find(:all) if @new_project_created
@contexts = current_user.contexts if @new_context_created
@projects = current_user.projects if @new_project_created
@initial_context_name = params['default_context_name']
@initial_project_name = params['default_project_name']
@initial_tags = params['initial_tag_list']
@ -225,8 +225,8 @@ class TodosController < ApplicationController
format.html { redirect_to :action => "index" }
format.js do
determine_down_count if @saved
@contexts = current_user.contexts.find(:all) if @new_context_created
@projects = current_user.projects.find(:all) if @new_project_created
@contexts = current_user.contexts if @new_context_created
@projects = current_user.projects if @new_project_created
@initial_context_name = params['default_context_name']
@initial_project_name = params['default_project_name']
@initial_tags = params['initial_tag_list']
@ -255,14 +255,14 @@ class TodosController < ApplicationController
end
def edit
@todo = current_user.todos.find(params['id'], :include => Todo::DEFAULT_INCLUDES)
@todo = current_user.todos.find_by_id(params['id']).includes(Todo::DEFAULT_INCLUDES)
@source_view = params['_source_view'] || 'todo'
@tag_name = params['_tag_name']
respond_to do |format|
format.js
format.m {
@projects = current_user.projects.active
@contexts = current_user.contexts.find(:all)
@contexts = current_user.contexts
@edit_mobile = true
@return_path=cookies[:mobile_url] ? cookies[:mobile_url] : mobile_path
render :template => "/todos/edit_mobile.html.erb"
@ -271,7 +271,7 @@ class TodosController < ApplicationController
end
def show
@todo = current_user.todos.find(params['id'])
@todo = current_user.todos.find_by_id(params['id'])
respond_to do |format|
format.m { render :action => 'show' }
format.xml { render :xml => @todo.to_xml( *to_xml_params ) }
@ -280,9 +280,9 @@ class TodosController < ApplicationController
def add_predecessor
@source_view = params['_source_view'] || 'todo'
@predecessor = current_user.todos.find(params['predecessor'])
@predecessor = current_user.todos.find_by_id(params['predecessor'])
@predecessors = @predecessor.predecessors
@todo = current_user.todos.find(params['successor'], :include => Todo::DEFAULT_INCLUDES)
@todo = current_user.todos.find_by_id(params['successor']).includes(Todo::DEFAULT_INCLUDES)
@original_state = @todo.state
unless @predecessor.completed?
@todo.add_predecessor(@predecessor)
@ -301,8 +301,8 @@ class TodosController < ApplicationController
def remove_predecessor
@source_view = params['_source_view'] || 'todo'
@todo = current_user.todos.find(params['id'], :include => Todo::DEFAULT_INCLUDES)
@predecessor = current_user.todos.find(params['predecessor'])
@todo = current_user.todos.find_by_id(params['id']).includes(Todo::DEFAULT_INCLUDES)
@predecessor = current_user.todos.find_by_id(params['predecessor'])
@predecessors = @predecessor.predecessors
@successor = @todo
@removed = @successor.remove_predecessor(@predecessor)
@ -315,7 +315,7 @@ class TodosController < ApplicationController
# Toggles the 'done' status of the action
#
def toggle_check
@todo = current_user.todos.find(params['id'])
@todo = current_user.todos.find_by_id(params['id'])
@source_view = params['_source_view'] || 'todo'
@original_item_due = @todo.due
@original_item_was_deferred = @todo.deferred?
@ -385,7 +385,7 @@ class TodosController < ApplicationController
end
def toggle_star
@todo = current_user.todos.find(params['id'])
@todo = current_user.todos.find_by_id(params['id'])
@todo.toggle_star!
@saved = true # cannot determine error
respond_to do |format|
@ -408,9 +408,9 @@ class TodosController < ApplicationController
def change_context
# TODO: is this method used?
@todo = Todo.find(params[:todo][:id])
@todo = Todo.find_by_id(params[:todo][:id])
@original_item_context_id = @todo.context_id
@context = Context.find(params[:todo][:context_id])
@context = Context.find_by_id(params[:todo][:context_id])
@todo.context = @context
@saved = @todo.save
@ -426,7 +426,7 @@ class TodosController < ApplicationController
end
def update
@todo = current_user.todos.find(params['id'])
@todo = current_user.todos.find_by_id(params['id'])
@source_view = params['_source_view'] || 'todo'
init_data_for_sidebar unless mobile?
@ -480,7 +480,7 @@ class TodosController < ApplicationController
def destroy
@source_view = params['_source_view'] || 'todo'
@todo = current_user.todos.find(params['id'])
@todo = current_user.todos.find_by_id(params['id'])
@original_item_due = @todo.due
@context_id = @todo.context_id
@project_id = @todo.project_id
@ -565,7 +565,7 @@ class TodosController < ApplicationController
@source_view = 'done'
@page_title = t('todos.completed_tasks_title')
@done = current_user.todos.completed.paginate :page => params[:page], :per_page => 20, :order => 'completed_at DESC', :include => Todo::DEFAULT_INCLUDES
@done = current_user.todos.completed.includes(Todo::DEFAULT_INCLUDES).order('completed_at DESC').paginate :page => params[:page], :per_page => 20
@count = @done.size
end
@ -577,7 +577,7 @@ class TodosController < ApplicationController
includes = params[:format]=='xml' ? [:context, :project] : Todo::DEFAULT_INCLUDES
@not_done_todos = current_user.todos.deferred(:include => includes) + current_user.todos.pending(:include => includes)
@not_done_todos = current_user.todos.deferred.includes(includes) + current_user.todos.pending.includes(includes)
@down_count = @count = @not_done_todos.size
respond_to do |format|
@ -587,8 +587,8 @@ class TodosController < ApplicationController
end
end
# Check for any due tickler items, activate them Called by
# periodically_call_remote
# Check for any due tickler items, activate them
# Called by periodically_call_remote
def check_deferred
@due_tickles = current_user.deferred_todos.find_and_activate_ready
respond_to do |format|
@ -598,12 +598,12 @@ class TodosController < ApplicationController
end
def filter_to_context
context = current_user.contexts.find(params['context']['id'])
context = current_user.contexts.find_by_id(params['context']['id'])
redirect_to context_todos_path(context, :format => 'm')
end
def filter_to_project
project = current_user.projects.find(params['project']['id'])
project = current_user.projects.find_by_id(params['project']['id'])
redirect_to project_todos_path(project, :format => 'm')
end
@ -622,21 +622,29 @@ class TodosController < ApplicationController
todos_with_tag_ids = find_todos_with_tag_expr(@tag_expr)
@not_done_todos = todos_with_tag_ids.active.not_hidden.find(:all,
:order => 'todos.due IS NULL, todos.due ASC, todos.created_at ASC', :include => Todo::DEFAULT_INCLUDES)
@hidden_todos = todos_with_tag_ids.hidden.find(:all,
:include => Todo::DEFAULT_INCLUDES,
:order => 'todos.completed_at DESC, todos.created_at DESC')
@deferred = todos_with_tag_ids.deferred.find(:all,
:order => 'todos.show_from ASC, todos.created_at DESC', :include => Todo::DEFAULT_INCLUDES)
@pending = todos_with_tag_ids.blocked.find(:all,
:order => 'todos.show_from ASC, todos.created_at DESC', :include => Todo::DEFAULT_INCLUDES)
@not_done_todos = todos_with_tag_ids.
active.not_hidden.
order('todos.due IS NULL, todos.due ASC, todos.created_at ASC').
includes(Todo::DEFAULT_INCLUDES)
@hidden_todos = todos_with_tag_ids.
hidden.
order('todos.completed_at DESC, todos.created_at DESC').
includes(Todo::DEFAULT_INCLUDES)
@deferred = todos_with_tag_ids.
deferred.
order('todos.show_from ASC, todos.created_at DESC').
includes(Todo::DEFAULT_INCLUDES)
@pending = todos_with_tag_ids.
blocked.
order('todos.show_from ASC, todos.created_at DESC').
includes(Todo::DEFAULT_INCLUDES)
# If you've set no_completed to zero, the completed items box isn't shown on
# the tag page
@done = todos_with_tag_ids.completed.find(:all,
:limit => current_user.prefs.show_number_completed,
:order => 'todos.completed_at DESC', :include => Todo::DEFAULT_INCLUDES)
@done = todos_with_tag_ids.completed.
limit(current_user.prefs.show_number_completed).
order('todos.completed_at DESC').
includes(Todo::DEFAULT_INCLUDES)
@projects = current_user.projects
@contexts = current_user.contexts
@ -688,15 +696,15 @@ class TodosController < ApplicationController
@tag = Tag.find_by_name(@tag_name)
@tag = Tag.new(:name => @tag_name) if @tag.nil?
@done = current_user.todos.completed.with_tag(@tag.id).paginate :page => params[:page], :per_page => 20, :order => 'completed_at DESC', :include => Todo::DEFAULT_INCLUDES
@done = current_user.todos.completed.with_tag(@tag.id).order('completed_at DESC').includes(Todo::DEFAULT_INCLUDES).paginate :page => params[:page], :per_page => 20
@count = @done.size
render :template => 'todos/all_done'
end
def tags
# TODO: limit to current_user
tags_beginning = Tag.find(:all, :conditions => ['name like ?', params[:term]+'%'])
tags_all = Tag.find(:all, :conditions =>['name like ?', '%'+params[:term]+'%'])
tags_beginning = Tag.where('name like ?', params[:term]+'%')
tags_all = Tag.where('name like ?', '%'+params[:term]+'%')
tags_all= tags_all - tags_beginning
respond_to do |format|
@ -708,7 +716,7 @@ class TodosController < ApplicationController
@source_view = params['_source_view'] || 'todo'
numdays = params['days'].to_i
@todo = current_user.todos.find(params[:id])
@todo = current_user.todos.find_by_id(params[:id])
@original_item_context_id = @todo.context_id
@todo_deferred_state_changed = true
@new_context_created = false
@ -725,7 +733,7 @@ class TodosController < ApplicationController
determine_remaining_in_context_count(@todo.context_id)
source_view do |page|
page.project {
@remaining_undone_in_project = current_user.projects.find(@todo.project_id).todos.not_completed.count
@remaining_undone_in_project = current_user.projects.find_by_id(@todo.project_id).todos.not_completed.count
@original_item_project_id = @todo.project_id
}
page.tag {
@ -753,45 +761,45 @@ class TodosController < ApplicationController
@source_view = params['_source_view'] || 'calendar'
@page_title = t('todos.calendar_page_title')
@projects = current_user.projects.find(:all)
@projects = current_user.projects
due_today_date = Time.zone.now
due_this_week_date = Time.zone.now.end_of_week
due_this_week_date = due_today_date.end_of_week
due_next_week_date = due_this_week_date + 7.days
due_this_month_date = Time.zone.now.end_of_month
due_this_month_date = due_today_date.end_of_month
included_tables = Todo::DEFAULT_INCLUDES
@due_today = current_user.todos.not_completed.find(:all,
:include => included_tables,
:conditions => ['todos.due <= ?', due_today_date],
:order => "due")
@due_this_week = current_user.todos.not_completed.find(:all,
:include => included_tables,
:conditions => ['todos.due > ? AND todos.due <= ?', due_today_date, due_this_week_date],
:order => "due")
@due_next_week = current_user.todos.not_completed.find(:all,
:include => included_tables,
:conditions => ['todos.due > ? AND todos.due <= ?', due_this_week_date, due_next_week_date],
:order => "due")
@due_this_month = current_user.todos.not_completed.find(:all,
:include => included_tables,
:conditions => ['todos.due > ? AND todos.due <= ?', due_next_week_date, due_this_month_date],
:order => "due")
@due_after_this_month = current_user.todos.not_completed.find(:all,
:include => included_tables,
:conditions => ['todos.due > ?', due_this_month_date],
:order => "due")
@due_today = current_user.todos.not_completed.
where('todos.due <= ?', due_today_date).
includes(included_tables).
order("due")
@due_this_week = current_user.todos.not_completed.
where('todos.due > ? AND todos.due <= ?', due_today_date, due_this_week_date).
includes(included_tables).
order("due")
@due_next_week = current_user.todos.not_completed.
where('todos.due > ? AND todos.due <= ?', due_this_week_date, due_next_week_date).
includes(included_tables).
order("due")
@due_this_month = current_user.todos.not_completed.
where('todos.due > ? AND todos.due <= ?', due_next_week_date, due_this_month_date).
includes(included_tables).
order("due")
@due_after_this_month = current_user.todos.not_completed.
where('todos.due > ?', due_this_month_date).
includes(included_tables).
order("due")
@count = current_user.todos.not_completed.are_due.count
respond_to do |format|
format.html
format.ics {
@due_all = current_user.todos.not_completed.are_due.find(:all, :order => "due")
@due_all = current_user.todos.not_completed.are_due.order("due")
render :action => 'calendar', :layout => false, :content_type => Mime::ICS
}
format.xml {
@due_all = current_user.todos.not_completed.are_due.find(:all, :order => "due")
@due_all = current_user.todos.not_completed.are_due.order("due")
render :xml => @due_all.to_xml( *to_xml_params )
}
end
@ -810,40 +818,36 @@ class TodosController < ApplicationController
unless params['id'].nil?
get_todo_from_params
# Begin matching todos in current project, excluding @todo itself
@items = @todo.project.todos.not_completed.find(:all,
:include => [:context, :project],
:conditions => ['(LOWER(todos.description) LIKE ?) AND NOT(todos.id=?)', "%#{params[:term].downcase}%", @todo.id],
:order => 'description ASC',
:limit => 10
) unless @todo.project.nil?
@items = @todo.project.todos.not_completed.
where('(LOWER(todos.description) LIKE ?) AND NOT(todos.id=?)', "%#{params[:term].downcase}%", @todo.id).
includes(:context, :project).
order('description ASC').
limit(10) unless @todo.project.nil?
# Then look in the current context, excluding @todo itself
@items = @todo.context.todos.not_completed.find(:all,
:include => [:context, :project],
:conditions => ['(LOWER(todos.description) LIKE ?) AND NOT(todos.id=?)', "%#{params[:term].downcase}%", @todo.id],
:order => 'description ASC',
:limit => 10
) unless !@items.empty? || @todo.context.nil?
@items = @todo.context.todos.not_completed
where('(LOWER(todos.description) LIKE ?) AND NOT(todos.id=?)', "%#{params[:term].downcase}%", @todo.id).
includes(:context, :project).
order('description ASC').
limit(10) unless !@items.empty? || @todo.context.nil?
# Match todos in other projects, excluding @todo itself
@items = current_user.todos.not_completed.find(:all,
:include => [:context, :project],
:conditions => ['(LOWER(todos.description) LIKE ?) AND NOT(todos.id=?)', "%#{params[:term].downcase}%", @todo.id],
:order => 'description ASC',
:limit => 10
) unless !@items.empty?
@items = current_user.todos.not_completed.
where('(LOWER(todos.description) LIKE ?) AND NOT(todos.id=?)', "%#{params[:term].downcase}%", @todo.id).
includes(:context, :project).
order('description ASC').
limit(10) unless !@items.empty?
else
# New todo - TODO: Filter on current project in project view
@items = current_user.todos.not_completed.find(:all,
:include => [:context, :project],
:conditions => ['(LOWER(todos.description) LIKE ?)', "%#{params[:term].downcase}%"],
:order => 'description ASC',
:limit => 10
)
@items = current_user.todos.not_completed.
where('(LOWER(todos.description) LIKE ?)', "%#{params[:term].downcase}%").
includes(:context, :project).
order('description ASC').
limit(10)
end
render :inline => format_dependencies_as_json_for_auto_complete(@items)
end
def convert_to_project
@todo = current_user.todos.find(params[:id])
@todo = current_user.todos.find_by_id(params[:id])
@project = current_user.projects.new(:name => @todo.description, :description => @todo.notes,
:default_context => @todo.context)
@ -858,7 +862,7 @@ class TodosController < ApplicationController
end
def show_notes
@todo = current_user.todos.find(params['id'])
@todo = current_user.todos.find_by_id(params['id'])
@return_path=cookies[:mobile_url] ? cookies[:mobile_url] : mobile_path
respond_to do |format|
format.html {
@ -883,7 +887,7 @@ class TodosController < ApplicationController
def get_todo_from_params
# TODO: this was a :append_before but was removed to tune performance per
# method. Reconsider re-enabling it
@todo = current_user.todos.find(params['id'])
@todo = current_user.todos.find_by_id(params['id'])
end
def find_and_activate_ready
@ -898,7 +902,7 @@ class TodosController < ApplicationController
def with_feed_query_scope(&block)
unless TodosController.is_feed_request(request)
Todo.send(:with_scope, :find => {:conditions => ['todos.state = ?', 'active']}) do
Todo.send(:where, ['todos.state = ?', 'active']) do
yield
return
end
@ -939,7 +943,7 @@ class TodosController < ApplicationController
condition_builder.add('taggings.tag_id = ?', tag.id)
end
Todo.send :with_scope, :find => {:conditions => condition_builder.to_conditions} do
Todo.send :where, condition_builder.to_conditions do
yield
end
@ -950,14 +954,14 @@ class TodosController < ApplicationController
if (params[:context_id])
@context = current_user.contexts.find_by_params(params)
@feed_title = @feed_title + t('todos.feed_title_in_context', :context => @context.name)
Todo.send :with_scope, :find => {:conditions => ['todos.context_id = ?', @context.id]} do
Todo.send :where, ['todos.context_id = ?', @context.id] do
yield
end
elsif (params[:project_id])
@project = current_user.projects.find_by_params(params)
@feed_title = @feed_title + t('todos.feed_title_in_project', :project => @project.name)
@project_feed = true
Todo.send :with_scope, :find => {:conditions => ['todos.project_id = ?', @project.id]} do
Todo.send :where, ['todos.project_id = ?', @project.id] do
yield
end
else
@ -995,13 +999,13 @@ class TodosController < ApplicationController
# current_users.todos.find but that broke with_scope for :limit
# Exclude hidden projects from count on home page
@todos = current_user.todos.find(:all, :include => Todo::DEFAULT_INCLUDES)
@todos = current_user.todos.includes(Todo::DEFAULT_INCLUDES)
# Exclude hidden projects from the home page
@not_done_todos = current_user.todos.find(:all,
:conditions => ['contexts.hide = ? AND (projects.state = ? OR todos.project_id IS NULL)', false, 'active'],
:order => "todos.due IS NULL, todos.due ASC, todos.created_at ASC",
:include => Todo::DEFAULT_INCLUDES)
@not_done_todos = current_user.todos.
where('contexts.hide = ? AND (projects.state = ? OR todos.project_id IS NULL)', false, 'active').
order("todos.due IS NULL, todos.due ASC, todos.created_at ASC").
includes(Todo::DEFAULT_INCLUDES)
end
end
@ -1014,10 +1018,10 @@ class TodosController < ApplicationController
# but that broke with_scope for :limit
# Exclude hidden projects from the home page
@not_done_todos = current_user.todos.find(:all,
:conditions => ['todos.state = ? AND contexts.hide = ? AND (projects.state = ? OR todos.project_id IS NULL)', 'active', false, 'active'],
:order => "todos.due IS NULL, todos.due ASC, todos.created_at ASC",
:include => [ :project, :context, :tags ])
@not_done_todos = current_user.todos.
where('todos.state = ? AND contexts.hide = ? AND (projects.state = ? OR todos.project_id IS NULL)', 'active', false, 'active').
order("todos.due IS NULL, todos.due ASC, todos.created_at ASC").
includes(:project, :context, :tags)
end
def tag_title(tag_expr)
@ -1079,23 +1083,23 @@ class TodosController < ApplicationController
end
from.context do
context_id = @original_item_context_id || @todo.context_id
todos = current_user.contexts.find(context_id).todos.not_completed
todos = current_user.contexts.find_by_id(context_id).todos.not_completed
if @todo.context.hide?
# include hidden todos
@down_count = todos.count(:all)
@down_count = todos.count
else
# exclude hidden_todos
@down_count = todos.not_hidden.count(:all)
@down_count = todos.not_hidden.count
end
end
from.project do
unless @todo.project_id == nil
@down_count = current_user.projects.find(@todo.project_id).todos.active_or_hidden.count
@down_count = current_user.projects.find_by_id(@todo.project_id).todos.active_or_hidden.count
end
end
from.deferred do
@down_count = current_user.todos.deferred_or_blocked.count(:all)
@down_count = current_user.todos.deferred_or_blocked.count
end
from.tag do
@tag_name = params['_tag_name']
@ -1112,8 +1116,8 @@ class TodosController < ApplicationController
source_view do |from|
from.deferred {
# force reload to todos to get correct count and not a cached one
@remaining_in_context = current_user.contexts.find(context_id).todos.deferred_or_blocked.count
@target_context_count = current_user.contexts.find(@todo.context_id).todos.deferred_or_blocked.count
@remaining_in_context = current_user.contexts.find_by_id(context_id).todos.deferred_or_blocked.count
@target_context_count = current_user.contexts.find_by_id(@todo.context_id).todos.deferred_or_blocked.count
}
from.tag {
tag = Tag.find_by_name(params['_tag_name'])
@ -1121,27 +1125,27 @@ class TodosController < ApplicationController
tag = Tag.new(:name => params['tag'])
end
@remaining_deferred_or_pending_count = current_user.todos.with_tag(tag.id).deferred_or_blocked.count
@remaining_in_context = current_user.contexts.find(context_id).todos.active.not_hidden.with_tag(tag.id).count
@target_context_count = current_user.contexts.find(@todo.context_id).todos.active.not_hidden.with_tag(tag.id).count
@remaining_in_context = current_user.contexts.find_by_id(context_id).todos.active.not_hidden.with_tag(tag.id).count
@target_context_count = current_user.contexts.find_by_id(@todo.context_id).todos.active.not_hidden.with_tag(tag.id).count
@remaining_hidden_count = current_user.todos.hidden.with_tag(tag.id).count
}
from.project {
project_id = @project_changed ? @original_item_project_id : @todo.project_id
@remaining_deferred_or_pending_count = current_user.projects.find(project_id).todos.deferred_or_blocked.count
@remaining_deferred_or_pending_count = current_user.projects.find_by_id(project_id).todos.deferred_or_blocked.count
if @todo_was_completed_from_deferred_or_blocked_state
@remaining_in_context = @remaining_deferred_or_pending_count
else
@remaining_in_context = current_user.projects.find(project_id).todos.active_or_hidden.count
@remaining_in_context = current_user.projects.find_by_id(project_id).todos.active_or_hidden.count
end
@target_context_count = current_user.projects.find(project_id).todos.active.count
@target_context_count = current_user.projects.find_by_id(project_id).todos.active.count
}
from.calendar {
@target_context_count = @new_due_id.blank? ? 0 : count_old_due_empty(@new_due_id)
}
from.context {
context = current_user.contexts.find(context_id)
context = current_user.contexts.find_by_id(context_id)
@remaining_deferred_or_pending_count = context.todos.deferred_or_blocked.count
remaining_actions_in_context = context.todos(true).active
@ -1149,7 +1153,7 @@ class TodosController < ApplicationController
@remaining_in_context = remaining_actions_in_context.count
if @todo_was_deferred_or_blocked
actions_in_target = current_user.contexts.find(@todo.context_id).todos(true).active
actions_in_target = current_user.contexts.find_by_id(@todo.context_id).todos(true).active
actions_in_target = actions_in_target.not_hidden if !context.hide?
else
actions_in_target = @todo.context.todos.deferred_or_blocked
@ -1157,8 +1161,8 @@ class TodosController < ApplicationController
@target_context_count = actions_in_target.count
}
end
@remaining_in_context = current_user.contexts.find(context_id).todos(true).active.not_hidden.count if !@remaining_in_context
@target_context_count = current_user.contexts.find(@todo.context_id).todos(true).active.not_hidden.count if !@target_context_count
@remaining_in_context = current_user.contexts.find_by_id(context_id).todos(true).active.not_hidden.count if !@remaining_in_context
@target_context_count = current_user.contexts.find_by_id(@todo.context_id).todos(true).active.not_hidden.count if !@target_context_count
end
def determine_completed_count
@ -1167,13 +1171,13 @@ class TodosController < ApplicationController
@completed_count = current_user.todos.not_hidden.completed.count
end
from.context do
todos = current_user.contexts.find(@todo.context_id).todos.completed
todos = current_user.contexts.find_by_id(@todo.context_id).todos.completed
todos = todos.not_hidden if !@todo.context.hidden?
@completed_count = todos.count
end
from.project do
unless @todo.project_id == nil
todos = current_user.projects.find(@todo.project_id).todos.completed
todos = current_user.projects.find_by_id(@todo.project_id).todos.completed
todos = todos.not_hidden if !@todo.project.hidden?
@completed_count = todos.count
end
@ -1197,7 +1201,7 @@ class TodosController < ApplicationController
# If you've set no_completed to zero, the completed items box isn't shown
# on the home page
max_completed = current_user.prefs.show_number_completed
@done = current_user.todos.completed.find(:all, :limit => max_completed, :include => Todo::DEFAULT_INCLUDES) unless max_completed == 0
@done = current_user.todos.completed.limit(max_completed).includes(Todo::DEFAULT_INCLUDES) unless max_completed == 0
# Set count badge to number of not-done, not hidden context items
@count = current_user.todos.active.not_hidden.count(:all)
@ -1212,7 +1216,7 @@ class TodosController < ApplicationController
@home = true
max_completed = current_user.prefs.show_number_completed
@done = current_user.todos.completed.find(:all, :limit => max_completed, :include => Todo::DEFAULT_INCLUDES) unless max_completed == 0
@done = current_user.todos.completed.limit(max_completed).includes(Todo::DEFAULT_INCLUDES) unless max_completed == 0
cookies[:mobile_url]= { :value => request.request_uri, :secure => SITE_CONFIG['secure_cookies']}
determine_down_count
@ -1349,20 +1353,15 @@ class TodosController < ApplicationController
due_this_month_date = Time.zone.now.end_of_month
case id
when "due_today"
return current_user.todos.not_completed.count(:all,
:conditions => ['todos.due <= ?', due_today_date])
return current_user.todos.not_completed.where('todos.due <= ?', due_today_date).count
when "due_this_week"
return current_user.todos.not_completed.count(:all,
:conditions => ['todos.due > ? AND todos.due <= ?', due_today_date, due_this_week_date])
return current_user.todos.not_completed.where('todos.due > ? AND todos.due <= ?', due_today_date, due_this_week_date).count
when "due_next_week"
return current_user.todos.not_completed.count(:all,
:conditions => ['todos.due > ? AND todos.due <= ?', due_this_week_date, due_next_week_date])
return current_user.todos.not_completed.where('todos.due > ? AND todos.due <= ?', due_this_week_date, due_next_week_date).count
when "due_this_month"
return current_user.todos.not_completed.count(:all,
:conditions => ['todos.due > ? AND todos.due <= ?', due_next_week_date, due_this_month_date])
return current_user.todos.not_completed.where('todos.due > ? AND todos.due <= ?', due_next_week_date, due_this_month_date).count
when "due_after_this_month"
return current_user.todos.not_completed.count(:all,
:conditions => ['todos.due > ?', due_this_month_date])
return current_user.todos.not_completed.where('todos.due > ?', due_this_month_date).count
else
raise Exception.new, "unknown due id for calendar: '#{id}'"
end
@ -1402,7 +1401,7 @@ class TodosController < ApplicationController
def update_todo_state_if_project_changed
if ( @project_changed ) then
@todo.update_state_from_project
@remaining_undone_in_project = current_user.projects.find(@original_item_project_id).todos.active.count if source_view_is :project
@remaining_undone_in_project = current_user.projects.find_by_id(@original_item_project_id).todos.active.count if source_view_is :project
end
end

View file

@ -18,7 +18,7 @@ class UsersController < ApplicationController
store_location
end
format.xml do
@users = User.find(:all, :order => 'login')
@users = User.order('login').all
render :xml => @users.to_xml(:except => [ :password ])
end
end
@ -139,7 +139,7 @@ class UsersController < ApplicationController
def destroy
@deleted_user = User.find_by_id(params[:id])
@saved = @deleted_user.destroy
@total_users = User.find(:all).size
@total_users = User.all.size
respond_to do |format|
format.html do

View file

@ -110,7 +110,7 @@ module TodosHelper
def successors_span(todo=@todo)
unless todo.pending_successors.empty?
pending_count = todo.pending_successors.length
pending_count = todo.pending_successors.count
title = "#{t('todos.has_x_pending', :count => pending_count)}: #{todo.pending_successors.map(&:description).join(', ')}"
image_tag( 'successor_off.png', :width=>'10', :height=>'16', :border=>'0', :title => title )
end
@ -272,12 +272,12 @@ module TodosHelper
end
def default_contexts_for_autocomplete
projects = current_user.projects.uncompleted.find(:all, :include => [:default_context], :conditions => ['NOT(default_context_id IS NULL)'])
projects = current_user.projects.uncompleted.includes(:default_context).where('NOT(default_context_id IS NULL)')
Hash[*projects.map{ |p| [escape_javascript(p.name), escape_javascript(p.default_context.name)] }.flatten].to_json
end
def default_tags_for_autocomplete
projects = current_user.projects.uncompleted.find(:all, :conditions => ["default_tags != ''"])
projects = current_user.projects.uncompleted.where("NOT(default_tags = '')")
Hash[*projects.map{ |p| [escape_javascript(p.name), p.default_tags] }.flatten].to_json
end

View file

@ -295,14 +295,14 @@ class Todo < ActiveRecord::Base
# activate todos that should be activated if the current todo is completed
def activate_pending_todos
pending_todos = successors.find_all {|t| t.uncompleted_predecessors.empty?}
pending_todos = successors.select {|t| t.uncompleted_predecessors.empty?}
pending_todos.each {|t| t.activate! }
return pending_todos
end
# Return todos that should be blocked if the current todo is undone
def block_successors
active_successors = successors.find_all {|t| t.active? or t.deferred?}
active_successors = successors.select {|t| t.active? or t.deferred?}
active_successors.each {|t| t.block!}
return active_successors
end
@ -320,7 +320,7 @@ class Todo < ActiveRecord::Base
# value will be a string. In that case convert to array
deps = [deps] unless deps.class == Array
deps.each { |dep| self.add_predecessor(self.user.todos.find(dep.to_i)) unless dep.blank? }
deps.each { |dep| self.add_predecessor(self.user.todos.find_by_id(dep.to_i)) unless dep.blank? }
end
alias_method :original_context=, :context=

View file

@ -10,7 +10,7 @@ class User < ActiveRecord::Base
:order => 'position ASC',
:dependent => :delete_all do
def find_by_params(params)
find(params['id'] || params['context_id']) || nil
find_by_id(params['id'] || params['context_id']) || nil
end
def update_positions(context_ids)
context_ids.each_with_index {|id, position|
@ -24,7 +24,7 @@ class User < ActiveRecord::Base
:order => 'projects.position ASC',
:dependent => :delete_all do
def find_by_params(params)
find(params['id'] || params['project_id'])
find_by_id(params['id'] || params['project_id'])
end
def update_positions(project_ids)
project_ids.each_with_index {|id, position|
@ -34,7 +34,7 @@ class User < ActiveRecord::Base
}
end
def projects_in_state_by_position(state)
self.sort{ |a,b| a.position <=> b.position }.select{ |p| p.state == state }
self.sort{ |a,b| a.position <=> b.position }.select{ |p| p.state == state }
end
def next_from(project)
self.offset_from(project, 1)
@ -49,29 +49,29 @@ class User < ActiveRecord::Base
projects.at( position + offset)
end
def cache_note_counts
project_note_counts = Note.count(:group => 'project_id')
project_note_counts = Note.group(:project_id).count
self.each do |project|
project.cached_note_count = project_note_counts[project.id] || 0
end
end
def alphabetize(scope_conditions = {})
projects = find(:all, :conditions => scope_conditions)
projects = where(scope_conditions)
projects.sort!{ |x,y| x.name.downcase <=> y.name.downcase }
self.update_positions(projects.map{ |p| p.id })
return projects
end
def actionize(scope_conditions = {})
todos_in_project = find(:all, :conditions => scope_conditions, :include => [:todos])
todos_in_project = where(scope_conditions).includes(:todos)
todos_in_project.sort!{ |x, y| -(x.todos.active.count <=> y.todos.active.count) }
todos_in_project.reject{ |p| p.todos.active.count > 0 }
sorted_project_ids = todos_in_project.map {|p| p.id}
all_project_ids = find(:all).map {|p| p.id}
all_project_ids = all.map {|p| p.id}
other_project_ids = all_project_ids - sorted_project_ids
update_positions(sorted_project_ids + other_project_ids)
return find(:all, :conditions => scope_conditions)
return where(scope_conditions)
end
end
has_many :todos,
@ -85,7 +85,7 @@ class User < ActiveRecord::Base
:conditions => [ 'state = ?', 'deferred' ],
:order => 'show_from ASC, todos.created_at DESC' do
def find_and_activate_ready
find(:all, :conditions => ['show_from <= ?', Time.zone.now ]).collect { |t| t.activate! }
where('show_from <= ?', Time.zone.now).collect { |t| t.activate! }
end
end
has_many :notes, :order => "created_at DESC", :dependent => :delete_all
@ -119,7 +119,7 @@ class User < ActiveRecord::Base
def self.authenticate(login, pass)
return nil if login.blank?
candidate = find(:first, :conditions => ["login = ?", login])
candidate = where("login = ?", login).first
return nil if candidate.nil?
if Tracks::Config.auth_schemes.include?('database')

View file

@ -6,7 +6,7 @@
</div>
<div id="context_new" class="context_new" style="display:block">
<% form_for(@new_context, :html => {:id => 'context-form',:name=>'context',:class => "inline-form", :method => :post }) do -%>
<%= form_for(@new_context, :html => {:id => 'context-form',:name=>'context',:class => "inline-form", :method => :post }) do -%>
<div id="error_status"><%= error_messages_for('context') %></div>

View file

@ -8,7 +8,7 @@
<p>F&uuml;gen Sie den Inhalt der kopierten YAML Datei in das untenstehende Formular ein:</p>
</div>
<p>
<% form_for :import, @import, :url => {:controller => 'data', :action => 'yaml_import'} do |f| %>
<%= form_for :import, @import, :url => {:controller => 'data', :action => 'yaml_import'} do |f| %>
<%= f.text_area :yaml %><br />
<input type="submit" value="Daten importieren">
<% end %>

View file

@ -1,14 +1,14 @@
<div id="display_box">
<div id="feeds">
<div id="feedlegend">
<p><b>Beware</b>: all your current data will be destroyed before importing
the YAML file, so if you have access to the database, we strongly recommend
<p><b>Beware</b>: all your current data will be destroyed before importing
the YAML file, so if you have access to the database, we strongly recommend
backing up the database right now in case that anything goes wrong.
</p>
<p>Paste the contents of the YAML file you exported into the text box below:</p>
</div>
<p>
<% form_for :import, @import, :url => {:controller => 'data', :action => 'yaml_import'} do |f| %>
<%= form_for :import, @import, :url => {:controller => 'data', :action => 'yaml_import'} do |f| %>
<%= f.text_area :yaml %><br />
<input type="submit" value="Import data">
<% end %>

View file

@ -11,21 +11,21 @@
<h3><%= t('login.please_login') %>:</h3>
<% if show_database_form %>
<div id="database_auth_form" style="display:<%=(@prefered_auth.eql?('database')) ? "block" : "none"%>">
<% form_tag :action=> 'login' do %>
<%= form_tag :action=> 'login' do %>
<table>
<tr>
<td><label for="user_login"><%= User.human_attribute_name('login') %>:</label></td>
<td><input type="text" name="user_login" id="user_login" value="" class="login_text" /></td>
</tr>
<tr>
<tr>
<td><label for="user_password"><%= User.human_attribute_name('password') %>:</label></td>
<td><input type="password" name="user_password" id="user_password" class="login_text" /></td>
</tr>
<tr>
<tr>
<td><label for="user_noexpiry"><%= t('login.user_no_expiry') %>:</label></td>
<td><input type="checkbox" name="user_noexpiry" id="user_noexpiry" checked /></td>
</tr>
<tr>
<tr>
<td></td>
<td><input type="submit" name="login" value="<%= t('login.sign_in') %> &#187;" class="primary" /></td>
</tr>
@ -36,17 +36,17 @@
<% if show_openid_form %>
<div id="openid_auth_form" style="display:<%=(@prefered_auth.eql?('openid')) ? "block" : "none"%>">
<% form_tag :action=> 'login' do %>
<%= form_tag :action=> 'login' do %>
<table>
<tr>
<td><label for="openid_url"><%= User.human_attribute_name('open_id_url') %>:</label></td>
<td><input type="text" name="openid_url" id="openid_url" value="<%= @openid_url %>" class="login_text open_id" /></td>
</tr>
<tr>
<tr>
<td><label for="user_noexpiry"><%= t('login.user_no_expiry') %>:</label></td>
<td><input type="checkbox" name="user_noexpiry" id="user_noexpiry" checked /></td>
</tr>
<tr>
<tr>
<td></td>
<td><input type="submit" name="login" value="<%= t('login.sign_in') %> &#187;" class="primary" /></td>
</tr>
@ -59,7 +59,7 @@
<div id="cas_auth_form" style="display:<%=(@prefered_auth.eql?('cas')) ? "block" : "none"%>">
<table>
<tr>
<td>
<td>
<% if @username && @user%>
<p><%= t('login.cas_logged_in_greeting', :username => @username) %></p>
<% elsif @username %>

View file

@ -11,21 +11,21 @@
<% if show_database_form %>
<div id="database_auth_form">
<% form_tag login_path(:format => 'm') do %>
<%= form_tag login_path(:format => 'm') do %>
<table>
<tr>
<td><label for="user_login"><%= User.human_attribute_name('login') %>:</label></td>
<td><input type="text" name="user_login" id="user_login" value="" class="login_text" /></td>
</tr>
<tr>
<tr>
<td><label for="user_password"><%= User.human_attribute_name('password') %>:</label></td>
<td><input type="password" name="user_password" id="user_password" class="login_text" /></td>
</tr>
<tr>
<tr>
<td><label for="user_noexpiry"><%= t('login.user_no_expiry') %>:</label></td>
<td><input type="checkbox" name="user_noexpiry" id="user_noexpiry" checked="checked" /></td>
</tr>
<tr>
<tr>
<td>&nbsp;</td>
<td><input type="submit" name="login" value="<%= t('login.sign_in') %> &#187;" class="primary" /></td>
</tr>
@ -34,28 +34,4 @@
</div>
<% end %>
<% if show_openid_form %>
<h4><%= t('login.mobile_use_openid') %>:</h4>
<div id="openid_auth_form">
<% form_tag login_path(:format => 'm') do %>
<table>
<tr>
<td width="100px"><label for="openid_url"><%= User.human_attribute_name('open_id_url') %>:</label></td>
<td width="100px"><input type="text" name="openid_url" id="openid_url" value="<%= @openid_url %>" class="login_text open_id" /></td>
</tr>
<tr>
<td width="100px"><label for="user_noexpiry"><%= t('login.user_no_expiry') %>:</label></td>
<td width="100px"><input type="checkbox" name="user_noexpiry" id="user_noexpiry" checked /></td>
</tr>
<tr>
<td width="100px"></td>
<td><input type="submit" name="login" value="<%= t('login.sign_in') %> &#187;" class="primary" /></td>
</tr>
</table>
<% end %>
</div>
<% end %>
</div>

View file

@ -2,7 +2,7 @@
<div id="edit_error_status"><%= error_messages_for(:user) + error_messages_for(:prefs) %></div>
<% form_tag :action => 'update' do %>
<%= form_tag :action => 'update' do %>
<div id="tabs">
<ul>
<li><a href="#tabs-1"><%= t('preferences.tabs.profile')%></a></li>

View file

@ -6,7 +6,7 @@
</div>
<div id="project_new" class="project_new" style="display:block">
<% form_for(@new_project, :html => {:id => 'project_form',:name=>'project',:class => "inline-form", :method => :post }) do -%>
<%= form_for(@new_project, :html => {:id => 'project_form',:name=>'project',:class => "inline-form", :method => :post }) do -%>
<div id="error_status"><%= error_messages_for("project") %></div>
<label for="project_name"><%= Project.human_attribute_name(:name) %>:</label><br />

View file

@ -1,5 +1,5 @@
<div class="recurring_container">
<% form_for(@recurring_todo, :html=> { :id=>'recurring-todo-form-edit-action', :name=>'recurring_todo', :class => 'inline-form' }) do |f| -%>
<%= form_for(@recurring_todo, :html=> { :id=>'recurring-todo-form-edit-action', :name=>'recurring_todo', :class => 'inline-form' }) do |f| -%>
<div id="edit_error_status"><%= error_messages_for("item", :object_name => 'action') %></div>
<div id="recurring_todo_form_container">

View file

@ -1,6 +1,6 @@
<%- reset_tab_index %>
<div class="recurring_container">
<% form_for(@new_recurring_todo, :html=> { :id=>'recurring-todo-form-new-action', :name=>'recurring_todo', :class => 'inline-form' }) do -%>
<%= form_for(@new_recurring_todo, :html=> { :id=>'recurring-todo-form-new-action', :name=>'recurring_todo', :class => 'inline-form' }) do -%>
<div id="error_status"><%= error_messages_for("item", :object_name => 'action') %></div>
<div id="recurring_todo_form_container">

View file

@ -1,5 +1,5 @@
<div id="display_box_search">
<% form_tag({:action => :results}, :id => 'search-form') do %>
<%= form_tag({:action => :results}, :id => 'search-form') do %>
<%= text_field_tag(:search, params[:search]) %>
<%= submit_tag t('common.search') %>
<% end %>

View file

@ -1,4 +1,4 @@
<% form_tag todo_path(@todo, :format => 'm'), :name => 'mobileEdit', :method => :put do %>
<%= form_tag todo_path(@todo, :format => 'm'), :name => 'mobileEdit', :method => :put do %>
<%= render :partial => 'edit_mobile_form', :locals => { :parent_container_type => "show_mobile" } %>
<p><input type="submit" value="<%= t('common.update') %>" tabindex="6" accesskey="#" /></p>
<% end -%>

View file

@ -1,4 +1,4 @@
<% form_tag todos_path(:format => 'm'), :method => :post do %>
<%= form_tag todos_path(:format => 'm'), :method => :post do %>
<%= render :partial => 'edit_mobile_form' %>
<p><input type="submit" value="<%= t('common.create') %>" tabindex="12" accesskey="#" /></p>
<% end -%>

View file

@ -6,7 +6,7 @@
<p><%= t('users.select_authentication_type') %></p>
<% form_tag :action => 'update_auth_type' do %>
<%= form_tag :action => 'update_auth_type' do %>
<div><label for="user_auth_type"><%= t('users.label_auth_type') %>:</label> <%= select('user', 'auth_type', Tracks::Config.auth_schemes.collect {|p| [ p, p ] }) %></div>
<div id="open_id" style="display:<%= current_user.auth_type == 'open_id' ? 'block' : 'none' %>"><label for="openid_url"><%= t('users.identity_url') %>:</label> <input type="text" name="openid_url" value="<%= current_user.open_id_url %>" class="open_id" /></div>
<div class="actions"><%= submit_tag t('users.auth_change_submit') %> <%= link_to t('common.cancel'), preferences_path %></div>

View file

@ -6,7 +6,7 @@
<p><%= t('users.change_password_prompt') %></p>
<% form_tag :action => 'update_password' do %>
<%= form_tag :action => 'update_password' do %>
<%= render :partial => 'update_password' %>
<br/>
<%= link_to t('common.cancel'), preferences_path %>

View file

@ -1,5 +1,5 @@
<div title="<%= t('users.account_signup') %>" id="signupform" class="form">
<% form_tag :action=> "create" do %>
<%= form_tag :action=> "create" do %>
<%= error_messages_for 'user' %><br/>

View file

@ -1,80 +0,0 @@
require File.expand_path(File.dirname(__FILE__) + '/../test_helper')
# Re-raise errors caught by the controller.
class BackendController; def rescue_action(e) raise e end; end
class BackendControllerTest < ActionController::TestCase
fixtures :users, :projects, :contexts, :todos, :recurring_todos, :notes
def setup
@controller = BackendController.new
request, response = ActionController::TestRequest.new, ActionController::TestResponse.new
assert_equal "change-me", Tracks::Config.salt
end
def test_new_todo_fails_with_incorrect_token
assert_raises_invalid_token { @controller.new_todo('admin', 'notthecorrecttoken', contexts('agenda').id, 'test', 'test') }
end
def test_new_todo_fails_with_context_that_does_not_belong_to_user
assert_raise(CannotAccessContext, "Cannot access a context that does not belong to this user.") { @controller.new_todo(users('other_user').login, users('other_user').token, contexts('agenda').id, 'test', 'test') }
end
def test_new_rich_todo_fails_with_incorrect_token
assert_raises_invalid_token { @controller.new_rich_todo('admin', 'notthecorrecttoken', contexts('agenda').id, 'test', 'test') }
end
#"Call mfox @call > Build a working time machine" should create the "Call mfox" todo in the 'call' context and the 'Build a working time machine' project.
def test_new_rich_todo_creates_todo_with_exact_match
assert_new_rich_todo_creates_mfox_todo("Call mfox @call > Build a working time machine")
end
#"Call mfox @cal > Build" should create the "Call mfox" todo in the 'call' context and the 'Build a working time machine' project.
def test_new_rich_todo_creates_todo_with_starts_with_match
assert_new_rich_todo_creates_mfox_todo("Call mfox @cal > Build")
end
#"Call mfox @call > new:Run for president" should create the 'Run for president' project, create the "Call mfox" todo in the 'call' context and the new project.
def test_new_rich_todo_creates_todo_with_new_project
max_todo_id = Todo.maximum('id')
max_project_id = Project.maximum('id')
@controller.new_rich_todo(users(:admin_user).login, users(:admin_user).token, contexts(:agenda).id, 'Call mfox @call > new:Run for president', 'test')
todo = Todo.find(:first, :conditions => ["id > ?", max_todo_id])
new_project = Project.find(:first, :conditions => ["id > ?", max_project_id])
assert_equal(users(:admin_user).id, todo.user_id)
assert_equal(contexts(:call).id, todo.context_id)
assert_equal(new_project.id, todo.project_id)
assert_equal("Call mfox", todo.description)
assert_equal("test", todo.notes)
end
def assert_new_rich_todo_creates_mfox_todo(description_input)
max_id = Todo.maximum('id')
@controller.new_rich_todo(users(:admin_user).login, users(:admin_user).token, contexts(:agenda).id, 'Call mfox @cal > Build', 'test')
todo = Todo.find(:first, :conditions => ["id > ?", max_id])
assert_equal(users(:admin_user).id, todo.user_id)
assert_equal(contexts(:call).id, todo.context_id)
assert_equal(projects(:timemachine).id, todo.project_id)
assert_equal('test', todo.notes)
assert_equal("Call mfox", todo.description)
end
def test_new_rich_todo_fails_with_context_that_does_not_belong_to_user
assert_raise(CannotAccessContext, "Cannot access a context that does not belong to this user.") { @controller.new_rich_todo(users('other_user').login, users('other_user').token, contexts('agenda').id, 'test', 'test') }
end
def test_list_projects_fails_with_incorrect_token
assert_raises_invalid_token { @controller.list_projects('admin', 'notthecorrecttoken') }
end
def test_list_contexts_fails_with_incorrect_token
assert_raises_invalid_token { @controller.list_contexts('admin', 'notthecorrecttoken') }
end
private
def assert_raises_invalid_token
assert_raise(InvalidToken, "Sorry, you don't have permission to perform this action.") { yield }
end
end

0
test/functional/stats_controller_test.rb Executable file → Normal file
View file

View file

@ -1,20 +0,0 @@
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.

View file

@ -1,26 +0,0 @@
= 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

View file

@ -1,22 +0,0 @@
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

View file

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

View file

@ -1,38 +0,0 @@
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

@ -1,506 +0,0 @@
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 compatibility, 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://blog.jordanwest.me/modest-rubyist-archive/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
#Check for old ActionMailer :sent_on attributes
def check_old_action_mailer_sent_on_setting
files = []
lines = grep_for("sent_on", "app/*")
files += extract_filenames(lines) || []
unless files.empty?
alert(
"Deprecated ActionMailer attribute :sent_on",
"Using the new mailer API, you can specify :date to the mail method.",
"http://stackoverflow.com/questions/7367185/weird-error-when-delivering-mail-undefined-method-index-for-2011-09-09-2215",
files
)
end
end
def check_old_filter_parameter
files = []
lines = grep_for("filter_parameter_logging", "app/controllers/*")
files += extract_filenames(lines) || []
unless files.empty?
alert(
"Deprecated filter_parameter_logging calls",
"The list of filtered parameters are now stored in /config/application.rb. For example: config.filter_parameters += [:password]",
"http://de.asciicasts.com/episodes/224-controller-in-rails-3",
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

@ -1,95 +0,0 @@
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

@ -1,59 +0,0 @@
require 'active_support/core_ext/string/inflections'
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__)
require 'rails/all'
Bundler.require(:default, Rails.env) if defined?(Bundler)
module #{app_name.classify}
class Application < Rails::Application
config.autoload_paths += [config.root.join('lib')]
config.encoding = 'utf-8'
%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

@ -1,344 +0,0 @@
# 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, &block)
_res(FakeResourceRoute, args, &block)
end
def resource(*args, &block)
_res(FakeSingletonResourceRoute, args, &block)
end
def _res(klass, args)
if args.last.is_a?(Hash)
options = args.pop
debug "options #{options.inspect}"
end
args.each do |a|
current_parent << klass.new(a, options || {})
debug "mapping resources #{current_parent.last.name}"
if block_given?
parent = current_parent.last
parent = stack(parent) do
yield(self)
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, Symbol, Array 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
@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

@ -1,79 +0,0 @@
$:.unshift(File.dirname(__FILE__) + "/../../lib")
require 'routes_upgrader'
require 'gemfile_generator'
require 'application_checker'
require 'new_configuration_generator'
require "active_support"
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" unless defined? CLEAR
CYAN = "\e[36m" unless defined? CYAN
WHITE = "\e[37m" unless defined? WHITE
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

@ -1,344 +0,0 @@
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
make_file("app/controllers", "application_controller.rb", "filter_parameter_logging :password")
@checker.check_old_filter_parameter
assert @checker.alerts.has_key?("Deprecated filter_parameter_logging 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 test_check_old_action_mailer_sent_on_setting
make_file("app/models", "mailer.rb", "sent_on Time.now")
@checker.check_old_action_mailer_sent_on_setting
assert @checker.alerts.has_key?("Deprecated ActionMailer attribute :sent_on")
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

@ -1,72 +0,0 @@
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

@ -1,63 +0,0 @@
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

@ -1,218 +0,0 @@
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_block_and_options
routes_code = <<-ROUTES
ActionController::Routing::Routes.draw do |map|
map.resources :people, :collection => {:search => :get} do |p|
p.resource :vuvuzela
end
end
ROUTES
upgrader = Rails::Upgrading::RoutesUpgrader.new
upgrader.routes_code = routes_code
result = upgrader.generate_new_routes
assert_equal "MyApplication::Application.routes.draw do\n resources :people do\n collection do\n get :search\n end\n \n resource :vuvuzela\n end\n\nend\n", result
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', :conditions => {: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
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', :conditions => {:method => [:delete, :get]}
end
}
new_routes_code = %Q{
MyApplication::Application.routes.draw do
match '/sign_out' => 'sessions#destroy', :as => :sign_out, :via => [:delete, :get]
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

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

View file

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