Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Namespace Inflector, Dependencies, OrderedOptions, and TimeZone under…

… ActiveSupport [#238 state:resolved]
  • Loading branch information...
commit c08547d2266c75f0a82d06dd91c6d0500740e12e 1 parent da91450
@josh josh authored
Showing with 1,554 additions and 1,514 deletions.
  1. +1 −1  actionpack/lib/action_controller/dispatcher.rb
  2. +1 −1  actionpack/lib/action_controller/routing.rb
  3. +2 −2 actionpack/test/controller/dispatcher_test.rb
  4. +1 −1  actionpack/test/controller/integration_upload_test.rb
  5. +2 −2 actionpack/test/controller/routing_test.rb
  6. +1 −1  activerecord/lib/active_record/base.rb
  7. +10 −10 activerecord/test/cases/attribute_methods_test.rb
  8. +14 −14 activerecord/test/cases/base_test.rb
  9. +2 −2 activerecord/test/cases/inheritance_test.rb
  10. +1 −1  activerecord/test/cases/multiple_db_test.rb
  11. +4 −0 activesupport/lib/active_support.rb
  12. +393 −392 activesupport/lib/active_support/dependencies.rb
  13. +25 −7 activesupport/lib/active_support/deprecation.rb
  14. +51 −49 activesupport/lib/active_support/inflections.rb
  15. +264 −262 activesupport/lib/active_support/inflector.rb
  16. +14 −12 activesupport/lib/active_support/ordered_options.rb
  17. +348 −346 activesupport/lib/active_support/values/time_zone.rb
  18. +7 −7 activesupport/test/core_ext/date_ext_test.rb
  19. +12 −12 activesupport/test/core_ext/date_time_ext_test.rb
  20. +4 −4 activesupport/test/core_ext/duration_test.rb
  21. +14 −14 activesupport/test/core_ext/time_ext_test.rb
  22. +120 −120 activesupport/test/core_ext/time_with_zone_test.rb
  23. +120 −120 activesupport/test/dependencies_test.rb
  24. +10 −0 activesupport/test/deprecation_test.rb
  25. +63 −63 activesupport/test/inflector_test.rb
  26. +3 −3 activesupport/test/ordered_options_test.rb
  27. +67 −68 activesupport/test/time_zone_test.rb
View
2  actionpack/lib/action_controller/dispatcher.rb
@@ -141,7 +141,7 @@ def reload_application
# be reloaded on the next request without restarting the server.
def cleanup_application
ActiveRecord::Base.reset_subclasses if defined?(ActiveRecord)
- Dependencies.clear
+ ActiveSupport::Dependencies.clear
ActiveRecord::Base.clear_reloadable_connections! if defined?(ActiveRecord)
end
View
2  actionpack/lib/action_controller/routing.rb
@@ -369,7 +369,7 @@ def controller_relative_to(controller, previous)
Routes = RouteSet.new
- ::Inflector.module_eval do
+ ActiveSupport::Inflector.module_eval do
# Ensures that routes are reloaded when Rails inflections are updated.
def inflections_with_route_reloading(&block)
returning(inflections_without_route_reloading(&block)) {
View
4 actionpack/test/controller/dispatcher_test.rb
@@ -27,14 +27,14 @@ def teardown
def test_clears_dependencies_after_dispatch_if_in_loading_mode
ActionController::Routing::Routes.expects(:reload).once
- Dependencies.expects(:clear).once
+ ActiveSupport::Dependencies.expects(:clear).once
dispatch(@output, false)
end
def test_leaves_dependencies_after_dispatch_if_not_in_loading_mode
ActionController::Routing::Routes.expects(:reload).never
- Dependencies.expects(:clear).never
+ ActiveSupport::Dependencies.expects(:clear).never
dispatch
end
View
2  actionpack/test/controller/integration_upload_test.rb
@@ -28,7 +28,7 @@ class << self
# end
def test_post_with_upload
uses_mocha "test_post_with_upload" do
- Dependencies.stubs(:load?).returns(false)
+ ActiveSupport::Dependencies.stubs(:load?).returns(false)
with_routing do |set|
set.draw do |map|
map.update 'update', :controller => "upload_test", :action => "update", :method => :post
View
4 actionpack/test/controller/routing_test.rb
@@ -2392,10 +2392,10 @@ def test_bang_forces_reload
end
def test_adding_inflections_forces_reload
- Inflector::Inflections.instance.expects(:uncountable).with('equipment')
+ ActiveSupport::Inflector::Inflections.instance.expects(:uncountable).with('equipment')
routes.expects(:reload!)
- Inflector.inflections { |inflect| inflect.uncountable('equipment') }
+ ActiveSupport::Inflector.inflections { |inflect| inflect.uncountable('equipment') }
end
def test_load_with_configuration
View
2  activerecord/lib/active_record/base.rb
@@ -372,7 +372,7 @@ def self.inherited(child) #:nodoc:
def self.reset_subclasses #:nodoc:
nonreloadables = []
subclasses.each do |klass|
- unless Dependencies.autoloaded? klass
+ unless ActiveSupport::Dependencies.autoloaded? klass
nonreloadables << klass
next
end
View
20 activerecord/test/cases/attribute_methods_test.rb
@@ -137,7 +137,7 @@ def test_accessing_cached_attributes_caches_the_converted_values_and_nothing_els
end
end
end
-
+
def test_time_attributes_are_retrieved_in_current_time_zone
in_time_zone "Pacific Time (US & Canada)" do
utc_time = Time.utc(2008, 1, 1)
@@ -145,7 +145,7 @@ def test_time_attributes_are_retrieved_in_current_time_zone
record[:written_on] = utc_time
assert_equal utc_time, record.written_on # record.written on is equal to (i.e., simultaneous with) utc_time
assert_kind_of ActiveSupport::TimeWithZone, record.written_on # but is a TimeWithZone
- assert_equal TimeZone["Pacific Time (US & Canada)"], record.written_on.time_zone # and is in the current Time.zone
+ assert_equal ActiveSupport::TimeZone["Pacific Time (US & Canada)"], record.written_on.time_zone # and is in the current Time.zone
assert_equal Time.utc(2007, 12, 31, 16), record.written_on.time # and represents time values adjusted accordingly
end
end
@@ -156,7 +156,7 @@ def test_setting_time_zone_aware_attribute_to_utc
record = @target.new
record.written_on = utc_time
assert_equal utc_time, record.written_on
- assert_equal TimeZone["Pacific Time (US & Canada)"], record.written_on.time_zone
+ assert_equal ActiveSupport::TimeZone["Pacific Time (US & Canada)"], record.written_on.time_zone
assert_equal Time.utc(2007, 12, 31, 16), record.written_on.time
end
end
@@ -168,7 +168,7 @@ def test_setting_time_zone_aware_attribute_in_other_time_zone
record = @target.new
record.written_on = cst_time
assert_equal utc_time, record.written_on
- assert_equal TimeZone["Pacific Time (US & Canada)"], record.written_on.time_zone
+ assert_equal ActiveSupport::TimeZone["Pacific Time (US & Canada)"], record.written_on.time_zone
assert_equal Time.utc(2007, 12, 31, 16), record.written_on.time
end
end
@@ -181,12 +181,12 @@ def test_setting_time_zone_aware_attribute_with_string
record = @target.new
record.written_on = time_string
assert_equal Time.zone.parse(time_string), record.written_on
- assert_equal TimeZone["Pacific Time (US & Canada)"], record.written_on.time_zone
+ assert_equal ActiveSupport::TimeZone["Pacific Time (US & Canada)"], record.written_on.time_zone
assert_equal Time.utc(2007, 12, 31, 16), record.written_on.time
end
end
end
-
+
def test_setting_time_zone_aware_attribute_to_blank_string_returns_nil
in_time_zone "Pacific Time (US & Canada)" do
record = @target.new
@@ -202,7 +202,7 @@ def test_setting_time_zone_aware_attribute_interprets_time_zone_unaware_string_i
record = @target.new
record.written_on = time_string
assert_equal Time.zone.parse(time_string), record.written_on
- assert_equal TimeZone[timezone_offset], record.written_on.time_zone
+ assert_equal ActiveSupport::TimeZone[timezone_offset], record.written_on.time_zone
assert_equal Time.utc(2008, 1, 1), record.written_on.time
end
end
@@ -214,7 +214,7 @@ def test_setting_time_zone_aware_attribute_in_current_time_zone
record = @target.new
record.written_on = utc_time.in_time_zone
assert_equal utc_time, record.written_on
- assert_equal TimeZone["Pacific Time (US & Canada)"], record.written_on.time_zone
+ assert_equal ActiveSupport::TimeZone["Pacific Time (US & Canada)"], record.written_on.time_zone
assert_equal Time.utc(2007, 12, 31, 16), record.written_on.time
end
end
@@ -223,12 +223,12 @@ def test_setting_time_zone_aware_attribute_in_current_time_zone
def time_related_columns_on_topic
Topic.columns.select{|c| [:time, :date, :datetime, :timestamp].include?(c.type)}.map(&:name)
end
-
+
def in_time_zone(zone)
old_zone = Time.zone
old_tz = ActiveRecord::Base.time_zone_aware_attributes
- Time.zone = zone ? TimeZone[zone] : nil
+ Time.zone = zone ? ActiveSupport::TimeZone[zone] : nil
ActiveRecord::Base.time_zone_aware_attributes = !zone.nil?
yield
ensure
View
28 activerecord/test/cases/base_test.rb
@@ -133,19 +133,19 @@ def test_read_attributes_before_type_cast
category_attrs = {"name"=>"Test categoty", "type" => nil}
assert_equal category_attrs , category.attributes_before_type_cast
end
-
+
if current_adapter?(:MysqlAdapter)
def test_read_attributes_before_type_cast_on_boolean
bool = Booleantest.create({ "value" => false })
assert_equal 0, bool.attributes_before_type_cast["value"]
end
end
-
+
def test_read_attributes_before_type_cast_on_datetime
developer = Developer.find(:first)
assert_equal developer.created_at.to_s(:db) , developer.attributes_before_type_cast["created_at"]
end
-
+
def test_hash_content
topic = Topic.new
topic.content = { "one" => 1, "two" => 2 }
@@ -251,7 +251,7 @@ def test_create_through_factory
topic = Topic.create("title" => "New Topic")
topicReloaded = Topic.find(topic.id)
assert_equal(topic, topicReloaded)
- end
+ end
def test_create_through_factory_with_block
topic = Topic.create("title" => "New Topic") do |t|
@@ -576,7 +576,7 @@ def test_table_name_guesses
def test_destroy_all
original_count = Topic.count
topics_by_mary = Topic.count(:conditions => mary = "author_name = 'Mary'")
-
+
Topic.destroy_all mary
assert_equal original_count - topics_by_mary, Topic.count
end
@@ -665,7 +665,7 @@ def test_update_many
def test_delete_all
assert Topic.count > 0
-
+
assert_equal Topic.count, Topic.delete_all
end
@@ -970,7 +970,7 @@ def test_multiparameter_attributes_on_time
topic.attributes = attributes
assert_equal Time.local(2004, 6, 24, 16, 24, 0), topic.written_on
end
-
+
def test_multiparameter_attributes_on_time_with_old_date
attributes = {
"written_on(1i)" => "1850", "written_on(2i)" => "6", "written_on(3i)" => "24",
@@ -998,7 +998,7 @@ def test_multiparameter_attributes_on_time_with_utc
def test_multiparameter_attributes_on_time_with_time_zone_aware_attributes
ActiveRecord::Base.time_zone_aware_attributes = true
ActiveRecord::Base.default_timezone = :utc
- Time.zone = TimeZone[-28800]
+ Time.zone = ActiveSupport::TimeZone[-28800]
attributes = {
"written_on(1i)" => "2004", "written_on(2i)" => "6", "written_on(3i)" => "24",
"written_on(4i)" => "16", "written_on(5i)" => "24", "written_on(6i)" => "00"
@@ -1016,7 +1016,7 @@ def test_multiparameter_attributes_on_time_with_time_zone_aware_attributes
def test_multiparameter_attributes_on_time_with_time_zone_aware_attributes_false
ActiveRecord::Base.time_zone_aware_attributes = false
- Time.zone = TimeZone[-28800]
+ Time.zone = ActiveSupport::TimeZone[-28800]
attributes = {
"written_on(1i)" => "2004", "written_on(2i)" => "6", "written_on(3i)" => "24",
"written_on(4i)" => "16", "written_on(5i)" => "24", "written_on(6i)" => "00"
@@ -1032,7 +1032,7 @@ def test_multiparameter_attributes_on_time_with_time_zone_aware_attributes_false
def test_multiparameter_attributes_on_time_with_skip_time_zone_conversion_for_attributes
ActiveRecord::Base.time_zone_aware_attributes = true
ActiveRecord::Base.default_timezone = :utc
- Time.zone = TimeZone[-28800]
+ Time.zone = ActiveSupport::TimeZone[-28800]
Topic.skip_time_zone_conversion_for_attributes = [:written_on]
attributes = {
"written_on(1i)" => "2004", "written_on(2i)" => "6", "written_on(3i)" => "24",
@@ -1647,7 +1647,7 @@ def test_find_last
last = Developer.find :last
assert_equal last, Developer.find(:first, :order => 'id desc')
end
-
+
def test_last
assert_equal Developer.find(:first, :order => 'id desc'), Developer.last
end
@@ -1655,7 +1655,7 @@ def test_last
def test_all_with_conditions
assert_equal Developer.find(:all, :order => 'id desc'), Developer.all(:order => 'id desc')
end
-
+
def test_find_ordered_last
last = Developer.find :last, :order => 'developers.salary ASC'
assert_equal last, Developer.find(:all, :order => 'developers.salary ASC').last
@@ -1670,14 +1670,14 @@ def test_find_multiple_ordered_last
last = Developer.find :last, :order => 'developers.name, developers.salary DESC'
assert_equal last, Developer.find(:all, :order => 'developers.name, developers.salary DESC').last
end
-
+
def test_find_scoped_ordered_last
last_developer = Developer.with_scope(:find => { :order => 'developers.salary ASC' }) do
Developer.find(:last)
end
assert_equal last_developer, Developer.find(:all, :order => 'developers.salary ASC').last
end
-
+
def test_abstract_class
assert !ActiveRecord::Base.abstract_class?
assert LoosePerson.abstract_class?
View
4 activerecord/test/cases/inheritance_test.rb
@@ -223,11 +223,11 @@ class InheritanceComputeTypeTest < ActiveRecord::TestCase
fixtures :companies
def setup
- Dependencies.log_activity = true
+ ActiveSupport::Dependencies.log_activity = true
end
def teardown
- Dependencies.log_activity = false
+ ActiveSupport::Dependencies.log_activity = false
self.class.const_remove :FirmOnTheFly rescue nil
Firm.const_remove :FirmOnTheFly rescue nil
end
View
2  activerecord/test/cases/multiple_db_test.rb
@@ -51,7 +51,7 @@ def test_associations
def test_course_connection_should_survive_dependency_reload
assert Course.connection
- Dependencies.clear
+ ActiveSupport::Dependencies.clear
Object.send(:remove_const, :Course)
require_dependency 'models/course'
View
4 activesupport/lib/active_support.rb
@@ -53,3 +53,7 @@
require 'active_support/base64'
require 'active_support/time_with_zone'
+
+Inflector = ActiveSupport::Deprecation::DeprecatedConstantProxy.new('Inflector', 'ActiveSupport::Inflector')
+Dependencies = ActiveSupport::Deprecation::DeprecatedConstantProxy.new('Dependencies', 'ActiveSupport::Dependencies')
+TimeZone = ActiveSupport::Deprecation::DeprecatedConstantProxy.new('TimeZone', 'ActiveSupport::TimeZone')
View
785 activesupport/lib/active_support/dependencies.rb
@@ -3,458 +3,459 @@
require 'active_support/core_ext/load_error'
require 'active_support/core_ext/kernel'
-module Dependencies #:nodoc:
- extend self
-
- # Should we turn on Ruby warnings on the first load of dependent files?
- mattr_accessor :warnings_on_first_load
- self.warnings_on_first_load = false
-
- # All files ever loaded.
- mattr_accessor :history
- self.history = Set.new
-
- # All files currently loaded.
- mattr_accessor :loaded
- self.loaded = Set.new
-
- # Should we load files or require them?
- mattr_accessor :mechanism
- self.mechanism = :load
-
- # The set of directories from which we may automatically load files. Files
- # under these directories will be reloaded on each request in development mode,
- # unless the directory also appears in load_once_paths.
- mattr_accessor :load_paths
- self.load_paths = []
-
- # The set of directories from which automatically loaded constants are loaded
- # only once. All directories in this set must also be present in +load_paths+.
- mattr_accessor :load_once_paths
- self.load_once_paths = []
-
- # An array of qualified constant names that have been loaded. Adding a name to
- # this array will cause it to be unloaded the next time Dependencies are cleared.
- mattr_accessor :autoloaded_constants
- self.autoloaded_constants = []
-
- # An array of constant names that need to be unloaded on every request. Used
- # to allow arbitrary constants to be marked for unloading.
- mattr_accessor :explicitly_unloadable_constants
- self.explicitly_unloadable_constants = []
-
- # Set to true to enable logging of const_missing and file loads
- mattr_accessor :log_activity
- self.log_activity = false
-
- # An internal stack used to record which constants are loaded by any block.
- mattr_accessor :constant_watch_stack
- self.constant_watch_stack = []
-
- def load?
- mechanism == :load
- end
-
- def depend_on(file_name, swallow_load_errors = false)
- path = search_for_file(file_name)
- require_or_load(path || file_name)
- rescue LoadError
- raise unless swallow_load_errors
- end
-
- def associate_with(file_name)
- depend_on(file_name, true)
- end
+module ActiveSupport #:nodoc:
+ module Dependencies #:nodoc:
+ extend self
+
+ # Should we turn on Ruby warnings on the first load of dependent files?
+ mattr_accessor :warnings_on_first_load
+ self.warnings_on_first_load = false
+
+ # All files ever loaded.
+ mattr_accessor :history
+ self.history = Set.new
+
+ # All files currently loaded.
+ mattr_accessor :loaded
+ self.loaded = Set.new
+
+ # Should we load files or require them?
+ mattr_accessor :mechanism
+ self.mechanism = :load
+
+ # The set of directories from which we may automatically load files. Files
+ # under these directories will be reloaded on each request in development mode,
+ # unless the directory also appears in load_once_paths.
+ mattr_accessor :load_paths
+ self.load_paths = []
+
+ # The set of directories from which automatically loaded constants are loaded
+ # only once. All directories in this set must also be present in +load_paths+.
+ mattr_accessor :load_once_paths
+ self.load_once_paths = []
+
+ # An array of qualified constant names that have been loaded. Adding a name to
+ # this array will cause it to be unloaded the next time Dependencies are cleared.
+ mattr_accessor :autoloaded_constants
+ self.autoloaded_constants = []
+
+ # An array of constant names that need to be unloaded on every request. Used
+ # to allow arbitrary constants to be marked for unloading.
+ mattr_accessor :explicitly_unloadable_constants
+ self.explicitly_unloadable_constants = []
+
+ # Set to true to enable logging of const_missing and file loads
+ mattr_accessor :log_activity
+ self.log_activity = false
+
+ # An internal stack used to record which constants are loaded by any block.
+ mattr_accessor :constant_watch_stack
+ self.constant_watch_stack = []
+
+ def load?
+ mechanism == :load
+ end
- def clear
- log_call
- loaded.clear
- remove_unloadable_constants!
- end
+ def depend_on(file_name, swallow_load_errors = false)
+ path = search_for_file(file_name)
+ require_or_load(path || file_name)
+ rescue LoadError
+ raise unless swallow_load_errors
+ end
- def require_or_load(file_name, const_path = nil)
- log_call file_name, const_path
- file_name = $1 if file_name =~ /^(.*)\.rb$/
- expanded = File.expand_path(file_name)
- return if loaded.include?(expanded)
+ def associate_with(file_name)
+ depend_on(file_name, true)
+ end
- # Record that we've seen this file *before* loading it to avoid an
- # infinite loop with mutual dependencies.
- loaded << expanded
+ def clear
+ log_call
+ loaded.clear
+ remove_unloadable_constants!
+ end
- begin
- if load?
- log "loading #{file_name}"
+ def require_or_load(file_name, const_path = nil)
+ log_call file_name, const_path
+ file_name = $1 if file_name =~ /^(.*)\.rb$/
+ expanded = File.expand_path(file_name)
+ return if loaded.include?(expanded)
- # Enable warnings iff this file has not been loaded before and
- # warnings_on_first_load is set.
- load_args = ["#{file_name}.rb"]
- load_args << const_path unless const_path.nil?
+ # Record that we've seen this file *before* loading it to avoid an
+ # infinite loop with mutual dependencies.
+ loaded << expanded
- if !warnings_on_first_load or history.include?(expanded)
- result = load_file(*load_args)
+ begin
+ if load?
+ log "loading #{file_name}"
+
+ # Enable warnings iff this file has not been loaded before and
+ # warnings_on_first_load is set.
+ load_args = ["#{file_name}.rb"]
+ load_args << const_path unless const_path.nil?
+
+ if !warnings_on_first_load or history.include?(expanded)
+ result = load_file(*load_args)
+ else
+ enable_warnings { result = load_file(*load_args) }
+ end
else
- enable_warnings { result = load_file(*load_args) }
+ log "requiring #{file_name}"
+ result = require file_name
end
- else
- log "requiring #{file_name}"
- result = require file_name
+ rescue Exception
+ loaded.delete expanded
+ raise
end
- rescue Exception
- loaded.delete expanded
- raise
- end
- # Record history *after* loading so first load gets warnings.
- history << expanded
- return result
- end
+ # Record history *after* loading so first load gets warnings.
+ history << expanded
+ return result
+ end
- # Is the provided constant path defined?
- def qualified_const_defined?(path)
- raise NameError, "#{path.inspect} is not a valid constant name!" unless
- /^(::)?([A-Z]\w*)(::[A-Z]\w*)*$/ =~ path
+ # Is the provided constant path defined?
+ def qualified_const_defined?(path)
+ raise NameError, "#{path.inspect} is not a valid constant name!" unless
+ /^(::)?([A-Z]\w*)(::[A-Z]\w*)*$/ =~ path
- names = path.to_s.split('::')
- names.shift if names.first.empty?
+ names = path.to_s.split('::')
+ names.shift if names.first.empty?
- # We can't use defined? because it will invoke const_missing for the parent
- # of the name we are checking.
- names.inject(Object) do |mod, name|
- return false unless uninherited_const_defined?(mod, name)
- mod.const_get name
+ # We can't use defined? because it will invoke const_missing for the parent
+ # of the name we are checking.
+ names.inject(Object) do |mod, name|
+ return false unless uninherited_const_defined?(mod, name)
+ mod.const_get name
+ end
+ return true
end
- return true
- end
- if Module.method(:const_defined?).arity == 1
- # Does this module define this constant?
- # Wrapper to accomodate changing Module#const_defined? in Ruby 1.9
- def uninherited_const_defined?(mod, const)
- mod.const_defined?(const)
- end
- else
- def uninherited_const_defined?(mod, const) #:nodoc:
- mod.const_defined?(const, false)
+ if Module.method(:const_defined?).arity == 1
+ # Does this module define this constant?
+ # Wrapper to accomodate changing Module#const_defined? in Ruby 1.9
+ def uninherited_const_defined?(mod, const)
+ mod.const_defined?(const)
+ end
+ else
+ def uninherited_const_defined?(mod, const) #:nodoc:
+ mod.const_defined?(const, false)
+ end
end
- end
-
- # Given +path+, a filesystem path to a ruby file, return an array of constant
- # paths which would cause Dependencies to attempt to load this file.
- def loadable_constants_for_path(path, bases = load_paths)
- path = $1 if path =~ /\A(.*)\.rb\Z/
- expanded_path = File.expand_path(path)
-
- bases.collect do |root|
- expanded_root = File.expand_path(root)
- next unless %r{\A#{Regexp.escape(expanded_root)}(/|\\)} =~ expanded_path
-
- nesting = expanded_path[(expanded_root.size)..-1]
- nesting = nesting[1..-1] if nesting && nesting[0] == ?/
- next if nesting.blank?
-
- [
- nesting.camelize,
- # Special case: application.rb might define ApplicationControlller.
- ('ApplicationController' if nesting == 'application')
- ]
- end.flatten.compact.uniq
- end
- # Search for a file in load_paths matching the provided suffix.
- def search_for_file(path_suffix)
- path_suffix = path_suffix + '.rb' unless path_suffix.ends_with? '.rb'
- load_paths.each do |root|
- path = File.join(root, path_suffix)
- return path if File.file? path
+ # Given +path+, a filesystem path to a ruby file, return an array of constant
+ # paths which would cause Dependencies to attempt to load this file.
+ def loadable_constants_for_path(path, bases = load_paths)
+ path = $1 if path =~ /\A(.*)\.rb\Z/
+ expanded_path = File.expand_path(path)
+
+ bases.collect do |root|
+ expanded_root = File.expand_path(root)
+ next unless %r{\A#{Regexp.escape(expanded_root)}(/|\\)} =~ expanded_path
+
+ nesting = expanded_path[(expanded_root.size)..-1]
+ nesting = nesting[1..-1] if nesting && nesting[0] == ?/
+ next if nesting.blank?
+
+ [
+ nesting.camelize,
+ # Special case: application.rb might define ApplicationControlller.
+ ('ApplicationController' if nesting == 'application')
+ ]
+ end.flatten.compact.uniq
end
- nil # Gee, I sure wish we had first_match ;-)
- end
- # Does the provided path_suffix correspond to an autoloadable module?
- # Instead of returning a boolean, the autoload base for this module is returned.
- def autoloadable_module?(path_suffix)
- load_paths.each do |load_path|
- return load_path if File.directory? File.join(load_path, path_suffix)
+ # Search for a file in load_paths matching the provided suffix.
+ def search_for_file(path_suffix)
+ path_suffix = path_suffix + '.rb' unless path_suffix.ends_with? '.rb'
+ load_paths.each do |root|
+ path = File.join(root, path_suffix)
+ return path if File.file? path
+ end
+ nil # Gee, I sure wish we had first_match ;-)
end
- nil
- end
-
- def load_once_path?(path)
- load_once_paths.any? { |base| path.starts_with? base }
- end
- # Attempt to autoload the provided module name by searching for a directory
- # matching the expect path suffix. If found, the module is created and assigned
- # to +into+'s constants with the name +const_name+. Provided that the directory
- # was loaded from a reloadable base path, it is added to the set of constants
- # that are to be unloaded.
- def autoload_module!(into, const_name, qualified_name, path_suffix)
- return nil unless base_path = autoloadable_module?(path_suffix)
- mod = Module.new
- into.const_set const_name, mod
- autoloaded_constants << qualified_name unless load_once_paths.include?(base_path)
- return mod
- end
-
- # Load the file at the provided path. +const_paths+ is a set of qualified
- # constant names. When loading the file, Dependencies will watch for the
- # addition of these constants. Each that is defined will be marked as
- # autoloaded, and will be removed when Dependencies.clear is next called.
- #
- # If the second parameter is left off, then Dependencies will construct a set
- # of names that the file at +path+ may define. See
- # +loadable_constants_for_path+ for more details.
- def load_file(path, const_paths = loadable_constants_for_path(path))
- log_call path, const_paths
- const_paths = [const_paths].compact unless const_paths.is_a? Array
- parent_paths = const_paths.collect { |const_path| /(.*)::[^:]+\Z/ =~ const_path ? $1 : :Object }
-
- result = nil
- newly_defined_paths = new_constants_in(*parent_paths) do
- result = load_without_new_constant_marking path
+ # Does the provided path_suffix correspond to an autoloadable module?
+ # Instead of returning a boolean, the autoload base for this module is returned.
+ def autoloadable_module?(path_suffix)
+ load_paths.each do |load_path|
+ return load_path if File.directory? File.join(load_path, path_suffix)
+ end
+ nil
end
- autoloaded_constants.concat newly_defined_paths unless load_once_path?(path)
- autoloaded_constants.uniq!
- log "loading #{path} defined #{newly_defined_paths * ', '}" unless newly_defined_paths.empty?
- return result
- end
+ def load_once_path?(path)
+ load_once_paths.any? { |base| path.starts_with? base }
+ end
- # Return the constant path for the provided parent and constant name.
- def qualified_name_for(mod, name)
- mod_name = to_constant_name mod
- (%w(Object Kernel).include? mod_name) ? name.to_s : "#{mod_name}::#{name}"
- end
+ # Attempt to autoload the provided module name by searching for a directory
+ # matching the expect path suffix. If found, the module is created and assigned
+ # to +into+'s constants with the name +const_name+. Provided that the directory
+ # was loaded from a reloadable base path, it is added to the set of constants
+ # that are to be unloaded.
+ def autoload_module!(into, const_name, qualified_name, path_suffix)
+ return nil unless base_path = autoloadable_module?(path_suffix)
+ mod = Module.new
+ into.const_set const_name, mod
+ autoloaded_constants << qualified_name unless load_once_paths.include?(base_path)
+ return mod
+ end
- # Load the constant named +const_name+ which is missing from +from_mod+. If
- # it is not possible to load the constant into from_mod, try its parent module
- # using const_missing.
- def load_missing_constant(from_mod, const_name)
- log_call from_mod, const_name
- if from_mod == Kernel
- if ::Object.const_defined?(const_name)
- log "Returning Object::#{const_name} for Kernel::#{const_name}"
- return ::Object.const_get(const_name)
- else
- log "Substituting Object for Kernel"
- from_mod = Object
+ # Load the file at the provided path. +const_paths+ is a set of qualified
+ # constant names. When loading the file, Dependencies will watch for the
+ # addition of these constants. Each that is defined will be marked as
+ # autoloaded, and will be removed when Dependencies.clear is next called.
+ #
+ # If the second parameter is left off, then Dependencies will construct a set
+ # of names that the file at +path+ may define. See
+ # +loadable_constants_for_path+ for more details.
+ def load_file(path, const_paths = loadable_constants_for_path(path))
+ log_call path, const_paths
+ const_paths = [const_paths].compact unless const_paths.is_a? Array
+ parent_paths = const_paths.collect { |const_path| /(.*)::[^:]+\Z/ =~ const_path ? $1 : :Object }
+
+ result = nil
+ newly_defined_paths = new_constants_in(*parent_paths) do
+ result = load_without_new_constant_marking path
end
- end
- # If we have an anonymous module, all we can do is attempt to load from Object.
- from_mod = Object if from_mod.name.blank?
+ autoloaded_constants.concat newly_defined_paths unless load_once_path?(path)
+ autoloaded_constants.uniq!
+ log "loading #{path} defined #{newly_defined_paths * ', '}" unless newly_defined_paths.empty?
+ return result
+ end
- unless qualified_const_defined?(from_mod.name) && from_mod.name.constantize.object_id == from_mod.object_id
- raise ArgumentError, "A copy of #{from_mod} has been removed from the module tree but is still active!"
+ # Return the constant path for the provided parent and constant name.
+ def qualified_name_for(mod, name)
+ mod_name = to_constant_name mod
+ (%w(Object Kernel).include? mod_name) ? name.to_s : "#{mod_name}::#{name}"
end
- raise ArgumentError, "#{from_mod} is not missing constant #{const_name}!" if uninherited_const_defined?(from_mod, const_name)
+ # Load the constant named +const_name+ which is missing from +from_mod+. If
+ # it is not possible to load the constant into from_mod, try its parent module
+ # using const_missing.
+ def load_missing_constant(from_mod, const_name)
+ log_call from_mod, const_name
+ if from_mod == Kernel
+ if ::Object.const_defined?(const_name)
+ log "Returning Object::#{const_name} for Kernel::#{const_name}"
+ return ::Object.const_get(const_name)
+ else
+ log "Substituting Object for Kernel"
+ from_mod = Object
+ end
+ end
- qualified_name = qualified_name_for from_mod, const_name
- path_suffix = qualified_name.underscore
- name_error = NameError.new("uninitialized constant #{qualified_name}")
+ # If we have an anonymous module, all we can do is attempt to load from Object.
+ from_mod = Object if from_mod.name.blank?
- file_path = search_for_file(path_suffix)
- if file_path && ! loaded.include?(File.expand_path(file_path)) # We found a matching file to load
- require_or_load file_path
- raise LoadError, "Expected #{file_path} to define #{qualified_name}" unless uninherited_const_defined?(from_mod, const_name)
- return from_mod.const_get(const_name)
- elsif mod = autoload_module!(from_mod, const_name, qualified_name, path_suffix)
- return mod
- elsif (parent = from_mod.parent) && parent != from_mod &&
- ! from_mod.parents.any? { |p| uninherited_const_defined?(p, const_name) }
- # If our parents do not have a constant named +const_name+ then we are free
- # to attempt to load upwards. If they do have such a constant, then this
- # const_missing must be due to from_mod::const_name, which should not
- # return constants from from_mod's parents.
- begin
- return parent.const_missing(const_name)
- rescue NameError => e
- raise unless e.missing_name? qualified_name_for(parent, const_name)
+ unless qualified_const_defined?(from_mod.name) && from_mod.name.constantize.object_id == from_mod.object_id
+ raise ArgumentError, "A copy of #{from_mod} has been removed from the module tree but is still active!"
+ end
+
+ raise ArgumentError, "#{from_mod} is not missing constant #{const_name}!" if uninherited_const_defined?(from_mod, const_name)
+
+ qualified_name = qualified_name_for from_mod, const_name
+ path_suffix = qualified_name.underscore
+ name_error = NameError.new("uninitialized constant #{qualified_name}")
+
+ file_path = search_for_file(path_suffix)
+ if file_path && ! loaded.include?(File.expand_path(file_path)) # We found a matching file to load
+ require_or_load file_path
+ raise LoadError, "Expected #{file_path} to define #{qualified_name}" unless uninherited_const_defined?(from_mod, const_name)
+ return from_mod.const_get(const_name)
+ elsif mod = autoload_module!(from_mod, const_name, qualified_name, path_suffix)
+ return mod
+ elsif (parent = from_mod.parent) && parent != from_mod &&
+ ! from_mod.parents.any? { |p| uninherited_const_defined?(p, const_name) }
+ # If our parents do not have a constant named +const_name+ then we are free
+ # to attempt to load upwards. If they do have such a constant, then this
+ # const_missing must be due to from_mod::const_name, which should not
+ # return constants from from_mod's parents.
+ begin
+ return parent.const_missing(const_name)
+ rescue NameError => e
+ raise unless e.missing_name? qualified_name_for(parent, const_name)
+ raise name_error
+ end
+ else
raise name_error
end
- else
- raise name_error
end
- end
- # Remove the constants that have been autoloaded, and those that have been
- # marked for unloading.
- def remove_unloadable_constants!
- autoloaded_constants.each { |const| remove_constant const }
- autoloaded_constants.clear
- explicitly_unloadable_constants.each { |const| remove_constant const }
- end
+ # Remove the constants that have been autoloaded, and those that have been
+ # marked for unloading.
+ def remove_unloadable_constants!
+ autoloaded_constants.each { |const| remove_constant const }
+ autoloaded_constants.clear
+ explicitly_unloadable_constants.each { |const| remove_constant const }
+ end
- # Determine if the given constant has been automatically loaded.
- def autoloaded?(desc)
- # No name => anonymous module.
- return false if desc.is_a?(Module) && desc.name.blank?
- name = to_constant_name desc
- return false unless qualified_const_defined? name
- return autoloaded_constants.include?(name)
- end
+ # Determine if the given constant has been automatically loaded.
+ def autoloaded?(desc)
+ # No name => anonymous module.
+ return false if desc.is_a?(Module) && desc.name.blank?
+ name = to_constant_name desc
+ return false unless qualified_const_defined? name
+ return autoloaded_constants.include?(name)
+ end
- # Will the provided constant descriptor be unloaded?
- def will_unload?(const_desc)
- autoloaded?(desc) ||
- explicitly_unloadable_constants.include?(to_constant_name(const_desc))
- end
+ # Will the provided constant descriptor be unloaded?
+ def will_unload?(const_desc)
+ autoloaded?(desc) ||
+ explicitly_unloadable_constants.include?(to_constant_name(const_desc))
+ end
- # Mark the provided constant name for unloading. This constant will be
- # unloaded on each request, not just the next one.
- def mark_for_unload(const_desc)
- name = to_constant_name const_desc
- if explicitly_unloadable_constants.include? name
- return false
- else
- explicitly_unloadable_constants << name
- return true
+ # Mark the provided constant name for unloading. This constant will be
+ # unloaded on each request, not just the next one.
+ def mark_for_unload(const_desc)
+ name = to_constant_name const_desc
+ if explicitly_unloadable_constants.include? name
+ return false
+ else
+ explicitly_unloadable_constants << name
+ return true
+ end
end
- end
- # Run the provided block and detect the new constants that were loaded during
- # its execution. Constants may only be regarded as 'new' once -- so if the
- # block calls +new_constants_in+ again, then the constants defined within the
- # inner call will not be reported in this one.
- #
- # If the provided block does not run to completion, and instead raises an
- # exception, any new constants are regarded as being only partially defined
- # and will be removed immediately.
- def new_constants_in(*descs)
- log_call(*descs)
-
- # Build the watch frames. Each frame is a tuple of
- # [module_name_as_string, constants_defined_elsewhere]
- watch_frames = descs.collect do |desc|
- if desc.is_a? Module
- mod_name = desc.name
- initial_constants = desc.local_constant_names
- elsif desc.is_a?(String) || desc.is_a?(Symbol)
- mod_name = desc.to_s
-
- # Handle the case where the module has yet to be defined.
- initial_constants = if qualified_const_defined?(mod_name)
- mod_name.constantize.local_constant_names
+ # Run the provided block and detect the new constants that were loaded during
+ # its execution. Constants may only be regarded as 'new' once -- so if the
+ # block calls +new_constants_in+ again, then the constants defined within the
+ # inner call will not be reported in this one.
+ #
+ # If the provided block does not run to completion, and instead raises an
+ # exception, any new constants are regarded as being only partially defined
+ # and will be removed immediately.
+ def new_constants_in(*descs)
+ log_call(*descs)
+
+ # Build the watch frames. Each frame is a tuple of
+ # [module_name_as_string, constants_defined_elsewhere]
+ watch_frames = descs.collect do |desc|
+ if desc.is_a? Module
+ mod_name = desc.name
+ initial_constants = desc.local_constant_names
+ elsif desc.is_a?(String) || desc.is_a?(Symbol)
+ mod_name = desc.to_s
+
+ # Handle the case where the module has yet to be defined.
+ initial_constants = if qualified_const_defined?(mod_name)
+ mod_name.constantize.local_constant_names
+ else
+ []
+ end
else
- []
+ raise Argument, "#{desc.inspect} does not describe a module!"
end
- else
- raise Argument, "#{desc.inspect} does not describe a module!"
- end
- [mod_name, initial_constants]
- end
+ [mod_name, initial_constants]
+ end
- constant_watch_stack.concat watch_frames
+ constant_watch_stack.concat watch_frames
- aborting = true
- begin
- yield # Now yield to the code that is to define new constants.
- aborting = false
- ensure
- # Find the new constants.
- new_constants = watch_frames.collect do |mod_name, prior_constants|
- # Module still doesn't exist? Treat it as if it has no constants.
- next [] unless qualified_const_defined?(mod_name)
-
- mod = mod_name.constantize
- next [] unless mod.is_a? Module
- new_constants = mod.local_constant_names - prior_constants
-
- # Make sure no other frames takes credit for these constants.
- constant_watch_stack.each do |frame_name, constants|
- constants.concat new_constants if frame_name == mod_name
+ aborting = true
+ begin
+ yield # Now yield to the code that is to define new constants.
+ aborting = false
+ ensure
+ # Find the new constants.
+ new_constants = watch_frames.collect do |mod_name, prior_constants|
+ # Module still doesn't exist? Treat it as if it has no constants.
+ next [] unless qualified_const_defined?(mod_name)
+
+ mod = mod_name.constantize
+ next [] unless mod.is_a? Module
+ new_constants = mod.local_constant_names - prior_constants
+
+ # Make sure no other frames takes credit for these constants.
+ constant_watch_stack.each do |frame_name, constants|
+ constants.concat new_constants if frame_name == mod_name
+ end
+
+ new_constants.collect do |suffix|
+ mod_name == "Object" ? suffix : "#{mod_name}::#{suffix}"
+ end
+ end.flatten
+
+ log "New constants: #{new_constants * ', '}"
+
+ if aborting
+ log "Error during loading, removing partially loaded constants "
+ new_constants.each { |name| remove_constant name }
+ new_constants.clear
end
+ end
- new_constants.collect do |suffix|
- mod_name == "Object" ? suffix : "#{mod_name}::#{suffix}"
+ return new_constants
+ ensure
+ # Remove the stack frames that we added.
+ if defined?(watch_frames) && ! watch_frames.blank?
+ frame_ids = watch_frames.collect(&:object_id)
+ constant_watch_stack.delete_if do |watch_frame|
+ frame_ids.include? watch_frame.object_id
end
- end.flatten
-
- log "New constants: #{new_constants * ', '}"
-
- if aborting
- log "Error during loading, removing partially loaded constants "
- new_constants.each { |name| remove_constant name }
- new_constants.clear
end
end
- return new_constants
- ensure
- # Remove the stack frames that we added.
- if defined?(watch_frames) && ! watch_frames.blank?
- frame_ids = watch_frames.collect(&:object_id)
- constant_watch_stack.delete_if do |watch_frame|
- frame_ids.include? watch_frame.object_id
+ class LoadingModule #:nodoc:
+ # Old style environment.rb referenced this method directly. Please note, it doesn't
+ # actually *do* anything any more.
+ def self.root(*args)
+ if defined?(RAILS_DEFAULT_LOGGER)
+ RAILS_DEFAULT_LOGGER.warn "Your environment.rb uses the old syntax, it may not continue to work in future releases."
+ RAILS_DEFAULT_LOGGER.warn "For upgrade instructions please see: http://manuals.rubyonrails.com/read/book/19"
+ end
end
end
- end
- class LoadingModule #:nodoc:
- # Old style environment.rb referenced this method directly. Please note, it doesn't
- # actually *do* anything any more.
- def self.root(*args)
- if defined?(RAILS_DEFAULT_LOGGER)
- RAILS_DEFAULT_LOGGER.warn "Your environment.rb uses the old syntax, it may not continue to work in future releases."
- RAILS_DEFAULT_LOGGER.warn "For upgrade instructions please see: http://manuals.rubyonrails.com/read/book/19"
+ # Convert the provided const desc to a qualified constant name (as a string).
+ # A module, class, symbol, or string may be provided.
+ def to_constant_name(desc) #:nodoc:
+ name = case desc
+ when String then desc.starts_with?('::') ? desc[2..-1] : desc
+ when Symbol then desc.to_s
+ when Module
+ raise ArgumentError, "Anonymous modules have no name to be referenced by" if desc.name.blank?
+ desc.name
+ else raise TypeError, "Not a valid constant descriptor: #{desc.inspect}"
end
end
- end
- # Convert the provided const desc to a qualified constant name (as a string).
- # A module, class, symbol, or string may be provided.
- def to_constant_name(desc) #:nodoc:
- name = case desc
- when String then desc.starts_with?('::') ? desc[2..-1] : desc
- when Symbol then desc.to_s
- when Module
- raise ArgumentError, "Anonymous modules have no name to be referenced by" if desc.name.blank?
- desc.name
- else raise TypeError, "Not a valid constant descriptor: #{desc.inspect}"
- end
- end
+ def remove_constant(const) #:nodoc:
+ return false unless qualified_const_defined? const
- def remove_constant(const) #:nodoc:
- return false unless qualified_const_defined? const
+ const = $1 if /\A::(.*)\Z/ =~ const.to_s
+ names = const.to_s.split('::')
+ if names.size == 1 # It's under Object
+ parent = Object
+ else
+ parent = (names[0..-2] * '::').constantize
+ end
- const = $1 if /\A::(.*)\Z/ =~ const.to_s
- names = const.to_s.split('::')
- if names.size == 1 # It's under Object
- parent = Object
- else
- parent = (names[0..-2] * '::').constantize
+ log "removing constant #{const}"
+ parent.instance_eval { remove_const names.last }
+ return true
end
- log "removing constant #{const}"
- parent.instance_eval { remove_const names.last }
- return true
- end
-
-protected
- def log_call(*args)
- if defined?(RAILS_DEFAULT_LOGGER) && RAILS_DEFAULT_LOGGER && log_activity
- arg_str = args.collect(&:inspect) * ', '
- /in `([a-z_\?\!]+)'/ =~ caller(1).first
- selector = $1 || '<unknown>'
- log "called #{selector}(#{arg_str})"
- end
- end
+ protected
+ def log_call(*args)
+ if defined?(RAILS_DEFAULT_LOGGER) && RAILS_DEFAULT_LOGGER && log_activity
+ arg_str = args.collect(&:inspect) * ', '
+ /in `([a-z_\?\!]+)'/ =~ caller(1).first
+ selector = $1 || '<unknown>'
+ log "called #{selector}(#{arg_str})"
+ end
+ end
- def log(msg)
- if defined?(RAILS_DEFAULT_LOGGER) && RAILS_DEFAULT_LOGGER && log_activity
- RAILS_DEFAULT_LOGGER.debug "Dependencies: #{msg}"
- end
+ def log(msg)
+ if defined?(RAILS_DEFAULT_LOGGER) && RAILS_DEFAULT_LOGGER && log_activity
+ RAILS_DEFAULT_LOGGER.debug "Dependencies: #{msg}"
+ end
+ end
end
-
end
Object.instance_eval do
- define_method(:require_or_load) { |file_name| Dependencies.require_or_load(file_name) } unless Object.respond_to?(:require_or_load)
- define_method(:require_dependency) { |file_name| Dependencies.depend_on(file_name) } unless Object.respond_to?(:require_dependency)
- define_method(:require_association) { |file_name| Dependencies.associate_with(file_name) } unless Object.respond_to?(:require_association)
+ define_method(:require_or_load) { |file_name| ActiveSupport::Dependencies.require_or_load(file_name) } unless Object.respond_to?(:require_or_load)
+ define_method(:require_dependency) { |file_name| ActiveSupport::Dependencies.depend_on(file_name) } unless Object.respond_to?(:require_dependency)
+ define_method(:require_association) { |file_name| ActiveSupport::Dependencies.associate_with(file_name) } unless Object.respond_to?(:require_association)
end
class Module #:nodoc:
@@ -464,7 +465,7 @@ class Module #:nodoc:
# Use const_missing to autoload associations so we don't have to
# require_association when using single-table inheritance.
def const_missing(class_id)
- Dependencies.load_missing_constant self, class_id
+ ActiveSupport::Dependencies.load_missing_constant self, class_id
end
def unloadable(const_desc = self)
@@ -480,15 +481,15 @@ def const_missing(const_name)
else
begin
begin
- Dependencies.load_missing_constant self, const_name
+ ActiveSupport::Dependencies.load_missing_constant self, const_name
rescue NameError
parent.send :const_missing, const_name
end
rescue NameError => e
# Make sure that the name we are missing is the one that caused the error
- parent_qualified_name = Dependencies.qualified_name_for parent, const_name
+ parent_qualified_name = ActiveSupport::Dependencies.qualified_name_for parent, const_name
raise unless e.missing_name? parent_qualified_name
- qualified_name = Dependencies.qualified_name_for self, const_name
+ qualified_name = ActiveSupport::Dependencies.qualified_name_for self, const_name
raise NameError.new("uninitialized constant #{qualified_name}").copy_blame!(e)
end
end
@@ -499,14 +500,14 @@ class Object
alias_method :load_without_new_constant_marking, :load
def load(file, *extras) #:nodoc:
- Dependencies.new_constants_in(Object) { super }
+ ActiveSupport::Dependencies.new_constants_in(Object) { super }
rescue Exception => exception # errors from loading file
exception.blame_file! file
raise
end
def require(file, *extras) #:nodoc:
- Dependencies.new_constants_in(Object) { super }
+ ActiveSupport::Dependencies.new_constants_in(Object) { super }
rescue Exception => exception # errors from required file
exception.blame_file! file
raise
@@ -526,7 +527,7 @@ def require(file, *extras) #:nodoc:
# Returns true if the constant was not previously marked for unloading, false
# otherwise.
def unloadable(const_desc)
- Dependencies.mark_for_unload const_desc
+ ActiveSupport::Dependencies.mark_for_unload const_desc
end
end
View
32 activesupport/lib/active_support/deprecation.rb
@@ -144,17 +144,11 @@ def collect_deprecations
end
end
- # Stand-in for <tt>@request</tt>, <tt>@attributes</tt>, <tt>@params</tt>, etc.
- # which emits deprecation warnings on any method call (except +inspect+).
- class DeprecatedInstanceVariableProxy #:nodoc:
+ class DeprecationProxy #:nodoc:
silence_warnings do
instance_methods.each { |m| undef_method m unless m =~ /^__/ }
end
- def initialize(instance, method, var = "@#{method}")
- @instance, @method, @var = instance, method, var
- end
-
# Don't give a deprecation warning on inspect since test/unit and error
# logs rely on it for diagnostics.
def inspect
@@ -166,7 +160,16 @@ def method_missing(called, *args, &block)
warn caller, called, args
target.__send__(called, *args, &block)
end
+ end
+ # Stand-in for <tt>@request</tt>, <tt>@attributes</tt>, <tt>@params</tt>, etc.
+ # which emits deprecation warnings on any method call (except +inspect+).
+ class DeprecatedInstanceVariableProxy < DeprecationProxy #:nodoc:
+ def initialize(instance, method, var = "@#{method}")
+ @instance, @method, @var = instance, method, var
+ end
+
+ private
def target
@instance.__send__(@method)
end
@@ -176,6 +179,21 @@ def warn(callstack, called, args)
end
end
+ class DeprecatedConstantProxy < DeprecationProxy #:nodoc:
+ def initialize(old_const, new_const)
+ @old_const = old_const
+ @new_const = new_const
+ end
+
+ private
+ def target
+ @new_const.to_s.constantize
+ end
+
+ def warn(callstack, called, args)
+ ActiveSupport::Deprecation.warn("#{@old_const} is deprecated! Use #{@new_const} instead.", callstack)
+ end
+ end
end
end
View
100 activesupport/lib/active_support/inflections.rb
@@ -1,53 +1,55 @@
-Inflector.inflections do |inflect|
- inflect.plural(/$/, 's')
- inflect.plural(/s$/i, 's')
- inflect.plural(/(ax|test)is$/i, '\1es')
- inflect.plural(/(octop|vir)us$/i, '\1i')
- inflect.plural(/(alias|status)$/i, '\1es')
- inflect.plural(/(bu)s$/i, '\1ses')
- inflect.plural(/(buffal|tomat)o$/i, '\1oes')
- inflect.plural(/([ti])um$/i, '\1a')
- inflect.plural(/sis$/i, 'ses')
- inflect.plural(/(?:([^f])fe|([lr])f)$/i, '\1\2ves')
- inflect.plural(/(hive)$/i, '\1s')
- inflect.plural(/([^aeiouy]|qu)y$/i, '\1ies')
- inflect.plural(/(x|ch|ss|sh)$/i, '\1es')
- inflect.plural(/(matr|vert|ind)(?:ix|ex)$/i, '\1ices')
- inflect.plural(/([m|l])ouse$/i, '\1ice')
- inflect.plural(/^(ox)$/i, '\1en')
- inflect.plural(/(quiz)$/i, '\1zes')
+module ActiveSupport
+ Inflector.inflections do |inflect|
+ inflect.plural(/$/, 's')
+ inflect.plural(/s$/i, 's')
+ inflect.plural(/(ax|test)is$/i, '\1es')
+ inflect.plural(/(octop|vir)us$/i, '\1i')
+ inflect.plural(/(alias|status)$/i, '\1es')
+ inflect.plural(/(bu)s$/i, '\1ses')
+ inflect.plural(/(buffal|tomat)o$/i, '\1oes')
+ inflect.plural(/([ti])um$/i, '\1a')
+ inflect.plural(/sis$/i, 'ses')
+ inflect.plural(/(?:([^f])fe|([lr])f)$/i, '\1\2ves')
+ inflect.plural(/(hive)$/i, '\1s')
+ inflect.plural(/([^aeiouy]|qu)y$/i, '\1ies')
+ inflect.plural(/(x|ch|ss|sh)$/i, '\1es')
+ inflect.plural(/(matr|vert|ind)(?:ix|ex)$/i, '\1ices')
+ inflect.plural(/([m|l])ouse$/i, '\1ice')
+ inflect.plural(/^(ox)$/i, '\1en')
+ inflect.plural(/(quiz)$/i, '\1zes')
- inflect.singular(/s$/i, '')
- inflect.singular(/(n)ews$/i, '\1ews')
- inflect.singular(/([ti])a$/i, '\1um')
- inflect.singular(/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/i, '\1\2sis')
- inflect.singular(/(^analy)ses$/i, '\1sis')
- inflect.singular(/([^f])ves$/i, '\1fe')
- inflect.singular(/(hive)s$/i, '\1')
- inflect.singular(/(tive)s$/i, '\1')
- inflect.singular(/([lr])ves$/i, '\1f')
- inflect.singular(/([^aeiouy]|qu)ies$/i, '\1y')
- inflect.singular(/(s)eries$/i, '\1eries')
- inflect.singular(/(m)ovies$/i, '\1ovie')
- inflect.singular(/(x|ch|ss|sh)es$/i, '\1')
- inflect.singular(/([m|l])ice$/i, '\1ouse')
- inflect.singular(/(bus)es$/i, '\1')
- inflect.singular(/(o)es$/i, '\1')
- inflect.singular(/(shoe)s$/i, '\1')
- inflect.singular(/(cris|ax|test)es$/i, '\1is')
- inflect.singular(/(octop|vir)i$/i, '\1us')
- inflect.singular(/(alias|status)es$/i, '\1')
- inflect.singular(/^(ox)en/i, '\1')
- inflect.singular(/(vert|ind)ices$/i, '\1ex')
- inflect.singular(/(matr)ices$/i, '\1ix')
- inflect.singular(/(quiz)zes$/i, '\1')
+ inflect.singular(/s$/i, '')
+ inflect.singular(/(n)ews$/i, '\1ews')
+ inflect.singular(/([ti])a$/i, '\1um')
+ inflect.singular(/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/i, '\1\2sis')
+ inflect.singular(/(^analy)ses$/i, '\1sis')
+ inflect.singular(/([^f])ves$/i, '\1fe')
+ inflect.singular(/(hive)s$/i, '\1')
+ inflect.singular(/(tive)s$/i, '\1')
+ inflect.singular(/([lr])ves$/i, '\1f')
+ inflect.singular(/([^aeiouy]|qu)ies$/i, '\1y')
+ inflect.singular(/(s)eries$/i, '\1eries')
+ inflect.singular(/(m)ovies$/i, '\1ovie')
+ inflect.singular(/(x|ch|ss|sh)es$/i, '\1')
+ inflect.singular(/([m|l])ice$/i, '\1ouse')
+ inflect.singular(/(bus)es$/i, '\1')
+ inflect.singular(/(o)es$/i, '\1')
+ inflect.singular(/(shoe)s$/i, '\1')
+ inflect.singular(/(cris|ax|test)es$/i, '\1is')
+ inflect.singular(/(octop|vir)i$/i, '\1us')
+ inflect.singular(/(alias|status)es$/i, '\1')
+ inflect.singular(/^(ox)en/i, '\1')
+ inflect.singular(/(vert|ind)ices$/i, '\1ex')
+ inflect.singular(/(matr)ices$/i, '\1ix')
+ inflect.singular(/(quiz)zes$/i, '\1')
- inflect.irregular('person', 'people')
- inflect.irregular('man', 'men')
- inflect.irregular('child', 'children')
- inflect.irregular('sex', 'sexes')
- inflect.irregular('move', 'moves')
- inflect.irregular('cow', 'kine')
+ inflect.irregular('person', 'people')
+ inflect.irregular('man', 'men')
+ inflect.irregular('child', 'children')
+ inflect.irregular('sex', 'sexes')
+ inflect.irregular('move', 'moves')
+ inflect.irregular('cow', 'kine')
- inflect.uncountable(%w(equipment information rice money species series fish sheep))
+ inflect.uncountable(%w(equipment information rice money species series fish sheep))
+ end
end
View
526 activesupport/lib/active_support/inflector.rb
@@ -1,305 +1,307 @@
require 'singleton'
-# The Inflector transforms words from singular to plural, class names to table names, modularized class names to ones without,
-# and class names to foreign keys. The default inflections for pluralization, singularization, and uncountable words are kept
-# in inflections.rb.
-#
-# The Rails core team has stated patches for the inflections library will not be accepted
-# in order to avoid breaking legacy applications which may be relying on errant inflections.
-# If you discover an incorrect inflection and require it for your application, you'll need
-# to correct it yourself (explained below).
-module Inflector
- # A singleton instance of this class is yielded by Inflector.inflections, which can then be used to specify additional
- # inflection rules. Examples:
+module ActiveSupport
+ # The Inflector transforms words from singular to plural, class names to table names, modularized class names to ones without,
+ # and class names to foreign keys. The default inflections for pluralization, singularization, and uncountable words are kept
+ # in inflections.rb.
#
- # Inflector.inflections do |inflect|
- # inflect.plural /^(ox)$/i, '\1\2en'
- # inflect.singular /^(ox)en/i, '\1'
- #
- # inflect.irregular 'octopus', 'octopi'
- #
- # inflect.uncountable "equipment"
- # end
- #
- # New rules are added at the top. So in the example above, the irregular rule for octopus will now be the first of the
- # pluralization and singularization rules that is runs. This guarantees that your rules run before any of the rules that may
- # already have been loaded.
- class Inflections
- include Singleton
+ # The Rails core team has stated patches for the inflections library will not be accepted
+ # in order to avoid breaking legacy applications which may be relying on errant inflections.
+ # If you discover an incorrect inflection and require it for your application, you'll need
+ # to correct it yourself (explained below).
+ module Inflector
+ # A singleton instance of this class is yielded by Inflector.inflections, which can then be used to specify additional
+ # inflection rules. Examples:
+ #
+ # Inflector.inflections do |inflect|
+ # inflect.plural /^(ox)$/i, '\1\2en'
+ # inflect.singular /^(ox)en/i, '\1'
+ #
+ # inflect.irregular 'octopus', 'octopi'
+ #
+ # inflect.uncountable "equipment"
+ # end
+ #
+ # New rules are added at the top. So in the example above, the irregular rule for octopus will now be the first of the
+ # pluralization and singularization rules that is runs. This guarantees that your rules run before any of the rules that may
+ # already have been loaded.
+ class Inflections
+ include Singleton
- attr_reader :plurals, :singulars, :uncountables
+ attr_reader :plurals, :singulars, :uncountables
- def initialize
- @plurals, @singulars, @uncountables = [], [], []
- end
+ def initialize
+ @plurals, @singulars, @uncountables = [], [], []
+ end
+
+ # Specifies a new pluralization rule and its replacement. The rule can either be a string or a regular expression.
+ # The replacement should always be a string that may include references to the matched data from the rule.
+ def plural(rule, replacement)
+ @plurals.insert(0, [rule, replacement])
+ end
+
+ # Specifies a new singularization rule and its replacement. The rule can either be a string or a regular expression.
+ # The replacement should always be a string that may include references to the matched data from the rule.
+ def singular(rule, replacement)
+ @singulars.insert(0, [rule, replacement])
+ end
- # Specifies a new pluralization rule and its replacement. The rule can either be a string or a regular expression.
- # The replacement should always be a string that may include references to the matched data from the rule.
- def plural(rule, replacement)
- @plurals.insert(0, [rule, replacement])
+ # Specifies a new irregular that applies to both pluralization and singularization at the same time. This can only be used
+ # for strings, not regular expressions. You simply pass the irregular in singular and plural form.
+ #
+ # Examples:
+ # irregular 'octopus', 'octopi'
+ # irregular 'person', 'people'
+ def irregular(singular, plural)
+ if singular[0,1].upcase == plural[0,1].upcase
+ plural(Regexp.new("(#{singular[0,1]})#{singular[1..-1]}$", "i"), '\1' + plural[1..-1])
+ singular(Regexp.new("(#{plural[0,1]})#{plural[1..-1]}$", "i"), '\1' + singular[1..-1])
+ else
+ plural(Regexp.new("#{singular[0,1].upcase}(?i)#{singular[1..-1]}$"), plural[0,1].upcase + plural[1..-1])
+ plural(Regexp.new("#{singular[0,1].downcase}(?i)#{singular[1..-1]}$"), plural[0,1].downcase + plural[1..-1])
+ singular(Regexp.new("#{plural[0,1].upcase}(?i)#{plural[1..-1]}$"), singular[0,1].upcase + singular[1..-1])
+ singular(Regexp.new("#{plural[0,1].downcase}(?i)#{plural[1..-1]}$"), singular[0,1].downcase + singular[1..-1])
+ end
+ end
+
+ # Add uncountable words that shouldn't be attempted inflected.
+ #
+ # Examples:
+ # uncountable "money"
+ # uncountable "money", "information"
+ # uncountable %w( money information rice )
+ def uncountable(*words)
+ (@uncountables << words).flatten!
+ end
+
+ # Clears the loaded inflections within a given scope (default is <tt>:all</tt>).
+ # Give the scope as a symbol of the inflection type, the options are: <tt>:plurals</tt>,
+ # <tt>:singulars</tt>, <tt>:uncountables</tt>.
+ #
+ # Examples:
+ # clear :all
+ # clear :plurals
+ def clear(scope = :all)
+ case scope
+ when :all
+ @plurals, @singulars, @uncountables = [], [], []
+ else
+ instance_variable_set "@#{scope}", []
+ end
+ end
end
- # Specifies a new singularization rule and its replacement. The rule can either be a string or a regular expression.
- # The replacement should always be a string that may include references to the matched data from the rule.
- def singular(rule, replacement)
- @singulars.insert(0, [rule, replacement])
+ extend self
+
+ # Yields a singleton instance of Inflector::Inflections so you can specify additional
+ # inflector rules.
+ #
+ # Example:
+ # Inflector.inflections do |inflect|
+ # inflect.uncountable "rails"
+ # end
+ def inflections
+ if block_given?
+ yield Inflections.instance
+ else
+ Inflections.instance
+ end
end
- # Specifies a new irregular that applies to both pluralization and singularization at the same time. This can only be used
- # for strings, not regular expressions. You simply pass the irregular in singular and plural form.
+ # Returns the plural form of the word in the string.
#
# Examples:
- # irregular 'octopus', 'octopi'
- # irregular 'person', 'people'
- def irregular(singular, plural)
- if singular[0,1].upcase == plural[0,1].upcase
- plural(Regexp.new("(#{singular[0,1]})#{singular[1..-1]}$", "i"), '\1' + plural[1..-1])
- singular(Regexp.new("(#{plural[0,1]})#{plural[1..-1]}$", "i"), '\1' + singular[1..-1])
+ # "post".pluralize # => "posts"
+ # "octopus".pluralize # => "octopi"
+ # "sheep".pluralize # => "sheep"
+ # "words".pluralize # => "words"
+ # "the blue mailman".pluralize # => "the blue mailmen"
+ # "CamelOctopus".pluralize # => "CamelOctopi"
+ def pluralize(word)
+ result = word.to_s.dup
+
+ if word.empty? || inflections.uncountables.include?(result.downcase)
+ result
else
- plural(Regexp.new("#{singular[0,1].upcase}(?i)#{singular[1..-1]}$"), plural[0,1].upcase + plural[1..-1])
- plural(Regexp.new("#{singular[0,1].downcase}(?i)#{singular[1..-1]}$"), plural[0,1].downcase + plural[1..-1])
- singular(Regexp.new("#{plural[0,1].upcase}(?i)#{plural[1..-1]}$"), singular[0,1].upcase + singular[1..-1])
- singular(Regexp.new("#{plural[0,1].downcase}(?i)#{plural[1..-1]}$"), singular[0,1].downcase + singular[1..-1])
+ inflections.plurals.each { |(rule, replacement)| break if result.gsub!(rule, replacement) }
+ result
end
end
- # Add uncountable words that shouldn't be attempted inflected.
+ # The reverse of +pluralize+, returns the singular form of a word in a string.
#
# Examples:
- # uncountable "money"
- # uncountable "money", "information"
- # uncountable %w( money information rice )
- def uncountable(*words)
- (@uncountables << words).flatten!
+ # "posts".singularize # => "post"
+ # "octopi".singularize # => "octopus"
+ # "sheep".singluarize # => "sheep"
+ # "word".singluarize # => "word"
+ # "the blue mailmen".singularize # => "the blue mailman"
+ # "CamelOctopi".singularize # => "CamelOctopus"
+ def singularize(word)
+ result = word.to_s.dup
+
+ if inflections.uncountables.include?(result.downcase)
+ result
+ else
+ inflections.singulars.each { |(rule, replacement)| break if result.gsub!(rule, replacement) }
+ result
+ end
end
- # Clears the loaded inflections within a given scope (default is <tt>:all</tt>).
- # Give the scope as a symbol of the inflection type, the options are: <tt>:plurals</tt>,
- # <tt>:singulars</tt>, <tt>:uncountables</tt>.
+ # By default, +camelize+ converts strings to UpperCamelCase. If the argument to +camelize+
+ # is set to <tt>:lower</tt> then +camelize+ produces lowerCamelCase.
+ #
+ # +camelize+ will also convert '/' to '::' which is useful for converting paths to namespaces.
#
# Examples:
- # clear :all
- # clear :plurals
- def clear(scope = :all)
- case scope
- when :all
- @plurals, @singulars, @uncountables = [], [], []
- else
- instance_variable_set "@#{scope}", []
+ # "active_record".camelize # => "ActiveRecord"
+ # "active_record".camelize(:lower) # => "activeRecord"
+ # "active_record/errors".camelize # => "ActiveRecord::Errors"
+ # "active_record/errors".camelize(:lower) # => "activeRecord::Errors"
+ def camelize(lower_case_and_underscored_word, first_letter_in_uppercase = true)
+ if first_letter_in_uppercase
+ lower_case_and_underscored_word.to_s.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase }
+ else
+ lower_case_and_underscored_word.first + camelize(lower_case_and_underscored_word)[1..-1]
end
end
- end
-
- extend self
- # Yields a singleton instance of Inflector::Inflections so you can specify additional
- # inflector rules.
- #
- # Example:
- # Inflector.inflections do |inflect|
- # inflect.uncountable "rails"
- # end
- def inflections
- if block_given?
- yield Inflections.instance
- else
- Inflections.instance
+ # Capitalizes all the words and replaces some characters in the string to create
+ # a nicer looking title. +titleize+ is meant for creating pretty output. It is not
+ # used in the Rails internals.
+ #
+ # +titleize+ is also aliased as as +titlecase+.
+ #
+ # Examples:
+ # "man from the boondocks".titleize # => "Man From The Boondocks"
+ # "x-men: the last stand".titleize # => "X Men: The Last Stand"
+ def titleize(word)
+ humanize(underscore(word)).gsub(/\b('?[a-z])/) { $1.capitalize }
end
- end
-
- # Returns the plural form of the word in the string.
- #
- # Examples:
- # "post".pluralize # => "posts"
- # "octopus".pluralize # => "octopi"
- # "sheep".pluralize # => "sheep"
- # "words".pluralize # => "words"
- # "the blue mailman".pluralize # => "the blue mailmen"
- # "CamelOctopus".pluralize # => "CamelOctopi"
- def pluralize(word)
- result = word.to_s.dup
- if word.empty? || inflections.uncountables.include?(result.downcase)
- result
- else
- inflections.plurals.each { |(rule, replacement)| break if result.gsub!(rule, replacement) }
- result
+ # The reverse of +camelize+. Makes an underscored, lowercase form from the expression in the string.
+ #
+ # Changes '::' to '/' to convert namespaces to paths.
+ #
+ # Examples:
+ # "ActiveRecord".underscore # => "active_record"
+ # "ActiveRecord::Errors".underscore # => active_record/errors
+ def underscore(camel_cased_word)
+ camel_cased_word.to_s.gsub(/::/, '/').
+ gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
+ gsub(/([a-z\d])([A-Z])/,'\1_\2').
+ tr("-", "_").
+ downcase
end
- end
-
- # The reverse of +pluralize+, returns the singular form of a word in a string.
- #
- # Examples:
- # "posts".singularize # => "post"
- # "octopi".singularize # => "octopus"
- # "sheep".singluarize # => "sheep"
- # "word".singluarize # => "word"
- # "the blue mailmen".singularize # => "the blue mailman"
- # "CamelOctopi".singularize # => "CamelOctopus"
- def singularize(word)
- result = word.to_s.dup
- if inflections.uncountables.include?(result.downcase)
- result
- else
- inflections.singulars.each { |(rule, replacement)| break if result.gsub!(rule, replacement) }
- result
+ # Replaces underscores with dashes in the string.
+ #
+ # Example:
+ # "puni_puni" # => "puni-puni"
+ def dasherize(underscored_word)
+ underscored_word.gsub(/_/, '-')
end
- end
- # By default, +camelize+ converts strings to UpperCamelCase. If the argument to +camelize+
- # is set to <tt>:lower</tt> then +camelize+ produces lowerCamelCase.
- #
- # +camelize+ will also convert '/' to '::' which is useful for converting paths to namespaces.
- #
- # Examples:
- # "active_record".camelize # => "ActiveRecord"
- # "active_record".camelize(:lower) # => "activeRecord"
- # "active_record/errors".camelize # => "ActiveRecord::Errors"
- # "active_record/errors".camelize(:lower) # => "activeRecord::Errors"
- def camelize(lower_case_and_underscored_word, first_letter_in_uppercase = true)
- if first_letter_in_uppercase
- lower_case_and_underscored_word.to_s.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase }
- else
- lower_case_and_underscored_word.first + camelize(lower_case_and_underscored_word)[1..-1]
+ # Capitalizes the first word and turns underscores into spaces and strips a
+ # trailing "_id", if any. Like +titleize+, this is meant for creating pretty output.
+ #
+ # Examples:
+ # "employee_salary" # => "Employee salary"
+ # "author_id" # => "Author"
+ def humanize(lower_case_and_underscored_word)
+ lower_case_and_underscored_word.to_s.gsub(/_id$/, "").gsub(/_/, " ").capitalize
end
- end
- # Capitalizes all the words and replaces some characters in the string to create
- # a nicer looking title. +titleize+ is meant for creating pretty output. It is not
- # used in the Rails internals.
- #
- # +titleize+ is also aliased as as +titlecase+.
- #
- # Examples:
- # "man from the boondocks".titleize # => "Man From The Boondocks"
- # "x-men: the last stand".titleize # => "X Men: The Last Stand"
- def titleize(word)
- humanize(underscore(word)).gsub(/\b('?[a-z])/) { $1.capitalize }
- end
-
- # The reverse of +camelize+. Makes an underscored, lowercase form from the expression in the string.
- #
- # Changes '::' to '/' to convert namespaces to paths.
- #
- # Examples:
- # "ActiveRecord".underscore # => "active_record"
- # "ActiveRecord::Errors".underscore # => active_record/errors
- def underscore(camel_cased_word)
- camel_cased_word.to_s.gsub(/::/, '/').
- gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
- gsub(/([a-z\d])([A-Z])/,'\1_\2').
- tr("-", "_").
- downcase
- end
-
- # Replaces underscores with dashes in the string.
- #
- # Example:
- # "puni_puni" # => "puni-puni"
- def dasherize(underscored_word)
- underscored_word.gsub(/_/, '-')
- end
-
- # Capitalizes the first word and turns underscores into spaces and strips a
- # trailing "_id", if any. Like +titleize+, this is meant for creating pretty output.
- #
- # Examples:
- # "employee_salary" # => "Employee salary"
- # "author_id" # => "Author"
- def humanize(lower_case_and_underscored_word)
- lower_case_and_underscored_word.to_s.gsub(/_id$/, "").gsub(/_/, " ").capitalize
- end
+ # Removes the module part from the expression in the string.
+ #
+ # Examples:
+ # "ActiveRecord::CoreExtensions::String::Inflections".demodulize # => "Inflections"
+ # "Inflections".demodulize # => "Inflections"
+ def demodulize(class_name_in_module)
+ class_name_in_module.to_s.gsub(/^.*::/, '')
+ end
- # Removes the module part from the expression in the string.
- #
- # Examples:
- # "ActiveRecord::CoreExtensions::String::Inflections".demodulize # => "Inflections"
- # "Inflections".demodulize # => "Inflections"
- def demodulize(class_name_in_module)
- class_name_in_module.to_s.gsub(/^.*::/, '')
- end
+ # Create the name of a table like Rails does for models to table names. This method
+ # uses the +pluralize+ method on the last word in the string.
+ #
+ # Examples
+ # "RawScaledScorer".tableize # => "raw_scaled_scorers"
+ # "egg_and_ham".tableize # => "egg_and_hams"
+ # "fancyCategory".tableize # => "fancy_categories"
+ def tableize(class_name)
+ pluralize(underscore(class_name))
+ end
- # Create the name of a table like Rails does for models to table names. This method
- # uses the +pluralize+ method on the last word in the string.
- #
- # Examples
- # "RawScaledScorer".tableize # => "raw_scaled_scorers"
- # "egg_and_ham".tableize # => "egg_and_hams"
- # "fancyCategory".tableize # => "fancy_categories"
- def tableize(class_name)
- pluralize(underscore(class_name))
- end
+ # Create a class name from a plural table name like Rails does for table names to models.
+ # Note that this returns a string and not a Class. (To convert to an actual class
+ # follow +classify+ with +constantize+.)
+ #
+ # Examples:
+ # "egg_and_hams".classify # => "EggAndHam"
+ # "posts".classify # => "Post"
+ #
+ # Singular names are not handled correctly:
+ # "business".classify # => "Busines"
+ def classify(table_name)
+ # strip out any leading schema name
+ camelize(singularize(table_name.to_s.sub(/.*\./, '')))
+ end
- # Create a class name from a plural table name like Rails does for table names to models.
- # Note that this returns a string and not a Class. (To convert to an actual class
- # follow +classify+ with +constantize+.)
- #
- # Examples:
- # "egg_and_hams".classify # => "EggAndHam"
- # "posts".classify # => "Post"
- #
- # Singular names are not handled correctly:
- # "business".classify # => "Busines"
- def classify(table_name)
- # strip out any leading schema name
- camelize(singularize(table_name.to_s.sub(/.*\./, '')))
- end
+ # Creates a foreign key name from a class name.
+ # +separate_class_name_and_id_with_underscore+ sets whether
+ # the method should put '_' between the name and 'id'.
+ #
+ # Examples:
+ # "Message".foreign_key # => "message_id"
+ # "Message".foreign_key(false) # => "messageid"
+ # "Admin::Post".foreign_key # => "post_id"
+ def foreign_key(class_name, separate_class_name_and_id_with_underscore = true)
+ underscore(demodulize(class_name)) + (separate_class_name_and_id_with_underscore ? "_id" : "id")
+ end
- # Creates a foreign key name from a class name.
- # +separate_class_name_and_id_with_underscore+ sets whether
- # the method should put '_' between the name and 'id'.
- #
- # Examples:
- # "Message".foreign_key # => "message_id"
- # "Message".foreign_key(false) # => "messageid"
- # "Admin::Post".foreign_key # => "post_id"
- def foreign_key(class_name, separate_class_name_and_id_with_underscore = true)
- underscore(demodulize(class_name)) + (separate_class_name_and_id_with_underscore ? "_id" : "id")
- end
+ # Tries to find a constant with the name specified in the argument string:
+ #
+ # "Module".constantize # => Module
+ # "Test::Unit".constantize # => Test::Unit
+ #
+ # The name is assumed to be the one of a top-level constant, no matter whether
+ # it starts with "::" or not. No lexical context is taken into account:
+ #
+ # C = 'outside'
+ # module M
+ # C = 'inside'
+ # C # => 'inside'
+ # "C".constantize # => 'outside', same as ::C
+ # end
+ #
+ # NameError is raised when the name is not in CamelCase or the constant is
+ # unknown.
+ def constantize(camel_cased_word)
+ unless /\A(?:::)?([A-Z]\w*(?:::[A-Z]\w*)*)\z/ =~ camel_cased_word
+ raise NameError, "#{camel_cased_word.inspect} is not a valid constant name!"
+ end
- # Tries to find a constant with the name specified in the argument string:
- #
- # "Module".constantize # => Module
- # "Test::Unit".constantize # => Test::Unit
- #
- # The name is assumed to be the one of a top-level constant, no matter whether
- # it starts with "::" or not. No lexical context is taken into account:
- #
- # C = 'outside'
- # module M
- # C = 'inside'
- # C # => 'inside'
- # "C".constantize # => 'outside', same as ::C
- # end
- #
- # NameError is raised when the name is not in CamelCase or the constant is
- # unknown.
- def constantize(camel_cased_word)
- unless /\A(?:::)?([A-Z]\w*(?:::[A-Z]\w*)*)\z/ =~ camel_cased_word
- raise NameError, "#{camel_cased_word.inspect} is not a valid constant name!"
+ Object.module_eval("::#{$1}", __FILE__, __LINE__)
end
- Object.module_eval("::#{$1}", __FILE__, __LINE__)
- end
-
- # Turns a number into an ordinal string used to denote the position in an
- # ordered sequence such as 1st, 2nd, 3rd, 4th.
- #
- # Examples:
- # ordinalize(1) # => "1st"
- # ordinalize(2) # => "2nd"
- # ordinalize(1002) # => "1002nd"
- # ordinalize(1003) # => "1003rd"
- def ordinalize(number)
- if (11..13).include?(number.to_i % 100)
- "#{number}th"
- else
- case number.to_i % 10
- when 1; "#{number}st"
- when 2; "#{number}nd"
- when 3; "#{number}rd"
- else "#{number}th"
+ # Turns a number into an ordinal string used to denote the position in an
+ # ordered sequence such as 1st, 2nd, 3rd, 4th.
+ #
+ # Examples:
+ # ordinalize(1) # => "1st"
+ # ordinalize(2) # => "2nd"
+ # ordinalize(1002) # => "1002nd"
+ # ordinalize(1003) # => "1003rd"
+ def ordinalize(number)
+ if (11..13).include?(number.to_i % 100)
+ "#{number}th"
+ else
+ case number.to_i % 10
+ when 1; "#{number}st"
+ when 2; "#{number}nd"
+ when 3; "#{number}rd"
+ else "#{number}th"
+ end
end
end
end
View
26 activesupport/lib/active_support/ordered_options.rb
@@ -1,17 +1,19 @@
-class OrderedOptions < ActiveSupport::OrderedHash #:nodoc:
- def []=(key, value)
- super(key.to_sym, value)
- end
+module ActiveSupport #:nodoc:
+ class OrderedOptions < OrderedHash #:nodoc:
+ def []=(key, value)
+ super(key.to_sym, value)
+ end
- def [](key)
- super(key.to_sym)
- end
+ def [](key)
+ super(key.to_sym)
+ end
- def method_missing(name, *args)
- if name.to_s =~ /(.*)=$/
- self[$1.to_sym] = args.first
- else
- self[name]
+ def method_missing(name, *args)
+ if name.to_s =~ /(.*)=$/
+ self[$1.to_sym] = args.first
+ else
+ self[name]
+ end
end
end
end
View
694 activesupport/lib/active_support/values/time_zone.rb
@@ -4,7 +4,7 @@
# * Retrieve and display zones with a friendlier name (e.g., "Eastern Time (US & Canada)" instead of "America/New_York").
# * Lazily load TZInfo::Timezone instances only when they're needed.
# * Create ActiveSupport::TimeWithZone instances via TimeZone's +local+, +parse+, +at+ and +now+ methods.
-#
+#
# If you set <tt>config.time_zone</tt> in the Rails Initializer, you can access this TimeZone object via <tt>Time.zone</tt>:
#
# # environment.rb:
@@ -16,379 +16,381 @@
# Time.zone.name # => "Eastern Time (US & Canada)"
# Time.zone.now # => Sun, 18 May 2008 14:30:44 EDT -04:00
#
-# The version of TZInfo bundled with Active Support only includes the definitions necessary to support the zones
+# The version of TZInfo bundled with Active Support only includes the definitions necessary to support the zones
# defined by the TimeZone class. If you need to use zones that aren't defined by TimeZone, you'll need to install the TZInfo gem
# (if a recent version of the gem is installed locally, this will be used instead of the bundled version.)
-class TimeZone
- unless const_defined?(:MAPPING)
- # Keys are Rails TimeZone names, values are TZInfo identifiers
- MAPPING = {
- "International Date Line West" => "Pacific/Midway",
- "Midway Island" => "Pacific/Midway",
- "Samoa" => "Pacific/Pago_Pago",
- "Hawaii" => "Pacific/Honolulu",
- "Alaska" => "America/Juneau",
- "Pacific Time (US & Canada)" => "America/Los_Angeles",
- "Tijuana" => "America/Tijuana",
- "Mountain Time (US & Canada)" => "America/Denver",
- "Arizona" => "America/Phoenix",
- "Chihuahua" => "America/Chihuahua",
- "Mazatlan" => "America/Mazatlan",
- "Central Time (US & Canada)" => "America/Chicago",
- "Saskatchewan" => "America/Regina",
- "Guadalajara" => "America/Mexico_City",
- "Mexico City" => "America/Mexico_City",
- "Monterrey" => "America/Monterrey",
- "Central America" => "America/Guatemala",
- "Eastern Time (US & Canada)" => "America/New_York",
- "Indiana (East)" => "America/Indiana/Indianapolis",
- "Bogota" => "America/Bogota",
- "Lima" => "America/Lima",
- "Quito" => "America/Lima",
- "Atlantic Time (Canada)" => "America/Halifax",
- "Caracas" => "America/Caracas",
- "La Paz" => "America/La_Paz",
- "Santiago" => "America/Santiago",
- "Newfoundland" => "America/St_Johns",
- "Brasilia" => "America/Argentina/Buenos_Aires",
- "Buenos Aires" => "America/Argentina/Buenos_Aires",
- "Georgetown" => "America/Argentina/San_Juan",
- "Greenland" => "America/Godthab",
- "Mid-Atlantic" => "Atlantic/South_Georgia",
- "Azores" => "Atlantic/Azores",
- "Cape Verde Is." => "Atlantic/Cape_Verde",
- "Dublin" => "Europe/Dublin",
- "Edinburgh" => "Europe/Dublin",
- "Lisbon" => "Europe/Lisbon",
- "London" => "Europe/London",
- "Casablanca" => "Africa/Casablanca",
- "Monrovia" => "Africa/Monrovia",
- "UTC" => "Etc/UTC",
- "Belgrade" => "Europe/Belgrade",
- "Bratislava" => "Europe/Bratislava",
- "Budapest" => "Europe/Budapest",
- "Ljubljana" => "Europe/Ljubljana",
- "Prague" => "Europe/Prague",
- "Sarajevo" => "Europe/Sarajevo",
- "Skopje" => "Europe/Skopje",
- "Warsaw" => "Europe/Warsaw",
- "Zagreb" => "Europe/Zagreb",
- "Brussels" => "Europe/Brussels",
- "Copenhagen" => "Europe/Copenhagen",
- "Madrid" => "Europe/Madrid",
- "Paris" => "Europe/Paris",
- "Amsterdam" => "Europe/Amsterdam",
- "Berlin" => "Europe/Berlin",
- "Bern" => "Europe/Berlin",
- "Rome" => "Europe/Rome",
- "Stockholm" => "Europe/Stockholm",
- "Vienna" => "Europe/Vienna",
- "West Central Africa" => "Africa/Algiers",
- "Bucharest" => "Europe/Bucharest",
- "Cairo" => "Africa/Cairo",
- "Helsinki" => "Europe/Helsinki",
- "Kyev" => "Europe/Kiev",
- "Riga" => "Europe/Riga",
- "Sofia" => "Europe/Sofia",
- "Tallinn" => "Europe/Tallinn",
- "Vilnius" => "Europe/Vilnius",
- "Athens" => "Europe/Athens",
- "Istanbul" => "Europe/Istanbul",
- "Minsk" => "Europe/Minsk",
- "Jerusalem" => "Asia/Jerusalem",
- "Harare" => "Africa/Harare",
- "Pretoria" => "Africa/Johannesburg",
- "Moscow" => "Europe/Moscow",
- "St. Petersburg" => "Europe/Moscow",
- "Volgograd" => "Europe/Moscow",
- "Kuwait" => "Asia/Kuwait",
- "Riyadh" => "Asia/Riyadh",
- "Nairobi" => "Africa/Nairobi",
- "Baghdad" => "Asia/Baghdad",
- "Tehran" => "Asia/Tehran",
- "Abu Dhabi" => "Asia/Muscat",
- "Muscat" => "Asia/Muscat",
- "Baku" => "Asia/Baku",
- "Tbilisi" => "Asia/Tbilisi",
- "Yerevan" => "Asia/Yerevan",
- "Kabul" => "Asia/Kabul",
- "Ekaterinburg" => "Asia/Yekaterinburg",