Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

start adding rails 3.0 support

This can successfully load rails console and rails server. There are
many, many problems still. The idea is this won't change anything under
rails 2.3, it's all backwards compatible.

closes CNVS-4711

test plan: `touch RAILS3` in your Canvas Rails.root directory. The run
`bundle update` and verify that you get rails 3 installed. Run `bundle
exec rails c` to load console or `bundle exec rails s` to start a
webrick server. You can login, though the dashboard currently breaks.
Also jammit isn't working yet.

But more importantly, Rails 2.3 should still work same as ever. All
tests should pass, and a basic regression sanity check would be good too.

Change-Id: Idd6f35de88adde84cd2db3a650f44b71bd6e9684
Reviewed-on: https://gerrit.instructure.com/18453
Reviewed-by: Brian Palmer <brianp@instructure.com>
Tested-by: Jenkins <jenkins@instructure.com>
QA-Review: Clare Hetherington <clare@instructure.com>
Product-Review: Bracken Mosbacker <bracken@instructure.com>
  • Loading branch information...
commit cb5e957965f97037ce6c6b3866eaece1c84fd39f 1 parent e6ed644
@codekitchen codekitchen authored
Showing with 637 additions and 462 deletions.
  1. +2 −0  .gitignore
  2. +25 −9 Gemfile
  3. +12 −2 Rakefile
  4. +7 −4 app/controllers/application_controller.rb
  5. +1 −1  app/middleware/load_account.rb
  6. +11 −10 app/models/submission.rb
  7. +8 −2 config.ru
  8. +16 −0 config/application.rb
  9. +11 −0 config/boot.rb
  10. +3 −0  config/canvas_rails3.rb
  11. +16 −160 config/environment.rb
  12. +58 −43 config/environments/development.rb
  13. +52 −21 config/environments/production.rb
  14. +60 −45 config/environments/test.rb
  15. +12 −7 config/initializers/active_record.rb
  16. +6 −4 config/initializers/authlogic_mods.rb
  17. +2 −2 config/initializers/backtrace_silencers.rb
  18. +1 −0  config/initializers/canvas_security.rb
  19. +16 −3 config/initializers/i18n.rb
  20. +14 −12 config/initializers/new_rails_defaults.rb
  21. +4 −1 config/initializers/rails_patches.rb
  22. +50 −56 config/initializers/ruby_version_compat.rb
  23. +7 −3 config/initializers/session_store.rb
  24. +141 −0 config/shared_boot.rb
  25. +9 −3 lib/canvas.rb
  26. +3 −5 lib/canvas/migration/worker.rb
  27. +53 −58 lib/cc/importer/cc_worker.rb
  28. +8 −0 lib/csv_compat.rb
  29. +2 −0  lib/ext/array.rb
  30. +1 −0  lib/kaltura/kaltura_client_v3.rb
  31. +5 −2 lib/stubs/shard.rb
  32. +6 −0 script/rails
  33. 0  script/startup.bat
  34. +6 −7 spec/lib/cc/importer/common_cartridge_converter_spec.rb
  35. +2 −0  spec/lib/gradebook_csv_parser_spec.rb
  36. +2 −1  spec/spec_helper.rb
  37. +5 −1 vendor/plugins/respondus_soap_endpoint/init.rb
