Skip to content
Browse files

Reorganize autoloads:

  * A new module (ActiveSupport::Autoload) is provide that extends
    autoloading with new behavior.
  * All autoloads in modules that have extended ActiveSupport::Autoload
    will be eagerly required in threadsafe environments
  * Autoloads can optionally leave off the path if the path is the same
    as full_constant_name.underscore
  * It is possible to specify that a group of autoloads live under an
    additional path. For instance, all of ActionDispatch's middlewares
    are ActionDispatch::MiddlewareName, but they live under 
    "action_dispatch/middlewares/middleware_name"
  * It is possible to specify that a group of autoloads are all found
    at the same path. For instance, a number of exceptions might all
    be declared there.
  * One consequence of this is that testing-related constants are not
    autoloaded. To get the testing helpers for a given component,
    require "component_name/test_case". For instance, "action_controller/test_case".
  * test_help.rb, which is automatically required by a Rails application's
    test helper, requires the test_case.rb for all active components, so
    this change will not be disruptive in existing or new applications.
  • Loading branch information...
1 parent 399909b commit c1304098cca8a9247a9ad1461a1a343354650843 Carlhuda committed Dec 2, 2009
Showing with 989 additions and 793 deletions.
  1. +18 −16 actionmailer/lib/action_mailer.rb
  2. +1 −1 actionmailer/lib/action_mailer/base.rb
  3. +1 −1 actionmailer/lib/action_mailer/delivery_method/file.rb
  4. +16 −14 actionmailer/lib/action_mailer/mail_helper.rb
  5. +15 −10 actionpack/lib/abstract_controller.rb
  6. +1 −1 actionpack/lib/abstract_controller/rendering_controller.rb
  7. +61 −55 actionpack/lib/action_controller.rb
  8. +1 −1 actionpack/lib/action_controller/base.rb
  9. +4 −3 actionpack/lib/action_controller/caching.rb
  10. +2 −0 actionpack/lib/action_controller/deprecated/integration_test.rb
  11. +1 −1 actionpack/lib/action_controller/metal/compatibility.rb
  12. +1 −1 actionpack/lib/action_controller/metal/helpers.rb
  13. 0 actionpack/lib/action_controller/metal/{rescuable.rb → rescue.rb}
  14. +3 −0 actionpack/lib/action_controller/{testing → }/test_case.rb
  15. +2 −0 actionpack/lib/action_controller/vendor/html-scanner.rb
  16. +21 −20 actionpack/lib/action_dispatch.rb
  17. +2 −2 actionpack/lib/action_dispatch/middleware/show_exceptions.rb
  18. +6 −0 actionpack/lib/action_dispatch/test_case.rb
  19. +12 −14 actionpack/lib/action_view.rb
  20. +1 −1 actionpack/lib/action_view/base.rb
  21. +1 −1 actionpack/lib/action_view/paths.rb
  22. +11 −4 actionpack/lib/action_view/{template → }/template.rb
  23. +77 −75 actionpack/lib/action_view/template/error.rb
  24. +26 −21 actionpack/lib/action_view/template/handler.rb
  25. +49 −47 actionpack/lib/action_view/template/handlers.rb
  26. +2 −2 actionpack/lib/action_view/template/handlers/builder.rb
  27. +2 −2 actionpack/lib/action_view/template/handlers/erb.rb
  28. +2 −2 actionpack/lib/action_view/template/handlers/rjs.rb
  29. +3 −3 actionpack/lib/action_view/template/resolver.rb
  30. +36 −34 actionpack/lib/action_view/template/text.rb
  31. +1 −1 actionpack/lib/action_view/test_case.rb
  32. +13 −13 actionpack/test/abstract/layouts_test.rb
  33. +1 −1 actionpack/test/abstract/render_test.rb
  34. +1 −1 actionpack/test/controller/helper_test.rb
  35. +1 −1 actionpack/test/controller/layout_test.rb
  36. +4 −4 actionpack/test/template/render_test.rb
  37. +23 −20 activemodel/lib/active_model.rb
  38. +1 −0 activemodel/test/cases/helper.rb
  39. +1 −0 activemodel/test/cases/tests_database.rb
  40. +53 −47 activerecord/lib/active_record.rb
  41. +9 −7 activeresource/lib/active_resource.rb
  42. +1 −0 activeresource/test/abstract_unit.rb
  43. +3 −3 activeresource/test/cases/base_test.rb
  44. +29 −26 activesupport/lib/active_support/autoload.rb
  45. +37 −0 activesupport/lib/active_support/dependencies/autoload.rb
  46. +341 −337 activesupport/lib/active_support/testing/performance.rb
  47. +80 −0 activesupport/test/autoload.rb
  48. +2 −0 activesupport/test/fixtures/autoload/another_class.rb
  49. +2 −0 activesupport/test/fixtures/autoload/some_class.rb
  50. +1 −0 railties/lib/rails/console_app.rb
  51. +6 −0 railties/lib/rails/test_help.rb
  52. +1 −0 railties/test/rails_info_controller_test.rb
