aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/lib
diff options
context:
space:
mode:
authorJoshua Peek <josh@joshpeek.com>2008-06-03 13:32:53 -0500
committerJoshua Peek <josh@joshpeek.com>2008-06-03 13:32:53 -0500
commitc08547d2266c75f0a82d06dd91c6d0500740e12e (patch)
treeafd294792deab652137c1d172e752882bbd91669 /activesupport/lib
parentda91450e687fe9faa7b0575062c2b2aacc261f68 (diff)
downloadrails-c08547d2266c75f0a82d06dd91c6d0500740e12e.tar.gz
rails-c08547d2266c75f0a82d06dd91c6d0500740e12e.tar.bz2
rails-c08547d2266c75f0a82d06dd91c6d0500740e12e.zip
Namespace Inflector, Dependencies, OrderedOptions, and TimeZone under ActiveSupport [#238 state:resolved]
Diffstat (limited to 'activesupport/lib')
-rw-r--r--activesupport/lib/active_support.rb4
-rw-r--r--activesupport/lib/active_support/dependencies.rb785
-rw-r--r--activesupport/lib/active_support/deprecation.rb32
-rw-r--r--activesupport/lib/active_support/inflections.rb100
-rw-r--r--activesupport/lib/active_support/inflector.rb526
-rw-r--r--activesupport/lib/active_support/ordered_options.rb26
-rw-r--r--activesupport/lib/active_support/values/time_zone.rb694
7 files changed, 1099 insertions, 1068 deletions
diff --git a/activesupport/lib/active_support.rb b/activesupport/lib/active_support.rb
index e4cb145c98..982adfb0cf 100644
--- a/activesupport/lib/active_support.rb
+++ b/activesupport/lib/active_support.rb
@@ -53,3 +53,7 @@ require 'active_support/multibyte'
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')
diff --git a/activesupport/lib/active_support/dependencies.rb b/activesupport/lib/active_support/dependencies.rb
index da2ece610a..7a8c4d0326 100644
--- a/activesupport/lib/active_support/dependencies.rb
+++ b/activesupport/lib/active_support/dependencies.rb
@@ -3,458 +3,459 @@ require 'active_support/core_ext/module/attribute_accessors'
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 @@ class Class
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 @@ class Object
# 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
diff --git a/activesupport/lib/active_support/deprecation.rb b/activesupport/lib/active_support/deprecation.rb
index 758aef5445..ebdaf86146 100644
--- a/activesupport/lib/active_support/deprecation.rb
+++ b/activesupport/lib/active_support/deprecation.rb
@@ -144,17 +144,11 @@ module ActiveSupport
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 @@ module ActiveSupport
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 @@ module ActiveSupport
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
diff --git a/activesupport/lib/active_support/inflections.rb b/activesupport/lib/active_support/inflections.rb
index 967722c2bf..b6d276953a 100644
--- a/activesupport/lib/active_support/inflections.rb
+++ b/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
diff --git a/activesupport/lib/active_support/inflector.rb b/activesupport/lib/active_support/inflector.rb
index a4fd619317..fc88d80cdb 100644
--- a/activesupport/lib/active_support/inflector.rb
+++ b/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
diff --git a/activesupport/lib/active_support/ordered_options.rb b/activesupport/lib/active_support/ordered_options.rb
index 306376e9ae..642045186f 100644
--- a/activesupport/lib/active_support/ordered_options.rb
+++ b/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
diff --git a/activesupport/lib/active_support/values/time_zone.rb b/activesupport/lib/active_support/values/time_zone.rb
index a71c819fba..5b2d42aa3c 100644
--- a/activesupport/lib/active_support/values/time_zone.rb
+++ b/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",
- "Islamabad" => "Asia/Karachi",
- "Karachi" => "Asia/Karachi",
- "Tashkent" => "Asia/Tashkent",
- "Chennai" => "Asia/Kolkata",
- "Kolkata" => "Asia/Kolkata",
- "Mumbai" => "Asia/Kolkata",
- "New Delhi" => "Asia/Kolkata",
- "Kathmandu" => "Asia/Katmandu",
- "Astana" => "Asia/Dhaka",
- "Dhaka" => "Asia/Dhaka",
- "Sri Jayawardenepura" => "Asia/Dhaka",
- "Almaty" => "Asia/Almaty",
- "Novosibirsk" => "Asia/Novosibirsk",
- "Rangoon" => "Asia/Rangoon",
- "Bangkok" => "Asia/Bangkok",
- "Hanoi" => "Asia/Bangkok",
- "Jakarta" => "Asia/Jakarta",
- "Krasnoyarsk" => "Asia/Krasnoyarsk",
- "Beijing" => "Asia/Shanghai",
- "Chongqing" => "Asia/Chongqing",
- "Hong Kong" => "Asia/Hong_Kong",
- "Urumqi" => "Asia/Urumqi",
- "Kuala Lumpur" => "Asia/Kuala_Lumpur",
- "Singapore" => "Asia/Singapore",
- "Taipei" => "Asia/Taipei",
- "Perth" => "Australia/Perth",
- "Irkutsk" => "Asia/Irkutsk",
- "Ulaan Bataar" => "Asia/Ulaanbaatar",
- "Seoul" => "Asia/Seoul",
- "Osaka" => "Asia/Tokyo",
- "Sapporo" => "Asia/Tokyo",
- "Tokyo" => "Asia/Tokyo",
- "Yakutsk" => "Asia/Yakutsk",
- "Darwin" => "Australia/Darwin",
- "Adelaide" => "Australia/Adelaide",
- "Canberra" => "Australia/Melbourne",
- "Melbourne" => "Australia/Melbourne",
- "Sydney" => "Australia/Sydney",
- "Brisbane" => "Australia/Brisbane",
- "Hobart" => "Australia/Hobart",
- "Vladivostok" => "Asia/Vladivostok",
- "Guam" => "Pacific/Guam",
- "Port Moresby" => "Pacific/Port_Moresby",
- "Magadan" => "Asia/Magadan",
- "Solomon Is." => "Asia/Magadan",
- "New Caledonia" => "Pacific/Noumea",
- "Fiji" => "Pacific/Fiji",
- "Kamchatka" => "Asia/Kamchatka",
- "Marshall Is." => "Pacific/Majuro",
- "Auckland" => "Pacific/Auckland",
- "Wellington" => "Pacific/Auckland",
- "Nuku'alofa" => "Pacific/Tongatapu"
- }.each { |name, zone| name.freeze; zone.freeze }
- MAPPING.freeze
- end
-
- include Comparable
- attr_reader :name
+module ActiveSupport
+ 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",
+ "Islamabad" => "Asia/Karachi",
+ "Karachi" => "Asia/Karachi",
+ "Tashkent" => "Asia/Tashkent",
+ "Chennai" => "Asia/Kolkata",
+ "Kolkata" => "Asia/Kolkata",
+ "Mumbai" => "Asia/Kolkata",
+ "New Delhi" => "Asia/Kolkata",
+ "Kathmandu" => "Asia/Katmandu",
+ "Astana" => "Asia/Dhaka",
+ "Dhaka" => "Asia/Dhaka",
+ "Sri Jayawardenepura" => "Asia/Dhaka",
+ "Almaty" => "Asia/Almaty",
+ "Novosibirsk" => "Asia/Novosibirsk",
+ "Rangoon" => "Asia/Rangoon",
+ "Bangkok" => "Asia/Bangkok",
+ "Hanoi" => "Asia/Bangkok",
+ "Jakarta" => "Asia/Jakarta",
+ "Krasnoyarsk" => "Asia/Krasnoyarsk",
+ "Beijing" => "Asia/Shanghai",
+ "Chongqing" => "Asia/Chongqing",
+ "Hong Kong" => "Asia/Hong_Kong",
+ "Urumqi" => "Asia/Urumqi",
+ "Kuala Lumpur" => "Asia/Kuala_Lumpur",
+ "Singapore" => "Asia/Singapore",
+ "Taipei" => "Asia/Taipei",
+ "Perth" => "Australia/Perth",
+ "Irkutsk" => "Asia/Irkutsk",
+ "Ulaan Bataar" => "Asia/Ulaanbaatar",
+ "Seoul" => "Asia/Seoul",
+ "Osaka" => "Asia/Tokyo",
+ "Sapporo" => "Asia/Tokyo",
+ "Tokyo" => "Asia/Tokyo",
+ "Yakutsk" => "Asia/Yakutsk",
+ "Darwin" => "Australia/Darwin",
+ "Adelaide" => "Australia/Adelaide",
+ "Canberra" => "Australia/Melbourne",
+ "Melbourne" => "Australia/Melbourne",
+ "Sydney" => "Australia/Sydney",
+ "Brisbane" => "Australia/Brisbane",
+ "Hobart" => "Australia/Hobart",
+ "Vladivostok" => "Asia/Vladivostok",
+ "Guam" => "Pacific/Guam",
+ "Port Moresby" => "Pacific/Port_Moresby",
+ "Magadan" => "Asia/Magadan",
+ "Solomon Is." => "Asia/Magadan",
+ "New Caledonia" => "Pacific/Noumea",
+ "Fiji" => "Pacific/Fiji",
+ "Kamchatka" => "Asia/Kamchatka",
+ "Marshall Is." => "Pacific/Majuro",
+ "Auckland" => "Pacific/Auckland",
+ "Wellington" => "Pacific/Auckland",
+ "Nuku'alofa" => "Pacific/Tongatapu"
+ }.each { |name, zone| name.freeze; zone.freeze }
+ MAPPING.freeze
+ end
- # Create a new TimeZone object with the given name and offset. The
- # offset is the number of seconds that this time zone is offset from UTC
- # (GMT). Seconds were chosen as the offset unit because that is the unit that
- # Ruby uses to represent time zone offsets (see Time#utc_offset).
- def initialize(name, utc_offset, tzinfo = nil)
- @name = name
- @utc_offset = utc_offset
- @tzinfo = tzinfo
- end
+ include Comparable
+ attr_reader :name
- def utc_offset
- @utc_offset ||= tzinfo.current_period.utc_offset
- end
-
- # Returns the offset of this time zone as a formatted string, of the
- # format "+HH:MM".
- def formatted_offset(colon=true, alternate_utc_string = nil)
- utc_offset == 0 && alternate_utc_string || utc_offset.to_utc_offset_s(colon)
- end
+ # Create a new TimeZone object with the given name and offset. The
+ # offset is the number of seconds that this time zone is offset from UTC
+ # (GMT). Seconds were chosen as the offset unit because that is the unit that
+ # Ruby uses to represent time zone offsets (see Time#utc_offset).
+ def initialize(name, utc_offset, tzinfo = nil)
+ @name = name
+ @utc_offset = utc_offset
+ @tzinfo = tzinfo
+ end
- # Compare this time zone to the parameter. The two are comapred first on
- # their offsets, and then by name.
- def <=>(zone)
- result = (utc_offset <=> zone.utc_offset)
- result = (name <=> zone.name) if result == 0
- result
- end
+ def utc_offset
+ @utc_offset ||= tzinfo.current_period.utc_offset
+ end
- # Returns a textual representation of this time zone.
- def to_s
- "(GMT#{formatted_offset}) #{name}"
- end
+ # Returns the offset of this time zone as a formatted string, of the
+ # format "+HH:MM".
+ def formatted_offset(colon=true, alternate_utc_string = nil)
+ utc_offset == 0 && alternate_utc_string || utc_offset.to_utc_offset_s(colon)
+ end
- # Method for creating new ActiveSupport::TimeWithZone instance in time zone of +self+ from given values. Example:
- #
- # Time.zone = "Hawaii" # => "Hawaii"
- # Time.zone.local(2007, 2, 1, 15, 30, 45) # => Thu, 01 Feb 2007 15:30:45 HST -10:00
- def local(*args)
- time = Time.utc_time(*args)
- ActiveSupport::TimeWithZone.new(nil, self, time)
- end
+ # Compare this time zone to the parameter. The two are comapred first on
+ # their offsets, and then by name.
+ def <=>(zone)
+ result = (utc_offset <=> zone.utc_offset)
+ result = (name <=> zone.name) if result == 0
+ result
+ end
- # Method for creating new ActiveSupport::TimeWithZone instance in time zone of +self+ from number of seconds since the Unix epoch. Example:
- #
- # Time.zone = "Hawaii" # => "Hawaii"
- # Time.utc(2000).to_f # => 946684800.0
- # Time.zone.at(946684800.0) # => Fri, 31 Dec 1999 14:00:00 HST -10:00
- def at(secs)
- utc = Time.at(secs).utc rescue DateTime.civil(1970).since(secs)
- utc.in_time_zone(self)
- end
+ # Returns a textual representation of this time zone.
+ def to_s
+ "(GMT#{formatted_offset}) #{name}"
+ end
- # Method for creating new ActiveSupport::TimeWithZone instance in time zone of +self+ from parsed string. Example:
- #
- # Time.zone = "Hawaii" # => "Hawaii"
- # Time.zone.parse('1999-12-31 14:00:00') # => Fri, 31 Dec 1999 14:00:00 HST -10:00
- #
- # If upper components are missing from the string, they are supplied from TimeZone#now:
- #
- # Time.zone.now # => Fri, 31 Dec 1999 14:00:00 HST -10:00
- # Time.zone.parse('22:30:00') # => Fri, 31 Dec 1999 22:30:00 HST -10:00
- def parse(str, now=now)
- date_parts = Date._parse(str)
- return if date_parts.blank?
- time = Time.parse(str, now) rescue DateTime.parse(str)
- if date_parts[:offset].nil?
+ # Method for creating new ActiveSupport::TimeWithZone instance in time zone of +self+ from given values. Example:
+ #
+ # Time.zone = "Hawaii" # => "Hawaii"
+ # Time.zone.local(2007, 2, 1, 15, 30, 45) # => Thu, 01 Feb 2007 15:30:45 HST -10:00
+ def local(*args)
+ time = Time.utc_time(*args)
ActiveSupport::TimeWithZone.new(nil, self, time)
- else
- time.in_time_zone(self)
end
- end
- # Returns an ActiveSupport::TimeWithZone instance representing the current time
- # in the time zone represented by +self+. Example:
- #
- # Time.zone = 'Hawaii' # => "Hawaii"
- # Time.zone.now # => Wed, 23 Jan 2008 20:24:27 HST -10:00
- def now
- Time.now.utc.in_time_zone(self)
- end
+ # Method for creating new ActiveSupport::TimeWithZone instance in time zone of +self+ from number of seconds since the Unix epoch. Example:
+ #
+ # Time.zone = "Hawaii" # => "Hawaii"
+ # Time.utc(2000).to_f # => 946684800.0
+ # Time.zone.at(946684800.0) # => Fri, 31 Dec 1999 14:00:00 HST -10:00
+ def at(secs)
+ utc = Time.at(secs).utc rescue DateTime.civil(1970).since(secs)
+ utc.in_time_zone(self)
+ end
- # Return the current date in this time zone.
- def today
- tzinfo.now.to_date
- end
+ # Method for creating new ActiveSupport::TimeWithZone instance in time zone of +self+ from parsed string. Example:
+ #
+ # Time.zone = "Hawaii" # => "Hawaii"
+ # Time.zone.parse('1999-12-31 14:00:00') # => Fri, 31 Dec 1999 14:00:00 HST -10:00
+ #
+ # If upper components are missing from the string, they are supplied from TimeZone#now:
+ #
+ # Time.zone.now # => Fri, 31 Dec 1999 14:00:00 HST -10:00
+ # Time.zone.parse('22:30:00') # => Fri, 31 Dec 1999 22:30:00 HST -10:00
+ def parse(str, now=now)
+ date_parts = Date._parse(str)
+ return if date_parts.blank?
+ time = Time.parse(str, now) rescue DateTime.parse(str)
+ if date_parts[:offset].nil?
+ ActiveSupport::TimeWithZone.new(nil, self, time)
+ else
+ time.in_time_zone(self)
+ end
+ end
- # Adjust the given time to the simultaneous time in the time zone represented by +self+. Returns a
- # Time.utc() instance -- if you want an ActiveSupport::TimeWithZone instance, use Time#in_time_zone() instead.
- def utc_to_local(time)
- tzinfo.utc_to_local(time)
- end
+ # Returns an ActiveSupport::TimeWithZone instance representing the current time
+ # in the time zone represented by +self+. Example:
+ #
+ # Time.zone = 'Hawaii' # => "Hawaii"
+ # Time.zone.now # => Wed, 23 Jan 2008 20:24:27 HST -10:00
+ def now
+ Time.now.utc.in_time_zone(self)
+ end
- # Adjust the given time to the simultaneous time in UTC. Returns a Time.utc() instance.
- def local_to_utc(time, dst=true)
- tzinfo.local_to_utc(time, dst)
- end
+ # Return the current date in this time zone.
+ def today
+ tzinfo.now.to_date
+ end
- # Available so that TimeZone instances respond like TZInfo::Timezone instances
- def period_for_utc(time)
- tzinfo.period_for_utc(time)
- end
+ # Adjust the given time to the simultaneous time in the time zone represented by +self+. Returns a
+ # Time.utc() instance -- if you want an ActiveSupport::TimeWithZone instance, use Time#in_time_zone() instead.
+ def utc_to_local(time)
+ tzinfo.utc_to_local(time)
+ end
- # Available so that TimeZone instances respond like TZInfo::Timezone instances
- def period_for_local(time, dst=true)
- tzinfo.period_for_local(time, dst)
- end
+ # Adjust the given time to the simultaneous time in UTC. Returns a Time.utc() instance.
+ def local_to_utc(time, dst=true)
+ tzinfo.local_to_utc(time, dst)
+ end
- # TODO: Preload instead of lazy load for thread safety
- def tzinfo
- @tzinfo ||= TZInfo::Timezone.get(MAPPING[name])
- end
+ # Available so that TimeZone instances respond like TZInfo::Timezone instances
+ def period_for_utc(time)
+ tzinfo.period_for_utc(time)
+ end
- unless const_defined?(:ZONES)
- ZONES = []
- ZONES_MAP = {}
- [[-39_600, "International Date Line West", "Midway Island", "Samoa" ],
- [-36_000, "Hawaii" ],
- [-32_400, "Alaska" ],
- [-28_800, "Pacific Time (US & Canada)", "Tijuana" ],
- [-25_200, "Mountain Time (US & Canada)", "Chihuahua", "Mazatlan",
- "Arizona" ],
- [-21_600, "Central Time (US & Canada)", "Saskatchewan", "Guadalajara",
- "Mexico City", "Monterrey", "Central America" ],
- [-18_000, "Eastern Time (US & Canada)", "Indiana (East)", "Bogota",
- "Lima", "Quito" ],
- [-14_400, "Atlantic Time (Canada)", "Caracas", "La Paz", "Santiago" ],
- [-12_600, "Newfoundland" ],
- [-10_800, "Brasilia", "Buenos Aires", "Georgetown", "Greenland" ],
- [ -7_200, "Mid-Atlantic" ],
- [ -3_600, "Azores", "Cape Verde Is." ],
- [ 0, "Dublin", "Edinburgh", "Lisbon", "London", "Casablanca",
- "Monrovia", "UTC" ],
- [ 3_600, "Belgrade", "Bratislava", "Budapest", "Ljubljana", "Prague",
- "Sarajevo", "Skopje", "Warsaw", "Zagreb", "Brussels",
- "Copenhagen", "Madrid", "Paris", "Amsterdam", "Berlin",
- "Bern", "Rome", "Stockholm", "Vienna",
- "West Central Africa" ],
- [ 7_200, "Bucharest", "Cairo", "Helsinki", "Kyev", "Riga", "Sofia",
- "Tallinn", "Vilnius", "Athens", "Istanbul", "Minsk",
- "Jerusalem", "Harare", "Pretoria" ],
- [ 10_800, "Moscow", "St. Petersburg", "Volgograd", "Kuwait", "Riyadh",
- "Nairobi", "Baghdad" ],
- [ 12_600, "Tehran" ],
- [ 14_400, "Abu Dhabi", "Muscat", "Baku", "Tbilisi", "Yerevan" ],
- [ 16_200, "Kabul" ],
- [ 18_000, "Ekaterinburg", "Islamabad", "Karachi", "Tashkent" ],
- [ 19_800, "Chennai", "Kolkata", "Mumbai", "New Delhi" ],
- [ 20_700, "Kathmandu" ],
- [ 21_600, "Astana", "Dhaka", "Sri Jayawardenepura", "Almaty",
- "Novosibirsk" ],
- [ 23_400, "Rangoon" ],
- [ 25_200, "Bangkok", "Hanoi", "Jakarta", "Krasnoyarsk" ],
- [ 28_800, "Beijing", "Chongqing", "Hong Kong", "Urumqi",
- "Kuala Lumpur", "Singapore", "Taipei", "Perth", "Irkutsk",
- "Ulaan Bataar" ],
- [ 32_400, "Seoul", "Osaka", "Sapporo", "Tokyo", "Yakutsk" ],
- [ 34_200, "Darwin", "Adelaide" ],
- [ 36_000, "Canberra", "Melbourne", "Sydney", "Brisbane", "Hobart",
- "Vladivostok", "Guam", "Port Moresby" ],
- [ 39_600, "Magadan", "Solomon Is.", "New Caledonia" ],
- [ 43_200, "Fiji", "Kamchatka", "Marshall Is.", "Auckland",
- "Wellington" ],
- [ 46_800, "Nuku'alofa" ]].
- each do |offset, *places|
- places.each do |place|
- place.freeze
- zone = new(place, offset)
- ZONES << zone
- ZONES_MAP[place] = zone
- end
+ # Available so that TimeZone instances respond like TZInfo::Timezone instances
+ def period_for_local(time, dst=true)
+ tzinfo.period_for_local(time, dst)
end
- ZONES.sort!
- ZONES.freeze
- ZONES_MAP.freeze
- US_ZONES = ZONES.find_all { |z| z.name =~ /US|Arizona|Indiana|Hawaii|Alaska/ }
- US_ZONES.freeze
- end
+ # TODO: Preload instead of lazy load for thread safety
+ def tzinfo
+ @tzinfo ||= TZInfo::Timezone.get(MAPPING[name])
+ end
- class << self
- alias_method :create, :new
+ unless const_defined?(:ZONES)
+ ZONES = []
+ ZONES_MAP = {}
+ [[-39_600, "International Date Line West", "Midway Island", "Samoa" ],
+ [-36_000, "Hawaii" ],
+ [-32_400, "Alaska" ],
+ [-28_800, "Pacific Time (US & Canada)", "Tijuana" ],
+ [-25_200, "Mountain Time (US & Canada)", "Chihuahua", "Mazatlan",
+ "Arizona" ],
+ [-21_600, "Central Time (US & Canada)", "Saskatchewan", "Guadalajara",
+ "Mexico City", "Monterrey", "Central America" ],
+ [-18_000, "Eastern Time (US & Canada)", "Indiana (East)", "Bogota",
+ "Lima", "Quito" ],
+ [-14_400, "Atlantic Time (Canada)", "Caracas", "La Paz", "Santiago" ],
+ [-12_600, "Newfoundland" ],
+ [-10_800, "Brasilia", "Buenos Aires", "Georgetown", "Greenland" ],
+ [ -7_200, "Mid-Atlantic" ],
+ [ -3_600, "Azores", "Cape Verde Is." ],
+ [ 0, "Dublin", "Edinburgh", "Lisbon", "London", "Casablanca",
+ "Monrovia", "UTC" ],
+ [ 3_600, "Belgrade", "Bratislava", "Budapest", "Ljubljana", "Prague",
+ "Sarajevo", "Skopje", "Warsaw", "Zagreb", "Brussels",
+ "Copenhagen", "Madrid", "Paris", "Amsterdam", "Berlin",
+ "Bern", "Rome", "Stockholm", "Vienna",
+ "West Central Africa" ],
+ [ 7_200, "Bucharest", "Cairo", "Helsinki", "Kyev", "Riga", "Sofia",
+ "Tallinn", "Vilnius", "Athens", "Istanbul", "Minsk",
+ "Jerusalem", "Harare", "Pretoria" ],
+ [ 10_800, "Moscow", "St. Petersburg", "Volgograd", "Kuwait", "Riyadh",
+ "Nairobi", "Baghdad" ],
+ [ 12_600, "Tehran" ],
+ [ 14_400, "Abu Dhabi", "Muscat", "Baku", "Tbilisi", "Yerevan" ],
+ [ 16_200, "Kabul" ],
+ [ 18_000, "Ekaterinburg", "Islamabad", "Karachi", "Tashkent" ],
+ [ 19_800, "Chennai", "Kolkata", "Mumbai", "New Delhi" ],
+ [ 20_700, "Kathmandu" ],
+ [ 21_600, "Astana", "Dhaka", "Sri Jayawardenepura", "Almaty",
+ "Novosibirsk" ],
+ [ 23_400, "Rangoon" ],
+ [ 25_200, "Bangkok", "Hanoi", "Jakarta", "Krasnoyarsk" ],
+ [ 28_800, "Beijing", "Chongqing", "Hong Kong", "Urumqi",
+ "Kuala Lumpur", "Singapore", "Taipei", "Perth", "Irkutsk",
+ "Ulaan Bataar" ],
+ [ 32_400, "Seoul", "Osaka", "Sapporo", "Tokyo", "Yakutsk" ],
+ [ 34_200, "Darwin", "Adelaide" ],
+ [ 36_000, "Canberra", "Melbourne", "Sydney", "Brisbane", "Hobart",
+ "Vladivostok", "Guam", "Port Moresby" ],
+ [ 39_600, "Magadan", "Solomon Is.", "New Caledonia" ],
+ [ 43_200, "Fiji", "Kamchatka", "Marshall Is.", "Auckland",
+ "Wellington" ],
+ [ 46_800, "Nuku'alofa" ]].
+ each do |offset, *places|
+ places.each do |place|
+ place.freeze
+ zone = new(place, offset)
+ ZONES << zone
+ ZONES_MAP[place] = zone
+ end
+ end
+ ZONES.sort!
+ ZONES.freeze
+ ZONES_MAP.freeze
- # Return a TimeZone instance with the given name, or +nil+ if no
- # such TimeZone instance exists. (This exists to support the use of
- # this class with the +composed_of+ macro.)
- def new(name)
- self[name]
+ US_ZONES = ZONES.find_all { |z| z.name =~ /US|Arizona|Indiana|Hawaii|Alaska/ }
+ US_ZONES.freeze
end
- # Return an array of all TimeZone objects. There are multiple
- # TimeZone objects per time zone, in many cases, to make it easier
- # for users to find their own time zone.
- def all
- ZONES
- end
+ class << self
+ alias_method :create, :new
- # Locate a specific time zone object. If the argument is a string, it
- # is interpreted to mean the name of the timezone to locate. If it is a
- # numeric value it is either the hour offset, or the second offset, of the
- # timezone to find. (The first one with that offset will be returned.)
- # Returns +nil+ if no such time zone is known to the system.
- def [](arg)
- case arg
- when String
- ZONES_MAP[arg]
- when Numeric, ActiveSupport::Duration
- arg *= 3600 if arg.abs <= 13
- all.find { |z| z.utc_offset == arg.to_i }
- else
- raise ArgumentError, "invalid argument to TimeZone[]: #{arg.inspect}"
+ # Return a TimeZone instance with the given name, or +nil+ if no
+ # such TimeZone instance exists. (This exists to support the use of
+ # this class with the +composed_of+ macro.)
+ def new(name)
+ self[name]
end
- end
- # A convenience method for returning a collection of TimeZone objects
- # for time zones in the USA.
- def us_zones
- US_ZONES
+ # Return an array of all TimeZone objects. There are multiple
+ # TimeZone objects per time zone, in many cases, to make it easier
+ # for users to find their own time zone.
+ def all
+ ZONES
+ end
+
+ # Locate a specific time zone object. If the argument is a string, it
+ # is interpreted to mean the name of the timezone to locate. If it is a
+ # numeric value it is either the hour offset, or the second offset, of the
+ # timezone to find. (The first one with that offset will be returned.)
+ # Returns +nil+ if no such time zone is known to the system.
+ def [](arg)
+ case arg
+ when String
+ ZONES_MAP[arg]
+ when Numeric, ActiveSupport::Duration
+ arg *= 3600 if arg.abs <= 13
+ all.find { |z| z.utc_offset == arg.to_i }
+ else
+ raise ArgumentError, "invalid argument to TimeZone[]: #{arg.inspect}"
+ end
+ end
+
+ # A convenience method for returning a collection of TimeZone objects
+ # for time zones in the USA.
+ def us_zones
+ US_ZONES
+ end
end
end
end