diff options
Diffstat (limited to 'activesupport/lib')
37 files changed, 776 insertions, 417 deletions
diff --git a/activesupport/lib/active_support.rb b/activesupport/lib/active_support.rb index e34e46b4cf..ba91e8bba3 100644 --- a/activesupport/lib/active_support.rb +++ b/activesupport/lib/active_support.rb @@ -39,6 +39,11 @@ require "active_support/dependencies/autoload" module ActiveSupport extend ActiveSupport::Autoload + autoload :DescendantsTracker + autoload :FileUpdateChecker + autoload :LogSubscriber + autoload :Notifications + # TODO: Narrow this list down eager_autoload do autoload :BacktraceCleaner @@ -61,7 +66,6 @@ module ActiveSupport autoload :OptionMerger autoload :OrderedHash autoload :OrderedOptions - autoload :Notifications autoload :Rescuable autoload :SecureRandom autoload :StringInquirer diff --git a/activesupport/lib/active_support/all.rb b/activesupport/lib/active_support/all.rb index f537818300..def8eca89f 100644 --- a/activesupport/lib/active_support/all.rb +++ b/activesupport/lib/active_support/all.rb @@ -1,3 +1,4 @@ require 'active_support' require 'active_support/time' require 'active_support/core_ext' +require 'active_support/json' diff --git a/activesupport/lib/active_support/cache.rb b/activesupport/lib/active_support/cache.rb index 2605a3f2b8..bef9c98ecf 100644 --- a/activesupport/lib/active_support/cache.rb +++ b/activesupport/lib/active_support/cache.rb @@ -22,7 +22,7 @@ module ActiveSupport EMPTY_OPTIONS = {}.freeze # These options mean something to all cache implementations. Individual cache - # implementations may support additional optons. + # implementations may support additional options. UNIVERSAL_OPTIONS = [:namespace, :compress, :compress_threshold, :expires_in, :race_condition_ttl] module Strategy @@ -267,27 +267,39 @@ module ActiveSupport # :bar # end # cache.fetch("foo") # => "bar" - def fetch(name, options = nil, &block) - options = merged_options(options) - key = namespaced_key(name, options) - entry = instrument(:read, name, options) { read_entry(key, options) } unless options[:force] - if entry && entry.expired? - race_ttl = options[:race_condition_ttl].to_f - if race_ttl and Time.now.to_f - entry.expires_at <= race_ttl - entry.expires_at = Time.now + race_ttl - write_entry(key, entry, :expires_in => race_ttl * 2) - else - delete_entry(key, options) + def fetch(name, options = nil) + if block_given? + options = merged_options(options) + key = namespaced_key(name, options) + unless options[:force] + entry = instrument(:read, name, options) do |payload| + payload[:super_operation] = :fetch if payload + read_entry(key, options) + end + end + if entry && entry.expired? + race_ttl = options[:race_condition_ttl].to_f + if race_ttl and Time.now.to_f - entry.expires_at <= race_ttl + entry.expires_at = Time.now + race_ttl + write_entry(key, entry, :expires_in => race_ttl * 2) + else + delete_entry(key, options) + end + entry = nil end - entry = nil - end - if entry - entry.value - elsif block_given? - result = instrument(:generate, name, options, &block) - write(name, result, options) - result + if entry + instrument(:fetch_hit, name, options) { |payload| } + entry.value + else + result = instrument(:generate, name, options) do |payload| + yield + end + write(name, result, options) + result + end + else + read(name, options) end end @@ -299,16 +311,19 @@ module ActiveSupport def read(name, options = nil) options = merged_options(options) key = namespaced_key(name, options) - instrument(:read, name, options) do + instrument(:read, name, options) do |payload| entry = read_entry(key, options) if entry if entry.expired? delete_entry(key, options) + payload[:hit] = false if payload nil else + payload[:hit] = true if payload entry.value end else + payload[:hit] = false if payload nil end end @@ -345,7 +360,7 @@ module ActiveSupport # +options+. def write(name, value, options = nil) options = merged_options(options) - instrument(:write, name, options) do + instrument(:write, name, options) do |payload| entry = Entry.new(value, options) write_entry(namespaced_key(name, options), entry, options) end @@ -356,7 +371,7 @@ module ActiveSupport # Options are passed to the underlying cache implementation. def delete(name, options = nil) options = merged_options(options) - instrument(:delete, name) do + instrument(:delete, name) do |payload| delete_entry(namespaced_key(name, options), options) end end @@ -366,7 +381,7 @@ module ActiveSupport # Options are passed to the underlying cache implementation. def exist?(name, options = nil) options = merged_options(options) - instrument(:exist?, name) do + instrument(:exist?, name) do |payload| entry = read_entry(namespaced_key(name, options), options) if entry && !entry.expired? true @@ -502,9 +517,9 @@ module ActiveSupport if self.class.instrument payload = { :key => key } payload.merge!(options) if options.is_a?(Hash) - ActiveSupport::Notifications.instrument("cache_#{operation}.active_support", payload){ yield } + ActiveSupport::Notifications.instrument("cache_#{operation}.active_support", payload){ yield(payload) } else - yield + yield(nil) end end diff --git a/activesupport/lib/active_support/cache/mem_cache_store.rb b/activesupport/lib/active_support/cache/mem_cache_store.rb index e3a2688e2f..852defeae8 100644 --- a/activesupport/lib/active_support/cache/mem_cache_store.rb +++ b/activesupport/lib/active_support/cache/mem_cache_store.rb @@ -35,7 +35,7 @@ module ActiveSupport def self.build_mem_cache(*addresses) addresses = addresses.flatten options = addresses.extract_options! - addresses = ["localhost"] if addresses.empty? + addresses = ["localhost:11211"] if addresses.empty? MemCache.new(addresses, options) end @@ -159,7 +159,7 @@ module ActiveSupport private def escape_key(key) - key = key.to_s.gsub(ESCAPE_KEY_CHARS){|match| "%#{match[0].to_s(16).upcase}"} + key = key.to_s.gsub(ESCAPE_KEY_CHARS){|match| "%#{match.getbyte(0).to_s(16).upcase}"} key = "#{key[0, 213]}:md5:#{Digest::MD5.hexdigest(key)}" if key.size > 250 key end diff --git a/activesupport/lib/active_support/cache/memory_store.rb b/activesupport/lib/active_support/cache/memory_store.rb index b1d14a0d8f..f5c2b8af8b 100644 --- a/activesupport/lib/active_support/cache/memory_store.rb +++ b/activesupport/lib/active_support/cache/memory_store.rb @@ -10,7 +10,7 @@ module ActiveSupport # appropriate cache for you. # # This cache has a bounded size specified by the :size options to the - # initializer (default is 32Mb). When the cache exceeds the alotted size, + # initializer (default is 32Mb). When the cache exceeds the allotted size, # a cleanup will occur which tries to prune the cache down to three quarters # of the maximum size by removing the least recently used entries. # diff --git a/activesupport/lib/active_support/callbacks.rb b/activesupport/lib/active_support/callbacks.rb index 3ff33eea72..c4e1eb2c04 100644 --- a/activesupport/lib/active_support/callbacks.rb +++ b/activesupport/lib/active_support/callbacks.rb @@ -1,6 +1,6 @@ +require 'active_support/descendants_tracker' require 'active_support/core_ext/array/wrap' require 'active_support/core_ext/class/inheritable_attributes' -require 'active_support/core_ext/class/subclasses' require 'active_support/core_ext/kernel/reporting' require 'active_support/core_ext/kernel/singleton_class' @@ -85,6 +85,10 @@ module ActiveSupport module Callbacks extend Concern + included do + extend ActiveSupport::DescendantsTracker + end + def run_callbacks(kind, *args, &block) send("_run_#{kind}_callbacks", *args, &block) end @@ -428,7 +432,7 @@ module ActiveSupport options = filters.last.is_a?(Hash) ? filters.pop : {} filters.unshift(block) if block - ([self] + self.descendents).each do |target| + ([self] + self.descendants).each do |target| chain = target.send("_#{name}_callbacks") yield chain, type, filters, options target.__define_runner(name) @@ -502,7 +506,7 @@ module ActiveSupport def reset_callbacks(symbol) callbacks = send("_#{symbol}_callbacks") - self.descendents.each do |target| + self.descendants.each do |target| chain = target.send("_#{symbol}_callbacks") callbacks.each { |c| chain.delete(c) } target.__define_runner(symbol) diff --git a/activesupport/lib/active_support/core_ext/array/grouping.rb b/activesupport/lib/active_support/core_ext/array/grouping.rb index ef416787a9..4cd9bfadac 100644 --- a/activesupport/lib/active_support/core_ext/array/grouping.rb +++ b/activesupport/lib/active_support/core_ext/array/grouping.rb @@ -55,7 +55,7 @@ class Array # ["6", "7"] def in_groups(number, fill_with = nil) # size / number gives minor group size; - # size % number gives how many objects need extra accomodation; + # size % number gives how many objects need extra accommodation; # each group hold either division or division + 1 items. division = size / number modulo = size % number diff --git a/activesupport/lib/active_support/core_ext/array/random_access.rb b/activesupport/lib/active_support/core_ext/array/random_access.rb index 7a4836cecd..edac7278bc 100644 --- a/activesupport/lib/active_support/core_ext/array/random_access.rb +++ b/activesupport/lib/active_support/core_ext/array/random_access.rb @@ -1,5 +1,12 @@ class Array # Backport of Array#sample based on Marc-Andre Lafortune's http://github.com/marcandre/backports/ + # Returns a random element or +n+ random elements from the array. + # If the array is empty and +n+ is nil, returns <tt>nil</tt>. if +n+ is passed, returns <tt>[]</tt>. + # + # [1,2,3,4,5,6].sample # => 4 + # [1,2,3,4,5,6].sample(3) # => [2, 4, 5] + # [].sample # => nil + # [].sample(3) # => [] def sample(n=nil) return self[Kernel.rand(size)] if n.nil? n = n.to_int diff --git a/activesupport/lib/active_support/core_ext/class.rb b/activesupport/lib/active_support/core_ext/class.rb index f2ca9c7cc9..6f308a0d62 100644 --- a/activesupport/lib/active_support/core_ext/class.rb +++ b/activesupport/lib/active_support/core_ext/class.rb @@ -1,3 +1,4 @@ +require 'active_support/core_ext/class/attribute' require 'active_support/core_ext/class/attribute_accessors' require 'active_support/core_ext/class/inheritable_attributes' require 'active_support/core_ext/class/delegating_attributes' diff --git a/activesupport/lib/active_support/core_ext/class/inheritable_attributes.rb b/activesupport/lib/active_support/core_ext/class/inheritable_attributes.rb index 4be7eaf476..7aff05dcdf 100644 --- a/activesupport/lib/active_support/core_ext/class/inheritable_attributes.rb +++ b/activesupport/lib/active_support/core_ext/class/inheritable_attributes.rb @@ -128,7 +128,7 @@ class Class # :nodoc: private # Prevent this constant from being created multiple times - EMPTY_INHERITABLE_ATTRIBUTES = {}.freeze unless const_defined?(:EMPTY_INHERITABLE_ATTRIBUTES) + EMPTY_INHERITABLE_ATTRIBUTES = {}.freeze def inherited_with_inheritable_attributes(child) inherited_without_inheritable_attributes(child) if respond_to?(:inherited_without_inheritable_attributes) diff --git a/activesupport/lib/active_support/core_ext/class/subclasses.rb b/activesupport/lib/active_support/core_ext/class/subclasses.rb index bbd8f5aef6..7d58a8b56a 100644 --- a/activesupport/lib/active_support/core_ext/class/subclasses.rb +++ b/activesupport/lib/active_support/core_ext/class/subclasses.rb @@ -11,9 +11,9 @@ class Class #:nodoc: # Rubinius if defined?(Class.__subclasses__) - def descendents + def descendants subclasses = [] - __subclasses__.each {|k| subclasses << k; subclasses.concat k.descendents } + __subclasses__.each {|k| subclasses << k; subclasses.concat k.descendants } subclasses end else @@ -21,7 +21,7 @@ class Class #:nodoc: begin ObjectSpace.each_object(Class.new) {} - def descendents + def descendants subclasses = [] ObjectSpace.each_object(class << self; self; end) do |k| subclasses << k unless k == self @@ -30,7 +30,7 @@ class Class #:nodoc: end # JRuby rescue StandardError - def descendents + def descendants subclasses = [] ObjectSpace.each_object(Class) do |k| subclasses << k if k < self @@ -48,7 +48,7 @@ class Class #:nodoc: def self.subclasses_of(*superclasses) #:nodoc: subclasses = [] superclasses.each do |klass| - subclasses.concat klass.descendents.select {|k| k.anonymous? || k.reachable?} + subclasses.concat klass.descendants.select {|k| k.anonymous? || k.reachable?} end subclasses end diff --git a/activesupport/lib/active_support/core_ext/logger.rb b/activesupport/lib/active_support/core_ext/logger.rb index c4994ca2ee..d023b4bcff 100644 --- a/activesupport/lib/active_support/core_ext/logger.rb +++ b/activesupport/lib/active_support/core_ext/logger.rb @@ -72,44 +72,6 @@ class Logger @formatter ||= SimpleFormatter.new end - unless const_defined? :Formatter - class Formatter - Format = "%s, [%s#%d] %5s -- %s: %s\n" - - attr_accessor :datetime_format - - def initialize - @datetime_format = nil - end - - def call(severity, time, progname, msg) - Format % [severity[0..0], format_datetime(time), $$, severity, progname, - msg2str(msg)] - end - - private - def format_datetime(time) - if @datetime_format.nil? - time.strftime("%Y-%m-%dT%H:%M:%S.") << "%06d " % time.usec - else - time.strftime(@datetime_format) - end - end - - def msg2str(msg) - case msg - when ::String - msg - when ::Exception - "#{ msg.message } (#{ msg.class })\n" << - (msg.backtrace || []).join("\n") - else - msg.inspect - end - end - end - end - # Simple formatter which only displays the message. class SimpleFormatter < Logger::Formatter # This method is invoked when a log event occurs diff --git a/activesupport/lib/active_support/core_ext/object/to_param.rb b/activesupport/lib/active_support/core_ext/object/to_param.rb index 06f077e920..06f077e920 100755..100644 --- a/activesupport/lib/active_support/core_ext/object/to_param.rb +++ b/activesupport/lib/active_support/core_ext/object/to_param.rb diff --git a/activesupport/lib/active_support/core_ext/range/overlaps.rb b/activesupport/lib/active_support/core_ext/range/overlaps.rb index 0dec6e0ac4..7df653b53f 100644 --- a/activesupport/lib/active_support/core_ext/range/overlaps.rb +++ b/activesupport/lib/active_support/core_ext/range/overlaps.rb @@ -1,5 +1,5 @@ class Range - # Compare two ranges and see if they overlap eachother + # Compare two ranges and see if they overlap each other # (1..5).overlaps?(4..6) # => true # (1..5).overlaps?(7..9) # => false def overlaps?(other) diff --git a/activesupport/lib/active_support/core_ext/string/conversions.rb b/activesupport/lib/active_support/core_ext/string/conversions.rb index cd7a42ed2b..5b2cb6e331 100644 --- a/activesupport/lib/active_support/core_ext/string/conversions.rb +++ b/activesupport/lib/active_support/core_ext/string/conversions.rb @@ -28,6 +28,9 @@ class String self[0] end unless method_defined?(:ord) + # +getbyte+ backport from Ruby 1.9 + alias_method :getbyte, :[] unless method_defined?(:getbyte) + # Form can be either :utc (default) or :local. def to_time(form = :utc) return nil if self.blank? @@ -47,15 +50,4 @@ class String d[5] += d.pop ::DateTime.civil(*d) end - - # +constantize+ tries to find a declared constant with the name specified - # in the string. It raises a NameError when the name is not in CamelCase - # or is not initialized. - # - # Examples - # "Module".constantize # => Module - # "Class".constantize # => Class - def constantize - ActiveSupport::Inflector.constantize(self) - end end diff --git a/activesupport/lib/active_support/core_ext/string/inflections.rb b/activesupport/lib/active_support/core_ext/string/inflections.rb index ef479d559e..66c4034781 100644 --- a/activesupport/lib/active_support/core_ext/string/inflections.rb +++ b/activesupport/lib/active_support/core_ext/string/inflections.rb @@ -28,6 +28,17 @@ class String ActiveSupport::Inflector.singularize(self) end + # +constantize+ tries to find a declared constant with the name specified + # in the string. It raises a NameError when the name is not in CamelCase + # or is not initialized. + # + # Examples + # "Module".constantize # => Module + # "Class".constantize # => Class + def constantize + ActiveSupport::Inflector.constantize(self) + end + # By default, +camelize+ converts strings to UpperCamelCase. If the argument to camelize # is set to <tt>:lower</tt> then camelize produces lowerCamelCase. # diff --git a/activesupport/lib/active_support/dependencies.rb b/activesupport/lib/active_support/dependencies.rb index 2cc812643f..7d5143ba37 100644 --- a/activesupport/lib/active_support/dependencies.rb +++ b/activesupport/lib/active_support/dependencies.rb @@ -33,14 +33,14 @@ module ActiveSupport #:nodoc: # 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 = [] + # unless the directory also appears in autoload_once_paths. + mattr_accessor :autoload_paths + self.autoload_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 = [] + # only once. All directories in this set must also be present in +autoload_paths+. + mattr_accessor :autoload_once_paths + self.autoload_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. @@ -340,7 +340,7 @@ module ActiveSupport #:nodoc: if Module.method(:const_defined?).arity == 1 # Does this module define this constant? - # Wrapper to accomodate changing Module#const_defined? in Ruby 1.9 + # Wrapper to accommodate changing Module#const_defined? in Ruby 1.9 def local_const_defined?(mod, const) mod.const_defined?(const) end @@ -352,22 +352,31 @@ module ActiveSupport #:nodoc: # 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) - expanded_path = Pathname.new(path[/\A(.*?)(\.rb)?\Z/, 1]).expand_path + def loadable_constants_for_path(path, bases = autoload_paths) + path = $1 if path =~ /\A(.*)\.rb\Z/ + expanded_path = File.expand_path(path) + paths = [] + + bases.each 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? - bases.inject([]) do |paths, root| - expanded_root = Pathname.new(root).expand_path - nesting = expanded_path.relative_path_from(expanded_root).to_s - next paths if nesting =~ /\.\./ paths << nesting.camelize - end.uniq + end + + paths.uniq! + paths end - # Search for a file in load_paths matching the provided suffix. + # Search for a file in autoload_paths matching the provided suffix. def search_for_file(path_suffix) path_suffix = path_suffix.sub(/(\.rb)?$/, ".rb") - load_paths.each do |root| + autoload_paths.each do |root| path = File.join(root, path_suffix) return path if File.file? path end @@ -377,14 +386,14 @@ module ActiveSupport #:nodoc: # 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| + autoload_paths.each do |load_path| return load_path if File.directory? File.join(load_path, path_suffix) end nil end def load_once_path?(path) - load_once_paths.any? { |base| path.starts_with? base } + autoload_once_paths.any? { |base| path.starts_with? base } end # Attempt to autoload the provided module name by searching for a directory @@ -396,7 +405,7 @@ module ActiveSupport #:nodoc: 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) + autoloaded_constants << qualified_name unless autoload_once_paths.include?(base_path) return mod end diff --git a/activesupport/lib/active_support/deprecation/behaviors.rb b/activesupport/lib/active_support/deprecation/behaviors.rb index 578c025fcf..feb1508586 100644 --- a/activesupport/lib/active_support/deprecation/behaviors.rb +++ b/activesupport/lib/active_support/deprecation/behaviors.rb @@ -1,28 +1,27 @@ +require "active_support/notifications" + module ActiveSupport module Deprecation class << self - # Behavior is a block that takes a message argument. - attr_writer :behavior - # Whether to print a backtrace along with the warning. attr_accessor :debug def behavior - @behavior ||= default_behavior + @behavior ||= DEFAULT_BEHAVIORS[:stderr] end - def default_behavior - Deprecation::DEFAULT_BEHAVIORS[defined?(Rails.env) ? Rails.env.to_s : 'test'] + def behavior=(behavior) + @behavior = DEFAULT_BEHAVIORS[behavior] || behavior end end - # Default warning behaviors per Rails.env. Ignored in production. + # Default warning behaviors per Rails.env. DEFAULT_BEHAVIORS = { - 'test' => Proc.new { |message, callstack| + :stderr => Proc.new { |message, callstack| $stderr.puts(message) $stderr.puts callstack.join("\n ") if debug }, - 'development' => Proc.new { |message, callstack| + :log => Proc.new { |message, callstack| logger = if defined?(Rails) && Rails.logger Rails.logger @@ -32,6 +31,10 @@ module ActiveSupport end logger.warn message logger.debug callstack.join("\n ") if debug + }, + :notify => Proc.new { |message, callstack| + ActiveSupport::Notifications.instrument("deprecation.rails", + :message => message, :callstack => callstack) } } end diff --git a/activesupport/lib/active_support/descendants_tracker.rb b/activesupport/lib/active_support/descendants_tracker.rb new file mode 100644 index 0000000000..a587d7770c --- /dev/null +++ b/activesupport/lib/active_support/descendants_tracker.rb @@ -0,0 +1,39 @@ +require 'active_support/dependencies' + +module ActiveSupport + # This module provides an internal implementation to track descendants + # which is faster than iterating through ObjectSpace. + module DescendantsTracker + @@descendants = Hash.new { |h, k| h[k] = [] } + + def self.descendants + @@descendants + end + + def self.clear + @@descendants.each do |klass, descendants| + if ActiveSupport::Dependencies.autoloaded?(klass) + @@descendants.delete(klass) + else + descendants.reject! { |v| ActiveSupport::Dependencies.autoloaded?(v) } + end + end + end + + def inherited(base) + self.direct_descendants << base + super + end + + def direct_descendants + @@descendants[self] + end + + def descendants + @@descendants[self].inject([]) do |descendants, klass| + descendants << klass + descendants.concat klass.descendants + end + end + end +end
\ No newline at end of file diff --git a/activesupport/lib/active_support/file_update_checker.rb b/activesupport/lib/active_support/file_update_checker.rb new file mode 100644 index 0000000000..5f5b264eb9 --- /dev/null +++ b/activesupport/lib/active_support/file_update_checker.rb @@ -0,0 +1,37 @@ +module ActiveSupport + # This class is responsible to track files and invoke the given block + # whenever one of these files are changed. For example, this class + # is used by Rails to reload routes whenever they are changed upon + # a new request. + # + # routes_reloader = ActiveSupport::FileUpdateChecker.new(paths) do + # paths.each { |p| load(p) } + # Rails::Application.routes.reload! + # end + # + # ActionDispatch::Callbacks.to_prepare do + # routes_reloader.execute_if_updated + # end + # + class FileUpdateChecker + attr_reader :paths, :last_update_at + + def initialize(paths, calculate=false, &block) + @paths = paths + @block = block + @last_update_at = calculate ? updated_at : nil + end + + def updated_at + paths.map { |path| File.stat(path).mtime }.max + end + + def execute_if_updated + current_update_at = self.updated_at + if @last_update_at != current_update_at + @last_update_at = current_update_at + @block.call + end + end + end +end diff --git a/activesupport/lib/active_support/i18n.rb b/activesupport/lib/active_support/i18n.rb index 0ffdd904fd..45b9d20c01 100644 --- a/activesupport/lib/active_support/i18n.rb +++ b/activesupport/lib/active_support/i18n.rb @@ -4,5 +4,6 @@ rescue LoadError => e $stderr.puts "You don't have i18n installed in your application. Please add it to your Gemfile and run bundle install" raise e end + I18n.load_path << "#{File.dirname(__FILE__)}/locale/en.yml" ActiveSupport.run_load_hooks(:i18n) diff --git a/activesupport/lib/active_support/i18n_railtie.rb b/activesupport/lib/active_support/i18n_railtie.rb new file mode 100644 index 0000000000..d82e54f1d4 --- /dev/null +++ b/activesupport/lib/active_support/i18n_railtie.rb @@ -0,0 +1,80 @@ +require "active_support" +require "rails" +require "active_support/file_update_checker" + +module I18n + class Railtie < Rails::Railtie + config.i18n = ActiveSupport::OrderedOptions.new + config.i18n.railties_load_path = [] + config.i18n.load_path = [] + config.i18n.fallbacks = ActiveSupport::OrderedOptions.new + + def self.reloader + @reloader ||= ActiveSupport::FileUpdateChecker.new([]){ I18n.reload! } + end + + # Add I18n::Railtie.reloader to ActionDispatch callbacks. Since, at this + # point, no path was added to the reloader, I18n.reload! is not triggered + # on to_prepare callbacks. This will only happen on the config.after_initialize + # callback below. + initializer "i18n.callbacks" do + ActionDispatch::Callbacks.to_prepare do + I18n::Railtie.reloader.execute_if_updated + end + end + + # Set the i18n configuration only after initialization since a lot of + # configuration is still usually done in application initializers. + config.after_initialize do |app| + fallbacks = app.config.i18n.delete(:fallbacks) + + app.config.i18n.each do |setting, value| + case setting + when :railties_load_path + app.config.i18n.load_path.unshift(*value) + when :load_path + I18n.load_path += value + else + I18n.send("#{setting}=", value) + end + end + + init_fallbacks(fallbacks) if fallbacks && validate_fallbacks(fallbacks) + + reloader.paths.concat I18n.load_path + reloader.execute_if_updated + end + + protected + + def self.include_fallbacks_module + I18n.backend.class.send(:include, I18n::Backend::Fallbacks) + end + + def self.init_fallbacks(fallbacks) + include_fallbacks_module + + args = case fallbacks + when ActiveSupport::OrderedOptions + [*(fallbacks[:defaults] || []) << fallbacks[:map]].compact + when Hash, Array + Array.wrap(fallbacks) + else # TrueClass + [] + end + + I18n.fallbacks = I18n::Locale::Fallbacks.new(*args) + end + + def self.validate_fallbacks(fallbacks) + case fallbacks + when ActiveSupport::OrderedOptions + !fallbacks.empty? + when TrueClass, Array, Hash + true + else + raise "Unexpected fallback type #{fallbacks.inspect}" + end + end + end +end
\ No newline at end of file diff --git a/activesupport/lib/active_support/json/backends/yajl.rb b/activesupport/lib/active_support/json/backends/yajl.rb index d76f8b03e4..64e50e0d87 100644 --- a/activesupport/lib/active_support/json/backends/yajl.rb +++ b/activesupport/lib/active_support/json/backends/yajl.rb @@ -1,4 +1,4 @@ -require 'yajl-ruby' unless defined?(Yajl) +require 'yajl' unless defined?(Yajl) module ActiveSupport module JSON diff --git a/activesupport/lib/active_support/json/encoding.rb b/activesupport/lib/active_support/json/encoding.rb index 02c233595d..dd94315111 100644 --- a/activesupport/lib/active_support/json/encoding.rb +++ b/activesupport/lib/active_support/json/encoding.rb @@ -128,12 +128,21 @@ module ActiveSupport end end -class Object - # Dumps object in JSON (JavaScript Object Notation). See www.json.org for more info. - def to_json(options = nil) - ActiveSupport::JSON.encode(self, options) - end +# The JSON gem adds a few modules to Ruby core classes containing :to_json definition, overwriting +# their default behavior. That said, we need to define the basic to_json method in all of them, +# otherwise they will always use to_json gem implementation, which is backwards incompatible in +# several cases (for instance, the JSON implementation for Hash does not work) with inheritance +# and consequently classes as ActiveSupport::OrderedHash cannot be serialized to json. +[Object, Array, FalseClass, Float, Hash, Integer, NilClass, String, TrueClass].each do |klass| + klass.class_eval <<-RUBY, __FILE__, __LINE__ + # Dumps object in JSON (JavaScript Object Notation). See www.json.org for more info. + def to_json(options = nil) + ActiveSupport::JSON.encode(self, options) + end + RUBY +end +class Object def as_json(options = nil) #:nodoc: if respond_to?(:to_hash) to_hash diff --git a/activesupport/lib/active_support/locale/en.yml b/activesupport/lib/active_support/locale/en.yml index 49ad192bf1..8f08f37a70 100644 --- a/activesupport/lib/active_support/locale/en.yml +++ b/activesupport/lib/active_support/locale/en.yml @@ -14,7 +14,7 @@ en: # Don't forget the nil at the beginning; there's no such thing as a 0th month month_names: [~, January, February, March, April, May, June, July, August, September, October, November, December] abbr_month_names: [~, Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec] - # Used in date_select and datime_select. + # Used in date_select and datetime_select. order: - :year - :month diff --git a/activesupport/lib/active_support/log_subscriber.rb b/activesupport/lib/active_support/log_subscriber.rb new file mode 100644 index 0000000000..891d718af3 --- /dev/null +++ b/activesupport/lib/active_support/log_subscriber.rb @@ -0,0 +1,118 @@ +require 'active_support/core_ext/module/attribute_accessors' +require 'active_support/core_ext/class/attribute' + +module ActiveSupport + # ActiveSupport::LogSubscriber is an object set to consume ActiveSupport::Notifications + # with solely purpose of logging. The log subscriber dispatches notifications to a + # regirested object based on its given namespace. + # + # An example would be Active Record log subscriber responsible for logging queries: + # + # module ActiveRecord + # class LogSubscriber < ActiveSupport::LogSubscriber + # def sql(event) + # "#{event.payload[:name]} (#{event.duration}) #{event.payload[:sql]}" + # end + # end + # end + # + # And it's finally registed as: + # + # ActiveRecord::LogSubscriber.attach_to :active_record + # + # Since we need to know all instance methods before attaching the log subscriber, + # the line above shuold be called after your ActiveRecord::LogSubscriber definition. + # + # After configured, whenever a "sql.active_record" notification is published, + # it will properly dispatch the event (ActiveSupport::Notifications::Event) to + # the sql method. + # + # Log subscriber also has some helpers to deal with logging and automatically flushes + # all logs when the request finishes (via action_dispatch.callback notification) in + # a Rails environment. + class LogSubscriber + mattr_accessor :colorize_logging + self.colorize_logging = true + + class_attribute :logger + + class << self + remove_method :logger + end + + def self.logger + @logger ||= Rails.logger if defined?(Rails) + end + + # Embed in a String to clear all previous ANSI sequences. + CLEAR = "\e[0m" + BOLD = "\e[1m" + + # Colors + BLACK = "\e[30m" + RED = "\e[31m" + GREEN = "\e[32m" + YELLOW = "\e[33m" + BLUE = "\e[34m" + MAGENTA = "\e[35m" + CYAN = "\e[36m" + WHITE = "\e[37m" + + def self.attach_to(namespace, log_subscriber=new, notifier=ActiveSupport::Notifications) + log_subscribers << log_subscriber + @@flushable_loggers = nil + + log_subscriber.public_methods(false).each do |event| + notifier.subscribe("#{event}.#{namespace}") do |*args| + next if log_subscriber.logger.nil? + + begin + log_subscriber.send(event, ActiveSupport::Notifications::Event.new(*args)) + rescue Exception => e + log_subscriber.logger.error "Could not log #{args[0].inspect} event. #{e.class}: #{e.message}" + end + end + end + end + + def self.log_subscribers + @@log_subscribers ||= [] + end + + def self.flushable_loggers + @@flushable_loggers ||= begin + loggers = log_subscribers.map(&:logger) + loggers.uniq! + loggers.select { |l| l.respond_to?(:flush) } + end + end + + # Flush all log_subscribers' logger. + def self.flush_all! + flushable_loggers.each(&:flush) + end + + protected + + %w(info debug warn error fatal unknown).each do |level| + class_eval <<-METHOD, __FILE__, __LINE__ + 1 + def #{level}(*args, &block) + return unless logger + logger.#{level}(*args, &block) + end + METHOD + end + + # Set color by using a string or one of the defined constants. If a third + # option is set to true, it also adds bold to the string. This is based + # on Highline implementation and it automatically appends CLEAR to the end + # of the returned String. + # + def color(text, color, bold=false) + return text unless colorize_logging + color = self.class.const_get(color.to_s.upcase) if color.is_a?(Symbol) + bold = bold ? BOLD : "" + "#{bold}#{color}#{text}#{CLEAR}" + end + end +end diff --git a/activesupport/lib/active_support/log_subscriber/test_helper.rb b/activesupport/lib/active_support/log_subscriber/test_helper.rb new file mode 100644 index 0000000000..96506a4b2b --- /dev/null +++ b/activesupport/lib/active_support/log_subscriber/test_helper.rb @@ -0,0 +1,90 @@ +require 'active_support/log_subscriber' + +module ActiveSupport + class LogSubscriber + # Provides some helpers to deal with testing log subscribers by setting up + # notifications. Take for instance Active Record subscriber tests: + # + # class SyncLogSubscriberTest < ActiveSupport::TestCase + # include ActiveSupport::LogSubscriber::TestHelper + # + # def setup + # ActiveRecord::LogSubscriber.attach_to(:active_record) + # end + # + # def test_basic_query_logging + # Developer.all + # wait + # assert_equal 1, @logger.logged(:debug).size + # assert_match /Developer Load/, @logger.logged(:debug).last + # assert_match /SELECT \* FROM "developers"/, @logger.logged(:debug).last + # end + # end + # + # All you need to do is to ensure that your log subscriber is added to Rails::Subscriber, + # as in the second line of the code above. The test helpers is reponsible for setting + # up the queue, subscriptions and turning colors in logs off. + # + # The messages are available in the @logger instance, which is a logger with limited + # powers (it actually do not send anything to your output), and you can collect them + # doing @logger.logged(level), where level is the level used in logging, like info, + # debug, warn and so on. + # + module TestHelper + def setup + @logger = MockLogger.new + @notifier = ActiveSupport::Notifications::Notifier.new(queue) + + ActiveSupport::LogSubscriber.colorize_logging = false + + set_logger(@logger) + ActiveSupport::Notifications.notifier = @notifier + end + + def teardown + set_logger(nil) + ActiveSupport::Notifications.notifier = nil + end + + class MockLogger + attr_reader :flush_count + + def initialize + @flush_count = 0 + @logged = Hash.new { |h,k| h[k] = [] } + end + + def method_missing(level, message) + @logged[level] << message + end + + def logged(level) + @logged[level].compact.map { |l| l.to_s.strip } + end + + def flush + @flush_count += 1 + end + end + + # Wait notifications to be published. + def wait + @notifier.wait + end + + # Overwrite if you use another logger in your log subscriber: + # + # def logger + # ActiveRecord::Base.logger = @logger + # end + # + def set_logger(logger) + ActiveSupport::LogSubscriber.logger = logger + end + + def queue + ActiveSupport::Notifications::Fanout.new + end + end + end +end
\ No newline at end of file diff --git a/activesupport/lib/active_support/multibyte.rb b/activesupport/lib/active_support/multibyte.rb index e7a271a660..8ffdf5a1bf 100644 --- a/activesupport/lib/active_support/multibyte.rb +++ b/activesupport/lib/active_support/multibyte.rb @@ -17,7 +17,7 @@ module ActiveSupport #:nodoc: @proxy_class = klass end - # Returns the currect proxy class + # Returns the current proxy class def self.proxy_class @proxy_class ||= ActiveSupport::Multibyte::Chars end diff --git a/activesupport/lib/active_support/multibyte/chars.rb b/activesupport/lib/active_support/multibyte/chars.rb index d6ccb4bac1..8823e4a5ed 100644 --- a/activesupport/lib/active_support/multibyte/chars.rb +++ b/activesupport/lib/active_support/multibyte/chars.rb @@ -50,10 +50,6 @@ module ActiveSupport #:nodoc: end end - def <=>(other) - @wrapped_string <=> other - end - # Forward all undefined methods to the wrapped string. def method_missing(method, *args, &block) if method.to_s =~ /!$/ @@ -87,6 +83,16 @@ module ActiveSupport #:nodoc: include Comparable + # Returns <tt>-1</tt>, <tt>0</tt> or <tt>+1</tt> depending on whether the Chars object is to be sorted before, + # equal or after the object on the right side of the operation. It accepts any object that implements +to_s+. + # See <tt>String#<=></tt> for more details. + # + # Example: + # 'é'.mb_chars <=> 'ü'.mb_chars #=> -1 + def <=>(other) + @wrapped_string <=> other.to_s + end + if RUBY_VERSION < "1.9" # Returns +true+ if the Chars class can and should act as a proxy for the string _string_. Returns # +false+ otherwise. @@ -94,22 +100,12 @@ module ActiveSupport #:nodoc: $KCODE == 'UTF8' && consumes?(string) end - # Returns <tt>-1</tt>, <tt>0</tt> or <tt>+1</tt> depending on whether the Chars object is to be sorted before, - # equal or after the object on the right side of the operation. It accepts any object that implements +to_s+. - # See <tt>String#<=></tt> for more details. - # - # Example: - # 'é'.mb_chars <=> 'ü'.mb_chars #=> -1 - def <=>(other) - @wrapped_string <=> other.to_s - end - # Returns a new Chars object containing the _other_ object concatenated to the string. # # Example: # ('Café'.mb_chars + ' périferôl').to_s #=> "Café périferôl" def +(other) - self << other + chars(@wrapped_string + other) end # Like <tt>String#=~</tt> only it returns the character offset (in codepoints) instead of the byte offset. @@ -199,6 +195,45 @@ module ActiveSupport #:nodoc: Unicode.u_unpack(@wrapped_string)[0] end + # Works just like <tt>String#rjust</tt>, only integer specifies characters instead of bytes. + # + # Example: + # + # "¾ cup".mb_chars.rjust(8).to_s + # #=> " ¾ cup" + # + # "¾ cup".mb_chars.rjust(8, " ").to_s # Use non-breaking whitespace + # #=> " ¾ cup" + def rjust(integer, padstr=' ') + justify(integer, :right, padstr) + end + + # Works just like <tt>String#ljust</tt>, only integer specifies characters instead of bytes. + # + # Example: + # + # "¾ cup".mb_chars.rjust(8).to_s + # #=> "¾ cup " + # + # "¾ cup".mb_chars.rjust(8, " ").to_s # Use non-breaking whitespace + # #=> "¾ cup " + def ljust(integer, padstr=' ') + justify(integer, :left, padstr) + end + + # Works just like <tt>String#center</tt>, only integer specifies characters instead of bytes. + # + # Example: + # + # "¾ cup".mb_chars.center(8).to_s + # #=> " ¾ cup " + # + # "¾ cup".mb_chars.center(8, " ").to_s # Use non-breaking whitespace + # #=> " ¾ cup " + def center(integer, padstr=' ') + justify(integer, :center, padstr) + end + else def =~(other) @wrapped_string =~ other @@ -254,46 +289,6 @@ module ActiveSupport #:nodoc: end end - # Works just like <tt>String#rjust</tt>, only integer specifies characters instead of bytes. - # - # Example: - # - # "¾ cup".mb_chars.rjust(8).to_s - # #=> " ¾ cup" - # - # "¾ cup".mb_chars.rjust(8, " ").to_s # Use non-breaking whitespace - # #=> " ¾ cup" - def rjust(integer, padstr=' ') - justify(integer, :right, padstr) - end - - # Works just like <tt>String#ljust</tt>, only integer specifies characters instead of bytes. - # - # Example: - # - # "¾ cup".mb_chars.rjust(8).to_s - # #=> "¾ cup " - # - # "¾ cup".mb_chars.rjust(8, " ").to_s # Use non-breaking whitespace - # #=> "¾ cup " - def ljust(integer, padstr=' ') - justify(integer, :left, padstr) - end - - # Works just like <tt>String#center</tt>, only integer specifies characters instead of bytes. - # - # Example: - # - # "¾ cup".mb_chars.center(8).to_s - # #=> " ¾ cup " - # - # "¾ cup".mb_chars.center(8, " ").to_s # Use non-breaking whitespace - # #=> " ¾ cup " - def center(integer, padstr=' ') - justify(integer, :center, padstr) - end - - # Reverses all characters in the string. # # Example: @@ -321,11 +316,12 @@ module ActiveSupport #:nodoc: result = @wrapped_string.slice(*args) elsif args.size == 1 && args[0].kind_of?(Numeric) character = Unicode.u_unpack(@wrapped_string)[args[0]] - result = character.nil? ? nil : [character].pack('U') + result = character && [character].pack('U') else - result = Unicode.u_unpack(@wrapped_string).slice(*args).pack('U*') + cps = Unicode.u_unpack(@wrapped_string).slice(*args) + result = cps && cps.pack('U*') end - result.nil? ? nil : chars(result) + result && chars(result) end alias_method :[], :slice @@ -375,6 +371,16 @@ module ActiveSupport #:nodoc: (slice(0) || chars('')).upcase + (slice(1..-1) || chars('')).downcase end + # Capitalizes the first letter of every word, when possible. + # + # Example: + # "ÉL QUE SE ENTERÓ".mb_chars.titleize # => "Él Que Se Enteró" + # "日本語".mb_chars.titleize # => "日本語" + def titleize + chars(downcase.to_s.gsub(/\b('?[\S])/u) { Unicode.apply_mapping $1, :uppercase_mapping }) + end + alias_method :titlecase, :titleize + # Returns the KC normalization of the string by default. NFKC is considered the best normalization form for # passing strings to databases and validations. # diff --git a/activesupport/lib/active_support/multibyte/unicode.rb b/activesupport/lib/active_support/multibyte/unicode.rb index f91e50c755..11c72d873b 100644 --- a/activesupport/lib/active_support/multibyte/unicode.rb +++ b/activesupport/lib/active_support/multibyte/unicode.rb @@ -9,7 +9,7 @@ module ActiveSupport NORMALIZATION_FORMS = [:c, :kc, :d, :kd] # The Unicode version that is supported by the implementation - UNICODE_VERSION = '5.1.0' + UNICODE_VERSION = '5.2.0' # The default normalization used for operations that require normalization. It can be set to any of the # normalizations in NORMALIZATION_FORMS. diff --git a/activesupport/lib/active_support/notifications.rb b/activesupport/lib/active_support/notifications.rb index 3f1fe64e9b..1444fc1609 100644 --- a/activesupport/lib/active_support/notifications.rb +++ b/activesupport/lib/active_support/notifications.rb @@ -23,8 +23,7 @@ module ActiveSupport # # event = @events.first # event.name #=> :render - # event.duration #=> 10 (in miliseconds) - # event.result #=> "Foo" + # event.duration #=> 10 (in milliseconds) # event.payload #=> { :extra => :information } # # When subscribing to Notifications, you can pass a pattern, to only consume diff --git a/activesupport/lib/active_support/ordered_hash.rb b/activesupport/lib/active_support/ordered_hash.rb index 91de722748..6b563b9063 100644 --- a/activesupport/lib/active_support/ordered_hash.rb +++ b/activesupport/lib/active_support/ordered_hash.rb @@ -149,6 +149,8 @@ module ActiveSupport self end + alias_method :update, :merge! + def merge(other_hash, &block) dup.merge!(other_hash, &block) end @@ -160,6 +162,10 @@ module ActiveSupport self end + def invert + OrderedHash[self.to_a.map!{|key_value_pair| key_value_pair.reverse}] + end + def inspect "#<OrderedHash #{super}>" end diff --git a/activesupport/lib/active_support/railtie.rb b/activesupport/lib/active_support/railtie.rb index 59f9ab18b1..c2deba3b1b 100644 --- a/activesupport/lib/active_support/railtie.rb +++ b/activesupport/lib/active_support/railtie.rb @@ -1,5 +1,6 @@ require "active_support" require "rails" +require "active_support/i18n_railtie" module ActiveSupport class Railtie < Rails::Railtie @@ -11,6 +12,36 @@ module ActiveSupport require 'active_support/whiny_nil' if app.config.whiny_nils end + initializer "active_support.deprecation_behavior" do |app| + if deprecation = app.config.active_support.deprecation + ActiveSupport::Deprecation.behavior = deprecation + else + defaults = {"development" => :log, + "production" => :notify, + "test" => :stderr} + + env = Rails.env + + if defaults.key?(env) + msg = "You did not specify how you would like Rails to report " \ + "deprecation notices for your #{env} environment, please " \ + "set config.active_support.deprecation to :#{defaults[env]} " \ + "at config/environments/#{env}.rb" + + warn msg + ActiveSupport::Deprecation.behavior = defaults[env] + else + msg = "You did not specify how you would like Rails to report " \ + "deprecation notices for your #{env} environment, please " \ + "set config.active_support.deprecation to :log, :notify or " \ + ":stderr at config/environments/#{env}.rb" + + warn msg + ActiveSupport::Deprecation.behavior = :stderr + end + end + end + # Sets the default value for Time.zone # If assigned value cannot be matched to a TimeZone, an exception will be raised. initializer "active_support.initialize_time_zone" do |app| @@ -27,74 +58,3 @@ module ActiveSupport end end end - -module I18n - class Railtie < Rails::Railtie - config.i18n = ActiveSupport::OrderedOptions.new - config.i18n.railties_load_path = [] - config.i18n.load_path = [] - config.i18n.fallbacks = ActiveSupport::OrderedOptions.new - - initializer "i18n.initialize" do - ActiveSupport.on_load(:i18n) do - I18n.reload! - - ActionDispatch::Callbacks.to_prepare do - I18n.reload! - end - end - end - - # Set the i18n configuration from config.i18n but special-case for - # the load_path which should be appended to what's already set instead of overwritten. - config.after_initialize do |app| - fallbacks = app.config.i18n.delete(:fallbacks) - - app.config.i18n.each do |setting, value| - case setting - when :railties_load_path - app.config.i18n.load_path.unshift(*value) - when :load_path - I18n.load_path += value - else - I18n.send("#{setting}=", value) - end - end - - init_fallbacks(fallbacks) if fallbacks && validate_fallbacks(fallbacks) - I18n.reload! - end - - class << self - protected - - def init_fallbacks(fallbacks) - include_fallbacks_module - args = case fallbacks - when ActiveSupport::OrderedOptions - [*(fallbacks[:defaults] || []) << fallbacks[:map]].compact - when Hash, Array - Array.wrap(fallbacks) - else # TrueClass - [] - end - I18n.fallbacks = I18n::Locale::Fallbacks.new(*args) - end - - def include_fallbacks_module - I18n.backend.class.send(:include, I18n::Backend::Fallbacks) - end - - def validate_fallbacks(fallbacks) - case fallbacks - when ActiveSupport::OrderedOptions - !fallbacks.empty? - when TrueClass, Array, Hash - true - else - raise "Unexpected fallback type #{fallbacks.inspect}" - end - end - end - end -end
\ No newline at end of file diff --git a/activesupport/lib/active_support/testing/isolation.rb b/activesupport/lib/active_support/testing/isolation.rb index 69df399cde..d629f6f2b7 100644 --- a/activesupport/lib/active_support/testing/isolation.rb +++ b/activesupport/lib/active_support/testing/isolation.rb @@ -45,12 +45,16 @@ module ActiveSupport end end + def _run_class_setup # class setup method should only happen in parent + unless defined?(@@ran_class_setup) || ENV['ISOLATION_TEST'] + self.class.setup if self.class.respond_to?(:setup) + @@ran_class_setup = true + end + end + module TestUnit def run(result) - unless defined?(@@ran_class_setup) - self.class.setup if self.class.respond_to?(:setup) - @@ran_class_setup = true - end + _run_class_setup yield(Test::Unit::TestCase::STARTED, name) @@ -74,10 +78,7 @@ module ActiveSupport module MiniTest def run(runner) - unless defined?(@@ran_class_setup) - self.class.setup if self.class.respond_to?(:setup) - @@ran_class_setup = true - end + _run_class_setup serialized = run_in_isolation do |isolated_runner| super(isolated_runner) @@ -109,6 +110,8 @@ module ActiveSupport end module Subprocess + ORIG_ARGV = ARGV.dup unless defined?(ORIG_ARGV) + # Crazy H4X to get this working in windows / jruby with # no forking. def run_in_isolation(&blk) diff --git a/activesupport/lib/active_support/time_with_zone.rb b/activesupport/lib/active_support/time_with_zone.rb index 710dce78de..62d02bdeb6 100644 --- a/activesupport/lib/active_support/time_with_zone.rb +++ b/activesupport/lib/active_support/time_with_zone.rb @@ -18,7 +18,7 @@ module ActiveSupport # # See Time and TimeZone for further documentation of these methods. # - # TimeWithZone instances implement the same API as Ruby Time instances, so that Time and TimeWithZone instances are interchangable. Examples: + # TimeWithZone instances implement the same API as Ruby Time instances, so that Time and TimeWithZone instances are interchangeable. Examples: # # t = Time.zone.now # => Sun, 18 May 2008 13:27:25 EDT -04:00 # t.hour # => 13 diff --git a/activesupport/lib/active_support/values/time_zone.rb b/activesupport/lib/active_support/values/time_zone.rb index 67b37785f5..05b40298d3 100644 --- a/activesupport/lib/active_support/values/time_zone.rb +++ b/activesupport/lib/active_support/values/time_zone.rb @@ -30,154 +30,152 @@ end # (if a recent version of the gem is installed locally, this will be used instead of the bundled version.) 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/Sao_Paulo", - "Buenos Aires" => "America/Argentina/Buenos_Aires", - "Georgetown" => "America/Guyana", - "Greenland" => "America/Godthab", - "Mid-Atlantic" => "Atlantic/South_Georgia", - "Azores" => "Atlantic/Azores", - "Cape Verde Is." => "Atlantic/Cape_Verde", - "Dublin" => "Europe/Dublin", - "Edinburgh" => "Europe/London", - "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", - "Kyiv" => "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/Kathmandu", - "Astana" => "Asia/Dhaka", - "Dhaka" => "Asia/Dhaka", - "Sri Jayawardenepura" => "Asia/Colombo", - "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 + # 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/Sao_Paulo", + "Buenos Aires" => "America/Argentina/Buenos_Aires", + "Georgetown" => "America/Guyana", + "Greenland" => "America/Godthab", + "Mid-Atlantic" => "Atlantic/South_Georgia", + "Azores" => "Atlantic/Azores", + "Cape Verde Is." => "Atlantic/Cape_Verde", + "Dublin" => "Europe/Dublin", + "Edinburgh" => "Europe/London", + "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", + "Kyiv" => "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/Kathmandu", + "Astana" => "Asia/Dhaka", + "Dhaka" => "Asia/Dhaka", + "Sri Jayawardenepura" => "Asia/Colombo", + "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 UTC_OFFSET_WITH_COLON = '%s%02d:%02d' UTC_OFFSET_WITHOUT_COLON = UTC_OFFSET_WITH_COLON.sub(':', '') @@ -224,7 +222,7 @@ module ActiveSupport utc_offset == 0 && alternate_utc_string || self.class.seconds_to_utc_offset(utc_offset, colon) end - # Compare this time zone to the parameter. The two are comapred first on + # Compare this time zone to the parameter. The two are compared first on # their offsets, and then by name. def <=>(zone) result = (utc_offset <=> zone.utc_offset) @@ -352,7 +350,11 @@ module ActiveSupport def [](arg) case arg when String - zones_map[arg] ||= lookup(arg) + begin + zones_map[arg] ||= lookup(arg).tap { |tz| tz.utc_offset } + rescue TZInfo::InvalidTimezoneIdentifier + nil + end when Numeric, ActiveSupport::Duration arg *= 3600 if arg.abs <= 13 all.find { |z| z.utc_offset == arg.to_i } diff --git a/activesupport/lib/active_support/values/unicode_tables.dat b/activesupport/lib/active_support/values/unicode_tables.dat Binary files differindex 10f2cae465..4fe0268cca 100644 --- a/activesupport/lib/active_support/values/unicode_tables.dat +++ b/activesupport/lib/active_support/values/unicode_tables.dat |