View
34 actionmailer/lib/action_mailer.rb
@@ -25,32 +25,34 @@
$:.unshift(actionpack_path) if File.directory?(actionpack_path)
require 'action_controller'
require 'action_view'
+require 'active_support/autoload'
module ActionMailer
- def self.load_all!
- [Base, Part, ::Text::Format, ::Net::SMTP]
- end
-
- autoload :AdvAttrAccessor, 'action_mailer/adv_attr_accessor'
- autoload :DeprecatedBody, 'action_mailer/deprecated_body'
- autoload :Base, 'action_mailer/base'
- autoload :DeliveryMethod, 'action_mailer/delivery_method'
- autoload :Part, 'action_mailer/part'
- autoload :PartContainer, 'action_mailer/part_container'
- autoload :Quoting, 'action_mailer/quoting'
- autoload :TestCase, 'action_mailer/test_case'
- autoload :TestHelper, 'action_mailer/test_helper'
- autoload :Utils, 'action_mailer/utils'
+ extend ::ActiveSupport::Autoload
+
+ autoload :AdvAttrAccessor
+ autoload :DeprecatedBody
+ autoload :Base
+ autoload :DeliveryMethod
+ autoload :MailHelper
+ autoload :Part
+ autoload :PartContainer
+ autoload :Quoting
+ autoload :TestHelper
+ autoload :Utils
end
module Text
+ extend ActiveSupport::Autoload
+
autoload :Format, 'action_mailer/vendor/text_format'
end
module Net
- autoload :SMTP, 'net/smtp'
+ extend ActiveSupport::Autoload
+
+ autoload :SMTP
end
-autoload :MailHelper, 'action_mailer/mail_helper'
require 'action_mailer/vendor/tmail'
View
2 actionmailer/lib/action_mailer/base.rb
@@ -258,7 +258,7 @@ class Base
include AbstractController::Layouts
include AbstractController::Helpers
- helper MailHelper
+ helper ActionMailer::MailHelper
if Object.const_defined?(:ActionController)
include ActionController::UrlWriter
View
2 actionmailer/lib/action_mailer/delivery_method/file.rb
@@ -6,7 +6,7 @@ module DeliveryMethod
# A delivery method implementation which writes all mails to a file.
class File < Method
self.settings = {
- :location => defined?(Rails) ? "#{Rails.root}/tmp/mails" : "#{Dir.tmpdir}/mails"
+ :location => defined?(Rails.root) ? "#{Rails.root}/tmp/mails" : "#{Dir.tmpdir}/mails"
}
def perform_delivery(mail)
View
30 actionmailer/lib/action_mailer/mail_helper.rb
@@ -1,17 +1,19 @@
-module MailHelper
- # Uses Text::Format to take the text and format it, indented two spaces for
- # each line, and wrapped at 72 columns.
- def block_format(text)
- formatted = text.split(/\n\r\n/).collect { |paragraph|
- Text::Format.new(
- :columns => 72, :first_indent => 2, :body_indent => 2, :text => paragraph
- ).format
- }.join("\n")
+module ActionMailer
+ module MailHelper
+ # Uses Text::Format to take the text and format it, indented two spaces for
+ # each line, and wrapped at 72 columns.
+ def block_format(text)
+ formatted = text.split(/\n\r\n/).collect { |paragraph|
+ Text::Format.new(
+ :columns => 72, :first_indent => 2, :body_indent => 2, :text => paragraph
+ ).format
+ }.join("\n")
- # Make list points stand on their own line
- formatted.gsub!(/[ ]*([*]+) ([^*]*)/) { |s| " #{$1} #{$2.strip}\n" }
- formatted.gsub!(/[ ]*([#]+) ([^#]*)/) { |s| " #{$1} #{$2.strip}\n" }
+ # Make list points stand on their own line
+ formatted.gsub!(/[ ]*([*]+) ([^*]*)/) { |s| " #{$1} #{$2.strip}\n" }
+ formatted.gsub!(/[ ]*([#]+) ([^#]*)/) { |s| " #{$1} #{$2.strip}\n" }
- formatted
+ formatted
+ end
end
-end
+end
View
25 actionpack/lib/abstract_controller.rb
@@ -2,15 +2,20 @@
require "active_support/core_ext/module/delegation"
module AbstractController
- autoload :Base, "abstract_controller/base"
- autoload :Callbacks, "abstract_controller/callbacks"
- autoload :Helpers, "abstract_controller/helpers"
- autoload :Layouts, "abstract_controller/layouts"
- autoload :LocalizedCache, "abstract_controller/localized_cache"
- autoload :Logger, "abstract_controller/logger"
- autoload :RenderingController, "abstract_controller/rendering_controller"
+ extend ActiveSupport::Autoload
+
+ autoload :Base
+ autoload :Callbacks
+ autoload :Helpers
+ autoload :Layouts
+ autoload :LocalizedCache
+ autoload :Logger
+ autoload :RenderingController
+
# === Exceptions
- autoload :ActionNotFound, "abstract_controller/exceptions"
- autoload :DoubleRenderError, "abstract_controller/exceptions"
- autoload :Error, "abstract_controller/exceptions"
+ autoload_at "abstract_controller/exceptions" do
+ autoload :ActionNotFound
+ autoload :DoubleRenderError
+ autoload :Error
+ end
end
View
2 actionpack/lib/abstract_controller/rendering_controller.rb
@@ -115,7 +115,7 @@ def self.body_to_s(body)
# _partial<TrueClass, FalseClass>:: Whether or not the file to look up is a partial
def _determine_template(options)
if options.key?(:text)
- options[:_template] = ActionView::TextTemplate.new(options[:text], format_for_text)
+ options[:_template] = ActionView::Template::Text.new(options[:text], format_for_text)
elsif options.key?(:inline)
handler = ActionView::Template.handler_class_for_extension(options[:type] || "erb")
template = ActionView::Template.new(options[:inline], "inline #{options[:inline].inspect}", handler, {})
View
116 actionpack/lib/action_controller.rb
@@ -1,66 +1,72 @@
+require "active_support"
+
module ActionController
- autoload :Base, "action_controller/base"
- autoload :Benchmarking, "action_controller/metal/benchmarking"
- autoload :ConditionalGet, "action_controller/metal/conditional_get"
- autoload :Configuration, "action_controller/metal/configuration"
- autoload :Head, "action_controller/metal/head"
- autoload :Helpers, "action_controller/metal/helpers"
- autoload :HideActions, "action_controller/metal/hide_actions"
- autoload :Layouts, "action_controller/metal/layouts"
- autoload :Metal, "action_controller/metal"
- autoload :Middleware, "action_controller/middleware"
- autoload :RackConvenience, "action_controller/metal/rack_convenience"
- autoload :Rails2Compatibility, "action_controller/metal/compatibility"
- autoload :Redirector, "action_controller/metal/redirector"
- autoload :RenderingController, "action_controller/metal/rendering_controller"
- autoload :RenderOptions, "action_controller/metal/render_options"
- autoload :Rescue, "action_controller/metal/rescuable"
- autoload :Responder, "action_controller/metal/responder"
- autoload :Session, "action_controller/metal/session"
- autoload :Testing, "action_controller/metal/testing"
- autoload :UrlFor, "action_controller/metal/url_for"
+ extend ActiveSupport::Autoload
- autoload :Caching, 'action_controller/caching'
- autoload :Dispatcher, 'action_controller/dispatch/dispatcher'
- autoload :Integration, 'action_controller/deprecated/integration_test'
- autoload :IntegrationTest, 'action_controller/deprecated/integration_test'
- autoload :MimeResponds, 'action_controller/metal/mime_responds'
- autoload :PerformanceTest, 'action_controller/deprecated/performance_test'
- autoload :PolymorphicRoutes, 'action_controller/polymorphic_routes'
- autoload :RecordIdentifier, 'action_controller/record_identifier'
- autoload :Routing, 'action_controller/deprecated'
- autoload :SessionManagement, 'action_controller/metal/session_management'
- autoload :TestCase, 'action_controller/testing/test_case'
- autoload :TestProcess, 'action_controller/testing/process'
- autoload :UrlRewriter, 'action_controller/url_rewriter'
- autoload :UrlWriter, 'action_controller/url_rewriter'
+ autoload :Base
+ autoload :Caching
+ autoload :PolymorphicRoutes
+ autoload :RecordIdentifier
+ autoload :UrlRewriter
+ autoload :Translation
+ autoload :Metal
+ autoload :Middleware
- autoload :Verification, 'action_controller/metal/verification'
- autoload :Flash, 'action_controller/metal/flash'
- autoload :RequestForgeryProtection, 'action_controller/metal/request_forgery_protection'
- autoload :Streaming, 'action_controller/metal/streaming'
- autoload :HttpAuthentication, 'action_controller/metal/http_authentication'
- autoload :FilterParameterLogging, 'action_controller/metal/filter_parameter_logging'
- autoload :Translation, 'action_controller/translation'
- autoload :Cookies, 'action_controller/metal/cookies'
+ autoload_under "metal" do
+ autoload :Benchmarking
+ autoload :ConditionalGet
+ autoload :Configuration
+ autoload :Head
+ autoload :Helpers
+ autoload :HideActions
+ autoload :Layouts
+ autoload :MimeResponds
+ autoload :RackConvenience
+ autoload :Compatibility
+ autoload :Redirector
+ autoload :RenderingController
+ autoload :RenderOptions
+ autoload :Rescue
+ autoload :Responder
+ autoload :Session
+ autoload :SessionManagement
+ autoload :UrlFor
+ autoload :Verification
+ autoload :Flash
+ autoload :RequestForgeryProtection
+ autoload :Streaming
+ autoload :HttpAuthentication
+ autoload :FilterParameterLogging
+ autoload :Cookies
+ end
- autoload :ActionControllerError, 'action_controller/metal/exceptions'
- autoload :RenderError, 'action_controller/metal/exceptions'
- autoload :RoutingError, 'action_controller/metal/exceptions'
- autoload :MethodNotAllowed, 'action_controller/metal/exceptions'
- autoload :NotImplemented, 'action_controller/metal/exceptions'
- autoload :UnknownController, 'action_controller/metal/exceptions'
- autoload :MissingFile, 'action_controller/metal/exceptions'
- autoload :RenderError, 'action_controller/metal/exceptions'
- autoload :SessionOverflowError, 'action_controller/metal/exceptions'
- autoload :UnknownHttpMethod, 'action_controller/metal/exceptions'
-end
+ autoload :Dispatcher, 'action_controller/dispatch/dispatcher'
+ autoload :PerformanceTest, 'action_controller/deprecated/performance_test'
+ autoload :Routing, 'action_controller/deprecated'
+ autoload :Integration, 'action_controller/deprecated/integration_test'
+ autoload :IntegrationTest, 'action_controller/deprecated/integration_test'
-autoload :HTML, 'action_controller/vendor/html-scanner'
-autoload :AbstractController, 'abstract_controller'
+ autoload :UrlWriter, 'action_controller/url_rewriter'
+
+ autoload_at "action_controller/metal/exceptions" do
+ autoload :ActionControllerError
+ autoload :RenderError
+ autoload :RoutingError
+ autoload :MethodNotAllowed
+ autoload :NotImplemented
+ autoload :UnknownController
+ autoload :MissingFile
+ autoload :RenderError
+ autoload :SessionOverflowError
+ autoload :UnknownHttpMethod
+ end
+end
+# All of these simply register additional autoloads
+require 'abstract_controller'
require 'action_dispatch'
require 'action_view'
+require 'action_controller/vendor/html-scanner'
# Common ActiveSupport usage in ActionController
require "active_support/concern"
View
2 actionpack/lib/action_controller/base.rb
@@ -24,7 +24,7 @@ class Base < Metal
include ActionController::MimeResponds
# Rails 2.x compatibility
- include ActionController::Rails2Compatibility
+ include ActionController::Compatibility
include ActionController::Cookies
include ActionController::Session
View
7 actionpack/lib/action_controller/caching.rb
@@ -30,10 +30,11 @@ module ActionController #:nodoc:
# config.action_controller.cache_store = MyOwnStore.new("parameter")
module Caching
extend ActiveSupport::Concern
+ extend ActiveSupport::Autoload
- autoload :Actions, 'action_controller/caching/actions'
- autoload :Fragments, 'action_controller/caching/fragments'
- autoload :Pages, 'action_controller/caching/pages'
+ autoload :Actions
+ autoload :Fragments
+ autoload :Pages
autoload :Sweeper, 'action_controller/caching/sweeping'
autoload :Sweeping, 'action_controller/caching/sweeping'
View
2 actionpack/lib/action_controller/deprecated/integration_test.rb
@@ -1,2 +1,4 @@
+require "action_dispatch/testing/integration"
+
ActionController::Integration = ActionDispatch::Integration
ActionController::IntegrationTest = ActionDispatch::IntegrationTest
View
2 actionpack/lib/action_controller/metal/compatibility.rb
@@ -1,5 +1,5 @@
module ActionController
- module Rails2Compatibility
+ module Compatibility
extend ActiveSupport::Concern
class ::ActionController::ActionControllerError < StandardError #:nodoc:
View
2 actionpack/lib/action_controller/metal/helpers.rb
@@ -52,7 +52,7 @@ module Helpers
included do
# Set the default directory for helpers
extlib_inheritable_accessor(:helpers_dir) do
- defined?(Rails) ? "#{Rails.root}/app/helpers" : "app/helpers"
+ defined?(Rails.root) ? "#{Rails.root}/app/helpers" : "app/helpers"
end
end
View
0 .../lib/action_controller/metal/rescuable.rb → ...ack/lib/action_controller/metal/rescue.rb
File renamed without changes.
View
3 ...ib/action_controller/testing/test_case.rb → ...onpack/lib/action_controller/test_case.rb
@@ -1,5 +1,8 @@
require 'active_support/test_case'
require 'rack/session/abstract/id'
+require 'action_controller/metal/testing'
+require 'action_controller/testing/process'
+require 'action_dispatch/test_case'
module ActionController
class TestRequest < ActionDispatch::TestRequest #:nodoc:
View
2 actionpack/lib/action_controller/vendor/html-scanner.rb
@@ -1,6 +1,8 @@
$LOAD_PATH << "#{File.dirname(__FILE__)}/html-scanner"
module HTML
+ extend ActiveSupport::Autoload
+
autoload :CDATA, 'html/node'
autoload :Document, 'html/document'
autoload :FullSanitizer, 'html/sanitizer'
View
41 actionpack/lib/action_dispatch.rb
@@ -28,37 +28,38 @@ module Rack
end
module ActionDispatch
- autoload :Request, 'action_dispatch/http/request'
- autoload :Response, 'action_dispatch/http/response'
- autoload :StatusCodes, 'action_dispatch/http/status_codes'
- autoload :Utils, 'action_dispatch/http/utils'
+ extend ActiveSupport::Autoload
- autoload :Callbacks, 'action_dispatch/middleware/callbacks'
- autoload :MiddlewareStack, 'action_dispatch/middleware/stack'
- autoload :ParamsParser, 'action_dispatch/middleware/params_parser'
- autoload :Rescue, 'action_dispatch/middleware/rescue'
- autoload :ShowExceptions, 'action_dispatch/middleware/show_exceptions'
- autoload :Static, 'action_dispatch/middleware/static'
- autoload :StringCoercion, 'action_dispatch/middleware/string_coercion'
+ autoload_under "http" do
+ autoload :Request
+ autoload :Response
+ autoload :StatusCodes
+ autoload :Utils
+ end
- autoload :Routing, 'action_dispatch/routing'
+ autoload_under "middleware" do
+ autoload :Callbacks
+ autoload :ParamsParser
+ autoload :Rescue
+ autoload :ShowExceptions
+ autoload :Static
+ autoload :StringCoercion
+ end
- autoload :Assertions, 'action_dispatch/testing/assertions'
- autoload :Integration, 'action_dispatch/testing/integration'
- autoload :IntegrationTest, 'action_dispatch/testing/integration'
- autoload :PerformanceTest, 'action_dispatch/testing/performance_test'
- autoload :TestRequest, 'action_dispatch/testing/test_request'
- autoload :TestResponse, 'action_dispatch/testing/test_response'
+ autoload :MiddlewareStack, 'action_dispatch/middleware/stack'
+ autoload :Routing
autoload :HTML, 'action_controller/vendor/html-scanner'
module Http
- autoload :Headers, 'action_dispatch/http/headers'
+ extend ActiveSupport::Autoload
+
+ autoload :Headers
end
module Session
autoload :AbstractStore, 'action_dispatch/middleware/session/abstract_store'
- autoload :CookieStore, 'action_dispatch/middleware/session/cookie_store'
+ autoload :CookieStore, 'action_dispatch/middleware/session/cookie_store'
autoload :MemCacheStore, 'action_dispatch/middleware/session/mem_cache_store'
end
end
View
4 actionpack/lib/action_dispatch/middleware/show_exceptions.rb
@@ -29,7 +29,7 @@ class ShowExceptions
'ActionView::MissingTemplate' => 'missing_template',
'ActionController::RoutingError' => 'routing_error',
ActionController::UnknownAction.name => 'unknown_action',
- 'ActionView::TemplateError' => 'template_error'
+ 'ActionView::Template::Error' => 'template_error'
})
FAILSAFE_RESPONSE = [500, {'Content-Type' => 'text/html'},
@@ -119,7 +119,7 @@ def log_error(exception)
return unless logger
ActiveSupport::Deprecation.silence do
- if ActionView::TemplateError === exception
+ if ActionView::Template::Error === exception
logger.fatal(exception.to_s)
else
logger.fatal(
View
6 actionpack/lib/action_dispatch/test_case.rb
@@ -0,0 +1,6 @@
+require "action_dispatch/testing/assertions"
+require "action_dispatch/testing/integration"
+require "action_dispatch/testing/performance_test"
+require "action_dispatch/testing/test_request"
+require "action_dispatch/testing/test_response"
+require "action_dispatch/testing/integration"
View
26 actionpack/lib/action_view.rb
@@ -24,27 +24,25 @@
require File.join(File.dirname(__FILE__), "action_pack")
module ActionView
- def self.load_all!
- [Context, Base, TemplateError]
+ extend ActiveSupport::Autoload
+
+ autoload :Base
+ autoload :Context
+ autoload :Template
+ autoload :Helpers
+ autoload :SafeBuffer
+
+
+ autoload_under "render" do
+ autoload :Partials
+ autoload :Rendering
end
- autoload :Base, 'action_view/base'
- autoload :Context, 'action_view/context'
- autoload :Helpers, 'action_view/helpers'
autoload :MissingTemplate, 'action_view/base'
- autoload :Partials, 'action_view/render/partials'
autoload :Resolver, 'action_view/template/resolver'
autoload :PathResolver, 'action_view/template/resolver'
autoload :PathSet, 'action_view/paths'
- autoload :Rendering, 'action_view/render/rendering'
- autoload :Template, 'action_view/template/template'
- autoload :TemplateError, 'action_view/template/error'
- autoload :TemplateHandler, 'action_view/template/handler'
- autoload :TemplateHandlers, 'action_view/template/handlers'
- autoload :TextTemplate, 'action_view/template/text'
- autoload :Helpers, 'action_view/helpers'
autoload :FileSystemResolverWithFallback, 'action_view/template/resolver'
- autoload :SafeBuffer, 'action_view/safe_buffer'
end
require 'action_view/erb/util'
View
2 actionpack/lib/action_view/base.rb
@@ -196,7 +196,7 @@ def reset_formats(formats)
end
class << self
- delegate :erb_trim_mode=, :to => 'ActionView::TemplateHandlers::ERB'
+ delegate :erb_trim_mode=, :to => 'ActionView::Template::Handlers::ERB'
delegate :logger, :to => 'ActionController::Base', :allow_nil => true
end
View
2 actionpack/lib/action_view/paths.rb
@@ -4,7 +4,7 @@ def self.type_cast(obj, cache = nil)
# TODO: Clean this up
if obj.is_a?(String)
if cache.nil?
- cache = !defined?(Rails) || Rails.application.config.cache_classes
+ cache = !defined?(Rails.application) || Rails.application.config.cache_classes
end
FileSystemResolverWithFallback.new(obj, :cache => cache)
else
View
15 ...pack/lib/action_view/template/template.rb → actionpack/lib/action_view/template.rb
@@ -6,7 +6,14 @@
module ActionView
class Template
- extend TemplateHandlers
+ extend ActiveSupport::Autoload
+
+ autoload :Error
+ autoload :Handler
+ autoload :Handlers
+ autoload :Text
+
+ extend Template::Handlers
attr_reader :source, :identifier, :handler, :mime_type, :formats, :details
def initialize(source, identifier, handler, details)
@@ -32,11 +39,11 @@ def render(view, locals, &block)
view.send(method_name, locals, &block)
end
rescue Exception => e
- if e.is_a?(TemplateError)
+ if e.is_a?(Template::Error)
e.sub_template_of(self)
raise e
else
- raise TemplateError.new(self, view.assigns, e)
+ raise Template::Error.new(self, view.assigns, e)
end
end
@@ -103,7 +110,7 @@ def #{method_name}(local_assigns)
logger.debug "Backtrace: #{e.backtrace.join("\n")}"
end
- raise ActionView::TemplateError.new(self, {}, e)
+ raise ActionView::Template::Error.new(self, {}, e)
end
end
View
152 actionpack/lib/action_view/template/error.rb
@@ -1,101 +1,103 @@
require "active_support/core_ext/enumerable"
module ActionView
- # The TemplateError exception is raised when the compilation of the template fails. This exception then gathers a
- # bunch of intimate details and uses it to report a very precise exception message.
- class TemplateError < ActionViewError #:nodoc:
- SOURCE_CODE_RADIUS = 3
+ class Template
+ # The Template::Error exception is raised when the compilation of the template fails. This exception then gathers a
+ # bunch of intimate details and uses it to report a very precise exception message.
+ class Error < ActionViewError #:nodoc:
+ SOURCE_CODE_RADIUS = 3
- attr_reader :original_exception
+ attr_reader :original_exception
- def initialize(template, assigns, original_exception)
- @template, @assigns, @original_exception = template, assigns.dup, original_exception
- @backtrace = compute_backtrace
- end
+ def initialize(template, assigns, original_exception)
+ @template, @assigns, @original_exception = template, assigns.dup, original_exception
+ @backtrace = compute_backtrace
+ end
- def file_name
- @template.identifier
- end
+ def file_name
+ @template.identifier
+ end
- def message
- ActiveSupport::Deprecation.silence { original_exception.message }
- end
+ def message
+ ActiveSupport::Deprecation.silence { original_exception.message }
+ end
- def clean_backtrace
- if defined?(Rails) && Rails.respond_to?(:backtrace_cleaner)
- Rails.backtrace_cleaner.clean(original_exception.backtrace)
- else
- original_exception.backtrace
+ def clean_backtrace
+ if defined?(Rails) && Rails.respond_to?(:backtrace_cleaner)
+ Rails.backtrace_cleaner.clean(original_exception.backtrace)
+ else
+ original_exception.backtrace
+ end
end
- end
- def sub_template_message
- if @sub_templates
- "Trace of template inclusion: " +
- @sub_templates.collect { |template| template.inspect }.join(", ")
- else
- ""
+ def sub_template_message
+ if @sub_templates
+ "Trace of template inclusion: " +
+ @sub_templates.collect { |template| template.inspect }.join(", ")
+ else
+ ""
+ end
end
- end
- def source_extract(indentation = 0)
- return unless num = line_number
- num = num.to_i
+ def source_extract(indentation = 0)
+ return unless num = line_number
+ num = num.to_i
- source_code = @template.source.split("\n")
+ source_code = @template.source.split("\n")
- start_on_line = [ num - SOURCE_CODE_RADIUS - 1, 0 ].max
- end_on_line = [ num + SOURCE_CODE_RADIUS - 1, source_code.length].min
+ start_on_line = [ num - SOURCE_CODE_RADIUS - 1, 0 ].max
+ end_on_line = [ num + SOURCE_CODE_RADIUS - 1, source_code.length].min
- indent = ' ' * indentation
- line_counter = start_on_line
- return unless source_code = source_code[start_on_line..end_on_line]
+ indent = ' ' * indentation
+ line_counter = start_on_line
+ return unless source_code = source_code[start_on_line..end_on_line]
- source_code.sum do |line|
- line_counter += 1
- "#{indent}#{line_counter}: #{line}\n"
+ source_code.sum do |line|
+ line_counter += 1
+ "#{indent}#{line_counter}: #{line}\n"
+ end
end
- end
- def sub_template_of(template_path)
- @sub_templates ||= []
- @sub_templates << template_path
- end
-
- def line_number
- @line_number ||=
- if file_name
- regexp = /#{Regexp.escape File.basename(file_name)}:(\d+)/
-
- $1 if message =~ regexp or clean_backtrace.find { |line| line =~ regexp }
- end
- end
+ def sub_template_of(template_path)
+ @sub_templates ||= []
+ @sub_templates << template_path
+ end
- def to_s
- "\n#{self.class} (#{message}) #{source_location}:\n" +
- "#{source_extract}\n #{clean_backtrace.join("\n ")}\n\n"
- end
+ def line_number
+ @line_number ||=
+ if file_name
+ regexp = /#{Regexp.escape File.basename(file_name)}:(\d+)/
- # don't do anything nontrivial here. Any raised exception from here becomes fatal
- # (and can't be rescued).
- def backtrace
- @backtrace
- end
+ $1 if message =~ regexp or clean_backtrace.find { |line| line =~ regexp }
+ end
+ end
- private
- def compute_backtrace
- [
- "#{source_location.capitalize}\n\n#{source_extract(4)}\n " +
- clean_backtrace.join("\n ")
- ]
+ def to_s
+ "\n#{self.class} (#{message}) #{source_location}:\n" +
+ "#{source_extract}\n #{clean_backtrace.join("\n ")}\n\n"
end
- def source_location
- if line_number
- "on line ##{line_number} of "
- else
- 'in '
- end + file_name
+ # don't do anything nontrivial here. Any raised exception from here becomes fatal
+ # (and can't be rescued).
+ def backtrace
+ @backtrace
end
+
+ private
+ def compute_backtrace
+ [
+ "#{source_location.capitalize}\n\n#{source_extract(4)}\n " +
+ clean_backtrace.join("\n ")
+ ]
+ end
+
+ def source_location
+ if line_number
+ "on line ##{line_number} of "
+ else
+ 'in '
+ end + file_name
+ end
+ end
end
end
View
47 actionpack/lib/action_view/template/handler.rb
@@ -3,34 +3,39 @@
# Legacy TemplateHandler stub
module ActionView
- module TemplateHandlers #:nodoc:
- module Compilable
- def self.included(base)
- base.extend(ClassMethods)
- end
+ class Template
+ module Handlers #:nodoc:
+ module Compilable
+ def self.included(base)
+ base.extend(ClassMethods)
+ end
- module ClassMethods
- def call(template)
- new.compile(template)
+ module ClassMethods
+ def call(template)
+ new.compile(template)
+ end
end
- end
- def compile(template)
- raise "Need to implement #{self.class.name}#compile(template)"
- end
+ def compile(template)
+ raise "Need to implement #{self.class.name}#compile(template)"
+ end
+ end
end
- end
- class TemplateHandler
- extlib_inheritable_accessor :default_format
- self.default_format = Mime::HTML
+ class Template::Handler
+ extlib_inheritable_accessor :default_format
+ self.default_format = Mime::HTML
- def self.call(template)
- raise "Need to implement #{self.class.name}#call(template)"
- end
+ def self.call(template)
+ raise "Need to implement #{self.class.name}#call(template)"
+ end
- def render(template, local_assigns)
- raise "Need to implement #{self.class.name}#render(template, local_assigns)"
+ def render(template, local_assigns)
+ raise "Need to implement #{self.class.name}#render(template, local_assigns)"
+ end
end
end
+
+ TemplateHandlers = Template::Handlers
+ TemplateHandler = Template::Handler
end
View
96 actionpack/lib/action_view/template/handlers.rb
@@ -1,52 +1,54 @@
module ActionView #:nodoc:
- module TemplateHandlers #:nodoc:
- autoload :ERB, 'action_view/template/handlers/erb'
- autoload :RJS, 'action_view/template/handlers/rjs'
- autoload :Builder, 'action_view/template/handlers/builder'
-
- def self.extended(base)
- base.register_default_template_handler :erb, TemplateHandlers::ERB
- base.register_template_handler :rjs, TemplateHandlers::RJS
- base.register_template_handler :builder, TemplateHandlers::Builder
-
- # TODO: Depreciate old template extensions
- base.register_template_handler :rhtml, TemplateHandlers::ERB
- base.register_template_handler :rxml, TemplateHandlers::Builder
- end
-
- @@template_handlers = {}
- @@default_template_handlers = nil
+ class Template
+ module Handlers #:nodoc:
+ autoload :ERB, 'action_view/template/handlers/erb'
+ autoload :RJS, 'action_view/template/handlers/rjs'
+ autoload :Builder, 'action_view/template/handlers/builder'
+
+ def self.extended(base)
+ base.register_default_template_handler :erb, ERB
+ base.register_template_handler :rjs, RJS
+ base.register_template_handler :builder, Builder
+
+ # TODO: Depreciate old template extensions
+ base.register_template_handler :rhtml, ERB
+ base.register_template_handler :rxml, Builder
+ end
+
+ @@template_handlers = {}
+ @@default_template_handlers = nil
- def self.extensions
- @@template_handlers.keys
- end
-
- # Register a class that knows how to handle template files with the given
- # extension. This can be used to implement new template types.
- # The constructor for the class must take the ActiveView::Base instance
- # as a parameter, and the class must implement a +render+ method that
- # takes the contents of the template to render as well as the Hash of
- # local assigns available to the template. The +render+ method ought to
- # return the rendered template as a string.
- def register_template_handler(extension, klass)
- @@template_handlers[extension.to_sym] = klass
- end
-
- def template_handler_extensions
- @@template_handlers.keys.map {|key| key.to_s }.sort
- end
-
- def registered_template_handler(extension)
- extension && @@template_handlers[extension.to_sym]
- end
-
- def register_default_template_handler(extension, klass)
- register_template_handler(extension, klass)
- @@default_template_handlers = klass
- end
-
- def handler_class_for_extension(extension)
- (extension && registered_template_handler(extension.to_sym)) || @@default_template_handlers
+ def self.extensions
+ @@template_handlers.keys
+ end
+
+ # Register a class that knows how to handle template files with the given
+ # extension. This can be used to implement new template types.
+ # The constructor for the class must take the ActiveView::Base instance
+ # as a parameter, and the class must implement a +render+ method that
+ # takes the contents of the template to render as well as the Hash of
+ # local assigns available to the template. The +render+ method ought to
+ # return the rendered template as a string.
+ def register_template_handler(extension, klass)
@jamesarosen
jamesarosen added a note Feb 2, 2012

@wycats @carllerche this documentation seems to be incorrect now. I believe the second argument is an instance, not a class, and it needs to respond to call(template), not render(). Am I incorrect? (I'm not saying it was incorrect as of this commit. I'm saying the documentation hasn't kept up with changes to this module.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+ @@template_handlers[extension.to_sym] = klass
+ end
+
+ def template_handler_extensions
+ @@template_handlers.keys.map {|key| key.to_s }.sort
+ end
+
+ def registered_template_handler(extension)
+ extension && @@template_handlers[extension.to_sym]
+ end
+
+ def register_default_template_handler(extension, klass)
+ register_template_handler(extension, klass)
+ @@default_template_handlers = klass
+ end
+
+ def handler_class_for_extension(extension)
+ (extension && registered_template_handler(extension.to_sym)) || @@default_template_handlers
+ end
end
end
end
View
4 actionpack/lib/action_view/template/handlers/builder.rb
@@ -1,6 +1,6 @@
module ActionView
- module TemplateHandlers
- class Builder < TemplateHandler
+ module Template::Handlers
+ class Builder < Template::Handler
include Compilable
self.default_format = Mime::XML
View
4 actionpack/lib/action_view/template/handlers/erb.rb
@@ -3,7 +3,7 @@
require 'erubis'
module ActionView
- module TemplateHandlers
+ module Template::Handlers
class Erubis < ::Erubis::Eruby
def add_preamble(src)
src << "@output_buffer = ActionView::SafeBuffer.new;"
@@ -26,7 +26,7 @@ def add_postamble(src)
end
end
- class ERB < TemplateHandler
+ class ERB < Template::Handler
include Compilable
##
View
4 actionpack/lib/action_view/template/handlers/rjs.rb
@@ -1,6 +1,6 @@
module ActionView
- module TemplateHandlers
- class RJS < TemplateHandler
+ module Template::Handlers
+ class RJS < Template::Handler
include Compilable
self.default_format = Mime::JS
View
6 actionpack/lib/action_view/template/resolver.rb
@@ -1,6 +1,6 @@
require "pathname"
require "active_support/core_ext/class"
-require "action_view/template/template"
+require "action_view/template"
module ActionView
# Abstract superclass
@@ -20,7 +20,7 @@ def self.register_detail(name, options = {})
register_detail(:locale) { [I18n.locale] }
register_detail(:formats) { Mime::SET.symbols }
register_detail(:handlers, :allow_nil => false) do
- TemplateHandlers.extensions
+ Template::Handlers.extensions
end
def initialize(options = {})
@@ -65,7 +65,7 @@ def normalize_details(details)
# as well as incorrectly putting part of the path in the template
# name instead of the prefix.
def normalize_name(name, prefix)
- handlers = TemplateHandlers.extensions.join('|')
+ handlers = Template::Handlers.extensions.join('|')
name = name.to_s.gsub(/\.(?:#{handlers})$/, '')
parts = name.split('/')
View
70 actionpack/lib/action_view/template/text.rb
@@ -1,38 +1,40 @@
module ActionView #:nodoc:
- class TextTemplate < String #:nodoc:
- HTML = Mime[:html]
-
- def initialize(string, content_type = HTML)
- super(string.to_s)
- @content_type = Mime[content_type] || content_type
- end
-
- def details
- {:formats => [@content_type.to_sym]}
- end
-
- def identifier
- self
- end
-
- def inspect
- 'text template'
- end
-
- def render(*args)
- to_s
- end
-
- def mime_type
- @content_type
- end
-
- def formats
- [mime_type]
- end
-
- def partial?
- false
+ class Template
+ class Text < String #:nodoc:
+ HTML = Mime[:html]
+
+ def initialize(string, content_type = HTML)
+ super(string.to_s)
+ @content_type = Mime[content_type] || content_type
+ end
+
+ def details
+ {:formats => [@content_type.to_sym]}
+ end
+
+ def identifier
+ self
+ end
+
+ def inspect
+ 'text template'
+ end
+
+ def render(*args)
+ to_s
+ end
+
+ def mime_type
+ @content_type
+ end
+
+ def formats
+ [mime_type]
+ end
+
+ def partial?
+ false
+ end
end
end
end
View
2 actionpack/lib/action_view/test_case.rb
@@ -1,5 +1,5 @@
require 'active_support/test_case'
-require 'action_controller/testing/test_case'
+require 'action_controller/test_case'
module ActionView
class Base
View
26 actionpack/test/abstract/layouts_test.rb
@@ -23,27 +23,27 @@ class Blank < Base
self.view_paths = []
def index
- render :_template => ActionView::TextTemplate.new("Hello blank!")
+ render :_template => ActionView::Template::Text.new("Hello blank!")
end
end
class WithString < Base
layout "hello"
def index
- render :_template => ActionView::TextTemplate.new("Hello string!")
+ render :_template => ActionView::Template::Text.new("Hello string!")
end
def overwrite_default
- render :_template => ActionView::TextTemplate.new("Hello string!"), :layout => :default
+ render :_template => ActionView::Template::Text.new("Hello string!"), :layout => :default
end
def overwrite_false
- render :_template => ActionView::TextTemplate.new("Hello string!"), :layout => false
+ render :_template => ActionView::Template::Text.new("Hello string!"), :layout => false
end
def overwrite_string
- render :_template => ActionView::TextTemplate.new("Hello string!"), :layout => "omg"
+ render :_template => ActionView::Template::Text.new("Hello string!"), :layout => "omg"
end
def overwrite_skip
@@ -72,7 +72,7 @@ class WithSymbol < Base
layout :hello
def index
- render :_template => ActionView::TextTemplate.new("Hello symbol!")
+ render :_template => ActionView::Template::Text.new("Hello symbol!")
end
private
def hello
@@ -84,7 +84,7 @@ class WithSymbolReturningString < Base
layout :no_hello
def index
- render :_template => ActionView::TextTemplate.new("Hello missing symbol!")
+ render :_template => ActionView::Template::Text.new("Hello missing symbol!")
end
private
def no_hello
@@ -96,7 +96,7 @@ class WithSymbolReturningNil < Base
layout :nilz
def index
- render :_template => ActionView::TextTemplate.new("Hello nilz!")
+ render :_template => ActionView::Template::Text.new("Hello nilz!")
end
def nilz() end
@@ -106,7 +106,7 @@ class WithSymbolReturningObj < Base
layout :objekt
def index
- render :_template => ActionView::TextTemplate.new("Hello nilz!")
+ render :_template => ActionView::Template::Text.new("Hello nilz!")
end
def objekt
@@ -118,31 +118,31 @@ class WithSymbolAndNoMethod < Base
layout :omg_no_method
def index
- render :_template => ActionView::TextTemplate.new("Hello boom!")
+ render :_template => ActionView::Template::Text.new("Hello boom!")
end
end
class WithMissingLayout < Base
layout "missing"
def index
- render :_template => ActionView::TextTemplate.new("Hello missing!")
+ render :_template => ActionView::Template::Text.new("Hello missing!")
end
end
class WithFalseLayout < Base
layout false
def index
- render :_template => ActionView::TextTemplate.new("Hello false!")
+ render :_template => ActionView::Template::Text.new("Hello false!")
end
end
class WithNilLayout < Base
layout nil
def index
- render :_template => ActionView::TextTemplate.new("Hello nil!")
+ render :_template => ActionView::Template::Text.new("Hello nil!")
end
end
View
2 actionpack/test/abstract/render_test.rb
@@ -38,7 +38,7 @@ def template_name
end
def object
- render :_template => ActionView::TextTemplate.new("With Object")
+ render :_template => ActionView::Template::Text.new("With Object")
end
end
View
2 actionpack/test/controller/helper_test.rb
@@ -191,7 +191,7 @@ def setup
end
def test_helper_in_a
- assert_raise(ActionView::TemplateError) { call_controller(A, "index") }
+ assert_raise(ActionView::Template::Error) { call_controller(A, "index") }
end
def test_helper_in_b
View
2 actionpack/test/controller/layout_test.rb
@@ -115,7 +115,7 @@ def hello
end
class LayoutSetInResponseTest < ActionController::TestCase
- include ActionView::TemplateHandlers
+ include ActionView::Template::Handlers
def test_layout_set_when_using_default_layout
@controller = DefaultLayoutController.new
View
8 actionpack/test/template/render_test.rb
@@ -106,8 +106,8 @@ def test_render_partial_with_locals_from_default
def test_render_partial_with_errors
@view.render(:partial => "test/raise")
- flunk "Render did not raise TemplateError"
- rescue ActionView::TemplateError => e
+ flunk "Render did not raise Template::Error"
+ rescue ActionView::Template::Error => e
assert_match "undefined local variable or method `doesnt_exist'", e.message
assert_equal "", e.sub_template_message
assert_equal "1", e.line_number
@@ -116,8 +116,8 @@ def test_render_partial_with_errors
def test_render_sub_template_with_errors
@view.render(:file => "test/sub_template_raise")
- flunk "Render did not raise TemplateError"
- rescue ActionView::TemplateError => e
+ flunk "Render did not raise Template::Error"
+ rescue ActionView::Template::Error => e
assert_match "undefined local variable or method `doesnt_exist'", e.message
assert_equal "Trace of template inclusion: #{File.expand_path("#{FIXTURE_LOAD_PATH}/test/sub_template_raise.html.erb")}", e.sub_template_message
assert_equal "1", e.line_number
View
43 activemodel/lib/active_model.rb
@@ -26,28 +26,31 @@
require 'active_support'
module ActiveModel
- autoload :AttributeMethods, 'active_model/attribute_methods'
- autoload :Conversion, 'active_model/conversion'
- autoload :DeprecatedErrorMethods, 'active_model/deprecated_error_methods'
- autoload :Dirty, 'active_model/dirty'
- autoload :Errors, 'active_model/errors'
- autoload :Lint, 'active_model/lint'
- autoload :Name, 'active_model/naming'
- autoload :Naming, 'active_model/naming'
- autoload :Observer, 'active_model/observing'
- autoload :Observing, 'active_model/observing'
- autoload :Serialization, 'active_model/serialization'
- autoload :StateMachine, 'active_model/state_machine'
- autoload :TestCase, 'active_model/test_case'
- autoload :Translation, 'active_model/translation'
- autoload :Validations, 'active_model/validations'
- autoload :ValidationsRepairHelper, 'active_model/validations_repair_helper'
- autoload :Validator, 'active_model/validator'
- autoload :VERSION, 'active_model/version'
+ extend ActiveSupport::Autoload
+
+ autoload :AttributeMethods
+ autoload :Conversion
+ autoload :DeprecatedErrorMethods
+ autoload :Dirty
+ autoload :Errors
+ autoload :Lint
+ autoload :Name, 'active_model/naming'
+ autoload :Naming
+ autoload :Observer, 'active_model/observing'
+ autoload :Observing
+ autoload :Serialization
+ autoload :StateMachine
+ autoload :Translation
+ autoload :Validations
+ autoload :ValidationsRepairHelper
+ autoload :Validator
+ autoload :VERSION
module Serializers
- autoload :JSON, 'active_model/serializers/json'
- autoload :Xml, 'active_model/serializers/xml'
+ extend ActiveSupport::Autoload
+
+ autoload :JSON
+ autoload :Xml
end
end
View
1 activemodel/test/cases/helper.rb
@@ -10,6 +10,7 @@
require 'config'
require 'active_model'
+require 'active_model/test_case'
# Show backtraces for deprecated behavior for quicker cleanup.
ActiveSupport::Deprecation.debug = true
View
1 activemodel/test/cases/tests_database.rb
@@ -2,6 +2,7 @@
$:.unshift(File.dirname(__FILE__) + '/../../../activerecord/lib')
require 'active_record'
+require 'active_record/test_case'
require 'active_record/fixtures'
module ActiveModel
View
100 activerecord/lib/active_record.rb
@@ -32,64 +32,66 @@
require 'arel'
module ActiveRecord
- # TODO: Review explicit loads to see if they will automatically be handled by the initializer.
- def self.load_all!
- [Base, DynamicFinderMatch, ConnectionAdapters::AbstractAdapter]
- end
+ extend ActiveSupport::Autoload
- autoload :VERSION, 'active_record/version'
+ autoload :VERSION
autoload :ActiveRecordError, 'active_record/base'
autoload :ConnectionNotEstablished, 'active_record/base'
- autoload :Aggregations, 'active_record/aggregations'
- autoload :AssociationPreload, 'active_record/association_preload'
- autoload :Associations, 'active_record/associations'
- autoload :AttributeMethods, 'active_record/attribute_methods'
- autoload :Attributes, 'active_record/attributes'
- autoload :AutosaveAssociation, 'active_record/autosave_association'
- autoload :Relation, 'active_record/relation'
- autoload :Base, 'active_record/base'
- autoload :Batches, 'active_record/batches'
- autoload :Calculations, 'active_record/calculations'
- autoload :Callbacks, 'active_record/callbacks'
- autoload :DynamicFinderMatch, 'active_record/dynamic_finder_match'
- autoload :DynamicScopeMatch, 'active_record/dynamic_scope_match'
- autoload :Migration, 'active_record/migration'
+ autoload :Aggregations
+ autoload :AssociationPreload
+ autoload :Associations
+ autoload :AttributeMethods
+ autoload :Attributes
+ autoload :AutosaveAssociation
+ autoload :Relation
+ autoload :Base
+ autoload :Batches
+ autoload :Calculations
+ autoload :Callbacks
+ autoload :DynamicFinderMatch
+ autoload :DynamicScopeMatch
+ autoload :Migration
autoload :Migrator, 'active_record/migration'
- autoload :NamedScope, 'active_record/named_scope'
- autoload :NestedAttributes, 'active_record/nested_attributes'
- autoload :Observer, 'active_record/observer'
- autoload :QueryCache, 'active_record/query_cache'
- autoload :Reflection, 'active_record/reflection'
- autoload :Schema, 'active_record/schema'
- autoload :SchemaDumper, 'active_record/schema_dumper'
- autoload :Serialization, 'active_record/serialization'
- autoload :SessionStore, 'active_record/session_store'
- autoload :StateMachine, 'active_record/state_machine'
- autoload :TestCase, 'active_record/test_case'
- autoload :Timestamp, 'active_record/timestamp'
- autoload :Transactions, 'active_record/transactions'
- autoload :Types, 'active_record/types'
- autoload :Validations, 'active_record/validations'
+ autoload :NamedScope
+ autoload :NestedAttributes
+ autoload :Observer
+ autoload :QueryCache
+ autoload :Reflection
+ autoload :Schema
+ autoload :SchemaDumper
+ autoload :Serialization
+ autoload :SessionStore
+ autoload :StateMachine
+ autoload :Timestamp
+ autoload :Transactions
+ autoload :Types
+ autoload :Validations
module AttributeMethods
- autoload :BeforeTypeCast, 'active_record/attribute_methods/before_type_cast'
- autoload :Dirty, 'active_record/attribute_methods/dirty'
- autoload :PrimaryKey, 'active_record/attribute_methods/primary_key'
- autoload :Query, 'active_record/attribute_methods/query'
- autoload :Read, 'active_record/attribute_methods/read'
- autoload :TimeZoneConversion, 'active_record/attribute_methods/time_zone_conversion'
- autoload :Write, 'active_record/attribute_methods/write'
+ extend ActiveSupport::Autoload
+
+ autoload :BeforeTypeCast
+ autoload :Dirty
+ autoload :PrimaryKey
+ autoload :Query
+ autoload :Read
+ autoload :TimeZoneConversion
+ autoload :Write
end
module Attributes
- autoload :Aliasing, 'active_record/attributes/aliasing'
- autoload :Store, 'active_record/attributes/store'
- autoload :Typecasting, 'active_record/attributes/typecasting'
+ extend ActiveSupport::Autoload
+
+ autoload :Aliasing
+ autoload :Store
+ autoload :Typecasting
end
module Type
+ extend ActiveSupport::Autoload
+
autoload :Number, 'active_record/types/number'
autoload :Object, 'active_record/types/object'
autoload :Serialize, 'active_record/types/serialize'
@@ -98,12 +100,16 @@ module Type
end
module Locking
- autoload :Optimistic, 'active_record/locking/optimistic'
- autoload :Pessimistic, 'active_record/locking/pessimistic'
+ extend ActiveSupport::Autoload
+
+ autoload :Optimistic
+ autoload :Pessimistic
end
module ConnectionAdapters
- autoload :AbstractAdapter, 'active_record/connection_adapters/abstract_adapter'
+ extend ActiveSupport::Autoload
+
+ autoload :AbstractAdapter
end
end
View
16 activeresource/lib/active_resource.rb
@@ -30,11 +30,13 @@
require 'active_model'
module ActiveResource
- autoload :Base, 'active_resource/base'
- autoload :Connection, 'active_resource/connection'
- autoload :CustomMethods, 'active_resource/custom_methods'
- autoload :Formats, 'active_resource/formats'
- autoload :Observing, 'active_resource/observing'
- autoload :Validations, 'active_resource/validations'
- autoload :HttpMock, 'active_resource/http_mock'
+ extend ActiveSupport::Autoload
+
+ autoload :Base
+ autoload :Connection
+ autoload :CustomMethods
+ autoload :Formats
+ autoload :Observing
+ autoload :Validations
+ autoload :HttpMock
end
View
1 activeresource/test/abstract_unit.rb
@@ -13,6 +13,7 @@
require 'active_support'
require 'active_support/test_case'
require 'active_resource'
+require 'active_model/test_case'
$:.unshift "#{File.dirname(__FILE__)}/../test"
require 'setter_trap'
View
6 activeresource/test/cases/base_test.rb
@@ -543,9 +543,9 @@ def test_collection_path_with_parameters
assert Person.collection_path(:gender => 'male', :student => true).include?('gender=male')
assert Person.collection_path(:gender => 'male', :student => true).include?('student=true')
- assert_equal '/people.xml?name%5B%5D=bob&name%5B%5D=your+uncle%2Bme&name%5B%5D=&name%5B%5D=false', Person.collection_path(:name => ['bob', 'your uncle+me', nil, false])
+ assert_equal '/people.xml?name[]=bob&name[]=your+uncle%2Bme&name[]=&name[]=false', Person.collection_path(:name => ['bob', 'your uncle+me', nil, false])
- assert_equal '/people.xml?struct%5Ba%5D%5B%5D=2&struct%5Ba%5D%5B%5D=1&struct%5Bb%5D=fred', Person.collection_path(:struct => {:a => [2,1], 'b' => 'fred'})
+ assert_equal '/people.xml?struct[a][]=2&struct[a][]=1&struct[b]=fred', Person.collection_path(:struct => {:a => [2,1], 'b' => 'fred'})
end
def test_custom_element_path
@@ -581,7 +581,7 @@ def test_custom_element_path_with_parameters
assert_equal '/people/1/addresses/1.xml?type=work', StreetAddress.element_path(1, :person_id => 1, :type => 'work')
assert_equal '/people/1/addresses/1.xml?type=work', StreetAddress.element_path(1, 'person_id' => 1, :type => 'work')
assert_equal '/people/1/addresses/1.xml?type=work', StreetAddress.element_path(1, :type => 'work', :person_id => 1)
- assert_equal '/people/1/addresses/1.xml?type%5B%5D=work&type%5B%5D=play+time', StreetAddress.element_path(1, :person_id => 1, :type => ['work', 'play time'])
+ assert_equal '/people/1/addresses/1.xml?type[]=work&type[]=play+time', StreetAddress.element_path(1, :person_id => 1, :type => ['work', 'play time'])
end
def test_custom_element_path_with_prefix_and_parameters
View
55 activesupport/lib/active_support/autoload.rb
@@ -1,28 +1,31 @@
+require "active_support/dependencies/autoload"
+
module ActiveSupport
- autoload :BacktraceCleaner, 'active_support/backtrace_cleaner'
- autoload :Base64, 'active_support/base64'
- autoload :BasicObject, 'active_support/basic_object'
- autoload :Benchmarkable, 'active_support/benchmarkable'
- autoload :BufferedLogger, 'active_support/buffered_logger'
- autoload :Cache, 'active_support/cache'
- autoload :Callbacks, 'active_support/callbacks'
- autoload :Concern, 'active_support/concern'
- autoload :Configurable, 'active_support/configurable'
- autoload :DependencyModule, 'active_support/dependency_module'
- autoload :DeprecatedCallbacks, 'active_support/deprecated_callbacks'
- autoload :Deprecation, 'active_support/deprecation'
- autoload :Gzip, 'active_support/gzip'
- autoload :Inflector, 'active_support/inflector'
- autoload :Memoizable, 'active_support/memoizable'
- autoload :MessageEncryptor, 'active_support/message_encryptor'
- autoload :MessageVerifier, 'active_support/message_verifier'
- autoload :Multibyte, 'active_support/multibyte'
- autoload :OptionMerger, 'active_support/option_merger'
- autoload :OrderedHash, 'active_support/ordered_hash'
- autoload :OrderedOptions, 'active_support/ordered_options'
- autoload :Notifications, 'active_support/notifications'
- autoload :Rescuable, 'active_support/rescuable'
- autoload :SecureRandom, 'active_support/secure_random'
- autoload :StringInquirer, 'active_support/string_inquirer'
- autoload :XmlMini, 'active_support/xml_mini'
+ extend ActiveSupport::Autoload
+
+ autoload :BacktraceCleaner
+ autoload :Base64
+ autoload :BasicObject
+ autoload :Benchmarkable
+ autoload :BufferedLogger
+ autoload :Cache
+ autoload :Callbacks
+ autoload :Concern
+ autoload :Configurable
+ autoload :DeprecatedCallbacks
+ autoload :Deprecation
+ autoload :Gzip
+ autoload :Inflector
+ autoload :Memoizable
+ autoload :MessageEncryptor
+ autoload :MessageVerifier
+ autoload :Multibyte
+ autoload :OptionMerger
+ autoload :OrderedHash
+ autoload :OrderedOptions
+ autoload :Notifications
+ autoload :Rescuable
+ autoload :SecureRandom
+ autoload :StringInquirer
+ autoload :XmlMini
end
View
37 activesupport/lib/active_support/dependencies/autoload.rb
@@ -0,0 +1,37 @@
+require "active_support/inflector/methods"
+
+module ActiveSupport
+ module Autoload
+
+ @@autoloads = {}
+ @@under_path = nil
+ @@at_path = nil
+
+ def autoload(const_name, path = @@at_path)
+ full = [self.name, @@under_path, const_name.to_s, path].compact.join("::")
+ location = path || Inflector.underscore(full)
+
+ @@autoloads[const_name] = location
+ super const_name, location
+ end
+
+ def autoload_under(path)
+ @@under_path, old_path = path, @@under_path
+ yield
+ ensure
+ @@under_path = old_path
+ end
+
+ def autoload_at(path)
+ @@at_path, old_path = path, @@at_path
+ yield
+ ensure
+ @@at_path = old_path
+ end
+
+ def self.eager_autoload!
+ @@autoloads.values.each {|file| require file }
+ end
+
+ end
+end
View
678 activesupport/lib/active_support/testing/performance.rb
@@ -1,450 +1,454 @@
-require 'ruby-prof'
-
-require 'fileutils'
-require 'rails/version'
-
-module ActiveSupport
- module Testing
- module Performance
- DEFAULTS =
- if benchmark = ARGV.include?('--benchmark') # HAX for rake test
- { :benchmark => true,
- :runs => 4,
- :metrics => [:wall_time, :memory, :objects, :gc_runs, :gc_time],
- :output => 'tmp/performance' }
- else
- { :benchmark => false,
- :runs => 1,
- :min_percent => 0.01,
- :metrics => [:process_time, :memory, :objects],
- :formats => [:flat, :graph_html, :call_tree],
- :output => 'tmp/performance' }
- end.freeze
-
- def self.included(base)
- base.superclass_delegating_accessor :profile_options
- base.profile_options = DEFAULTS
- end
+begin
+ require 'ruby-prof'
+
+ require 'fileutils'
+ require 'rails/version'
+ require 'active_support/core_ext/class/delegating_attributes'
+
+ module ActiveSupport
+ module Testing
+ module Performance
+ DEFAULTS =
+ if benchmark = ARGV.include?('--benchmark') # HAX for rake test
+ { :benchmark => true,
+ :runs => 4,
+ :metrics => [:wall_time, :memory, :objects, :gc_runs, :gc_time],
+ :output => 'tmp/performance' }
+ else
+ { :benchmark => false,
+ :runs => 1,
+ :min_percent => 0.01,
+ :metrics => [:process_time, :memory, :objects],
+ :formats => [:flat, :graph_html, :call_tree],
+ :output => 'tmp/performance' }
+ end.freeze
+
+ def self.included(base)
+ base.superclass_delegating_accessor :profile_options
+ base.profile_options = DEFAULTS
+ end
- def full_test_name
- "#{self.class.name}##{method_name}"
- end
+ def full_test_name
+ "#{self.class.name}##{method_name}"
+ end
- def run(result)
- return if method_name =~ /^default_test$/
+ def run(result)
+ return if method_name =~ /^default_test$/
- yield(self.class::STARTED, name)
- @_result = result
+ yield(self.class::STARTED, name)
+ @_result = result
- run_warmup
- if profile_options && metrics = profile_options[:metrics]
- metrics.each do |metric_name|
- if klass = Metrics[metric_name.to_sym]
- run_profile(klass.new)
- result.add_run
+ run_warmup
+ if profile_options && metrics = profile_options[:metrics]
+ metrics.each do |metric_name|
+ if klass = Metrics[metric_name.to_sym]
+ run_profile(klass.new)
+ result.add_run
+ end
end
end
- end
- yield(self.class::FINISHED, name)
- end
+ yield(self.class::FINISHED, name)
+ end
- def run_test(metric, mode)
- run_callbacks :setup
- setup
- metric.send(mode) { __send__ @method_name }
- rescue ::Test::Unit::AssertionFailedError => e
- add_failure(e.message, e.backtrace)
- rescue StandardError, ScriptError
- add_error($!)
- ensure
- begin
- teardown
- run_callbacks :teardown, :enumerator => :reverse_each
+ def run_test(metric, mode)
+ run_callbacks :setup
+ setup
+ metric.send(mode) { __send__ @method_name }
rescue ::Test::Unit::AssertionFailedError => e
add_failure(e.message, e.backtrace)
rescue StandardError, ScriptError
add_error($!)
+ ensure
+ begin
+ teardown
+ run_callbacks :teardown, :enumerator => :reverse_each
+ rescue ::Test::Unit::AssertionFailedError => e
+ add_failure(e.message, e.backtrace)
+ rescue StandardError, ScriptError
+ add_error($!)
+ end
end
- end
- protected
- def run_warmup
- GC.start
+ protected
+ def run_warmup
+ GC.start
- time = Metrics::Time.new
- run_test(time, :benchmark)
- puts "%s (%s warmup)" % [full_test_name, time.format(time.total)]
+ time = Metrics::Time.new
+ run_test(time, :benchmark)
+ puts "%s (%s warmup)" % [full_test_name, time.format(time.total)]
- GC.start
- end
-
- def run_profile(metric)
- klass = profile_options[:benchmark] ? Benchmarker : Profiler
- performer = klass.new(self, metric)
+ GC.start
+ end
- performer.run
- puts performer.report
- performer.record
- end
+ def run_profile(metric)
+ klass = profile_options[:benchmark] ? Benchmarker : Profiler
+ performer = klass.new(self, metric)
- class Performer
- delegate :run_test, :profile_options, :full_test_name, :to => :@harness
+ performer.run
+ puts performer.report
+ performer.record
+ end
- def initialize(harness, metric)
- @harness, @metric = harness, metric
- end
+ class Performer
+ delegate :run_test, :profile_options, :full_test_name, :to => :@harness
- def report
- rate = @total / profile_options[:runs]
- '%20s: %s' % [@metric.name, @metric.format(rate)]
- end
+ def initialize(harness, metric)
+ @harness, @metric = harness, metric
+ end
- protected
- def output_filename
- "#{profile_options[:output]}/#{full_test_name}_#{@metric.name}"
+ def report
+ rate = @total / profile_options[:runs]
+ '%20s: %s' % [@metric.name, @metric.format(rate)]
end
- end
- class Benchmarker < Performer
- def run
- profile_options[:runs].to_i.times { run_test(@metric, :benchmark) }
- @total = @metric.total
+ protected
+ def output_filename
+ "#{profile_options[:output]}/#{full_test_name}_#{@metric.name}"
+ end
end
- def record
- avg = @metric.total / profile_options[:runs].to_i
- now = Time.now.utc.xmlschema
- with_output_file do |file|
- file.puts "#{avg},#{now},#{environment}"
+ class Benchmarker < Performer
+ def run
+ profile_options[:runs].to_i.times { run_test(@metric, :benchmark) }
+ @total = @metric.total
end
- end
- def environment
- unless defined? @env
- app = "#{$1}.#{$2}" if File.directory?('.git') && `git branch -v` =~ /^\* (\S+)\s+(\S+)/
-
- rails = Rails::VERSION::STRING
- if File.directory?('vendor/rails/.git')
- Dir.chdir('vendor/rails') do
- rails += ".#{$1}.#{$2}" if `git branch -v` =~ /^\* (\S+)\s+(\S+)/
- end
+ def record
+ avg = @metric.total / profile_options[:runs].to_i
+ now = Time.now.utc.xmlschema
+ with_output_file do |file|
+ file.puts "#{avg},#{now},#{environment}"
end
-
- ruby = defined?(RUBY_ENGINE) ? RUBY_ENGINE : 'ruby'
- ruby += "-#{RUBY_VERSION}.#{RUBY_PATCHLEVEL}"
-
- @env = [app, rails, ruby, RUBY_PLATFORM] * ','
end
- @env
- end
+ def environment
+ unless defined? @env
+ app = "#{$1}.#{$2}" if File.directory?('.git') && `git branch -v` =~ /^\* (\S+)\s+(\S+)/
- protected
- HEADER = 'measurement,created_at,app,rails,ruby,platform'
+ rails = Rails::VERSION::STRING
+ if File.directory?('vendor/rails/.git')
+ Dir.chdir('vendor/rails') do
+ rails += ".#{$1}.#{$2}" if `git branch -v` =~ /^\* (\S+)\s+(\S+)/
+ end
+ end
- def with_output_file
- fname = output_filename
+ ruby = defined?(RUBY_ENGINE) ? RUBY_ENGINE : 'ruby'
+ ruby += "-#{RUBY_VERSION}.#{RUBY_PATCHLEVEL}"
- if new = !File.exist?(fname)
- FileUtils.mkdir_p(File.dirname(fname))
+ @env = [app, rails, ruby, RUBY_PLATFORM] * ','
end
- File.open(fname, 'ab') do |file|
- file.puts(HEADER) if new
- yield file
- end
+ @env
end
- def output_filename
- "#{super}.csv"
- end
- end
+ protected
+ HEADER = 'measurement,created_at,app,rails,ruby,platform'
- class Profiler < Performer
- def initialize(*args)
- super
- @supported = @metric.measure_mode rescue false
- end
+ def with_output_file
+ fname = output_filename
+
+ if new = !File.exist?(fname)
+ FileUtils.mkdir_p(File.dirname(fname))
+ end
- def run
- return unless @supported
+ File.open(fname, 'ab') do |file|
+ file.puts(HEADER) if new
+ yield file
+ end
+ end
- RubyProf.measure_mode = @metric.measure_mode
- RubyProf.start
- RubyProf.pause
- profile_options[:runs].to_i.times { run_test(@metric, :profile) }
- @data = RubyProf.stop
- @total = @data.threads.values.sum(0) { |method_infos| method_infos.sort.last.total_time }
+ def output_filename
+ "#{super}.csv"
+ end
end
- def report
- if @supported
+ class Profiler < Performer
+ def initialize(*args)
super
- else
- '%20s: unsupported' % @metric.name
+ @supported = @metric.measure_mode rescue false
end
- end
- def record
- return unless @supported
+ def run