View
2  .gitignore
@@ -28,8 +28,10 @@
/public/javascripts/translations/
/public/optimized/
/public/stylesheets/compiled/
+/RAILS3
/spec/javascripts/
/tmp/
+/vendor/plugins/rails_upgrade
# generated plugin stuff
/app/coffeescripts/plugins/
View
34 Gemfile
@@ -1,19 +1,35 @@
source 'https://rubygems.org/'
ONE_NINE = RUBY_VERSION >= "1.9."
+require File.expand_path("../config/canvas_rails3", __FILE__)
+
+if CANVAS_RAILS3
+ # 3.0.20 is transitional, we will be on 3.2.x before support is complete
+ # that's also why some gems below have to be downgraded, 3.0.20 relies on old versions of some gems
+ # just to be clear, Canvas is NOT READY to run under Rails 3 in production
+ gem 'rails', '3.0.20'
+ gem 'authlogic', '3.2.0'
+else
+ gem 'rails', '2.3.17'
+ gem 'authlogic', '2.1.3'
+end
-gem 'rails', '2.3.17'
-gem 'authlogic', '2.1.3'
gem "aws-sdk", '1.8.3.1'
gem 'barby', '0.5.0'
gem 'bcrypt-ruby', '3.0.1'
gem 'builder', '2.1.2'
-gem 'canvas_connect', '0.0.8'
+if !CANVAS_RAILS3
+ gem 'canvas_connect', '0.0.8'
+end
gem 'daemons', '1.1.0'
gem 'diff-lcs', '1.1.2', :require => 'diff/lcs'
-gem 'encrypted_cookie_store-instructure', '1.0.2', :require => 'encrypted_cookie_store'
-gem 'erubis', '2.7.0'
-gem 'fake_arel', '1.0.0'
+if !CANVAS_RAILS3
+ gem 'encrypted_cookie_store-instructure', '1.0.2', :require => 'encrypted_cookie_store'
+end
+gem 'erubis', CANVAS_RAILS3 ? '2.6.6' : '2.7.0'
+if !CANVAS_RAILS3
+ gem 'fake_arel', '1.0.0'
+end
gem 'ffi', '1.1.5'
gem 'hairtrigger', '0.1.14'
gem 'sass', '3.2.3'
@@ -22,7 +38,7 @@ if !ONE_NINE
end
gem 'hashery', '1.3.0', :require => 'hashery/dictionary'
gem 'highline', '1.6.1'
-gem 'i18n', '0.6.0'
+gem 'i18n', CANVAS_RAILS3 ? '0.5.0' : '0.6.0'
gem 'icalendar', '1.1.5'
gem 'jammit', '0.6.0'
gem 'json', '1.5.5'
@@ -30,7 +46,7 @@ gem 'json', '1.5.5'
gem 'libxml-ruby', '2.3.2', :require => 'xml/libxml'
gem 'macaddr', '1.0.0' # macaddr 1.2.0 tries to require 'systemu' which isn't a dependency
if ONE_NINE
- gem 'mail', '2.5.3'
+ gem 'mail', CANVAS_RAILS3 ? '2.2.19' : '2.5.3'
else
gem 'mail', '2.4.4'
end
@@ -42,7 +58,7 @@ gem 'mini_magick', '1.3.2'
gem 'netaddr', '1.5.0'
gem 'nokogiri', '1.5.5'
gem 'oauth', '0.4.5'
-gem 'rack', '1.1.3'
+gem 'rack', CANVAS_RAILS3 ? '1.2.5' : '1.1.3'
gem 'rake', '10.0.3'
gem 'rdoc', '3.12'
gem 'ratom-instructure', '0.6.9', :require => "atom" # custom gem until necessary changes are merged into mainstream
View
14 Rakefile
@@ -1,12 +1,22 @@
# Add your own tasks in files placed in lib/tasks ending in .rake,
# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
-require(File.join(File.dirname(__FILE__), 'config', 'boot'))
+require File.expand_path("../config/canvas_rails3", __FILE__)
+
+if CANVAS_RAILS3
+ require File.expand_path('../config/application', __FILE__)
+else
+ require File.expand_path('../config/boot', __FILE__)
+end
require 'rake'
require 'rake/testtask'
require 'rdoc/task'
-require 'tasks/rails'
+if CANVAS_RAILS3
+ CanvasRails::Application.load_tasks
+else
+ require 'tasks/rails'
+end
begin; require 'parallelized_specs/tasks'; rescue LoadError; end
View
11 app/controllers/application_controller.rb
@@ -831,7 +831,11 @@ def rescue_action_in_public(exception)
end
end
- rescue_responses['AuthenticationMethods::AccessTokenError'] = 401
+ if Rails.version < "3.0"
+ rescue_responses['AuthenticationMethods::AccessTokenError'] = 401
+ else
+ ActionDispatch::ShowExceptions.rescue_responses['AuthenticationMethods::AccessTokenError'] = 401
+ end
def rescue_action_in_api(exception, error_report)
status_code = response_code_for_rescue(exception) || 500
@@ -900,9 +904,8 @@ def verify_authenticity_token
params[request_forgery_protection_token] = token if token
if protect_against_forgery? &&
- request.method != :get &&
- !api_request? &&
- verifiable_request_format?
+ !request.get? &&
+ !api_request?
if session[:_csrf_token].nil? && session.empty? && !request.xhr? && !api_request?
# the session should have the token stored by now, but doesn't? sounds
# like the user doesn't have cookies enabled.
View
2  app/middleware/load_account.rb
@@ -5,7 +5,7 @@ def initialize(app)
def call(env)
Account.clear_special_account_cache!
- domain_root_account = LoadAccount.default_domain_root_account
+ domain_root_account = ::LoadAccount.default_domain_root_account
configure_for_root_account(domain_root_account)
env['canvas.domain_root_account'] = domain_root_account
View
21 app/models/submission.rb
@@ -78,25 +78,26 @@ class Submission < ActiveRecord::Base
}
}
- named_scope :needs_grading, :conditions => <<-SQL
- submissions.submission_type IS NOT NULL
- AND (submissions.workflow_state = 'pending_review'
- OR (submissions.workflow_state = 'submitted'
- AND (submissions.score IS NULL OR NOT submissions.grade_matches_current_submission)
- )
- )
- SQL
-
named_scope :for_course, lambda{ |course|
{ :conditions => ["submissions.assignment_id IN (SELECT assignments.id FROM assignments WHERE assignments.context_id = ? AND assignments.context_type = 'Course')", course.id] }
}
def self.needs_grading_conditions(prefix = nil)
- conditions = needs_grading.proxy_options[:conditions].gsub(/\s+/, ' ')
+ conditions = <<-SQL
+ submissions.submission_type IS NOT NULL
+ AND (submissions.workflow_state = 'pending_review'
+ OR (submissions.workflow_state = 'submitted'
+ AND (submissions.score IS NULL OR NOT submissions.grade_matches_current_submission)
+ )
+ )
+ SQL
+ conditions.gsub!(/\s+/, ' ')
conditions.gsub!("submissions.", prefix + ".") if prefix
conditions
end
+ named_scope :needs_grading, :conditions => needs_grading_conditions
+
sanitize_field :body, Instructure::SanitizeField::SANITIZE
View
10 config.ru
@@ -1,2 +1,8 @@
-require File.expand_path(File.dirname(__FILE__) + '/config/environment')
-run ActionController::Dispatcher.new
+# This file is used by Rack-based servers to start the application.
+
+require ::File.expand_path('../config/environment', __FILE__)
+if defined?(CanvasRails)
+ run CanvasRails::Application
+else
+ run ActionController::Dispatcher.new
+end
View
16 config/application.rb
@@ -0,0 +1,16 @@
+# Put this in config/application.rb
+require File.expand_path('../boot', __FILE__)
+
+require 'rails/all'
+
+Bundler.require(:default, Rails.env) if defined?(Bundler)
+
+module CanvasRails
+ class Application < Rails::Application
+ config.autoload_paths += [config.root.join('lib').to_s]
+ $LOAD_PATH << config.root.to_s
+ config.encoding = 'utf-8'
+
+ eval(File.read(File.expand_path("../shared_boot.rb", __FILE__)), binding, "config/shared_boot.rb", 1)
+ end
+end
View
11 config/boot.rb
@@ -1,6 +1,16 @@
# Don't change this file!
# Configure your app in config/environment.rb and config/environments/*.rb
+require File.expand_path("../canvas_rails3", __FILE__)
+
+if CANVAS_RAILS3
+ require 'rubygems'
+
+ # Set up gems listed in the Gemfile.
+ ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
+ require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE'])
+else
+
RAILS_ROOT = "#{File.dirname(__FILE__)}/.." unless defined?(RAILS_ROOT)
$LOAD_PATH.unshift RAILS_ROOT.dup
@@ -120,3 +130,4 @@ def read_environment_rb
# All that for this:
Rails.boot!
+end
View
3  config/canvas_rails3.rb
@@ -0,0 +1,3 @@
+# You can enable the not-yet-complete Rails3 support by either defining a
+# CANVAS_RAILS3 env var, or create an empty RAILS3 file in the canvas RAILS_ROOT dir
+CANVAS_RAILS3 = !!ENV['CANVAS_RAILS3'] || File.exist?(File.expand_path("../../RAILS3", __FILE__))
View
176 config/environment.rb
@@ -1,170 +1,26 @@
-# Be sure to restart your server when you modify this file
+require File.expand_path("../canvas_rails3", __FILE__)
-# Bootstrap the Rails environment, frameworks, and default configuration
-require File.join(File.dirname(__FILE__), 'boot')
-
-# This is because the aws-s3 gem is using the XML:: namespace instead of LIBXML::
-require 'xml/libxml'
-
-Rails::Initializer.run do |config|
- # Settings in config/environments/* take precedence over those specified here.
- # Application configuration should go into files in config/initializers
- # -- all .rb files in that directory are automatically loaded.
- # See Rails::Configuration for more options.
-
- # Skip frameworks you're not going to use. To use Rails without a database
- # you must remove the Active Record framework.
- # config.frameworks -= [ :active_record, :active_resource, :action_mailer ]
-
- # dont specify gems here, use the gemfile with bundler, see: http://gembundler.com/
-
- # Only load the plugins named here, in the order given. By default, all plugins
- # in vendor/plugins are loaded in alphabetical order.
- # :all can be used as a placeholder for all plugins not explicitly named
- # config.plugins = [ :exception_notification, :all ]
-
- # Force all environments to use the same logger level
- # (by default production uses :info, the others :debug)
- # config.log_level = :info
-
- # Make Time.zone default to the specified zone, and make Active Record store time values
- # in the database in UTC, and return them converted to the specified local zone.
- # Run "rake -D time" for a list of tasks for finding time zone names. Comment line to use default local time.
- config.time_zone = 'UTC'
-
- if ENV['RUNNING_AS_DAEMON'] == 'true'
- config.log_path = Rails.root+'log/delayed_job.log'
- end
-
- log_config = File.exists?(Rails.root+"config/logging.yml") && YAML.load_file(Rails.root+"config/logging.yml")[RAILS_ENV]
- log_config = { 'logger' => 'rails', 'log_level' => 'debug' }.merge(log_config || {})
- opts = {}
- require 'canvas/logger'
- log_level = ActiveSupport::BufferedLogger.const_get(log_config['log_level'].to_s.upcase)
- opts[:skip_thread_context] = true if log_config['log_context'] == false
- case log_config["logger"]
- when "syslog"
- require 'syslog_wrapper'
- log_config["app_ident"] ||= "canvas-lms"
- log_config["daemon_ident"] ||= "canvas-lms-daemon"
- facilities = 0
- (log_config["facilities"] || []).each do |facility|
- facilities |= Syslog.const_get "LOG_#{facility.to_s.upcase}"
+if CANVAS_RAILS3
+ def environment_configuration(_config)
+ CanvasRails::Application.configure do
+ yield(config)
end
- ident = ENV['RUNNING_AS_DAEMON'] == 'true' ? log_config["daemon_ident"] : log_config["app_ident"]
- opts[:include_pid] = true if log_config["include_pid"] == true
- config.logger = RAILS_DEFAULT_LOGGER = SyslogWrapper.new(ident, facilities, opts)
- config.logger.level = log_level
- else
- config.logger = RAILS_DEFAULT_LOGGER = CanvasLogger.new(config.log_path, log_level, opts)
- end
-
- # Use SQL instead of Active Record's schema dumper when creating the test database.
- # This is necessary if your schema can't be completely dumped by the schema dumper,
- # like if you have constraints or database-specific column types
- # config.active_record.schema_format = :sql
-
- # Activate observers that should always be running
- config.active_record.observers = [:cacher, :stream_item_cache]
-
- config.autoload_paths += %W(#{Rails.root}/app/middleware
- #{Rails.root}/app/observers
- #{Rails.root}/app/presenters)
-
- config.middleware.insert_after(ActionController::Base.session_store, 'SessionsTimeout')
- config.middleware.insert_before('ActionController::ParamsParser', 'LoadAccount')
- config.middleware.insert_before('ActionController::ParamsParser', 'StatsTiming')
- config.middleware.insert_before('ActionController::ParamsParser', 'PreventNonMultipartParse')
- config.middleware.insert_before('ActionController::ParamsParser', "RequestContextGenerator")
- config.to_prepare do
- require_dependency 'canvas/plugins/default_plugins'
- ActiveSupport::JSON::Encoding.escape_html_entities_in_json = true
end
- # this patch is perfectly placed to go in as soon as the PostgreSQLAdapter
- # is required for the first time, but before it's actually used
- Rails::Initializer.class_eval do
- def initialize_database_with_postgresql_patches
- initialize_database_without_postgresql_patches
-
- if defined?(ActiveRecord::ConnectionAdapters::PostgreSQLAdapter)
- ActiveRecord::Base.class_eval do
- # Override to support custom postgresql connection parameters
- def self.postgresql_connection(config) # :nodoc:
- config = config.symbolize_keys
- config[:user] = config.delete(:username)
-
- if config.has_key?(:database)
- config[:dbname] = config.delete(:database)
- else
- raise ArgumentError, "No database specified. Missing argument: database."
- end
-
- # The postgres drivers don't allow the creation of an unconnected PGconn object,
- # so just pass a nil connection object for the time being.
- ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.new(nil, logger, [config], config)
- end
- end
+ # Load the rails application
+ require File.expand_path('../application', __FILE__)
- # now let's try this again
- ActiveRecord::Base.establish_connection
- end
- end
- alias_method_chain :initialize_database, :postgresql_patches
+ # Initialize the rails application
+ CanvasRails::Application.initialize!
+else
+ def environment_configuration(config)
+ yield(config)
end
-end
-
-# We need to make sure that safe_yaml is loaded *after* the YAML engine
-# is switched to Syck (which DelayedJob needs for now). Otherwise we
-# won't have access to (safe|unsafe)_load.
-require 'yaml'
-YAML::ENGINE.yamler = 'syck' if defined?(YAML::ENGINE)
-require 'safe_yaml'
-YAML.enable_symbol_parsing!
-# We don't need to be reminded that safe loads are being used everywhere.
-SafeYAML::OPTIONS[:suppress_warnings] = true
-# This tag whitelist is syck specific. We'll need to tweak it when we upgrade to psych.
-# See the tests in spec/lib/safe_yaml_spec.rb
-YAML.whitelist.add(*%w[
- tag:ruby.yaml.org,2002:symbol
- tag:yaml.org,2002:map:HashWithIndifferentAccess
- tag:ruby.yaml.org,2002:object:OpenStruct
- tag:ruby.yaml.org,2002:object:Scribd::Document
- tag:ruby.yaml.org,2002:object:Mime::Type
- tag:ruby.yaml.org,2002:object:URI::HTTP
- tag:ruby.yaml.org,2002:object:URI::HTTPS
- tag:ruby.yaml.org,2002:object:OpenObject
-])
-YAML.whitelist.add('tag:ruby.yaml.org,2002:object:Class') { |classname| Canvas::Migration.valid_converter_classes.include?(classname) }
+ # Bootstrap the Rails environment, frameworks, and default configuration
+ require File.expand_path('../boot', __FILE__)
-# Extend any base classes, even gem classes
-Dir.glob("#{Rails.root}/lib/ext/**/*.rb").each { |file| require file }
-
-Canvas::Security.validate_encryption_key(ENV['UPDATE_ENCRYPTION_KEY_HASH'])
-
-# Require parts of the lib that are interesting
-%w(
- gradebook_csv_parser
- workflow
- file_splitter
- gradebook_importer
- auto_handle
- zip_extractor
-).each { |f| require f }
-
-require 'kaltura/kaltura_client_v3'
-
-# tell Rails to use the native XML parser instead of REXML
-ActiveSupport::XmlMini.backend = 'LibXML'
-
-class NotImplemented < StandardError; end
-
-if defined?(PhusionPassenger)
- PhusionPassenger.on_event(:starting_worker_process) do |forked|
- if forked
- # We're in smart spawning mode, and need to make unique connections for this fork.
- Canvas.reconnect_redis
- end
+ Rails::Initializer.run do |config|
+ eval(File.read(File.expand_path("../shared_boot.rb", __FILE__)), binding, "config/shared_boot.rb", 1)
end
end
View
101 config/environments/development.rb
@@ -1,53 +1,68 @@
-# Settings specified here will take precedence over those in config/environment.rb
+environment_configuration(defined?(config) && config) do |config|
+ # Settings specified here will take precedence over those in config/application.rb
-# In the development environment your application's code is reloaded on
-# every request. This slows down response time but is perfect for development
-# since you don't have to restart the webserver when you make code changes.
-config.cache_classes = false
+ # In the development environment your application's code is reloaded on
+ # every request. This slows down response time but is perfect for development
+ # since you don't have to restart the webserver when you make code changes.
+ config.cache_classes = false
-# Log error messages when you accidentally call methods on nil.
-config.whiny_nils = true
+ # Log error messages when you accidentally call methods on nil.
+ config.whiny_nils = true
-# Show full error reports and disable caching
-config.action_controller.consider_all_requests_local = true
-config.action_view.debug_rjs = true
-config.action_controller.perform_caching = false
+ # Show full error reports and disable caching
+ if Rails.version < "3.0"
+ config.action_controller.consider_all_requests_local = true
+ else
+ config.consider_all_requests_local = true
+ end
+ config.action_view.debug_rjs = true
+ config.action_controller.perform_caching = false
-# run rake js:build to build the optimized JS if set to true
-# ENV['USE_OPTIMIZED_JS'] = 'true'
+ # run rake js:build to build the optimized JS if set to true
+ # ENV['USE_OPTIMIZED_JS'] = 'true'
-# Really do care if the message wasn't sent.
-config.action_mailer.raise_delivery_errors = true
+ # Really do care if the message wasn't sent.
+ config.action_mailer.raise_delivery_errors = true
-config.to_prepare do
- # Raise an exception on bad mass assignment. Helps us catch these bugs before
- # they hit.
- Canvas.protected_attribute_error = :raise
+ # initialize cache store
+ # this needs to happen in each environment config file, rather than a
+ # config/initializer/* file, to allow Rails' full initialization of the cache
+ # to take place, including middleware inserts and such.
+ require_dependency 'canvas'
+ config.cache_store = Canvas.cache_store_config
- # Raise an exception on finder type mismatch or nil arguments. Helps us catch
- # these bugs before they hit.
- Canvas.dynamic_finder_nil_arguments_error = :raise
-end
+ # eval <env>-local.rb if it exists
+ Dir[File.dirname(__FILE__) + "/" + File.basename(__FILE__, ".rb") + "-*.rb"].each { |localfile| eval(File.new(localfile).read) }
+
+ # allow debugging only in development environment by default
+ # ruby-debug is currently broken in 1.9.3
+ #
+ # Option to DISABLE_RUBY_DEBUGGING is helpful IDE-based debugging.
+ # The ruby debug gems conflict with the IDE-based debugger gem.
+ # Set this option in your dev environment to disable.
+ unless ENV['DISABLE_RUBY_DEBUGGING']
+ if RUBY_VERSION < "1.9."
+ require "ruby-debug"
+ else
+ require "debugger"
+ end
+ end
+
+ if Rails.version < "3.0"
+ config.to_prepare do
+ # Raise an exception on bad mass assignment. Helps us catch these bugs before
+ # they hit.
+ Canvas.protected_attribute_error = :raise
-# initialize cache store
-# this needs to happen in each environment config file, rather than a
-# config/initializer/* file, to allow Rails' full initialization of the cache
-# to take place, including middleware inserts and such.
-config.cache_store = Canvas.cache_store_config
-
-# eval <env>-local.rb if it exists
-Dir[File.dirname(__FILE__) + "/" + File.basename(__FILE__, ".rb") + "-*.rb"].each { |localfile| eval(File.new(localfile).read) }
-
-# allow debugging only in development environment by default
-# ruby-debug is currently broken in 1.9.3
-#
-# Option to DISABLE_RUBY_DEBUGGING is helpful IDE-based debugging.
-# The ruby debug gems conflict with the IDE-based debugger gem.
-# Set this option in your dev environment to disable.
-unless ENV['DISABLE_RUBY_DEBUGGING']
- if RUBY_VERSION < "1.9."
- require "ruby-debug"
+ # Raise an exception on finder type mismatch or nil arguments. Helps us catch
+ # these bugs before they hit.
+ Canvas.dynamic_finder_nil_arguments_error = :raise
+ end
else
- require "debugger"
+ # Print deprecation notices to the Rails logger
+ config.active_support.deprecation = :log
+
+ # Only use best-standards-support built into browsers
+ config.action_dispatch.best_standards_support = :builtin
end
-end
+end
View
73 config/environments/production.rb
@@ -1,28 +1,59 @@
-# Settings specified here will take precedence over those in config/environment.rb
+environment_configuration(defined?(config) && config) do |config|
+ # Settings specified here will take precedence over those in config/application.rb
-# The production environment is meant for finished, "live" apps.
-# Code is not reloaded between requests
-config.cache_classes = true
+ # The production environment is meant for finished, "live" apps.
+ # Code is not reloaded between requests
+ config.cache_classes = true
-# Full error reports are disabled and caching is turned on
-config.action_controller.consider_all_requests_local = false
-config.action_controller.perform_caching = true
-config.action_view.cache_template_loading = true
+ # Full error reports are disabled and caching is turned on
+ if Rails.version < "3.0"
+ config.action_controller.consider_all_requests_local = true
+ else
+ config.consider_all_requests_local = true
+ end
+ config.action_controller.perform_caching = true
-# run rake js:build to build the optimized JS if set to true
-ENV['USE_OPTIMIZED_JS'] = "true"
+ # run rake js:build to build the optimized JS if set to true
+ ENV['USE_OPTIMIZED_JS'] = "true"
-# Enable serving of images, stylesheets, and javascripts from an asset server
-# config.action_controller.asset_host = "http://assets.example.com"
+ # initialize cache store
+ # this needs to happen in each environment config file, rather than a
+ # config/initializer/* file, to allow Rails' full initialization of the cache
+ # to take place, including middleware inserts and such.
+ require_dependency 'canvas'
+ config.cache_store = Canvas.cache_store_config
-# Disable delivery errors, bad email addresses will be ignored
-# config.action_mailer.raise_delivery_errors = false
+ # eval <env>-local.rb if it exists
+ Dir[File.dirname(__FILE__) + "/" + File.basename(__FILE__, ".rb") + "-*.rb"].each { |localfile| eval(File.new(localfile).read) }
-# initialize cache store
-# this needs to happen in each environment config file, rather than a
-# config/initializer/* file, to allow Rails' full initialization of the cache
-# to take place, including middleware inserts and such.
-config.cache_store = Canvas.cache_store_config
+ if Rails.version >= "3.0"
+ # Specifies the header that your server uses for sending files
+ config.action_dispatch.x_sendfile_header = "X-Sendfile"
-# eval <env>-local.rb if it exists
-Dir[File.dirname(__FILE__) + "/" + File.basename(__FILE__, ".rb") + "-*.rb"].each { |localfile| eval(File.new(localfile).read) }
+ # For nginx:
+ # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect'
+
+ # If you have no front-end server that supports something like X-Sendfile,
+ # just comment this out and Rails will serve the files
+
+ # Disable Rails's static asset server
+ # In production, Apache or nginx will already do this
+ config.serve_static_assets = false
+
+ # Enable serving of images, stylesheets, and javascripts from an asset server
+ # config.action_controller.asset_host = "http://assets.example.com"
+
+ # Disable delivery errors, bad email addresses will be ignored
+ # config.action_mailer.raise_delivery_errors = false
+
+ # Enable threaded mode
+ # config.threadsafe!
+
+ # Enable locale fallbacks for I18n (makes lookups for any locale fall back to
+ # the I18n.default_locale when a translation can not be found)
+ # config.i18n.fallbacks = true
+
+ # Send deprecation notices to registered listeners
+ config.active_support.deprecation = :notify
+ end
+end
View
105 config/environments/test.rb
@@ -1,46 +1,61 @@
-# Settings specified here will take precedence over those in config/environment.rb
-
-# The test environment is used exclusively to run your application's
-# test suite. You never need to work with it otherwise. Remember that
-# your test database is "scratch space" for the test suite and is wiped
-# and recreated between test runs. Don't rely on the data there!
-config.cache_classes = true
-
-# Log error messages when you accidentally call methods on nil.
-if RUBY_VERSION >= "1.9."
- # in 1.9, whiny_nils causes a huge performance penalty on tests for some reason
- config.whiny_nils = false
-else
- config.whiny_nils = true
+environment_configuration(defined?(config) && config) do |config|
+ # Settings specified here will take precedence over those in config/application.rb
+
+ # The test environment is used exclusively to run your application's
+ # test suite. You never need to work with it otherwise. Remember that
+ # your test database is "scratch space" for the test suite and is wiped
+ # and recreated between test runs. Don't rely on the data there!
+ config.cache_classes = true
+
+ # Log error messages when you accidentally call methods on nil.
+ if RUBY_VERSION >= "1.9."
+ # in 1.9, whiny_nils causes a huge performance penalty on tests for some reason
+ config.whiny_nils = false
+ else
+ config.whiny_nils = true
+ end
+
+ # Show full error reports and disable caching
+ if Rails.version < "3.0"
+ config.action_controller.consider_all_requests_local = true
+ else
+ config.consider_all_requests_local = true
+ end
+ config.action_controller.perform_caching = false
+
+ # run rake js:build to build the optimized JS if set to true
+ # ENV['USE_OPTIMIZED_JS'] = 'true'
+
+ # Disable request forgery protection in test environment
+ config.action_controller.allow_forgery_protection = false
+
+ # Tell Action Mailer not to deliver emails to the real world.
+ # The :test delivery method accumulates sent emails in the
+ # ActionMailer::Base.deliveries array.
+ config.action_mailer.delivery_method = :test
+
+ #hairtrigger parallelized runtime race conditions
+ config.active_record.schema_format = :sql
+
+ # eval <env>-local.rb if it exists
+ Dir[File.dirname(__FILE__) + "/" + File.basename(__FILE__, ".rb") + "-*.rb"].each { |localfile| eval(File.new(localfile).read) }
+
+ require_dependency 'nil_store'
+ config.cache_store = NilStore.new
+
+ if Rails.version < "3.0"
+ # Raise an exception on bad mass assignment. Helps us catch these bugs before
+ # they hit.
+ Canvas.protected_attribute_error = :raise
+
+ # Raise an exception on finder type mismatch or nil arguments. Helps us catch
+ # these bugs before they hit.
+ Canvas.dynamic_finder_nil_arguments_error = :raise
+ else
+ # Raise exceptions instead of rendering exception templates
+ config.action_dispatch.show_exceptions = false
+
+ # Print deprecation notices to the stderr
+ config.active_support.deprecation = :stderr
+ end
end
-
-# Show full error reports and disable caching
-config.action_controller.consider_all_requests_local = true
-config.action_controller.perform_caching = false
-
-# run rake js:build to build the optimized JS if set to true
-# ENV['USE_OPTIMIZED_JS'] = 'true'
-
-# Disable request forgery protection in test environment
-config.action_controller.allow_forgery_protection = false
-
-# Tell Action Mailer not to deliver emails to the real world.
-# The :test delivery method accumulates sent emails in the
-# ActionMailer::Base.deliveries array.
-config.action_mailer.delivery_method = :test
-
-# Raise an exception on bad mass assignment. Helps us catch these bugs before
-# they hit.
-Canvas.protected_attribute_error = :raise
-
-# Raise an exception on finder type mismatch or nil arguments. Helps us catch
-# these bugs before they hit.
-Canvas.dynamic_finder_nil_arguments_error = :raise
-
-#hairtrigger parallelized runtime race conditions
-config.active_record.schema_format = :sql
-
-# eval <env>-local.rb if it exists
-Dir[File.dirname(__FILE__) + "/" + File.basename(__FILE__, ".rb") + "-*.rb"].each { |localfile| eval(File.new(localfile).read) }
-
-config.cache_store = :nil_store
View
19 config/initializers/active_record.rb
@@ -1,15 +1,20 @@
class ActiveRecord::Base
+ # XXX: Rails3 There are lots of issues with these patches in Rails3 still
+
extend ActiveSupport::Memoizable # used for a lot of the reporting queries
- class ProtectedAttributeAssigned < Exception; end
- def log_protected_attribute_removal_with_raise(*attributes)
- if Canvas.protected_attribute_error == :raise
- raise ProtectedAttributeAssigned, "Can't mass-assign these protected attributes for class #{self.class.name}: #{attributes.join(', ')}"
- else
- log_protected_attribute_removal_without_raise(*attributes)
+ if Rails.version < "3.0"
+ # this functionality is built into rails 3
+ class ProtectedAttributeAssigned < Exception; end
+ def log_protected_attribute_removal_with_raise(*attributes)
+ if Canvas.protected_attribute_error == :raise
+ raise ProtectedAttributeAssigned, "Can't mass-assign these protected attributes for class #{self.class.name}: #{attributes.join(', ')}"
+ else
+ log_protected_attribute_removal_without_raise(*attributes)
+ end
end
+ alias_method_chain :log_protected_attribute_removal, :raise
end
- alias_method_chain :log_protected_attribute_removal, :raise
def feed_code
id = self.uuid rescue self.id
View
10 config/initializers/authlogic_mods.rb
@@ -8,14 +8,16 @@ class RailsAdapter < AbstractAdapter
end
end
+callback_chain = Rails.version < "3.0" ? Authlogic::Session::Base.persist_callback_chain : Authlogic::Session::Base._persist_callbacks
+
# we need http basic auth to take precedence over the session cookie, for the api.
-cb = Authlogic::Session::Base.persist_callback_chain.delete(:persist_by_http_auth)
-Authlogic::Session::Base.persist_callback_chain.unshift(cb) if cb
+cb = callback_chain.delete(:persist_by_http_auth)
+callback_chain.unshift(cb) if cb
# we also need the session cookie to take precendence over the "remember me" cookie,
# otherwise we'll use the "remember me" cookie every request, which triggers
# generating a new "remember me" cookie since they're one-time use.
-cb = Authlogic::Session::Base.persist_callback_chain.delete(:persist_by_cookie)
-Authlogic::Session::Base.persist_callback_chain.push(cb) if cb
+cb = callback_chain.delete(:persist_by_cookie)
+callback_chain.push(cb) if cb
# be tolerant of using a slave
Authlogic::Session::Callbacks.module_eval do
View
4 config/initializers/backtrace_silencers.rb
@@ -3,5 +3,5 @@
# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
-# You can also remove all the silencers if you're trying do debug a problem that might steem from framework code.
-# Rails.backtrace_cleaner.remove_silencers!
+# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code.
+# Rails.backtrace_cleaner.remove_silencers!
View
1  config/initializers/canvas_security.rb
@@ -0,0 +1 @@
+Canvas::Security.validate_encryption_key(ENV['UPDATE_ENCRYPTION_KEY_HASH'])
View
19 config/initializers/i18n.rb
@@ -163,8 +163,19 @@ def self.apply_wrappers(string, wrappers)
end
ActionView::Base.class_eval do
- def i18n_scope
- "#{template.base_path}.#{template.name.sub(/\A_/, '')}"
+ if Rails.version < "3.0"
+ def i18n_scope
+ "#{template.base_path}.#{template.name.sub(/\A_/, '')}"
+ end
+ else
+ def _render_template_with_assign(template, *a)
+ @current_template = template
+ _render_template_without_assign(template, *a)
+ end
+ alias_method_chain :_render_template, :assign
+ def i18n_scope
+ @current_template.virtual_path.sub(/\/_/, '/').gsub('/', '.')
+ end
end
def translate(key, default, options = {})
@@ -227,7 +238,9 @@ def translate(key, default, options = {})
alias :t :translate
end
-ActiveSupport::CoreExtensions::Array::Conversions.class_eval do
+require 'active_support/core_ext/array/conversions'
+
+class Array
def to_sentence_with_simple_or(options = {})
if options == :or
to_sentence_without_simple_or(:two_words_connector => I18n.t('support.array.or.two_words_connector'),
View
26 config/initializers/new_rails_defaults.rb
@@ -3,19 +3,21 @@
# These settings change the behavior of Rails 2 apps and will be defaults
# for Rails 3. You can remove this initializer when Rails 3 is released.
-if defined?(ActiveRecord)
- # Include Active Record class name as root for JSON serialized output.
- ActiveRecord::Base.include_root_in_json = true
+if Rails.version < "3.0"
+ if defined?(ActiveRecord)
+ # Include Active Record class name as root for JSON serialized output.
+ ActiveRecord::Base.include_root_in_json = true
- # Store the full class name (including module namespace) in STI type column.
- ActiveRecord::Base.store_full_sti_class = true
-end
+ # Store the full class name (including module namespace) in STI type column.
+ ActiveRecord::Base.store_full_sti_class = true
+ end
-ActionController::Routing.generate_best_match = false
+ ActionController::Routing.generate_best_match = false
-# Use ISO 8601 format for JSON serialized times and dates.
-ActiveSupport.use_standard_json_time_format = true
+ # Use ISO 8601 format for JSON serialized times and dates.
+ ActiveSupport.use_standard_json_time_format = true
-# Don't escape HTML entities in JSON, leave that for the #json_escape helper.
-# if you're including raw json in an HTML page.
-ActiveSupport.escape_html_entities_in_json = false
+ # Don't escape HTML entities in JSON, leave that for the #json_escape helper.
+ # if you're including raw json in an HTML page.
+ ActiveSupport.escape_html_entities_in_json = false
+end
View
5 config/initializers/rails_patches.rb
@@ -1,4 +1,7 @@
-ActionController::Base.param_parsers.delete(Mime::XML)
+if Rails.version < "3.0"
+ ActionController::Base.param_parsers.delete(Mime::XML)
+end
+
# CVE-2013-0333
# https://groups.google.com/d/topic/rubyonrails-security/1h2DR63ViGo/discussion
# With Rails 2.3.16 we could remove this line, but we still prefer JSONGem for performance reasons
View
106 config/initializers/ruby_version_compat.rb
@@ -1,17 +1,12 @@
-if RUBY_VERSION < "1.9."
- require 'fastercsv'
-else
+require 'csv_compat'
+
+if RUBY_VERSION >= "1.9"
# ruby 1.9 compatibility fixes
if ActiveRecord::Base.configurations[Rails.env]['adapter'] == 'mysql'
STDERR.puts "NOTE: It's recommended that you change your database adapter to mysql2 for usage with Ruby 1.9"
end
- # 1.9 has a built-in equivalent to fastercsv
- # make an alias for CSV, which has replaced FasterCSV
- require 'csv'
- FasterCSV = CSV
-
# See http://developer.uservoice.com/entries/how-to-upgrade-a-rails-2.3.14-app-to-ruby-1.9.3/
# TZInfo needs to be patched. In particular, you'll need to re-implement the datetime_new! method:
require 'tzinfo'
@@ -58,43 +53,57 @@ def self.datetime_new!(ajd = 0, of = 0, sg = Date::ITALY)
end
end
- if Rails.version > "3."
- raise "These following patches shouldn't be necessary in Rails 3.x"
- end
-
- require "active_support/core_ext/string/output_safety"
- class ERB
- module Util
- # see https://github.com/rails/rails/issues/7430
- def html_escape(s)
- s = s.to_s
- if s.html_safe?
- s
- else
- s.gsub(/[&"'><]/, HTML_ESCAPE).html_safe
+ if Rails.version < "3.0"
+
+ require "active_support/core_ext/string/output_safety"
+ class ERB
+ module Util
+ # see https://github.com/rails/rails/issues/7430
+ def html_escape(s)
+ s = s.to_s
+ if s.html_safe?
+ s
+ else
+ s.gsub(/[&"'><]/, HTML_ESCAPE).html_safe
+ end
end
+
+ alias h html_escape
+
+ singleton_class.send(:remove_method, :html_escape)
+ module_function :html_escape, :h
end
-
- alias h html_escape
-
- singleton_class.send(:remove_method, :html_escape)
- module_function :html_escape, :h
end
- end
- # also https://groups.google.com/forum/#!msg/rubyonrails-core/gb5woRkmDlk/iQ2G7jjNWKkJ
- MissingSourceFile::REGEXPS << [/^cannot load such file -- (.+)$/i, 1]
-
- # In Ruby 1.9, respond_to? (which is what proxy_respond_to? REALLY is), chains to
- # respond_to_missing?. However, respond_to_missing? is *not* defined on
- # AssociationProxy because Rails removes *all* methods besides __*, send,
- # nil?, and object_id, so it hits method_missing, and tries to load the
- # target.
- # See https://rails.lighthouseapp.com/projects/8994/tickets/5410-multiple-database-queries-when-chaining-named-scopes-with-rails-238-and-ruby-192
- # (The patch in that lighthouse bug was not, in fact, merged in).
- class ActiveRecord::Associations::AssociationProxy
- def respond_to_missing?(meth, incl_priv)
- false
+ # also https://groups.google.com/forum/#!msg/rubyonrails-core/gb5woRkmDlk/iQ2G7jjNWKkJ
+ MissingSourceFile::REGEXPS << [/^cannot load such file -- (.+)$/i, 1]
+
+ # In Ruby 1.9, respond_to? (which is what proxy_respond_to? REALLY is), chains to
+ # respond_to_missing?. However, respond_to_missing? is *not* defined on
+ # AssociationProxy because Rails removes *all* methods besides __*, send,
+ # nil?, and object_id, so it hits method_missing, and tries to load the
+ # target.
+ # See https://rails.lighthouseapp.com/projects/8994/tickets/5410-multiple-database-queries-when-chaining-named-scopes-with-rails-238-and-ruby-192
+ # (The patch in that lighthouse bug was not, in fact, merged in).
+ class ActiveRecord::Associations::AssociationProxy
+ def respond_to_missing?(meth, incl_priv)
+ false
+ end
+ end
+
+ # ActiveSupport::SafeBuffer is a subclass of String, and while string
+ # literals get the encoding of the source file,
+ #
+ # String.new always gets ascii-8bit encoding. This means that depending on
+ # the contents of a template and the data interpolated into the template,
+ # things either work great or you get an incompatible encoding error.
+ #
+ # This patch fixes the problem by giving new SafeBuffers the default encoding
+ # (which in canvas is utf-8)
+ class ActiveSupport::SafeBuffer
+ def initialize(*a)
+ super.force_encoding('utf-8')
+ end
end
end
@@ -176,21 +185,6 @@ def [](k)
end
end
- # ActiveSupport::SafeBuffer is a subclass of String, and while string
- # literals get the encoding of the source file,
- #
- # String.new always gets ascii-8bit encoding. This means that depending on
- # the contents of a template and the data interpolated into the template,
- # things either work great or you get an incompatible encoding error.
- #
- # This patch fixes the problem by giving new SafeBuffers the default encoding
- # (which in canvas is utf-8)
- class ActiveSupport::SafeBuffer
- def initialize(*a)
- super.force_encoding('utf-8')
- end
- end
-
# Fix for https://bugs.ruby-lang.org/issues/7278 , which was filling up our logs with these warnings
if RUBY_VERSION < "2."
require 'net/protocol'
View
10 config/initializers/session_store.rb
@@ -37,12 +37,16 @@
config[:db] ||= config[:database]
end
-ActionController::Base.session = config
-ActionController::Base.session_store = session_store
+if Rails.version < "3.0"
+ ActionController::Base.session = config
+ ActionController::Base.session_store = session_store
+else
+ CanvasRails::Application.config.session_store(session_store, config)
+end
ActionController::Flash::FlashHash.class_eval do
def store(session, key = "flash")
return session.delete(key) if self.empty?
session[key] = self
end
-end
+end
View
141 config/shared_boot.rb
@@ -0,0 +1,141 @@
+# this file is shared config between rails 2 and rails 3 (config/environment.rb and config/application.rb)
+# it will get folded into config/application.rb once the transition to rails 3 is complete
+
+# Settings in config/environments/* take precedence over those specified here.
+# Application configuration should go into files in config/initializers
+# -- all .rb files in that directory are automatically loaded.
+# See Rails::Configuration for more options.
+
+# Make Time.zone default to the specified zone, and make Active Record store time values
+# in the database in UTC, and return them converted to the specified local zone.
+# Run "rake -D time" for a list of tasks for finding time zone names. Comment line to use default local time.
+config.time_zone = 'UTC'
+
+if ENV['RUNNING_AS_DAEMON'] == 'true'
+ config.log_path = Rails.root+'log/delayed_job.log'
+end
+
+log_config = File.exists?(Rails.root+"config/logging.yml") && YAML.load_file(Rails.root+"config/logging.yml")[RAILS_ENV]
+log_config = { 'logger' => 'rails', 'log_level' => 'debug' }.merge(log_config || {})
+opts = {}
+require 'canvas/logger'
+log_level = ActiveSupport::BufferedLogger.const_get(log_config['log_level'].to_s.upcase)
+opts[:skip_thread_context] = true if log_config['log_context'] == false
+case log_config["logger"]
+when "syslog"
+ require 'syslog_wrapper'
+ log_config["app_ident"] ||= "canvas-lms"
+ log_config["daemon_ident"] ||= "canvas-lms-daemon"
+ facilities = 0
+ (log_config["facilities"] || []).each do |facility|
+ facilities |= Syslog.const_get "LOG_#{facility.to_s.upcase}"
+ end
+ ident = ENV['RUNNING_AS_DAEMON'] == 'true' ? log_config["daemon_ident"] : log_config["app_ident"]
+ opts[:include_pid] = true if log_config["include_pid"] == true
+ config.logger = RAILS_DEFAULT_LOGGER = SyslogWrapper.new(ident, facilities, opts)
+ config.logger.level = log_level
+else
+ log_path = Rails.version >= "3.0" ? config.paths.log.first : config.log_path
+ config.logger = RAILS_DEFAULT_LOGGER = CanvasLogger.new(log_path, log_level, opts)
+end
+
+# Activate observers that should always be running
+config.active_record.observers = [:cacher, :stream_item_cache]
+
+config.autoload_paths += %W(#{Rails.root}/app/middleware
+ #{Rails.root}/app/observers
+ #{Rails.root}/app/presenters)
+
+if Rails.version < "3.0"
+ # XXX: Rails3 needs SessionsTimeout
+ config.middleware.insert_after(ActionController::Base.session_store, 'SessionsTimeout')
+ config.middleware.insert_before('ActionController::ParamsParser', 'LoadAccount')
+ config.middleware.insert_before('ActionController::ParamsParser', 'StatsTiming')
+ config.middleware.insert_before('ActionController::ParamsParser', 'PreventNonMultipartParse')
+ config.middleware.insert_before('ActionController::ParamsParser', "RequestContextGenerator")
+else
+ config.middleware.insert_before('ActionDispatch::ParamsParser', 'LoadAccount')
+ config.middleware.insert_before('ActionDispatch::ParamsParser', 'StatsTiming')
+ config.middleware.insert_before('ActionDispatch::ParamsParser', 'PreventNonMultipartParse')
+ config.middleware.insert_before('ActionDispatch::ParamsParser', "RequestContextGenerator")
+end
+config.to_prepare do
+ require_dependency 'canvas/plugins/default_plugins'
+ ActiveSupport::JSON::Encoding.escape_html_entities_in_json = true
+end
+
+# this patch is perfectly placed to go in as soon as the PostgreSQLAdapter
+# is required for the first time, but before it's actually used
+# XXX: Rails3
+if Rails.version < "3.0"
+ Rails::Initializer.class_eval do
+ def initialize_database_with_postgresql_patches
+ initialize_database_without_postgresql_patches
+
+ if defined?(ActiveRecord::ConnectionAdapters::PostgreSQLAdapter)
+ ActiveRecord::Base.class_eval do
+ # Override to support custom postgresql connection parameters
+ def self.postgresql_connection(config) # :nodoc:
+ config = config.symbolize_keys
+ config[:user] = config.delete(:username)
+
+ if config.has_key?(:database)
+ config[:dbname] = config.delete(:database)
+ else
+ raise ArgumentError, "No database specified. Missing argument: database."
+ end
+
+ # The postgres drivers don't allow the creation of an unconnected PGconn object,
+ # so just pass a nil connection object for the time being.
+ ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.new(nil, logger, [config], config)
+ end
+ end
+
+ # now let's try this again
+ ActiveRecord::Base.establish_connection
+ end
+ end
+ alias_method_chain :initialize_database, :postgresql_patches
+ end
+end
+
+# We need to make sure that safe_yaml is loaded *after* the YAML engine
+# is switched to Syck (which DelayedJob needs for now). Otherwise we
+# won't have access to (safe|unsafe)_load.
+require 'yaml'
+YAML::ENGINE.yamler = 'syck' if defined?(YAML::ENGINE)
+require 'safe_yaml'
+YAML.enable_symbol_parsing!
+# We don't need to be reminded that safe loads are being used everywhere.
+SafeYAML::OPTIONS[:suppress_warnings] = true
+
+# This tag whitelist is syck specific. We'll need to tweak it when we upgrade to psych.
+# See the tests in spec/lib/safe_yaml_spec.rb
+YAML.whitelist.add(*%w[
+ tag:ruby.yaml.org,2002:symbol
+ tag:yaml.org,2002:map:HashWithIndifferentAccess
+ tag:ruby.yaml.org,2002:object:OpenStruct
+ tag:ruby.yaml.org,2002:object:Scribd::Document
+ tag:ruby.yaml.org,2002:object:Mime::Type
+ tag:ruby.yaml.org,2002:object:URI::HTTP
+ tag:ruby.yaml.org,2002:object:URI::HTTPS
+ tag:ruby.yaml.org,2002:object:OpenObject
+])
+YAML.whitelist.add('tag:ruby.yaml.org,2002:object:Class') { |classname| Canvas::Migration.valid_converter_classes.include?(classname) }
+
+# Extend any base classes, even gem classes
+Dir.glob("#{Rails.root}/lib/ext/**/*.rb").each { |file| require file }
+
+# tell Rails to use the native XML parser instead of REXML
+ActiveSupport::XmlMini.backend = 'LibXML'
+
+class NotImplemented < StandardError; end
+
+if defined?(PhusionPassenger)
+ PhusionPassenger.on_event(:starting_worker_process) do |forked|
+ if forked
+ # We're in smart spawning mode, and need to make unique connections for this fork.
+ Canvas.reconnect_redis
+ end
+ end
+end
View
12 lib/canvas.rb
@@ -61,6 +61,9 @@ def self.reconnect_redis
end
def self.cache_store_config(rails_env = :current, nil_is_nil = false)
+ # this method is called really early in the bootup process, and autoloading
+ # might not be available yet, so we need to manually require Setting
+ require_dependency "app/models/setting"
cache_store_config = {
'cache_store' => 'mem_cache_store',
}.merge(Setting.from_config('cache_store', rails_env) || {})
@@ -74,6 +77,7 @@ def self.cache_store_config(rails_env = :current, nil_is_nil = false)
end
when 'redis_store'
Bundler.require 'redis'
+ require_dependency 'canvas/redis'
Canvas::Redis.patch
# merge in redis.yml, but give precedence to cache_store.yml
#
@@ -86,10 +90,12 @@ def self.cache_store_config(rails_env = :current, nil_is_nil = false)
when 'memory_store'
config = :memory_store
when 'nil_store'
- config = :nil_store
+ require 'nil_store'
+ config = NilStore.new
end
if !config && !nil_is_nil
- config = :nil_store
+ require 'nil_store'
+ config = NilStore.new
end
config
end
@@ -128,7 +134,7 @@ def self.sample_cpu_time
def self.reloadable_plugin(dirname)
return unless Rails.env.development?
base_path = File.expand_path(dirname)
- ActiveSupport::Dependencies.load_once_paths.reject! { |p|
+ ActiveSupport::Dependencies.autoload_once_paths.reject! { |p|
p[0, base_path.length] == base_path
}
end
View
8 lib/canvas/migration/worker.rb
@@ -17,11 +17,10 @@
#
require 'action_controller'
-require 'action_controller/test_process.rb'
+# XXX: Rails3 doesn't have ActionController::TestUploadedFile, time to fix this
+require 'action_controller/test_process.rb' if Rails.version < "3.0"
-module Canvas::Migration
-module Worker
-
+module Canvas::Migration::Worker
def self.get_converter(settings)
Canvas::Migration::PackageIdentifier.new(settings).get_converter
end
@@ -84,4 +83,3 @@ def self.clear_exported_data(folder)
end
end
end
-end
View
111 lib/cc/importer/cc_worker.rb
@@ -15,72 +15,67 @@
# You should have received a copy of the GNU Affero General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
#
-module Canvas::Migration
- module Worker
- class CCWorker < Struct.new(:migration_id)
+class Canvas::Migration::Worker::CCWorker < Struct.new(:migration_id)
+ def perform
+ cm = ContentMigration.find_by_id migration_id
+ begin
+ cm.fast_update_progress(1)
+ settings = cm.migration_settings.clone
+ settings[:content_migration_id] = migration_id
+ settings[:user_id] = cm.user_id
+ settings[:attachment_id] = cm.attachment.id rescue nil
+ settings[:content_migration] = cm
- def perform
- cm = ContentMigration.find_by_id migration_id
- begin
- cm.fast_update_progress(1)
- settings = cm.migration_settings.clone
- settings[:content_migration_id] = migration_id
- settings[:user_id] = cm.user_id
- settings[:attachment_id] = cm.attachment.id rescue nil
- settings[:content_migration] = cm
-
- converter_class = settings[:converter_class] || Worker::get_converter(settings)
- converter = converter_class.new(settings)
+ converter_class = settings[:converter_class] || Canvas::Migration::Worker::get_converter(settings)
+ converter = converter_class.new(settings)
- course = converter.export
- export_folder_path = course[:export_folder_path]
- overview_file_path = course[:overview_file_path]
+ course = converter.export
+ export_folder_path = course[:export_folder_path]
+ overview_file_path = course[:overview_file_path]
- if overview_file_path
- file = File.new(overview_file_path)
- Canvas::Migration::Worker::upload_overview_file(file, cm)
- cm.fast_update_progress(95)
- end
- if export_folder_path
- Canvas::Migration::Worker::upload_exported_data(export_folder_path, cm)
- Canvas::Migration::Worker::clear_exported_data(export_folder_path)
- cm.fast_update_progress(100)
- end
+ if overview_file_path
+ file = File.new(overview_file_path)
+ Canvas::Migration::Worker::upload_overview_file(file, cm)
+ cm.fast_update_progress(95)
+ end
+ if export_folder_path
+ Canvas::Migration::Worker::upload_exported_data(export_folder_path, cm)
+ Canvas::Migration::Worker::clear_exported_data(export_folder_path)
+ cm.fast_update_progress(100)
+ end
+
+ cm.migration_settings[:worker_class] = converter_class.name
+ if !cm.migration_settings[:migration_ids_to_import] || !cm.migration_settings[:migration_ids_to_import][:copy]
+ cm.migration_settings[:migration_ids_to_import] = {:copy=>{:everything => true}}
+ end
+ cm.workflow_state = :exported
+ cm.progress = 0
+ saved = cm.save
- cm.migration_settings[:worker_class] = converter_class.name
- if !cm.migration_settings[:migration_ids_to_import] || !cm.migration_settings[:migration_ids_to_import][:copy]
- cm.migration_settings[:migration_ids_to_import] = {:copy=>{:everything => true}}
- end
- cm.workflow_state = :exported
- cm.progress = 0
- saved = cm.save
-
- if cm.import_immediately?
- cm.import_content_without_send_later
- cm.progress = 100
- saved = cm.save
- if converter.respond_to?(:post_process)
- converter.post_process
- end
- end
-
- saved
- rescue => e
- report = ErrorReport.log_exception(:content_migration, e)
- if cm
- cm.workflow_state = :failed
- cm.migration_settings[:last_error] = "ErrorReport:#{report.id}"
- cm.save
- end
+ if cm.import_immediately?
+ cm.import_content_without_send_later
+ cm.progress = 100
+ saved = cm.save
+ if converter.respond_to?(:post_process)
+ converter.post_process
end
end
- def self.enqueue(content_migration)
- Delayed::Job.enqueue(new(content_migration.id),
- :priority => Delayed::LOW_PRIORITY,
- :max_attempts => 1,
- :strand => content_migration.strand)
+ saved
+ rescue => e
+ report = ErrorReport.log_exception(:content_migration, e)
+ if cm
+ cm.workflow_state = :failed
+ cm.migration_settings[:last_error] = "ErrorReport:#{report.id}"
+ cm.save
end
end
end
+
+ def self.enqueue(content_migration)
+ Delayed::Job.enqueue(new(content_migration.id),
+ :priority => Delayed::LOW_PRIORITY,
+ :max_attempts => 1,
+ :strand => content_migration.strand)
+ end
end
View
8 lib/csv_compat.rb
@@ -0,0 +1,8 @@
+if RUBY_VERSION < "1.9"
+ require 'fastercsv'
+else
+ # 1.9 has a built-in equivalent to fastercsv
+ # make an alias for CSV, which has replaced FasterCSV
+ require 'csv'
+ FasterCSV = CSV
+end
View
2  lib/ext/array.rb
@@ -16,6 +16,8 @@
# with this program. If not, see <http://www.gnu.org/licenses/>.
#
+require 'csv_compat'
+
class Array
def to_csv(options = {})
if all? { |e| e.respond_to?(:to_row) }
View
1  lib/kaltura/kaltura_client_v3.rb
@@ -54,6 +54,7 @@ def self.config
return nil unless res && res['partner_id'] && res['subpartner_id']
# default settings
+ res = res.dup
res['max_file_size_bytes'] = 500.megabytes unless res['max_file_size_bytes'].to_i > 0
res
View
7 lib/stubs/shard.rb
@@ -86,8 +86,10 @@ def self.included(klass)
end
ActiveRecord::Base.class_eval do
- class << self
- VALID_FIND_OPTIONS << :shard
+ if Rails.version < "3.0"
+ class << self
+ VALID_FIND_OPTIONS << :shard
+ end
end
def shard
@@ -120,6 +122,7 @@ def shard
def with_each_shard(*shards_or_options)
options = shards_or_options.pop if shards_or_options.last.is_a?(Hash)
scope = self
+ # XXX: Rails3 -- fake_arel should help with fixing this and maintaining rails 2 compat
scope = self.scoped(options) if options
scope = yield(scope) if block_given?
Array(scope)
View
6 script/rails
@@ -0,0 +1,6 @@
+#!/usr/bin/env ruby
+# This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application.
+
+APP_PATH = File.expand_path('../../config/application', __FILE__)
+require File.expand_path('../../config/boot', __FILE__)
+require 'rails/commands'
View
0  script/startup.bat 100644 → 100755
File mode changed
View
13 spec/lib/cc/importer/common_cartridge_converter_spec.rb
@@ -11,6 +11,11 @@
@course_data = @converter.course.with_indifferent_access
@course_data['all_files_export'] ||= {}
@course_data['all_files_export']['file_path'] = @course_data['all_files_zip']
+
+ @course = course
+ @migration = ContentMigration.create(:context => @course)
+ @migration.migration_settings[:migration_ids_to_import] = {:copy => {}}
+ @course.import_from_migration(@course_data, nil, @migration)
end
after(:all) do
@@ -18,13 +23,7 @@
if File.exists?(@export_folder)
FileUtils::rm_rf(@export_folder)
end
- end
-
- before(:each) do
- @course = course
- @migration = ContentMigration.create(:context => @course)
- @migration.migration_settings[:migration_ids_to_import] = {:copy => {}}
- @course.import_from_migration(@course_data, nil, @migration)
+ truncate_all_tables
end
it "should import webcontent" do
View
2  spec/lib/gradebook_csv_parser_spec.rb
@@ -18,6 +18,8 @@
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper.rb')
+require 'gradebook_csv_parser'
+
describe CSVParser do
context "initialize" do
it "should require contents" do
View
3  spec/spec_helper.rb
@@ -17,7 +17,8 @@
#
ENV["RAILS_ENV"] = 'test'
-require File.expand_path(File.dirname(__FILE__) + "/../config/environment") unless defined?(Rails)
+
+require File.expand_path('../../config/environment', __FILE__) unless defined?(Rails)
require 'spec'
# require 'spec/autorun'
require 'spec/rails'
View
6 vendor/plugins/respondus_soap_endpoint/init.rb
@@ -20,5 +20,9 @@
# I guess we just gotta hope that no middlewares after that one have any
# useful-to-this-plugin functionality. At least we still get the AR query
# cache.
- Rails.configuration.middleware.insert_before 'ActionController::ParamsParser', 'RespondusAPIMiddleware'
+ if Rails.version < "3.0"
+ Rails.configuration.middleware.insert_before 'ActionController::ParamsParser', 'RespondusAPIMiddleware'
+ else
+ Rails.configuration.middleware.insert_before 'ActionDispatch::ParamsParser', 'RespondusAPIMiddleware'
+ end
end
Please sign in to comment.
Something went wrong with that request. Please try again.