Merge branch 'master' into erbout

This commit is contained in:
Jeremy Kemper
2008-06-03 22:38:27 -07:00
45 changed files with 1794 additions and 1595 deletions

View File

@@ -1,3 +1,9 @@
*Edge*
* Fixed Request#remote_ip to only raise hell if the HTTP_CLIENT_IP and HTTP_X_FORWARDED_FOR doesn't match (not just if they're both present) [Mark Imbriaco, Bradford Folkens]
* Allow caches_action to accept a layout option [José Valim]
* Added Rack processor [Ezra Zygmuntowicz, Josh Peek]

View File

@@ -97,7 +97,7 @@ module ActionController
value['controller'] = value['controller'].to_s
if key == :actual && value['controller'].first != '/' && !value['controller'].include?('/')
new_controller_path = ActionController::Routing.controller_relative_to(value['controller'], @controller.class.controller_path)
value['controller'] = new_controller_path if value['controller'] != new_controller_path && ActionController::Routing.possible_controllers.include?(new_controller_path)
value['controller'] = new_controller_path if value['controller'] != new_controller_path && ActionController::Routing.possible_controllers.include?(new_controller_path) && @response.redirected_to.is_a?(Hash)
end
value['controller'] = value['controller'][1..-1] if value['controller'].first == '/' # strip leading hash
end

View File

@@ -40,6 +40,8 @@ module ActionController #:nodoc:
# controller.send(:list_url, c.params[:id]) }
# end
#
# If you pass :layout => false, it will only cache your action content. It is useful when your layout has dynamic information.
#
module Actions
def self.included(base) #:nodoc:
base.extend(ClassMethods)
@@ -54,7 +56,8 @@ module ActionController #:nodoc:
def caches_action(*actions)
return unless cache_configured?
options = actions.extract_options!
around_filter(ActionCacheFilter.new(:cache_path => options.delete(:cache_path)), {:only => actions}.merge(options))
cache_filter = ActionCacheFilter.new(:layout => options.delete(:layout), :cache_path => options.delete(:cache_path))
around_filter(cache_filter, {:only => actions}.merge(options))
end
end
@@ -81,7 +84,9 @@ module ActionController #:nodoc:
if cache = controller.read_fragment(cache_path.path)
controller.rendered_action_cache = true
set_content_type!(controller, cache_path.extension)
controller.send!(:render_for_text, cache)
options = { :text => cache }
options.merge!(:layout => true) if cache_layout?
controller.send!(:render, options)
false
else
controller.action_cache_path = cache_path
@@ -90,7 +95,8 @@ module ActionController #:nodoc:
def after(controller)
return if controller.rendered_action_cache || !caching_allowed(controller)
controller.write_fragment(controller.action_cache_path.path, controller.response.body)
action_content = cache_layout? ? content_for_layout(controller) : controller.response.body
controller.write_fragment(controller.action_cache_path.path, action_content)
end
private
@@ -105,6 +111,14 @@ module ActionController #:nodoc:
def caching_allowed(controller)
controller.request.get? && controller.response.headers['Status'].to_i == 200
end
def cache_layout?
@options[:layout] == false
end
def content_for_layout(controller)
controller.response.layout && controller.response.template.instance_variable_get('@content_for_layout')
end
end
class ActionCachePath

View File

@@ -141,7 +141,7 @@ module ActionController
# be reloaded on the next request without restarting the server.
def cleanup_application
ActiveRecord::Base.reset_subclasses if defined?(ActiveRecord)
Dependencies.clear
ActiveSupport::Dependencies.clear
ActiveRecord::Base.clear_reloadable_connections! if defined?(ActiveRecord)
end

View File

@@ -134,14 +134,15 @@ module ActionController
# REMOTE_ADDR is a proxy. HTTP_X_FORWARDED_FOR may be a comma-
# delimited list in the case of multiple chained proxies; the last
# address which is not trusted is the originating IP.
def remote_ip
if TRUSTED_PROXIES !~ @env['REMOTE_ADDR']
return @env['REMOTE_ADDR']
end
remote_ips = @env['HTTP_X_FORWARDED_FOR'] && @env['HTTP_X_FORWARDED_FOR'].split(',')
if @env.include? 'HTTP_CLIENT_IP'
if @env.include? 'HTTP_X_FORWARDED_FOR'
if remote_ips && !remote_ips.include?(@env['HTTP_CLIENT_IP'])
# We don't know which came from the proxy, and which from the user
raise ActionControllerError.new(<<EOM)
IP spoofing attack?!
@@ -149,11 +150,11 @@ HTTP_CLIENT_IP=#{@env['HTTP_CLIENT_IP'].inspect}
HTTP_X_FORWARDED_FOR=#{@env['HTTP_X_FORWARDED_FOR'].inspect}
EOM
end
return @env['HTTP_CLIENT_IP']
end
if @env.include? 'HTTP_X_FORWARDED_FOR' then
remote_ips = @env['HTTP_X_FORWARDED_FOR'].split(',')
if remote_ips
while remote_ips.size > 1 && TRUSTED_PROXIES =~ remote_ips.last.strip
remote_ips.pop
end

View File

@@ -369,7 +369,7 @@ module ActionController
Routes = RouteSet.new
::Inflector.module_eval do
ActiveSupport::Inflector.module_eval do
# Ensures that routes are reloaded when Rails inflections are updated.
def inflections_with_route_reloading(&block)
returning(inflections_without_route_reloading(&block)) {

View File

@@ -137,6 +137,9 @@ class AssertResponseWithUnexpectedErrorController < ActionController::Base
end
end
class UserController < ActionController::Base
end
module Admin
class InnerModuleController < ActionController::Base
def index
@@ -174,7 +177,7 @@ class ActionPackAssertionsControllerTest < Test::Unit::TestCase
# let's get this party started
def setup
ActionController::Routing::Routes.reload
ActionController::Routing.use_controllers!(%w(action_pack_assertions admin/inner_module content admin/user))
ActionController::Routing.use_controllers!(%w(action_pack_assertions admin/inner_module user content admin/user))
@controller = ActionPackAssertionsController.new
@request, @response = ActionController::TestRequest.new, ActionController::TestResponse.new
end
@@ -268,7 +271,7 @@ class ActionPackAssertionsControllerTest < Test::Unit::TestCase
assert_redirected_to admin_inner_module_path
end
end
def test_assert_redirected_to_top_level_named_route_from_nested_controller
with_routing do |set|
set.draw do |map|
@@ -277,11 +280,25 @@ class ActionPackAssertionsControllerTest < Test::Unit::TestCase
end
@controller = Admin::InnerModuleController.new
process :redirect_to_top_level_named_route
# passes -> assert_redirected_to "http://test.host/action_pack_assertions/foo"
# assert_redirected_to "http://test.host/action_pack_assertions/foo" would pass because of exact match early return
assert_redirected_to "/action_pack_assertions/foo"
end
end
def test_assert_redirected_to_top_level_named_route_with_same_controller_name_in_both_namespaces
with_routing do |set|
set.draw do |map|
# this controller exists in the admin namespace as well which is the only difference from previous test
map.top_level '/user/:id', :controller => 'user', :action => 'index'
map.connect ':controller/:action/:id'
end
@controller = Admin::InnerModuleController.new
process :redirect_to_top_level_named_route
# assert_redirected_to top_level_url('foo') would pass because of exact match early return
assert_redirected_to top_level_path('foo')
end
end
# -- standard request/response object testing --------------------------------
# make sure that the template objects exist

View File

@@ -156,6 +156,7 @@ class ActionCachingTestController < ActionController::Base
caches_action :show, :cache_path => 'http://test.host/custom/show'
caches_action :edit, :cache_path => Proc.new { |c| c.params[:id] ? "http://test.host/#{c.params[:id]};edit" : "http://test.host/edit" }
caches_action :with_layout
caches_action :layout_false, :layout => false
layout 'talk_from_action.erb'
@@ -181,6 +182,7 @@ class ActionCachingTestController < ActionController::Base
alias_method :show, :index
alias_method :edit, :index
alias_method :destroy, :index
alias_method :layout_false, :with_layout
def expire
expire_action :controller => 'action_caching_test', :action => 'index'
@@ -263,6 +265,19 @@ class ActionCacheTest < Test::Unit::TestCase
assert_equal @response.body, read_fragment('hostname.com/action_caching_test/with_layout')
end
def test_action_cache_with_layout_and_layout_cache_false
get :layout_false
cached_time = content_to_cache
assert_not_equal cached_time, @response.body
assert fragment_exist?('hostname.com/action_caching_test/layout_false')
reset!
get :layout_false
assert_not_equal cached_time, @response.body
assert_equal cached_time, read_fragment('hostname.com/action_caching_test/layout_false')
end
def test_action_cache_conditional_options
@request.env['HTTP_ACCEPT'] = 'application/json'
get :index

View File

@@ -27,14 +27,14 @@ class DispatcherTest < Test::Unit::TestCase
def test_clears_dependencies_after_dispatch_if_in_loading_mode
ActionController::Routing::Routes.expects(:reload).once
Dependencies.expects(:clear).once
ActiveSupport::Dependencies.expects(:clear).once
dispatch(@output, false)
end
def test_leaves_dependencies_after_dispatch_if_not_in_loading_mode
ActionController::Routing::Routes.expects(:reload).never
Dependencies.expects(:clear).never
ActiveSupport::Dependencies.expects(:clear).never
dispatch
end

View File

@@ -28,7 +28,7 @@ class SessionUploadTest < ActionController::IntegrationTest
# end
def test_post_with_upload
uses_mocha "test_post_with_upload" do
Dependencies.stubs(:load?).returns(false)
ActiveSupport::Dependencies.stubs(:load?).returns(false)
with_routing do |set|
set.draw do |map|
map.update 'update', :controller => "upload_test", :action => "update", :method => :post

View File

@@ -59,6 +59,9 @@ class RequestTest < Test::Unit::TestCase
assert_match /HTTP_X_FORWARDED_FOR="9.9.9.9, 3.4.5.6, 10.0.0.1, 172.31.4.4"/, e.message
assert_match /HTTP_CLIENT_IP="8.8.8.8"/, e.message
@request.env['HTTP_X_FORWARDED_FOR'] = '8.8.8.8, 9.9.9.9'
assert_equal '8.8.8.8', @request.remote_ip
@request.env.delete 'HTTP_CLIENT_IP'
@request.env.delete 'HTTP_X_FORWARDED_FOR'
end

View File

@@ -2392,10 +2392,10 @@ uses_mocha 'route loading' do
end
def test_adding_inflections_forces_reload
Inflector::Inflections.instance.expects(:uncountable).with('equipment')
ActiveSupport::Inflector::Inflections.instance.expects(:uncountable).with('equipment')
routes.expects(:reload!)
Inflector.inflections { |inflect| inflect.uncountable('equipment') }
ActiveSupport::Inflector.inflections { |inflect| inflect.uncountable('equipment') }
end
def test_load_with_configuration

View File

@@ -372,7 +372,7 @@ module ActiveRecord #:nodoc:
def self.reset_subclasses #:nodoc:
nonreloadables = []
subclasses.each do |klass|
unless Dependencies.autoloaded? klass
unless ActiveSupport::Dependencies.autoloaded? klass
nonreloadables << klass
next
end

View File

@@ -293,14 +293,14 @@ module ActiveRecord
private
def callback(method)
notify(method)
result = run_callbacks(method) { |result, object| result == false }
if result != false && respond_to_without_attributes?(method)
result = send(method)
end
notify(method)
return result
end

View File

@@ -137,7 +137,7 @@ class AttributeMethodsTest < ActiveRecord::TestCase
end
end
end
def test_time_attributes_are_retrieved_in_current_time_zone
in_time_zone "Pacific Time (US & Canada)" do
utc_time = Time.utc(2008, 1, 1)
@@ -145,7 +145,7 @@ class AttributeMethodsTest < ActiveRecord::TestCase
record[:written_on] = utc_time
assert_equal utc_time, record.written_on # record.written on is equal to (i.e., simultaneous with) utc_time
assert_kind_of ActiveSupport::TimeWithZone, record.written_on # but is a TimeWithZone
assert_equal TimeZone["Pacific Time (US & Canada)"], record.written_on.time_zone # and is in the current Time.zone
assert_equal ActiveSupport::TimeZone["Pacific Time (US & Canada)"], record.written_on.time_zone # and is in the current Time.zone
assert_equal Time.utc(2007, 12, 31, 16), record.written_on.time # and represents time values adjusted accordingly
end
end
@@ -156,7 +156,7 @@ class AttributeMethodsTest < ActiveRecord::TestCase
record = @target.new
record.written_on = utc_time
assert_equal utc_time, record.written_on
assert_equal TimeZone["Pacific Time (US & Canada)"], record.written_on.time_zone
assert_equal ActiveSupport::TimeZone["Pacific Time (US & Canada)"], record.written_on.time_zone
assert_equal Time.utc(2007, 12, 31, 16), record.written_on.time
end
end
@@ -168,7 +168,7 @@ class AttributeMethodsTest < ActiveRecord::TestCase
record = @target.new
record.written_on = cst_time
assert_equal utc_time, record.written_on
assert_equal TimeZone["Pacific Time (US & Canada)"], record.written_on.time_zone
assert_equal ActiveSupport::TimeZone["Pacific Time (US & Canada)"], record.written_on.time_zone
assert_equal Time.utc(2007, 12, 31, 16), record.written_on.time
end
end
@@ -181,12 +181,12 @@ class AttributeMethodsTest < ActiveRecord::TestCase
record = @target.new
record.written_on = time_string
assert_equal Time.zone.parse(time_string), record.written_on
assert_equal TimeZone["Pacific Time (US & Canada)"], record.written_on.time_zone
assert_equal ActiveSupport::TimeZone["Pacific Time (US & Canada)"], record.written_on.time_zone
assert_equal Time.utc(2007, 12, 31, 16), record.written_on.time
end
end
end
def test_setting_time_zone_aware_attribute_to_blank_string_returns_nil
in_time_zone "Pacific Time (US & Canada)" do
record = @target.new
@@ -202,7 +202,7 @@ class AttributeMethodsTest < ActiveRecord::TestCase
record = @target.new
record.written_on = time_string
assert_equal Time.zone.parse(time_string), record.written_on
assert_equal TimeZone[timezone_offset], record.written_on.time_zone
assert_equal ActiveSupport::TimeZone[timezone_offset], record.written_on.time_zone
assert_equal Time.utc(2008, 1, 1), record.written_on.time
end
end
@@ -214,7 +214,7 @@ class AttributeMethodsTest < ActiveRecord::TestCase
record = @target.new
record.written_on = utc_time.in_time_zone
assert_equal utc_time, record.written_on
assert_equal TimeZone["Pacific Time (US & Canada)"], record.written_on.time_zone
assert_equal ActiveSupport::TimeZone["Pacific Time (US & Canada)"], record.written_on.time_zone
assert_equal Time.utc(2007, 12, 31, 16), record.written_on.time
end
end
@@ -223,12 +223,12 @@ class AttributeMethodsTest < ActiveRecord::TestCase
def time_related_columns_on_topic
Topic.columns.select{|c| [:time, :date, :datetime, :timestamp].include?(c.type)}.map(&:name)
end
def in_time_zone(zone)
old_zone = Time.zone
old_tz = ActiveRecord::Base.time_zone_aware_attributes
Time.zone = zone ? TimeZone[zone] : nil
Time.zone = zone ? ActiveSupport::TimeZone[zone] : nil
ActiveRecord::Base.time_zone_aware_attributes = !zone.nil?
yield
ensure

View File

@@ -133,19 +133,19 @@ class BasicsTest < ActiveRecord::TestCase
category_attrs = {"name"=>"Test categoty", "type" => nil}
assert_equal category_attrs , category.attributes_before_type_cast
end
if current_adapter?(:MysqlAdapter)
def test_read_attributes_before_type_cast_on_boolean
bool = Booleantest.create({ "value" => false })
assert_equal 0, bool.attributes_before_type_cast["value"]
end
end
def test_read_attributes_before_type_cast_on_datetime
developer = Developer.find(:first)
assert_equal developer.created_at.to_s(:db) , developer.attributes_before_type_cast["created_at"]
end
def test_hash_content
topic = Topic.new
topic.content = { "one" => 1, "two" => 2 }
@@ -251,7 +251,7 @@ class BasicsTest < ActiveRecord::TestCase
topic = Topic.create("title" => "New Topic")
topicReloaded = Topic.find(topic.id)
assert_equal(topic, topicReloaded)
end
end
def test_create_through_factory_with_block
topic = Topic.create("title" => "New Topic") do |t|
@@ -576,7 +576,7 @@ class BasicsTest < ActiveRecord::TestCase
def test_destroy_all
original_count = Topic.count
topics_by_mary = Topic.count(:conditions => mary = "author_name = 'Mary'")
Topic.destroy_all mary
assert_equal original_count - topics_by_mary, Topic.count
end
@@ -665,7 +665,7 @@ class BasicsTest < ActiveRecord::TestCase
def test_delete_all
assert Topic.count > 0
assert_equal Topic.count, Topic.delete_all
end
@@ -970,7 +970,7 @@ class BasicsTest < ActiveRecord::TestCase
topic.attributes = attributes
assert_equal Time.local(2004, 6, 24, 16, 24, 0), topic.written_on
end
def test_multiparameter_attributes_on_time_with_old_date
attributes = {
"written_on(1i)" => "1850", "written_on(2i)" => "6", "written_on(3i)" => "24",
@@ -998,7 +998,7 @@ class BasicsTest < ActiveRecord::TestCase
def test_multiparameter_attributes_on_time_with_time_zone_aware_attributes
ActiveRecord::Base.time_zone_aware_attributes = true
ActiveRecord::Base.default_timezone = :utc
Time.zone = TimeZone[-28800]
Time.zone = ActiveSupport::TimeZone[-28800]
attributes = {
"written_on(1i)" => "2004", "written_on(2i)" => "6", "written_on(3i)" => "24",
"written_on(4i)" => "16", "written_on(5i)" => "24", "written_on(6i)" => "00"
@@ -1016,7 +1016,7 @@ class BasicsTest < ActiveRecord::TestCase
def test_multiparameter_attributes_on_time_with_time_zone_aware_attributes_false
ActiveRecord::Base.time_zone_aware_attributes = false
Time.zone = TimeZone[-28800]
Time.zone = ActiveSupport::TimeZone[-28800]
attributes = {
"written_on(1i)" => "2004", "written_on(2i)" => "6", "written_on(3i)" => "24",
"written_on(4i)" => "16", "written_on(5i)" => "24", "written_on(6i)" => "00"
@@ -1032,7 +1032,7 @@ class BasicsTest < ActiveRecord::TestCase
def test_multiparameter_attributes_on_time_with_skip_time_zone_conversion_for_attributes
ActiveRecord::Base.time_zone_aware_attributes = true
ActiveRecord::Base.default_timezone = :utc
Time.zone = TimeZone[-28800]
Time.zone = ActiveSupport::TimeZone[-28800]
Topic.skip_time_zone_conversion_for_attributes = [:written_on]
attributes = {
"written_on(1i)" => "2004", "written_on(2i)" => "6", "written_on(3i)" => "24",
@@ -1647,7 +1647,7 @@ class BasicsTest < ActiveRecord::TestCase
last = Developer.find :last
assert_equal last, Developer.find(:first, :order => 'id desc')
end
def test_last
assert_equal Developer.find(:first, :order => 'id desc'), Developer.last
end
@@ -1655,7 +1655,7 @@ class BasicsTest < ActiveRecord::TestCase
def test_all_with_conditions
assert_equal Developer.find(:all, :order => 'id desc'), Developer.all(:order => 'id desc')
end
def test_find_ordered_last
last = Developer.find :last, :order => 'developers.salary ASC'
assert_equal last, Developer.find(:all, :order => 'developers.salary ASC').last
@@ -1670,14 +1670,14 @@ class BasicsTest < ActiveRecord::TestCase
last = Developer.find :last, :order => 'developers.name, developers.salary DESC'
assert_equal last, Developer.find(:all, :order => 'developers.name, developers.salary DESC').last
end
def test_find_scoped_ordered_last
last_developer = Developer.with_scope(:find => { :order => 'developers.salary ASC' }) do
Developer.find(:last)
end
assert_equal last_developer, Developer.find(:all, :order => 'developers.salary ASC').last
end
def test_abstract_class
assert !ActiveRecord::Base.abstract_class?
assert LoosePerson.abstract_class?

View File

@@ -0,0 +1,38 @@
require "cases/helper"
class Comment < ActiveRecord::Base
attr_accessor :callers
before_validation :record_callers
def after_validation
record_callers
end
def record_callers
callers << self.class if callers
end
end
class CommentObserver < ActiveRecord::Observer
attr_accessor :callers
def after_validation(model)
callers << self.class if callers
end
end
class CallbacksObserversTest < ActiveRecord::TestCase
def test_model_callbacks_fire_before_observers_are_notified
callers = []
comment = Comment.new
comment.callers = callers
CommentObserver.instance.callers = callers
comment.valid?
assert_equal [Comment, Comment, CommentObserver], callers, "model callbacks did not fire before observers were notified"
end
end

View File

@@ -223,11 +223,11 @@ class InheritanceComputeTypeTest < ActiveRecord::TestCase
fixtures :companies
def setup
Dependencies.log_activity = true
ActiveSupport::Dependencies.log_activity = true
end
def teardown
Dependencies.log_activity = false
ActiveSupport::Dependencies.log_activity = false
self.class.const_remove :FirmOnTheFly rescue nil
Firm.const_remove :FirmOnTheFly rescue nil
end

View File

@@ -51,7 +51,7 @@ class MultipleDbTest < ActiveRecord::TestCase
def test_course_connection_should_survive_dependency_reload
assert Course.connection
Dependencies.clear
ActiveSupport::Dependencies.clear
Object.send(:remove_const, :Course)
require_dependency 'models/course'

View File

@@ -1,5 +1,11 @@
*Edge*
* Add more standard Hash methods to ActiveSupport::OrderedHash [Steve Purcell]
* Namespace Inflector, Dependencies, OrderedOptions, and TimeZone under ActiveSupport [Josh Peek]
* Added StringQuestioneer for doing things like StringQuestioneer.new("production").production? # => true and StringQuestioneer.new("production").development? # => false [DHH]
* Fixed Date#end_of_quarter to not blow up on May 31st [#289 state:resolved] (Danger)

View File

@@ -43,6 +43,8 @@ require 'active_support/ordered_hash'
require 'active_support/ordered_options'
require 'active_support/option_merger'
require 'active_support/string_questioneer'
require 'active_support/values/time_zone'
require 'active_support/duration'
@@ -53,3 +55,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')

View File

@@ -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
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
# 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 ever loaded.
mattr_accessor :history
self.history = Set.new
# All files currently loaded.
mattr_accessor :loaded
self.loaded = 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
# 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 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 = []
# 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 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 = []
# 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
# 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 = []
# 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
def clear
log_call
loaded.clear
remove_unloadable_constants!
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)
# Record that we've seen this file *before* loading it to avoid an
# infinite loop with mutual dependencies.
loaded << expanded
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
log "requiring #{file_name}"
result = require file_name
end
rescue Exception
loaded.delete expanded
raise
def load?
mechanism == :load
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
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
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)
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
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)
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
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
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
# 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
# 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
def associate_with(file_name)
depend_on(file_name, true)
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?
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!"
def clear
log_call
loaded.clear
remove_unloadable_constants!
end
raise ArgumentError, "#{from_mod} is not missing constant #{const_name}!" if uninherited_const_defined?(from_mod, const_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)
qualified_name = qualified_name_for from_mod, const_name
path_suffix = qualified_name.underscore
name_error = NameError.new("uninitialized constant #{qualified_name}")
# Record that we've seen this file *before* loading it to avoid an
# infinite loop with mutual dependencies.
loaded << expanded
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
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
log "requiring #{file_name}"
result = require file_name
end
rescue Exception
loaded.delete expanded
raise
end
else
raise name_error
# Record history *after* loading so first load gets warnings.
history << expanded
return result
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
# 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
# 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
names = path.to_s.split('::')
names.shift if names.first.empty?
# 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
# 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
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)
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
# 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
# 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)
# 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
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
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)
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
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
# 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
# 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
# If we have an anonymous module, all we can do is attempt to load from Object.
from_mod = Object if from_mod.name.blank?
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 Argument, "#{desc.inspect} does not describe a module!"
raise name_error
end
[mod_name, initial_constants]
end
constant_watch_stack.concat watch_frames
# 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
aborting = true
begin
yield # Now yield to the code that is to define new constants.
aborting = false
# 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
# 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
# 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
[mod_name, initial_constants]
end
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
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
return new_constants
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
# 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
end
new_constants.collect do |suffix|
mod_name == "Object" ? suffix : "#{mod_name}::#{suffix}"
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.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
# 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
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"
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
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
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
def log(msg)
if defined?(RAILS_DEFAULT_LOGGER) && RAILS_DEFAULT_LOGGER && log_activity
RAILS_DEFAULT_LOGGER.debug "Dependencies: #{msg}"
end
end
end
def log(msg)
if defined?(RAILS_DEFAULT_LOGGER) && RAILS_DEFAULT_LOGGER && log_activity
RAILS_DEFAULT_LOGGER.debug "Dependencies: #{msg}"
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

View File

@@ -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

View File

@@ -1,53 +1,55 @@
Inflector.inflections do |inflect|
inflect.plural(/$/, 's')
inflect.plural(/s$/i, 's')
inflect.plural(/(ax|test)is$/i, '\1es')
inflect.plural(/(octop|vir)us$/i, '\1i')
inflect.plural(/(alias|status)$/i, '\1es')
inflect.plural(/(bu)s$/i, '\1ses')
inflect.plural(/(buffal|tomat)o$/i, '\1oes')
inflect.plural(/([ti])um$/i, '\1a')
inflect.plural(/sis$/i, 'ses')
inflect.plural(/(?:([^f])fe|([lr])f)$/i, '\1\2ves')
inflect.plural(/(hive)$/i, '\1s')
inflect.plural(/([^aeiouy]|qu)y$/i, '\1ies')
inflect.plural(/(x|ch|ss|sh)$/i, '\1es')
inflect.plural(/(matr|vert|ind)(?:ix|ex)$/i, '\1ices')
inflect.plural(/([m|l])ouse$/i, '\1ice')
inflect.plural(/^(ox)$/i, '\1en')
inflect.plural(/(quiz)$/i, '\1zes')
module ActiveSupport
Inflector.inflections do |inflect|
inflect.plural(/$/, 's')
inflect.plural(/s$/i, 's')
inflect.plural(/(ax|test)is$/i, '\1es')
inflect.plural(/(octop|vir)us$/i, '\1i')
inflect.plural(/(alias|status)$/i, '\1es')
inflect.plural(/(bu)s$/i, '\1ses')
inflect.plural(/(buffal|tomat)o$/i, '\1oes')
inflect.plural(/([ti])um$/i, '\1a')
inflect.plural(/sis$/i, 'ses')
inflect.plural(/(?:([^f])fe|([lr])f)$/i, '\1\2ves')
inflect.plural(/(hive)$/i, '\1s')
inflect.plural(/([^aeiouy]|qu)y$/i, '\1ies')
inflect.plural(/(x|ch|ss|sh)$/i, '\1es')
inflect.plural(/(matr|vert|ind)(?:ix|ex)$/i, '\1ices')
inflect.plural(/([m|l])ouse$/i, '\1ice')
inflect.plural(/^(ox)$/i, '\1en')
inflect.plural(/(quiz)$/i, '\1zes')
inflect.singular(/s$/i, '')
inflect.singular(/(n)ews$/i, '\1ews')
inflect.singular(/([ti])a$/i, '\1um')
inflect.singular(/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/i, '\1\2sis')
inflect.singular(/(^analy)ses$/i, '\1sis')
inflect.singular(/([^f])ves$/i, '\1fe')
inflect.singular(/(hive)s$/i, '\1')
inflect.singular(/(tive)s$/i, '\1')
inflect.singular(/([lr])ves$/i, '\1f')
inflect.singular(/([^aeiouy]|qu)ies$/i, '\1y')
inflect.singular(/(s)eries$/i, '\1eries')
inflect.singular(/(m)ovies$/i, '\1ovie')
inflect.singular(/(x|ch|ss|sh)es$/i, '\1')
inflect.singular(/([m|l])ice$/i, '\1ouse')
inflect.singular(/(bus)es$/i, '\1')
inflect.singular(/(o)es$/i, '\1')
inflect.singular(/(shoe)s$/i, '\1')
inflect.singular(/(cris|ax|test)es$/i, '\1is')
inflect.singular(/(octop|vir)i$/i, '\1us')
inflect.singular(/(alias|status)es$/i, '\1')
inflect.singular(/^(ox)en/i, '\1')
inflect.singular(/(vert|ind)ices$/i, '\1ex')
inflect.singular(/(matr)ices$/i, '\1ix')
inflect.singular(/(quiz)zes$/i, '\1')
inflect.singular(/s$/i, '')
inflect.singular(/(n)ews$/i, '\1ews')
inflect.singular(/([ti])a$/i, '\1um')
inflect.singular(/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/i, '\1\2sis')
inflect.singular(/(^analy)ses$/i, '\1sis')
inflect.singular(/([^f])ves$/i, '\1fe')
inflect.singular(/(hive)s$/i, '\1')
inflect.singular(/(tive)s$/i, '\1')
inflect.singular(/([lr])ves$/i, '\1f')
inflect.singular(/([^aeiouy]|qu)ies$/i, '\1y')
inflect.singular(/(s)eries$/i, '\1eries')
inflect.singular(/(m)ovies$/i, '\1ovie')
inflect.singular(/(x|ch|ss|sh)es$/i, '\1')
inflect.singular(/([m|l])ice$/i, '\1ouse')
inflect.singular(/(bus)es$/i, '\1')
inflect.singular(/(o)es$/i, '\1')
inflect.singular(/(shoe)s$/i, '\1')
inflect.singular(/(cris|ax|test)es$/i, '\1is')
inflect.singular(/(octop|vir)i$/i, '\1us')
inflect.singular(/(alias|status)es$/i, '\1')
inflect.singular(/^(ox)en/i, '\1')
inflect.singular(/(vert|ind)ices$/i, '\1ex')
inflect.singular(/(matr)ices$/i, '\1ix')
inflect.singular(/(quiz)zes$/i, '\1')
inflect.irregular('person', 'people')
inflect.irregular('man', 'men')
inflect.irregular('child', 'children')
inflect.irregular('sex', 'sexes')
inflect.irregular('move', 'moves')
inflect.irregular('cow', 'kine')
inflect.irregular('person', 'people')
inflect.irregular('man', 'men')
inflect.irregular('child', 'children')
inflect.irregular('sex', 'sexes')
inflect.irregular('move', 'moves')
inflect.irregular('cow', 'kine')
inflect.uncountable(%w(equipment information rice money species series fish sheep))
inflect.uncountable(%w(equipment information rice money species series fish sheep))
end
end

View File

@@ -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
attr_reader :plurals, :singulars, :uncountables
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 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.
# 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:
#
# 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])
# 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
def initialize
@plurals, @singulars, @uncountables = [], [], []
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
# 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
# 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 = [], [], []
# 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 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
instance_variable_set "@#{scope}", []
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
end
extend self
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
# 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
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
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]
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
# 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
# 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!"
# 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
Object.module_eval("::#{$1}", __FILE__, __LINE__)
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
# 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"
if word.empty? || inflections.uncountables.include?(result.downcase)
result
else
inflections.plurals.each { |(rule, replacement)| break if result.gsub!(rule, replacement) }
result
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
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]
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
# 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
# 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
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"
end
end
end
end

View File

@@ -38,6 +38,20 @@ module ActiveSupport
each { |array| hash[array[0]] = array[1] }
end
end
def has_key?(k)
!assoc(k).nil?
end
alias_method :key?, :has_key?
alias_method :include?, :has_key?
alias_method :member?, :has_key?
def has_value?(v)
any? { |key, value| value == v }
end
alias_method :value?, :has_value?
end
end
end

View File

@@ -1,17 +1,19 @@
class OrderedOptions < ActiveSupport::OrderedHash #:nodoc:
def []=(key, value)
super(key.to_sym, value)
end
module ActiveSupport #:nodoc:
class OrderedOptions < OrderedHash #:nodoc:
def []=(key, value)
super(key.to_sym, value)
end
def [](key)
super(key.to_sym)
end
def [](key)
super(key.to_sym)
end
def method_missing(name, *args)
if name.to_s =~ /(.*)=$/
self[$1.to_sym] = args.first
else
self[name]
def method_missing(name, *args)
if name.to_s =~ /(.*)=$/
self[$1.to_sym] = args.first
else
self[name]
end
end
end
end

View File

@@ -0,0 +1,9 @@
class StringQuestioneer < String
def method_missing(method_name, *arguments)
if method_name.to_s.ends_with?("?")
self == method_name.to_s[0..-2]
else
super
end
end
end

View File

@@ -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
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
include Comparable
attr_reader :name
include Comparable
attr_reader :name
# 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
# 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
def utc_offset
@utc_offset ||= tzinfo.current_period.utc_offset
end
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
# 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
# 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
# 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
# Returns a textual representation of this time zone.
def to_s
"(GMT#{formatted_offset}) #{name}"
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 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
# 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
# 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
# Return the current date in this time zone.
def today
tzinfo.now.to_date
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
# 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
# Available so that TimeZone instances respond like TZInfo::Timezone instances
def period_for_utc(time)
tzinfo.period_for_utc(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
# TODO: Preload instead of lazy load for thread safety
def tzinfo
@tzinfo ||= TZInfo::Timezone.get(MAPPING[name])
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
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
class << self
alias_method :create, :new
# 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
# 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
# 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
# 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}"
# 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
# A convenience method for returning a collection of TimeZone objects
# for time zones in the USA.
def us_zones
US_ZONES
# 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
# Return the current date in this time zone.
def today
tzinfo.now.to_date
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
# 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
# Available so that TimeZone instances respond like TZInfo::Timezone instances
def period_for_utc(time)
tzinfo.period_for_utc(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
# TODO: Preload instead of lazy load for thread safety
def tzinfo
@tzinfo ||= TZInfo::Timezone.get(MAPPING[name])
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
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
class << self
alias_method :create, :new
# 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
# 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

View File

@@ -21,7 +21,7 @@ class ArrayExtToParamTests < Test::Unit::TestCase
"#{self}1"
end
end
def test_string_array
assert_equal '', %w().to_param
assert_equal 'hello/world', %w(hello world).to_param
@@ -31,7 +31,7 @@ class ArrayExtToParamTests < Test::Unit::TestCase
def test_number_array
assert_equal '10/20', [10, 20].to_param
end
def test_to_param_array
assert_equal 'custom1/param1', [ToParam.new('custom'), ToParam.new('param')].to_param
end
@@ -222,10 +222,10 @@ class ArrayToXmlTests < Test::Unit::TestCase
assert xml.include?(%(<count>2</count>)), xml
end
def test_to_xml_with_empty
xml = [].to_xml
assert_match /type="array"\/>/, xml
assert_match(/type="array"\/>/, xml)
end
end
@@ -239,17 +239,15 @@ class ArrayExtractOptionsTests < Test::Unit::TestCase
end
uses_mocha "ArrayExtRandomTests" do
class ArrayExtRandomTests < Test::Unit::TestCase
def test_random_element_from_array
assert_nil [].rand
class ArrayExtRandomTests < Test::Unit::TestCase
def test_random_element_from_array
assert_nil [].rand
Kernel.expects(:rand).with(1).returns(0)
assert_equal 'x', ['x'].rand
Kernel.expects(:rand).with(1).returns(0)
assert_equal 'x', ['x'].rand
Kernel.expects(:rand).with(3).returns(1)
assert_equal 2, [1, 2, 3].rand
Kernel.expects(:rand).with(3).returns(1)
assert_equal 2, [1, 2, 3].rand
end
end
end
end

View File

@@ -172,7 +172,7 @@ class DateExtCalculationsTest < Test::Unit::TestCase
def test_last_month_on_31st
assert_equal Date.new(2004, 2, 29), Date.new(2004, 3, 31).last_month
end
end
def test_yesterday_constructor
assert_equal Date.today - 1, Date.yesterday
@@ -197,11 +197,11 @@ class DateExtCalculationsTest < Test::Unit::TestCase
def test_end_of_day
assert_equal Time.local(2005,2,21,23,59,59), Date.new(2005,2,21).end_of_day
end
def test_date_acts_like_date
assert Date.new.acts_like_date?
end
def test_xmlschema
with_env_tz 'US/Eastern' do
assert_match(/^1980-02-28T00:00:00-05:?00$/, Date.new(1980, 2, 28).xmlschema)
@@ -213,7 +213,7 @@ class DateExtCalculationsTest < Test::Unit::TestCase
end
end
end
uses_mocha 'TestDateCurrent' do
def test_current_returns_date_today_when_zone_default_not_set
with_env_tz 'US/Central' do
@@ -222,10 +222,10 @@ class DateExtCalculationsTest < Test::Unit::TestCase
assert_equal Date.new(1999, 12, 31), Date.current
end
end
def test_current_returns_time_zone_today_when_zone_default_set
silence_warnings do # silence warnings raised by tzinfo gem
Time.zone_default = TimeZone['Eastern Time (US & Canada)']
Time.zone_default = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
with_env_tz 'US/Central' do
Time.stubs(:now).returns Time.local(1999, 12, 31, 23)
assert_equal Date.new(1999, 12, 31), Date.today
@@ -243,5 +243,5 @@ class DateExtCalculationsTest < Test::Unit::TestCase
yield
ensure
old_tz ? ENV['TZ'] = old_tz : ENV.delete('TZ')
end
end
end

View File

@@ -219,14 +219,14 @@ class DateTimeExtCalculationsTest < Test::Unit::TestCase
assert_equal Rational(-6, 24), DateTime.local_offset
end
end
def test_utc?
assert_equal true, DateTime.civil(2005, 2, 21, 10, 11, 12).utc?
assert_equal true, DateTime.civil(2005, 2, 21, 10, 11, 12, 0).utc?
assert_equal false, DateTime.civil(2005, 2, 21, 10, 11, 12, 0.25).utc?
assert_equal false, DateTime.civil(2005, 2, 21, 10, 11, 12, -0.25).utc?
end
def test_utc_offset
assert_equal 0, DateTime.civil(2005, 2, 21, 10, 11, 12).utc_offset
assert_equal 0, DateTime.civil(2005, 2, 21, 10, 11, 12, 0).utc_offset
@@ -234,7 +234,7 @@ class DateTimeExtCalculationsTest < Test::Unit::TestCase
assert_equal( -21600, DateTime.civil(2005, 2, 21, 10, 11, 12, -0.25).utc_offset )
assert_equal( -18000, DateTime.civil(2005, 2, 21, 10, 11, 12, Rational(-5, 24)).utc_offset )
end
def test_utc
assert_equal DateTime.civil(2005, 2, 21, 16, 11, 12, 0), DateTime.civil(2005, 2, 21, 10, 11, 12, Rational(-6, 24)).utc
assert_equal DateTime.civil(2005, 2, 21, 15, 11, 12, 0), DateTime.civil(2005, 2, 21, 10, 11, 12, Rational(-5, 24)).utc
@@ -242,37 +242,37 @@ class DateTimeExtCalculationsTest < Test::Unit::TestCase
assert_equal DateTime.civil(2005, 2, 21, 9, 11, 12, 0), DateTime.civil(2005, 2, 21, 10, 11, 12, Rational(1, 24)).utc
assert_equal DateTime.civil(2005, 2, 21, 9, 11, 12, 0), DateTime.civil(2005, 2, 21, 10, 11, 12, Rational(1, 24)).getutc
end
def test_formatted_offset_with_utc
assert_equal '+00:00', DateTime.civil(2000).formatted_offset
assert_equal '+0000', DateTime.civil(2000).formatted_offset(false)
assert_equal 'UTC', DateTime.civil(2000).formatted_offset(true, 'UTC')
end
def test_formatted_offset_with_local
dt = DateTime.civil(2005, 2, 21, 10, 11, 12, Rational(-5, 24))
assert_equal '-05:00', dt.formatted_offset
assert_equal '-0500', dt.formatted_offset(false)
end
def test_compare_with_time
assert_equal 1, DateTime.civil(2000) <=> Time.utc(1999, 12, 31, 23, 59, 59)
assert_equal 0, DateTime.civil(2000) <=> Time.utc(2000, 1, 1, 0, 0, 0)
assert_equal(-1, DateTime.civil(2000) <=> Time.utc(2000, 1, 1, 0, 0, 1))
end
def test_compare_with_datetime
assert_equal 1, DateTime.civil(2000) <=> DateTime.civil(1999, 12, 31, 23, 59, 59)
assert_equal 0, DateTime.civil(2000) <=> DateTime.civil(2000, 1, 1, 0, 0, 0)
assert_equal(-1, DateTime.civil(2000) <=> DateTime.civil(2000, 1, 1, 0, 0, 1))
end
def test_compare_with_time_with_zone
assert_equal 1, DateTime.civil(2000) <=> ActiveSupport::TimeWithZone.new( Time.utc(1999, 12, 31, 23, 59, 59), TimeZone['UTC'] )
assert_equal 0, DateTime.civil(2000) <=> ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1, 0, 0, 0), TimeZone['UTC'] )
assert_equal(-1, DateTime.civil(2000) <=> ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1, 0, 0, 1), TimeZone['UTC'] ))
assert_equal 1, DateTime.civil(2000) <=> ActiveSupport::TimeWithZone.new( Time.utc(1999, 12, 31, 23, 59, 59), ActiveSupport::TimeZone['UTC'] )
assert_equal 0, DateTime.civil(2000) <=> ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1, 0, 0, 0), ActiveSupport::TimeZone['UTC'] )
assert_equal(-1, DateTime.civil(2000) <=> ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1, 0, 0, 1), ActiveSupport::TimeZone['UTC'] ))
end
def test_to_f
assert_equal 946684800.0, DateTime.civil(2000).to_f
assert_equal 946684800.0, DateTime.civil(1999,12,31,19,0,0,Rational(-5,24)).to_f

View File

@@ -29,7 +29,7 @@ class DurationTest < Test::Unit::TestCase
flunk("ArgumentError should be raised, but we got #{$!.class} instead")
end
end
uses_mocha 'TestDurationSinceAndAgoWithCurrentTime' do
def test_since_and_ago_anchored_to_time_now_when_time_zone_default_not_set
Time.zone_default = nil
@@ -43,10 +43,10 @@ class DurationTest < Test::Unit::TestCase
assert_equal Time.local(1999,12,31,23,59,55), 5.seconds.ago
end
end
def test_since_and_ago_anchored_to_time_zone_now_when_time_zone_default_set
silence_warnings do # silence warnings raised by tzinfo gem
Time.zone_default = TimeZone['Eastern Time (US & Canada)']
Time.zone_default = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
with_env_tz 'US/Eastern' do
Time.stubs(:now).returns Time.local(2000)
# since
@@ -63,7 +63,7 @@ class DurationTest < Test::Unit::TestCase
Time.zone_default = nil
end
end
protected
def with_env_tz(new_tz = 'US/Eastern')
old_tz, ENV['TZ'] = ENV['TZ'], new_tz

View File

@@ -449,7 +449,7 @@ class TimeExtCalculationsTest < Test::Unit::TestCase
assert_equal "17:44", time.to_s(:time)
assert_equal "February 21, 2005 17:44", time.to_s(:long)
assert_equal "February 21st, 2005 17:44", time.to_s(:long_ordinal)
with_env_tz "UTC" do
with_env_tz "UTC" do
assert_equal "Mon, 21 Feb 2005 17:44:30 +0000", time.to_s(:rfc822)
end
end
@@ -505,13 +505,13 @@ class TimeExtCalculationsTest < Test::Unit::TestCase
assert_equal 30, Time.days_in_month(11, 2005)
assert_equal 31, Time.days_in_month(12, 2005)
end
uses_mocha 'TestTimeDaysInMonthWithoutYearArg' do
def test_days_in_month_feb_in_common_year_without_year_arg
Time.stubs(:now).returns(Time.utc(2007))
assert_equal 28, Time.days_in_month(2)
end
def test_days_in_month_feb_in_leap_year_without_year_arg
Time.stubs(:now).returns(Time.utc(2008))
assert_equal 29, Time.days_in_month(2)
@@ -559,13 +559,13 @@ class TimeExtCalculationsTest < Test::Unit::TestCase
def test_acts_like_time
assert Time.new.acts_like_time?
end
def test_formatted_offset_with_utc
assert_equal '+00:00', Time.utc(2000).formatted_offset
assert_equal '+0000', Time.utc(2000).formatted_offset(false)
assert_equal 'UTC', Time.utc(2000).formatted_offset(true, 'UTC')
end
def test_formatted_offset_with_local
with_env_tz 'US/Eastern' do
assert_equal '-05:00', Time.local(2000).formatted_offset
@@ -574,27 +574,27 @@ class TimeExtCalculationsTest < Test::Unit::TestCase
assert_equal '-0400', Time.local(2000, 7).formatted_offset(false)
end
end
def test_compare_with_time
assert_equal 1, Time.utc(2000) <=> Time.utc(1999, 12, 31, 23, 59, 59, 999)
assert_equal 0, Time.utc(2000) <=> Time.utc(2000, 1, 1, 0, 0, 0)
assert_equal(-1, Time.utc(2000) <=> Time.utc(2000, 1, 1, 0, 0, 0, 001))
end
def test_compare_with_datetime
assert_equal 1, Time.utc(2000) <=> DateTime.civil(1999, 12, 31, 23, 59, 59)
assert_equal 0, Time.utc(2000) <=> DateTime.civil(2000, 1, 1, 0, 0, 0)
assert_equal(-1, Time.utc(2000) <=> DateTime.civil(2000, 1, 1, 0, 0, 1))
end
def test_compare_with_time_with_zone
assert_equal 1, Time.utc(2000) <=> ActiveSupport::TimeWithZone.new( Time.utc(1999, 12, 31, 23, 59, 59), TimeZone['UTC'] )
assert_equal 0, Time.utc(2000) <=> ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1, 0, 0, 0), TimeZone['UTC'] )
assert_equal(-1, Time.utc(2000) <=> ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1, 0, 0, 1), TimeZone['UTC'] ))
assert_equal 1, Time.utc(2000) <=> ActiveSupport::TimeWithZone.new( Time.utc(1999, 12, 31, 23, 59, 59), ActiveSupport::TimeZone['UTC'] )
assert_equal 0, Time.utc(2000) <=> ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1, 0, 0, 0), ActiveSupport::TimeZone['UTC'] )
assert_equal(-1, Time.utc(2000) <=> ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1, 0, 0, 1), ActiveSupport::TimeZone['UTC'] ))
end
def test_minus_with_time_with_zone
assert_equal 86_400.0, Time.utc(2000, 1, 2) - ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1), TimeZone['UTC'] )
assert_equal 86_400.0, Time.utc(2000, 1, 2) - ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1), ActiveSupport::TimeZone['UTC'] )
end
def test_time_created_with_local_constructor_cannot_represent_times_during_hour_skipped_by_dst
@@ -608,7 +608,7 @@ class TimeExtCalculationsTest < Test::Unit::TestCase
def test_case_equality
assert Time === Time.utc(2000)
assert Time === ActiveSupport::TimeWithZone.new(Time.utc(2000), TimeZone['UTC'])
assert Time === ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone['UTC'])
assert_equal false, Time === DateTime.civil(2000)
end

View File

@@ -1,10 +1,10 @@
require 'abstract_unit'
class TimeWithZoneTest < Test::Unit::TestCase
def setup
@utc = Time.utc(2000, 1, 1, 0)
@time_zone = TimeZone['Eastern Time (US & Canada)']
@time_zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
@twz = ActiveSupport::TimeWithZone.new(@utc, @time_zone)
end
@@ -21,114 +21,114 @@ class TimeWithZoneTest < Test::Unit::TestCase
def test_time_zone
assert_equal @time_zone, @twz.time_zone
end
def test_in_time_zone
Time.use_zone 'Alaska' do
assert_equal ActiveSupport::TimeWithZone.new(@utc, TimeZone['Alaska']), @twz.in_time_zone
assert_equal ActiveSupport::TimeWithZone.new(@utc, ActiveSupport::TimeZone['Alaska']), @twz.in_time_zone
end
end
def test_in_time_zone_with_argument
assert_equal ActiveSupport::TimeWithZone.new(@utc, TimeZone['Alaska']), @twz.in_time_zone('Alaska')
assert_equal ActiveSupport::TimeWithZone.new(@utc, ActiveSupport::TimeZone['Alaska']), @twz.in_time_zone('Alaska')
end
def test_in_time_zone_with_new_zone_equal_to_old_zone_does_not_create_new_object
assert_equal @twz.object_id, @twz.in_time_zone(TimeZone['Eastern Time (US & Canada)']).object_id
assert_equal @twz.object_id, @twz.in_time_zone(ActiveSupport::TimeZone['Eastern Time (US & Canada)']).object_id
end
def test_utc?
assert_equal false, @twz.utc?
assert_equal true, ActiveSupport::TimeWithZone.new(Time.utc(2000), TimeZone['UTC']).utc?
assert_equal true, ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone['UTC']).utc?
end
def test_formatted_offset
silence_warnings do # silence warnings raised by tzinfo gem
assert_equal '-05:00', @twz.formatted_offset
assert_equal '-04:00', ActiveSupport::TimeWithZone.new(Time.utc(2000, 6), @time_zone).formatted_offset #dst
end
end
def test_dst?
silence_warnings do # silence warnings raised by tzinfo gem
assert_equal false, @twz.dst?
assert_equal true, ActiveSupport::TimeWithZone.new(Time.utc(2000, 6), @time_zone).dst?
end
end
def test_zone
silence_warnings do # silence warnings raised by tzinfo gem
assert_equal 'EST', @twz.zone
assert_equal 'EDT', ActiveSupport::TimeWithZone.new(Time.utc(2000, 6), @time_zone).zone #dst
end
end
def test_to_json
silence_warnings do # silence warnings raised by tzinfo gem
assert_equal "\"1999/12/31 19:00:00 -0500\"", @twz.to_json
end
end
def test_to_json_with_use_standard_json_time_format_config_set_to_true
old, ActiveSupport.use_standard_json_time_format = ActiveSupport.use_standard_json_time_format, true
assert_equal "\"1999-12-31T19:00:00-05:00\"", @twz.to_json
ensure
ActiveSupport.use_standard_json_time_format = old
end
def test_strftime
silence_warnings do # silence warnings raised by tzinfo gem
assert_equal '1999-12-31 19:00:00 EST -0500', @twz.strftime('%Y-%m-%d %H:%M:%S %Z %z')
end
end
def test_inspect
silence_warnings do # silence warnings raised by tzinfo gem
assert_equal 'Fri, 31 Dec 1999 19:00:00 EST -05:00', @twz.inspect
end
end
def test_to_s
silence_warnings do # silence warnings raised by tzinfo gem
assert_equal '1999-12-31 19:00:00 -0500', @twz.to_s
end
end
def test_to_s_db
silence_warnings do # silence warnings raised by tzinfo gem
assert_equal '2000-01-01 00:00:00', @twz.to_s(:db)
end
end
def test_xmlschema
silence_warnings do # silence warnings raised by tzinfo gem
assert_equal "1999-12-31T19:00:00-05:00", @twz.xmlschema
end
end
def test_to_yaml
silence_warnings do # silence warnings raised by tzinfo gem
assert_equal "--- 1999-12-31 19:00:00 -05:00\n", @twz.to_yaml
end
end
def test_ruby_to_yaml
silence_warnings do
assert_equal "--- \n:twz: 2000-01-01 00:00:00 Z\n", {:twz => @twz}.to_yaml
end
end
def test_httpdate
silence_warnings do # silence warnings raised by tzinfo gem
assert_equal 'Sat, 01 Jan 2000 00:00:00 GMT', @twz.httpdate
end
end
def test_rfc2822
silence_warnings do # silence warnings raised by tzinfo gem
assert_equal "Fri, 31 Dec 1999 19:00:00 -0500", @twz.rfc2822
end
end
def test_compare_with_time
assert_equal 1, @twz <=> Time.utc(1999, 12, 31, 23, 59, 59)
assert_equal 0, @twz <=> Time.utc(2000, 1, 1, 0, 0, 0)
@@ -142,27 +142,27 @@ class TimeWithZoneTest < Test::Unit::TestCase
end
def test_compare_with_time_with_zone
assert_equal 1, @twz <=> ActiveSupport::TimeWithZone.new( Time.utc(1999, 12, 31, 23, 59, 59), TimeZone['UTC'] )
assert_equal 0, @twz <=> ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1, 0, 0, 0), TimeZone['UTC'] )
assert_equal(-1, @twz <=> ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1, 0, 0, 1), TimeZone['UTC'] ))
assert_equal 1, @twz <=> ActiveSupport::TimeWithZone.new( Time.utc(1999, 12, 31, 23, 59, 59), ActiveSupport::TimeZone['UTC'] )
assert_equal 0, @twz <=> ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1, 0, 0, 0), ActiveSupport::TimeZone['UTC'] )
assert_equal(-1, @twz <=> ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1, 0, 0, 1), ActiveSupport::TimeZone['UTC'] ))
end
def test_between?
assert @twz.between?(Time.utc(1999,12,31,23,59,59), Time.utc(2000,1,1,0,0,1))
assert_equal false, @twz.between?(Time.utc(2000,1,1,0,0,1), Time.utc(2000,1,1,0,0,2))
end
def test_eql?
assert @twz.eql?(Time.utc(2000))
assert @twz.eql?( ActiveSupport::TimeWithZone.new(Time.utc(2000), TimeZone["Hawaii"]) )
assert @twz.eql?( ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone["Hawaii"]) )
end
def test_plus_with_integer
silence_warnings do # silence warnings raised by tzinfo gem
assert_equal Time.utc(1999, 12, 31, 19, 0 ,5), (@twz + 5).time
end
end
def test_plus_with_integer_when_self_wraps_datetime
silence_warnings do # silence warnings raised by tzinfo gem
datetime = DateTime.civil(2000, 1, 1, 0)
@@ -170,26 +170,26 @@ class TimeWithZoneTest < Test::Unit::TestCase
assert_equal DateTime.civil(1999, 12, 31, 19, 0 ,5), (twz + 5).time
end
end
def test_plus_when_crossing_time_class_limit
silence_warnings do # silence warnings raised by tzinfo gem
twz = ActiveSupport::TimeWithZone.new(Time.utc(2038, 1, 19), @time_zone)
assert_equal [0, 0, 19, 19, 1, 2038], (twz + 86_400).to_a[0,6]
end
end
def test_plus_with_duration
silence_warnings do # silence warnings raised by tzinfo gem
assert_equal Time.utc(2000, 1, 5, 19, 0 ,0), (@twz + 5.days).time
end
end
def test_minus_with_integer
silence_warnings do # silence warnings raised by tzinfo gem
assert_equal Time.utc(1999, 12, 31, 18, 59 ,55), (@twz - 5).time
end
end
def test_minus_with_integer_when_self_wraps_datetime
silence_warnings do # silence warnings raised by tzinfo gem
datetime = DateTime.civil(2000, 1, 1, 0)
@@ -197,24 +197,24 @@ class TimeWithZoneTest < Test::Unit::TestCase
assert_equal DateTime.civil(1999, 12, 31, 18, 59 ,55), (twz - 5).time
end
end
def test_minus_with_duration
silence_warnings do # silence warnings raised by tzinfo gem
assert_equal Time.utc(1999, 12, 26, 19, 0 ,0), (@twz - 5.days).time
end
end
def test_minus_with_time
assert_equal 86_400.0, ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 2), TimeZone['UTC'] ) - Time.utc(2000, 1, 1)
assert_equal 86_400.0, ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 2), TimeZone['Hawaii'] ) - Time.utc(2000, 1, 1)
assert_equal 86_400.0, ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 2), ActiveSupport::TimeZone['UTC'] ) - Time.utc(2000, 1, 1)
assert_equal 86_400.0, ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 2), ActiveSupport::TimeZone['Hawaii'] ) - Time.utc(2000, 1, 1)
end
def test_minus_with_time_with_zone
twz1 = ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1), TimeZone['UTC'] )
twz2 = ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 2), TimeZone['UTC'] )
twz1 = ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1), ActiveSupport::TimeZone['UTC'] )
twz2 = ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 2), ActiveSupport::TimeZone['UTC'] )
assert_equal 86_400.0, twz2 - twz1
end
def test_plus_and_minus_enforce_spring_dst_rules
silence_warnings do # silence warnings raised by tzinfo gem
utc = Time.utc(2006,4,2,6,59,59) # == Apr 2 2006 01:59:59 EST; i.e., 1 second before daylight savings start
@@ -232,7 +232,7 @@ class TimeWithZoneTest < Test::Unit::TestCase
assert_equal 'EST', twz.zone
end
end
def test_plus_and_minus_enforce_fall_dst_rules
silence_warnings do # silence warnings raised by tzinfo gem
utc = Time.utc(2006,10,29,5,59,59) # == Oct 29 2006 01:59:59 EST; i.e., 1 second before daylight savings end
@@ -250,25 +250,25 @@ class TimeWithZoneTest < Test::Unit::TestCase
assert_equal 'EDT', twz.zone
end
end
def test_to_a
silence_warnings do # silence warnings raised by tzinfo gem
assert_equal [45, 30, 5, 1, 2, 2000, 2, 32, false, "HST"], ActiveSupport::TimeWithZone.new( Time.utc(2000, 2, 1, 15, 30, 45), TimeZone['Hawaii'] ).to_a
assert_equal [45, 30, 5, 1, 2, 2000, 2, 32, false, "HST"], ActiveSupport::TimeWithZone.new( Time.utc(2000, 2, 1, 15, 30, 45), ActiveSupport::TimeZone['Hawaii'] ).to_a
end
end
def test_to_f
result = ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1), TimeZone['Hawaii'] ).to_f
result = ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1), ActiveSupport::TimeZone['Hawaii'] ).to_f
assert_equal 946684800.0, result
assert result.is_a?(Float)
end
def test_to_i
result = ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1), TimeZone['Hawaii'] ).to_i
result = ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1), ActiveSupport::TimeZone['Hawaii'] ).to_i
assert_equal 946684800, result
assert result.is_a?(Integer)
end
def test_to_time
assert_equal @twz, @twz.to_time
end
@@ -276,55 +276,55 @@ class TimeWithZoneTest < Test::Unit::TestCase
def test_to_date
silence_warnings do # silence warnings raised by tzinfo gem
# 1 sec before midnight Jan 1 EST
assert_equal Date.new(1999, 12, 31), ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1, 4, 59, 59), TimeZone['Eastern Time (US & Canada)'] ).to_date
assert_equal Date.new(1999, 12, 31), ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1, 4, 59, 59), ActiveSupport::TimeZone['Eastern Time (US & Canada)'] ).to_date
# midnight Jan 1 EST
assert_equal Date.new(2000, 1, 1), ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1, 5, 0, 0), TimeZone['Eastern Time (US & Canada)'] ).to_date
assert_equal Date.new(2000, 1, 1), ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1, 5, 0, 0), ActiveSupport::TimeZone['Eastern Time (US & Canada)'] ).to_date
# 1 sec before midnight Jan 2 EST
assert_equal Date.new(2000, 1, 1), ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 2, 4, 59, 59), TimeZone['Eastern Time (US & Canada)'] ).to_date
assert_equal Date.new(2000, 1, 1), ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 2, 4, 59, 59), ActiveSupport::TimeZone['Eastern Time (US & Canada)'] ).to_date
# midnight Jan 2 EST
assert_equal Date.new(2000, 1, 2), ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 2, 5, 0, 0), TimeZone['Eastern Time (US & Canada)'] ).to_date
assert_equal Date.new(2000, 1, 2), ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 2, 5, 0, 0), ActiveSupport::TimeZone['Eastern Time (US & Canada)'] ).to_date
end
end
def test_to_datetime
silence_warnings do # silence warnings raised by tzinfo gem
assert_equal DateTime.civil(1999, 12, 31, 19, 0, 0, Rational(-18_000, 86_400)), @twz.to_datetime
end
end
def test_acts_like_time
assert @twz.acts_like?(:time)
assert ActiveSupport::TimeWithZone.new(DateTime.civil(2000), @time_zone).acts_like?(:time)
end
def test_acts_like_date
assert_equal false, @twz.acts_like?(:date)
assert_equal false, ActiveSupport::TimeWithZone.new(DateTime.civil(2000), @time_zone).acts_like?(:date)
end
def test_is_a
assert @twz.is_a?(Time)
assert @twz.kind_of?(Time)
assert @twz.is_a?(ActiveSupport::TimeWithZone)
end
def test_method_missing_with_time_return_value
silence_warnings do # silence warnings raised by tzinfo gem
assert_instance_of ActiveSupport::TimeWithZone, @twz.months_since(1)
assert_equal Time.utc(2000, 1, 31, 19, 0 ,0), @twz.months_since(1).time
end
end
def test_marshal_dump_and_load
silence_warnings do # silence warnings raised by tzinfo gem
marshal_str = Marshal.dump(@twz)
mtime = Marshal.load(marshal_str)
assert_equal Time.utc(2000, 1, 1, 0), mtime.utc
assert_equal TimeZone['Eastern Time (US & Canada)'], mtime.time_zone
assert_equal ActiveSupport::TimeZone['Eastern Time (US & Canada)'], mtime.time_zone
assert_equal Time.utc(1999, 12, 31, 19), mtime.time
end
end
def test_marshal_dump_and_load_with_tzinfo_identifier
silence_warnings do # silence warnings raised by tzinfo gem
twz = ActiveSupport::TimeWithZone.new(@utc, TZInfo::Timezone.get('America/New_York'))
@@ -335,14 +335,14 @@ class TimeWithZoneTest < Test::Unit::TestCase
assert_equal Time.utc(1999, 12, 31, 19), mtime.time
end
end
def test_method_missing_with_non_time_return_value
silence_warnings do # silence warnings raised by tzinfo gem
@twz.time.expects(:foo).returns('bar')
assert_equal 'bar', @twz.foo
end
end
def test_date_part_value_methods
silence_warnings do # silence warnings raised by tzinfo gem
twz = ActiveSupport::TimeWithZone.new(Time.utc(1999,12,31,19,18,17,500), @time_zone)
@@ -356,14 +356,14 @@ class TimeWithZoneTest < Test::Unit::TestCase
assert_equal 500, twz.usec
end
end
def test_usec_returns_0_when_datetime_is_wrapped
silence_warnings do # silence warnings raised by tzinfo gem
twz = ActiveSupport::TimeWithZone.new(DateTime.civil(2000), @time_zone)
assert_equal 0, twz.usec
end
end
def test_utc_to_local_conversion_saves_period_in_instance_variable
silence_warnings do # silence warnings raised by tzinfo gem
assert_nil @twz.instance_variable_get('@period')
@@ -371,14 +371,14 @@ class TimeWithZoneTest < Test::Unit::TestCase
assert_kind_of TZInfo::TimezonePeriod, @twz.instance_variable_get('@period')
end
end
def test_instance_created_with_local_time_returns_correct_utc_time
silence_warnings do # silence warnings raised by tzinfo gem
twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(1999, 12, 31, 19))
assert_equal Time.utc(2000), twz.utc
end
end
def test_instance_created_with_local_time_enforces_spring_dst_rules
silence_warnings do # silence warnings raised by tzinfo gem
twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006,4,2,2)) # first second of DST
@@ -387,7 +387,7 @@ class TimeWithZoneTest < Test::Unit::TestCase
assert_equal 'EDT', twz.zone
end
end
def test_instance_created_with_local_time_enforces_fall_dst_rules
silence_warnings do # silence warnings raised by tzinfo gem
twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006,10,29,1)) # 1AM can be either DST or non-DST; we'll pick DST
@@ -396,14 +396,14 @@ class TimeWithZoneTest < Test::Unit::TestCase
assert_equal 'EDT', twz.zone
end
end
def test_ruby_19_weekday_name_query_methods
ruby_19_or_greater = RUBY_VERSION >= '1.9'
%w(sunday? monday? tuesday? wednesday? thursday? friday? saturday?).each do |name|
assert_equal ruby_19_or_greater, @twz.respond_to?(name)
end
end
def test_utc_to_local_conversion_with_far_future_datetime
silence_warnings do # silence warnings raised by tzinfo gem
assert_equal [0,0,19,31,12,2049], ActiveSupport::TimeWithZone.new(DateTime.civil(2050), @time_zone).to_a[0,6]
@@ -415,7 +415,7 @@ class TimeWithZoneTest < Test::Unit::TestCase
assert_equal DateTime.civil(2050).to_f, ActiveSupport::TimeWithZone.new(nil, @time_zone, DateTime.civil(2049,12,31,19)).to_f
end
end
def test_change
assert_equal "Fri, 31 Dec 1999 19:00:00 EST -05:00", @twz.inspect
assert_equal "Mon, 31 Dec 2001 19:00:00 EST -05:00", @twz.change(:year => 2001).inspect
@@ -426,7 +426,7 @@ class TimeWithZoneTest < Test::Unit::TestCase
assert_equal "Fri, 31 Dec 1999 19:15:00 EST -05:00", @twz.change(:min => 15).inspect
assert_equal "Fri, 31 Dec 1999 19:00:30 EST -05:00", @twz.change(:sec => 30).inspect
end
def test_advance
assert_equal "Fri, 31 Dec 1999 19:00:00 EST -05:00", @twz.inspect
assert_equal "Mon, 31 Dec 2001 19:00:00 EST -05:00", @twz.advance(:years => 2).inspect
@@ -436,77 +436,77 @@ class TimeWithZoneTest < Test::Unit::TestCase
assert_equal "Fri, 31 Dec 1999 19:15:00 EST -05:00", @twz.advance(:minutes => 15).inspect
assert_equal "Fri, 31 Dec 1999 19:00:30 EST -05:00", @twz.advance(:seconds => 30).inspect
end
def beginning_of_year
assert_equal "Fri, 31 Dec 1999 19:00:00 EST -05:00", @twz.inspect
assert_equal "Fri, 01 Jan 1999 00:00:00 EST -05:00", @twz.beginning_of_year.inspect
end
def end_of_year
assert_equal "Fri, 31 Dec 1999 19:00:00 EST -05:00", @twz.inspect
assert_equal "Fri, 31 Dec 1999 23:59:59 EST -05:00", @twz.end_of_year.inspect
end
def beginning_of_month
assert_equal "Fri, 31 Dec 1999 19:00:00 EST -05:00", @twz.inspect
assert_equal "Fri, 01 Dec 1999 00:00:00 EST -05:00", @twz.beginning_of_month.inspect
end
def end_of_month
assert_equal "Fri, 31 Dec 1999 19:00:00 EST -05:00", @twz.inspect
assert_equal "Fri, 31 Dec 1999 23:59:59 EST -05:00", @twz.end_of_month.inspect
end
def beginning_of_day
assert_equal "Fri, 31 Dec 1999 19:00:00 EST -05:00", @twz.inspect
assert_equal "Fri, 31 Dec 1999 00:00:00 EST -05:00", @twz.beginning_of_day.inspect
end
def end_of_day
assert_equal "Fri, 31 Dec 1999 19:00:00 EST -05:00", @twz.inspect
assert_equal "Fri, 31 Dec 1999 23:59:59 EST -05:00", @twz.end_of_day.inspect
end
def test_since
assert_equal "Fri, 31 Dec 1999 19:00:01 EST -05:00", @twz.since(1).inspect
end
def test_ago
assert_equal "Fri, 31 Dec 1999 18:59:59 EST -05:00", @twz.ago(1).inspect
end
def test_seconds_since_midnight
assert_equal 19 * 60 * 60, @twz.seconds_since_midnight
end
def test_advance_1_year_from_leap_day
twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2004,2,29))
assert_equal "Mon, 28 Feb 2005 00:00:00 EST -05:00", twz.advance(:years => 1).inspect
assert_equal "Mon, 28 Feb 2005 00:00:00 EST -05:00", twz.years_since(1).inspect
assert_equal "Mon, 28 Feb 2005 00:00:00 EST -05:00", (twz + 1.year).inspect
end
def test_advance_1_month_from_last_day_of_january
twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2005,1,31))
assert_equal "Mon, 28 Feb 2005 00:00:00 EST -05:00", twz.advance(:months => 1).inspect
assert_equal "Mon, 28 Feb 2005 00:00:00 EST -05:00", twz.months_since(1).inspect
assert_equal "Mon, 28 Feb 2005 00:00:00 EST -05:00", (twz + 1.month).inspect
end
def test_advance_1_month_from_last_day_of_january_during_leap_year
twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2000,1,31))
assert_equal "Tue, 29 Feb 2000 00:00:00 EST -05:00", twz.advance(:months => 1).inspect
assert_equal "Tue, 29 Feb 2000 00:00:00 EST -05:00", twz.months_since(1).inspect
assert_equal "Tue, 29 Feb 2000 00:00:00 EST -05:00", (twz + 1.month).inspect
end
def test_advance_1_month_into_spring_dst_gap
twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006,3,2,2))
assert_equal "Sun, 02 Apr 2006 03:00:00 EDT -04:00", twz.advance(:months => 1).inspect
assert_equal "Sun, 02 Apr 2006 03:00:00 EDT -04:00", twz.months_since(1).inspect
assert_equal "Sun, 02 Apr 2006 03:00:00 EDT -04:00", (twz + 1.month).inspect
end
def test_advance_1_second_into_spring_dst_gap
twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006,4,2,1,59,59))
assert_equal "Sun, 02 Apr 2006 03:00:00 EDT -04:00", twz.advance(:seconds => 1).inspect
@@ -519,11 +519,11 @@ class TimeWithZoneMethodsForTimeAndDateTimeTest < Test::Unit::TestCase
def setup
@t, @dt = Time.utc(2000), DateTime.civil(2000)
end
def teardown
Time.zone = nil
end
def test_in_time_zone
silence_warnings do # silence warnings raised by tzinfo gem
Time.use_zone 'Alaska' do
@@ -554,7 +554,7 @@ class TimeWithZoneMethodsForTimeAndDateTimeTest < Test::Unit::TestCase
end
end
end
def test_in_time_zone_with_time_local_instance
silence_warnings do # silence warnings raised by tzinfo gem
with_env_tz 'US/Eastern' do
@@ -563,85 +563,85 @@ class TimeWithZoneMethodsForTimeAndDateTimeTest < Test::Unit::TestCase
end
end
end
def test_use_zone
Time.zone = 'Alaska'
Time.use_zone 'Hawaii' do
assert_equal TimeZone['Hawaii'], Time.zone
assert_equal ActiveSupport::TimeZone['Hawaii'], Time.zone
end
assert_equal TimeZone['Alaska'], Time.zone
assert_equal ActiveSupport::TimeZone['Alaska'], Time.zone
end
def test_use_zone_with_exception_raised
Time.zone = 'Alaska'
assert_raises RuntimeError do
Time.use_zone('Hawaii') { raise RuntimeError }
end
assert_equal TimeZone['Alaska'], Time.zone
assert_equal ActiveSupport::TimeZone['Alaska'], Time.zone
end
def test_time_zone_getter_and_setter
Time.zone = TimeZone['Alaska']
assert_equal TimeZone['Alaska'], Time.zone
Time.zone = ActiveSupport::TimeZone['Alaska']
assert_equal ActiveSupport::TimeZone['Alaska'], Time.zone
Time.zone = 'Alaska'
assert_equal TimeZone['Alaska'], Time.zone
assert_equal ActiveSupport::TimeZone['Alaska'], Time.zone
Time.zone = -9.hours
assert_equal TimeZone['Alaska'], Time.zone
assert_equal ActiveSupport::TimeZone['Alaska'], Time.zone
Time.zone = nil
assert_equal nil, Time.zone
end
def test_time_zone_getter_and_setter_with_zone_default
Time.zone_default = TimeZone['Alaska']
assert_equal TimeZone['Alaska'], Time.zone
Time.zone = TimeZone['Hawaii']
assert_equal TimeZone['Hawaii'], Time.zone
Time.zone_default = ActiveSupport::TimeZone['Alaska']
assert_equal ActiveSupport::TimeZone['Alaska'], Time.zone
Time.zone = ActiveSupport::TimeZone['Hawaii']
assert_equal ActiveSupport::TimeZone['Hawaii'], Time.zone
Time.zone = nil
assert_equal TimeZone['Alaska'], Time.zone
assert_equal ActiveSupport::TimeZone['Alaska'], Time.zone
ensure
Time.zone_default = nil
end
def test_time_zone_setter_is_thread_safe
Time.use_zone 'Paris' do
t1 = Thread.new { Time.zone = 'Alaska' }.join
t2 = Thread.new { Time.zone = 'Hawaii' }.join
assert t1.stop?, "Thread 1 did not finish running"
assert t2.stop?, "Thread 2 did not finish running"
assert_equal TimeZone['Paris'], Time.zone
assert_equal TimeZone['Alaska'], t1[:time_zone]
assert_equal TimeZone['Hawaii'], t2[:time_zone]
assert_equal ActiveSupport::TimeZone['Paris'], Time.zone
assert_equal ActiveSupport::TimeZone['Alaska'], t1[:time_zone]
assert_equal ActiveSupport::TimeZone['Hawaii'], t2[:time_zone]
end
end
def test_time_zone_setter_with_tzinfo_timezone_object_wraps_in_rails_time_zone
silence_warnings do # silence warnings raised by tzinfo gem
tzinfo = TZInfo::Timezone.get('America/New_York')
Time.zone = tzinfo
assert_kind_of TimeZone, Time.zone
assert_kind_of ActiveSupport::TimeZone, Time.zone
assert_equal tzinfo, Time.zone.tzinfo
assert_equal 'America/New_York', Time.zone.name
assert_equal(-18_000, Time.zone.utc_offset)
end
end
def test_time_zone_setter_with_tzinfo_timezone_identifier_does_lookup_and_wraps_in_rails_time_zone
silence_warnings do # silence warnings raised by tzinfo gem
Time.zone = 'America/New_York'
assert_kind_of TimeZone, Time.zone
assert_kind_of ActiveSupport::TimeZone, Time.zone
assert_equal 'America/New_York', Time.zone.tzinfo.name
assert_equal 'America/New_York', Time.zone.name
assert_equal(-18_000, Time.zone.utc_offset)
end
end
def test_time_zone_setter_with_non_identifying_argument_returns_nil
Time.zone = 'foo'
assert_equal nil, Time.zone
Time.zone = -15.hours
assert_equal nil, Time.zone
end
uses_mocha 'TestTimeCurrent' do
def test_current_returns_time_now_when_zone_default_not_set
with_env_tz 'US/Eastern' do
@@ -650,10 +650,10 @@ class TimeWithZoneMethodsForTimeAndDateTimeTest < Test::Unit::TestCase
assert_equal Time.local(2000), Time.current
end
end
def test_current_returns_time_zone_now_when_zone_default_set
silence_warnings do # silence warnings raised by tzinfo gem
Time.zone_default = TimeZone['Eastern Time (US & Canada)']
Time.zone_default = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
with_env_tz 'US/Eastern' do
Time.stubs(:now).returns Time.local(2000)
assert_equal true, Time.current.is_a?(ActiveSupport::TimeWithZone)
@@ -665,7 +665,7 @@ class TimeWithZoneMethodsForTimeAndDateTimeTest < Test::Unit::TestCase
Time.zone_default = nil
end
end
protected
def with_env_tz(new_tz = 'US/Eastern')
old_tz, ENV['TZ'] = ENV['TZ'], new_tz

View File

@@ -15,31 +15,31 @@ end
class DependenciesTest < Test::Unit::TestCase
def teardown
Dependencies.clear
ActiveSupport::Dependencies.clear
end
def with_loading(*from)
old_mechanism, Dependencies.mechanism = Dependencies.mechanism, :load
old_mechanism, ActiveSupport::Dependencies.mechanism = ActiveSupport::Dependencies.mechanism, :load
dir = File.dirname(__FILE__)
prior_load_paths = Dependencies.load_paths
Dependencies.load_paths = from.collect { |f| "#{dir}/#{f}" }
prior_load_paths = ActiveSupport::Dependencies.load_paths
ActiveSupport::Dependencies.load_paths = from.collect { |f| "#{dir}/#{f}" }
yield
ensure
Dependencies.load_paths = prior_load_paths
Dependencies.mechanism = old_mechanism
Dependencies.explicitly_unloadable_constants = []
ActiveSupport::Dependencies.load_paths = prior_load_paths
ActiveSupport::Dependencies.mechanism = old_mechanism
ActiveSupport::Dependencies.explicitly_unloadable_constants = []
end
def test_tracking_loaded_files
require_dependency 'dependencies/service_one'
require_dependency 'dependencies/service_two'
assert_equal 2, Dependencies.loaded.size
assert_equal 2, ActiveSupport::Dependencies.loaded.size
end
def test_tracking_identical_loaded_files
require_dependency 'dependencies/service_one'
require_dependency 'dependencies/service_one'
assert_equal 1, Dependencies.loaded.size
assert_equal 1, ActiveSupport::Dependencies.loaded.size
end
def test_missing_dependency_raises_missing_source_file
@@ -64,46 +64,46 @@ class DependenciesTest < Test::Unit::TestCase
end
assert_equal count + 1, $raises_exception_load_count
assert !Dependencies.loaded.include?(filename)
assert !Dependencies.history.include?(filename)
assert !ActiveSupport::Dependencies.loaded.include?(filename)
assert !ActiveSupport::Dependencies.history.include?(filename)
end
end
end
def test_warnings_should_be_enabled_on_first_load
with_loading 'dependencies' do
old_warnings, Dependencies.warnings_on_first_load = Dependencies.warnings_on_first_load, true
old_warnings, ActiveSupport::Dependencies.warnings_on_first_load = ActiveSupport::Dependencies.warnings_on_first_load, true
filename = "check_warnings"
expanded = File.expand_path("test/dependencies/#{filename}")
$check_warnings_load_count = 0
assert !Dependencies.loaded.include?(expanded)
assert !Dependencies.history.include?(expanded)
assert !ActiveSupport::Dependencies.loaded.include?(expanded)
assert !ActiveSupport::Dependencies.history.include?(expanded)
silence_warnings { require_dependency filename }
assert_equal 1, $check_warnings_load_count
assert_equal true, $checked_verbose, 'On first load warnings should be enabled.'
assert Dependencies.loaded.include?(expanded)
Dependencies.clear
assert !Dependencies.loaded.include?(expanded)
assert Dependencies.history.include?(expanded)
assert ActiveSupport::Dependencies.loaded.include?(expanded)
ActiveSupport::Dependencies.clear
assert !ActiveSupport::Dependencies.loaded.include?(expanded)
assert ActiveSupport::Dependencies.history.include?(expanded)
silence_warnings { require_dependency filename }
assert_equal 2, $check_warnings_load_count
assert_equal nil, $checked_verbose, 'After first load warnings should be left alone.'
assert Dependencies.loaded.include?(expanded)
Dependencies.clear
assert !Dependencies.loaded.include?(expanded)
assert Dependencies.history.include?(expanded)
assert ActiveSupport::Dependencies.loaded.include?(expanded)
ActiveSupport::Dependencies.clear
assert !ActiveSupport::Dependencies.loaded.include?(expanded)
assert ActiveSupport::Dependencies.history.include?(expanded)
enable_warnings { require_dependency filename }
assert_equal 3, $check_warnings_load_count
assert_equal true, $checked_verbose, 'After first load warnings should be left alone.'
assert Dependencies.loaded.include?(expanded)
assert ActiveSupport::Dependencies.loaded.include?(expanded)
end
end
@@ -113,7 +113,7 @@ class DependenciesTest < Test::Unit::TestCase
assert_nothing_raised { require_dependency 'mutual_one' }
assert_equal 2, $mutual_dependencies_count
Dependencies.clear
ActiveSupport::Dependencies.clear
$mutual_dependencies_count = 0
assert_nothing_raised { require_dependency 'mutual_two' }
@@ -239,7 +239,7 @@ class DependenciesTest < Test::Unit::TestCase
end
def test_loadable_constants_for_path_should_handle_empty_autoloads
assert_equal [], Dependencies.loadable_constants_for_path('hello')
assert_equal [], ActiveSupport::Dependencies.loadable_constants_for_path('hello')
end
def test_loadable_constants_for_path_should_handle_relative_paths
@@ -247,7 +247,7 @@ class DependenciesTest < Test::Unit::TestCase
relative_root = File.dirname(__FILE__) + '/dependencies'
['', '/'].each do |suffix|
with_loading fake_root + suffix do
assert_equal ["A::B"], Dependencies.loadable_constants_for_path(relative_root + '/a/b')
assert_equal ["A::B"], ActiveSupport::Dependencies.loadable_constants_for_path(relative_root + '/a/b')
end
end
end
@@ -255,106 +255,106 @@ class DependenciesTest < Test::Unit::TestCase
def test_loadable_constants_for_path_should_provide_all_results
fake_root = '/usr/apps/backpack'
with_loading fake_root, fake_root + '/lib' do
root = Dependencies.load_paths.first
assert_equal ["Lib::A::B", "A::B"], Dependencies.loadable_constants_for_path(root + '/lib/a/b')
root = ActiveSupport::Dependencies.load_paths.first
assert_equal ["Lib::A::B", "A::B"], ActiveSupport::Dependencies.loadable_constants_for_path(root + '/lib/a/b')
end
end
def test_loadable_constants_for_path_should_uniq_results
fake_root = '/usr/apps/backpack/lib'
with_loading fake_root, fake_root + '/' do
root = Dependencies.load_paths.first
assert_equal ["A::B"], Dependencies.loadable_constants_for_path(root + '/a/b')
root = ActiveSupport::Dependencies.load_paths.first
assert_equal ["A::B"], ActiveSupport::Dependencies.loadable_constants_for_path(root + '/a/b')
end
end
def test_loadable_constants_with_load_path_without_trailing_slash
path = File.dirname(__FILE__) + '/autoloading_fixtures/class_folder/inline_class.rb'
with_loading 'autoloading_fixtures/class/' do
assert_equal [], Dependencies.loadable_constants_for_path(path)
assert_equal [], ActiveSupport::Dependencies.loadable_constants_for_path(path)
end
end
def test_qualified_const_defined
assert Dependencies.qualified_const_defined?("Object")
assert Dependencies.qualified_const_defined?("::Object")
assert Dependencies.qualified_const_defined?("::Object::Kernel")
assert Dependencies.qualified_const_defined?("::Object::Dependencies")
assert Dependencies.qualified_const_defined?("::Test::Unit::TestCase")
assert ActiveSupport::Dependencies.qualified_const_defined?("Object")
assert ActiveSupport::Dependencies.qualified_const_defined?("::Object")
assert ActiveSupport::Dependencies.qualified_const_defined?("::Object::Kernel")
assert ActiveSupport::Dependencies.qualified_const_defined?("::Object::Dependencies")
assert ActiveSupport::Dependencies.qualified_const_defined?("::Test::Unit::TestCase")
end
def test_qualified_const_defined_should_not_call_method_missing
ModuleWithMissing.missing_count = 0
assert ! Dependencies.qualified_const_defined?("ModuleWithMissing::A")
assert ! ActiveSupport::Dependencies.qualified_const_defined?("ModuleWithMissing::A")
assert_equal 0, ModuleWithMissing.missing_count
assert ! Dependencies.qualified_const_defined?("ModuleWithMissing::A::B")
assert ! ActiveSupport::Dependencies.qualified_const_defined?("ModuleWithMissing::A::B")
assert_equal 0, ModuleWithMissing.missing_count
end
def test_autoloaded?
with_loading 'autoloading_fixtures' do
assert ! Dependencies.autoloaded?("ModuleFolder")
assert ! Dependencies.autoloaded?("ModuleFolder::NestedClass")
assert ! ActiveSupport::Dependencies.autoloaded?("ModuleFolder")
assert ! ActiveSupport::Dependencies.autoloaded?("ModuleFolder::NestedClass")
assert Dependencies.autoloaded?(ModuleFolder)
assert ActiveSupport::Dependencies.autoloaded?(ModuleFolder)
assert Dependencies.autoloaded?("ModuleFolder")
assert ! Dependencies.autoloaded?("ModuleFolder::NestedClass")
assert ActiveSupport::Dependencies.autoloaded?("ModuleFolder")
assert ! ActiveSupport::Dependencies.autoloaded?("ModuleFolder::NestedClass")
assert Dependencies.autoloaded?(ModuleFolder::NestedClass)
assert ActiveSupport::Dependencies.autoloaded?(ModuleFolder::NestedClass)
assert Dependencies.autoloaded?("ModuleFolder")
assert Dependencies.autoloaded?("ModuleFolder::NestedClass")
assert ActiveSupport::Dependencies.autoloaded?("ModuleFolder")
assert ActiveSupport::Dependencies.autoloaded?("ModuleFolder::NestedClass")
assert Dependencies.autoloaded?("::ModuleFolder")
assert Dependencies.autoloaded?(:ModuleFolder)
assert ActiveSupport::Dependencies.autoloaded?("::ModuleFolder")
assert ActiveSupport::Dependencies.autoloaded?(:ModuleFolder)
# Anonymous modules aren't autoloaded.
assert !Dependencies.autoloaded?(Module.new)
assert !ActiveSupport::Dependencies.autoloaded?(Module.new)
nil_name = Module.new
def nil_name.name() nil end
assert !Dependencies.autoloaded?(nil_name)
assert !ActiveSupport::Dependencies.autoloaded?(nil_name)
Object.class_eval { remove_const :ModuleFolder }
end
end
def test_qualified_name_for
assert_equal "A", Dependencies.qualified_name_for(Object, :A)
assert_equal "A", Dependencies.qualified_name_for(:Object, :A)
assert_equal "A", Dependencies.qualified_name_for("Object", :A)
assert_equal "A", Dependencies.qualified_name_for("::Object", :A)
assert_equal "A", Dependencies.qualified_name_for("::Kernel", :A)
assert_equal "A", ActiveSupport::Dependencies.qualified_name_for(Object, :A)
assert_equal "A", ActiveSupport::Dependencies.qualified_name_for(:Object, :A)
assert_equal "A", ActiveSupport::Dependencies.qualified_name_for("Object", :A)
assert_equal "A", ActiveSupport::Dependencies.qualified_name_for("::Object", :A)
assert_equal "A", ActiveSupport::Dependencies.qualified_name_for("::Kernel", :A)
assert_equal "Dependencies::A", Dependencies.qualified_name_for(:Dependencies, :A)
assert_equal "Dependencies::A", Dependencies.qualified_name_for(Dependencies, :A)
assert_equal "ActiveSupport::Dependencies::A", ActiveSupport::Dependencies.qualified_name_for(:'ActiveSupport::Dependencies', :A)
assert_equal "ActiveSupport::Dependencies::A", ActiveSupport::Dependencies.qualified_name_for(ActiveSupport::Dependencies, :A)
end
def test_file_search
with_loading 'dependencies' do
root = Dependencies.load_paths.first
assert_equal nil, Dependencies.search_for_file('service_three')
assert_equal nil, Dependencies.search_for_file('service_three.rb')
assert_equal root + '/service_one.rb', Dependencies.search_for_file('service_one')
assert_equal root + '/service_one.rb', Dependencies.search_for_file('service_one.rb')
root = ActiveSupport::Dependencies.load_paths.first
assert_equal nil, ActiveSupport::Dependencies.search_for_file('service_three')
assert_equal nil, ActiveSupport::Dependencies.search_for_file('service_three.rb')
assert_equal root + '/service_one.rb', ActiveSupport::Dependencies.search_for_file('service_one')
assert_equal root + '/service_one.rb', ActiveSupport::Dependencies.search_for_file('service_one.rb')
end
end
def test_file_search_uses_first_in_load_path
with_loading 'dependencies', 'autoloading_fixtures' do
deps, autoload = Dependencies.load_paths
deps, autoload = ActiveSupport::Dependencies.load_paths
assert_match %r/dependencies/, deps
assert_match %r/autoloading_fixtures/, autoload
assert_equal deps + '/conflict.rb', Dependencies.search_for_file('conflict')
assert_equal deps + '/conflict.rb', ActiveSupport::Dependencies.search_for_file('conflict')
end
with_loading 'autoloading_fixtures', 'dependencies' do
autoload, deps = Dependencies.load_paths
autoload, deps = ActiveSupport::Dependencies.load_paths
assert_match %r/dependencies/, deps
assert_match %r/autoloading_fixtures/, autoload
assert_equal autoload + '/conflict.rb', Dependencies.search_for_file('conflict')
assert_equal autoload + '/conflict.rb', ActiveSupport::Dependencies.search_for_file('conflict')
end
end
@@ -383,7 +383,7 @@ class DependenciesTest < Test::Unit::TestCase
with_loading 'autoloading_fixtures' do
require_dependency '././counting_loader'
assert_equal 1, $counting_loaded_times
assert_raises(ArgumentError) { Dependencies.load_missing_constant Object, :CountingLoader }
assert_raises(ArgumentError) { ActiveSupport::Dependencies.load_missing_constant Object, :CountingLoader }
assert_equal 1, $counting_loaded_times
end
end
@@ -407,12 +407,12 @@ class DependenciesTest < Test::Unit::TestCase
def test_removal_from_tree_should_be_detected
with_loading 'dependencies' do
root = Dependencies.load_paths.first
root = ActiveSupport::Dependencies.load_paths.first
c = ServiceOne
Dependencies.clear
ActiveSupport::Dependencies.clear
assert ! defined?(ServiceOne)
begin
Dependencies.load_missing_constant(c, :FakeMissing)
ActiveSupport::Dependencies.load_missing_constant(c, :FakeMissing)
flunk "Expected exception"
rescue ArgumentError => e
assert_match %r{ServiceOne has been removed from the module tree}i, e.message
@@ -430,25 +430,25 @@ class DependenciesTest < Test::Unit::TestCase
def test_load_once_paths_do_not_add_to_autoloaded_constants
with_loading 'autoloading_fixtures' do
Dependencies.load_once_paths = Dependencies.load_paths.dup
ActiveSupport::Dependencies.load_once_paths = ActiveSupport::Dependencies.load_paths.dup
assert ! Dependencies.autoloaded?("ModuleFolder")
assert ! Dependencies.autoloaded?("ModuleFolder::NestedClass")
assert ! Dependencies.autoloaded?(ModuleFolder)
assert ! ActiveSupport::Dependencies.autoloaded?("ModuleFolder")
assert ! ActiveSupport::Dependencies.autoloaded?("ModuleFolder::NestedClass")
assert ! ActiveSupport::Dependencies.autoloaded?(ModuleFolder)
1 if ModuleFolder::NestedClass # 1 if to avoid warning
assert ! Dependencies.autoloaded?(ModuleFolder::NestedClass)
assert ! ActiveSupport::Dependencies.autoloaded?(ModuleFolder::NestedClass)
end
ensure
Object.class_eval { remove_const :ModuleFolder }
Dependencies.load_once_paths = []
ActiveSupport::Dependencies.load_once_paths = []
end
def test_application_should_special_case_application_controller
with_loading 'autoloading_fixtures' do
require_dependency 'application'
assert_equal 10, ApplicationController
assert Dependencies.autoloaded?(:ApplicationController)
assert ActiveSupport::Dependencies.autoloaded?(:ApplicationController)
end
end
@@ -463,15 +463,15 @@ class DependenciesTest < Test::Unit::TestCase
def test_preexisting_constants_are_not_marked_as_autoloaded
with_loading 'autoloading_fixtures' do
require_dependency 'e'
assert Dependencies.autoloaded?(:E)
Dependencies.clear
assert ActiveSupport::Dependencies.autoloaded?(:E)
ActiveSupport::Dependencies.clear
end
Object.const_set :E, Class.new
with_loading 'autoloading_fixtures' do
require_dependency 'e'
assert ! Dependencies.autoloaded?(:E), "E shouldn't be marked autoloaded!"
Dependencies.clear
assert ! ActiveSupport::Dependencies.autoloaded?(:E), "E shouldn't be marked autoloaded!"
ActiveSupport::Dependencies.clear
end
ensure
@@ -483,11 +483,11 @@ class DependenciesTest < Test::Unit::TestCase
Object.const_set :M, Module.new
M.unloadable
Dependencies.clear
ActiveSupport::Dependencies.clear
assert ! defined?(M)
Object.const_set :M, Module.new
Dependencies.clear
ActiveSupport::Dependencies.clear
assert ! defined?(M), "Dependencies should unload unloadable constants each time"
end
end
@@ -508,24 +508,24 @@ class DependenciesTest < Test::Unit::TestCase
end
def test_new_contants_in_without_constants
assert_equal [], (Dependencies.new_constants_in(Object) { })
assert Dependencies.constant_watch_stack.empty?
assert_equal [], (ActiveSupport::Dependencies.new_constants_in(Object) { })
assert ActiveSupport::Dependencies.constant_watch_stack.empty?
end
def test_new_constants_in_with_a_single_constant
assert_equal ["Hello"], Dependencies.new_constants_in(Object) {
assert_equal ["Hello"], ActiveSupport::Dependencies.new_constants_in(Object) {
Object.const_set :Hello, 10
}.map(&:to_s)
assert Dependencies.constant_watch_stack.empty?
assert ActiveSupport::Dependencies.constant_watch_stack.empty?
ensure
Object.class_eval { remove_const :Hello }
end
def test_new_constants_in_with_nesting
outer = Dependencies.new_constants_in(Object) do
outer = ActiveSupport::Dependencies.new_constants_in(Object) do
Object.const_set :OuterBefore, 10
assert_equal ["Inner"], Dependencies.new_constants_in(Object) {
assert_equal ["Inner"], ActiveSupport::Dependencies.new_constants_in(Object) {
Object.const_set :Inner, 20
}.map(&:to_s)
@@ -533,7 +533,7 @@ class DependenciesTest < Test::Unit::TestCase
end
assert_equal ["OuterAfter", "OuterBefore"], outer.sort.map(&:to_s)
assert Dependencies.constant_watch_stack.empty?
assert ActiveSupport::Dependencies.constant_watch_stack.empty?
ensure
%w(OuterBefore Inner OuterAfter).each do |name|
Object.class_eval { remove_const name if const_defined?(name) }
@@ -543,10 +543,10 @@ class DependenciesTest < Test::Unit::TestCase
def test_new_constants_in_module
Object.const_set :M, Module.new
outer = Dependencies.new_constants_in(M) do
outer = ActiveSupport::Dependencies.new_constants_in(M) do
M.const_set :OuterBefore, 10
inner = Dependencies.new_constants_in(M) do
inner = ActiveSupport::Dependencies.new_constants_in(M) do
M.const_set :Inner, 20
end
assert_equal ["M::Inner"], inner
@@ -554,17 +554,17 @@ class DependenciesTest < Test::Unit::TestCase
M.const_set :OuterAfter, 30
end
assert_equal ["M::OuterAfter", "M::OuterBefore"], outer.sort
assert Dependencies.constant_watch_stack.empty?
assert ActiveSupport::Dependencies.constant_watch_stack.empty?
ensure
Object.class_eval { remove_const :M }
end
def test_new_constants_in_module_using_name
outer = Dependencies.new_constants_in(:M) do
outer = ActiveSupport::Dependencies.new_constants_in(:M) do
Object.const_set :M, Module.new
M.const_set :OuterBefore, 10
inner = Dependencies.new_constants_in(:M) do
inner = ActiveSupport::Dependencies.new_constants_in(:M) do
M.const_set :Inner, 20
end
assert_equal ["M::Inner"], inner
@@ -572,13 +572,13 @@ class DependenciesTest < Test::Unit::TestCase
M.const_set :OuterAfter, 30
end
assert_equal ["M::OuterAfter", "M::OuterBefore"], outer.sort
assert Dependencies.constant_watch_stack.empty?
assert ActiveSupport::Dependencies.constant_watch_stack.empty?
ensure
Object.class_eval { remove_const :M }
end
def test_new_constants_in_with_inherited_constants
m = Dependencies.new_constants_in(:Object) do
m = ActiveSupport::Dependencies.new_constants_in(:Object) do
Object.class_eval { include ModuleWithConstant }
end
assert_equal [], m
@@ -586,7 +586,7 @@ class DependenciesTest < Test::Unit::TestCase
def test_new_constants_in_with_illegal_module_name_raises_correct_error
assert_raises(NameError) do
Dependencies.new_constants_in("Illegal-Name") {}
ActiveSupport::Dependencies.new_constants_in("Illegal-Name") {}
end
end
@@ -598,10 +598,10 @@ class DependenciesTest < Test::Unit::TestCase
require_dependency 'multiple_constant_file'
assert defined?(MultipleConstantFile)
assert defined?(SiblingConstant)
assert Dependencies.autoloaded?(:MultipleConstantFile)
assert Dependencies.autoloaded?(:SiblingConstant)
assert ActiveSupport::Dependencies.autoloaded?(:MultipleConstantFile)
assert ActiveSupport::Dependencies.autoloaded?(:SiblingConstant)
Dependencies.clear
ActiveSupport::Dependencies.clear
assert ! defined?(MultipleConstantFile)
assert ! defined?(SiblingConstant)
@@ -617,10 +617,10 @@ class DependenciesTest < Test::Unit::TestCase
assert defined?(MultipleConstantFile)
assert defined?(SiblingConstant)
assert Dependencies.autoloaded?(:MultipleConstantFile)
assert Dependencies.autoloaded?(:SiblingConstant)
assert ActiveSupport::Dependencies.autoloaded?(:MultipleConstantFile)
assert ActiveSupport::Dependencies.autoloaded?(:SiblingConstant)
Dependencies.clear
ActiveSupport::Dependencies.clear
assert ! defined?(MultipleConstantFile)
assert ! defined?(SiblingConstant)
@@ -636,10 +636,10 @@ class DependenciesTest < Test::Unit::TestCase
assert defined?(ClassFolder::NestedClass)
assert defined?(ClassFolder::SiblingClass)
assert Dependencies.autoloaded?("ClassFolder::NestedClass")
assert Dependencies.autoloaded?("ClassFolder::SiblingClass")
assert ActiveSupport::Dependencies.autoloaded?("ClassFolder::NestedClass")
assert ActiveSupport::Dependencies.autoloaded?("ClassFolder::SiblingClass")
Dependencies.clear
ActiveSupport::Dependencies.clear
assert ! defined?(ClassFolder::NestedClass)
assert ! defined?(ClassFolder::SiblingClass)
@@ -655,10 +655,10 @@ class DependenciesTest < Test::Unit::TestCase
assert defined?(ClassFolder::NestedClass)
assert defined?(ClassFolder::SiblingClass)
assert Dependencies.autoloaded?("ClassFolder::NestedClass")
assert Dependencies.autoloaded?("ClassFolder::SiblingClass")
assert ActiveSupport::Dependencies.autoloaded?("ClassFolder::NestedClass")
assert ActiveSupport::Dependencies.autoloaded?("ClassFolder::SiblingClass")
Dependencies.clear
ActiveSupport::Dependencies.clear
assert ! defined?(ClassFolder::NestedClass)
assert ! defined?(ClassFolder::SiblingClass)
@@ -693,7 +693,7 @@ class DependenciesTest < Test::Unit::TestCase
def test_autoload_doesnt_shadow_error_when_mechanism_not_set_to_load
with_loading 'autoloading_fixtures' do
Dependencies.mechanism = :require
ActiveSupport::Dependencies.mechanism = :require
2.times do
assert_raise(NameError) {"RaisesNameError".constantize}
end
@@ -727,39 +727,39 @@ class DependenciesTest < Test::Unit::TestCase
def test_remove_constant_handles_double_colon_at_start
Object.const_set 'DeleteMe', Module.new
DeleteMe.const_set 'OrMe', Module.new
Dependencies.remove_constant "::DeleteMe::OrMe"
ActiveSupport::Dependencies.remove_constant "::DeleteMe::OrMe"
assert ! defined?(DeleteMe::OrMe)
assert defined?(DeleteMe)
Dependencies.remove_constant "::DeleteMe"
ActiveSupport::Dependencies.remove_constant "::DeleteMe"
assert ! defined?(DeleteMe)
end
def test_load_once_constants_should_not_be_unloaded
with_loading 'autoloading_fixtures' do
Dependencies.load_once_paths = Dependencies.load_paths
ActiveSupport::Dependencies.load_once_paths = ActiveSupport::Dependencies.load_paths
::A.to_s
assert defined?(A)
Dependencies.clear
ActiveSupport::Dependencies.clear
assert defined?(A)
end
ensure
Dependencies.load_once_paths = []
ActiveSupport::Dependencies.load_once_paths = []
Object.class_eval { remove_const :A if const_defined?(:A) }
end
def test_load_once_paths_should_behave_when_recursively_loading
with_loading 'dependencies', 'autoloading_fixtures' do
Dependencies.load_once_paths = [Dependencies.load_paths.last]
ActiveSupport::Dependencies.load_once_paths = [ActiveSupport::Dependencies.load_paths.last]
assert !defined?(CrossSiteDependency)
assert_nothing_raised { CrossSiteDepender.nil? }
assert defined?(CrossSiteDependency)
assert !Dependencies.autoloaded?(CrossSiteDependency),
assert !ActiveSupport::Dependencies.autoloaded?(CrossSiteDependency),
"CrossSiteDependency shouldn't be marked as autoloaded!"
Dependencies.clear
ActiveSupport::Dependencies.clear
assert defined?(CrossSiteDependency),
"CrossSiteDependency shouldn't have been unloaded!"
end
ensure
Dependencies.load_once_paths = []
ActiveSupport::Dependencies.load_once_paths = []
end
end

View File

@@ -24,6 +24,11 @@ class Deprecatee
def d; end
def e; end
deprecate :a, :b, :c => :e, :d => "you now need to do something extra for this one"
module B
C = 1
end
A = ActiveSupport::Deprecation::DeprecatedConstantProxy.new('Deprecatee::A', 'Deprecatee::B::C')
end
@@ -83,6 +88,11 @@ class DeprecationTest < Test::Unit::TestCase
assert_not_deprecated { assert_equal @dtc.request.inspect, @dtc.old_request.inspect }
end
def test_deprecated_constant_proxy
assert_not_deprecated { Deprecatee::B::C }
assert_deprecated('Deprecatee::A') { assert_equal Deprecatee::B::C, Deprecatee::A }
end
def test_assert_deprecation_without_match
assert_deprecated do
@dtc.partially

View File

@@ -12,188 +12,188 @@ class InflectorTest < Test::Unit::TestCase
include InflectorTestCases
def test_pluralize_plurals
assert_equal "plurals", Inflector.pluralize("plurals")
assert_equal "Plurals", Inflector.pluralize("Plurals")
assert_equal "plurals", ActiveSupport::Inflector.pluralize("plurals")
assert_equal "Plurals", ActiveSupport::Inflector.pluralize("Plurals")
end
def test_pluralize_empty_string
assert_equal "", Inflector.pluralize("")
assert_equal "", ActiveSupport::Inflector.pluralize("")
end
SingularToPlural.each do |singular, plural|
define_method "test_pluralize_#{singular}" do
assert_equal(plural, Inflector.pluralize(singular))
assert_equal(plural.capitalize, Inflector.pluralize(singular.capitalize))
assert_equal(plural, ActiveSupport::Inflector.pluralize(singular))
assert_equal(plural.capitalize, ActiveSupport::Inflector.pluralize(singular.capitalize))
end
end
SingularToPlural.each do |singular, plural|
define_method "test_singularize_#{plural}" do
assert_equal(singular, Inflector.singularize(plural))
assert_equal(singular.capitalize, Inflector.singularize(plural.capitalize))
assert_equal(singular, ActiveSupport::Inflector.singularize(plural))
assert_equal(singular.capitalize, ActiveSupport::Inflector.singularize(plural.capitalize))
end
end
MixtureToTitleCase.each do |before, titleized|
define_method "test_titleize_#{before}" do
assert_equal(titleized, Inflector.titleize(before))
assert_equal(titleized, ActiveSupport::Inflector.titleize(before))
end
end
def test_camelize
CamelToUnderscore.each do |camel, underscore|
assert_equal(camel, Inflector.camelize(underscore))
assert_equal(camel, ActiveSupport::Inflector.camelize(underscore))
end
end
def test_underscore
CamelToUnderscore.each do |camel, underscore|
assert_equal(underscore, Inflector.underscore(camel))
assert_equal(underscore, ActiveSupport::Inflector.underscore(camel))
end
CamelToUnderscoreWithoutReverse.each do |camel, underscore|
assert_equal(underscore, Inflector.underscore(camel))
assert_equal(underscore, ActiveSupport::Inflector.underscore(camel))
end
end
def test_camelize_with_module
CamelWithModuleToUnderscoreWithSlash.each do |camel, underscore|
assert_equal(camel, Inflector.camelize(underscore))
assert_equal(camel, ActiveSupport::Inflector.camelize(underscore))
end
end
def test_underscore_with_slashes
CamelWithModuleToUnderscoreWithSlash.each do |camel, underscore|
assert_equal(underscore, Inflector.underscore(camel))
assert_equal(underscore, ActiveSupport::Inflector.underscore(camel))
end
end
def test_demodulize
assert_equal "Account", Inflector.demodulize("MyApplication::Billing::Account")
assert_equal "Account", ActiveSupport::Inflector.demodulize("MyApplication::Billing::Account")
end
def test_foreign_key
ClassNameToForeignKeyWithUnderscore.each do |klass, foreign_key|
assert_equal(foreign_key, Inflector.foreign_key(klass))
assert_equal(foreign_key, ActiveSupport::Inflector.foreign_key(klass))
end
ClassNameToForeignKeyWithoutUnderscore.each do |klass, foreign_key|
assert_equal(foreign_key, Inflector.foreign_key(klass, false))
assert_equal(foreign_key, ActiveSupport::Inflector.foreign_key(klass, false))
end
end
def test_tableize
ClassNameToTableName.each do |class_name, table_name|
assert_equal(table_name, Inflector.tableize(class_name))
assert_equal(table_name, ActiveSupport::Inflector.tableize(class_name))
end
end
def test_classify
ClassNameToTableName.each do |class_name, table_name|
assert_equal(class_name, Inflector.classify(table_name))
assert_equal(class_name, Inflector.classify("table_prefix." + table_name))
assert_equal(class_name, ActiveSupport::Inflector.classify(table_name))
assert_equal(class_name, ActiveSupport::Inflector.classify("table_prefix." + table_name))
end
end
def test_classify_with_symbol
assert_nothing_raised do
assert_equal 'FooBar', Inflector.classify(:foo_bars)
assert_equal 'FooBar', ActiveSupport::Inflector.classify(:foo_bars)
end
end
def test_classify_with_leading_schema_name
assert_equal 'FooBar', Inflector.classify('schema.foo_bar')
assert_equal 'FooBar', ActiveSupport::Inflector.classify('schema.foo_bar')
end
def test_humanize
UnderscoreToHuman.each do |underscore, human|
assert_equal(human, Inflector.humanize(underscore))
assert_equal(human, ActiveSupport::Inflector.humanize(underscore))
end
end
def test_constantize
assert_nothing_raised { assert_equal Ace::Base::Case, Inflector.constantize("Ace::Base::Case") }
assert_nothing_raised { assert_equal Ace::Base::Case, Inflector.constantize("::Ace::Base::Case") }
assert_nothing_raised { assert_equal InflectorTest, Inflector.constantize("InflectorTest") }
assert_nothing_raised { assert_equal InflectorTest, Inflector.constantize("::InflectorTest") }
assert_raises(NameError) { Inflector.constantize("UnknownClass") }
assert_raises(NameError) { Inflector.constantize("An invalid string") }
assert_raises(NameError) { Inflector.constantize("InvalidClass\n") }
assert_nothing_raised { assert_equal Ace::Base::Case, ActiveSupport::Inflector.constantize("Ace::Base::Case") }
assert_nothing_raised { assert_equal Ace::Base::Case, ActiveSupport::Inflector.constantize("::Ace::Base::Case") }
assert_nothing_raised { assert_equal InflectorTest, ActiveSupport::Inflector.constantize("InflectorTest") }
assert_nothing_raised { assert_equal InflectorTest, ActiveSupport::Inflector.constantize("::InflectorTest") }
assert_raises(NameError) { ActiveSupport::Inflector.constantize("UnknownClass") }
assert_raises(NameError) { ActiveSupport::Inflector.constantize("An invalid string") }
assert_raises(NameError) { ActiveSupport::Inflector.constantize("InvalidClass\n") }
end
def test_constantize_does_lexical_lookup
assert_raises(NameError) { Inflector.constantize("Ace::Base::InflectorTest") }
assert_raises(NameError) { ActiveSupport::Inflector.constantize("Ace::Base::InflectorTest") }
end
def test_ordinal
OrdinalNumbers.each do |number, ordinalized|
assert_equal(ordinalized, Inflector.ordinalize(number))
assert_equal(ordinalized, ActiveSupport::Inflector.ordinalize(number))
end
end
def test_dasherize
UnderscoresToDashes.each do |underscored, dasherized|
assert_equal(dasherized, Inflector.dasherize(underscored))
assert_equal(dasherized, ActiveSupport::Inflector.dasherize(underscored))
end
end
def test_underscore_as_reverse_of_dasherize
UnderscoresToDashes.each do |underscored, dasherized|
assert_equal(underscored, Inflector.underscore(Inflector.dasherize(underscored)))
assert_equal(underscored, ActiveSupport::Inflector.underscore(ActiveSupport::Inflector.dasherize(underscored)))
end
end
def test_underscore_to_lower_camel
UnderscoreToLowerCamel.each do |underscored, lower_camel|
assert_equal(lower_camel, Inflector.camelize(underscored, false))
assert_equal(lower_camel, ActiveSupport::Inflector.camelize(underscored, false))
end
end
%w{plurals singulars uncountables}.each do |inflection_type|
class_eval "
def test_clear_#{inflection_type}
cached_values = Inflector.inflections.#{inflection_type}
Inflector.inflections.clear :#{inflection_type}
assert Inflector.inflections.#{inflection_type}.empty?, \"#{inflection_type} inflections should be empty after clear :#{inflection_type}\"
Inflector.inflections.instance_variable_set :@#{inflection_type}, cached_values
cached_values = ActiveSupport::Inflector.inflections.#{inflection_type}
ActiveSupport::Inflector.inflections.clear :#{inflection_type}
assert ActiveSupport::Inflector.inflections.#{inflection_type}.empty?, \"#{inflection_type} inflections should be empty after clear :#{inflection_type}\"
ActiveSupport::Inflector.inflections.instance_variable_set :@#{inflection_type}, cached_values
end
"
end
def test_clear_all
cached_values = Inflector.inflections.plurals, Inflector.inflections.singulars, Inflector.inflections.uncountables
Inflector.inflections.clear :all
assert Inflector.inflections.plurals.empty?
assert Inflector.inflections.singulars.empty?
assert Inflector.inflections.uncountables.empty?
Inflector.inflections.instance_variable_set :@plurals, cached_values[0]
Inflector.inflections.instance_variable_set :@singulars, cached_values[1]
Inflector.inflections.instance_variable_set :@uncountables, cached_values[2]
cached_values = ActiveSupport::Inflector.inflections.plurals, ActiveSupport::Inflector.inflections.singulars, ActiveSupport::Inflector.inflections.uncountables
ActiveSupport::Inflector.inflections.clear :all
assert ActiveSupport::Inflector.inflections.plurals.empty?
assert ActiveSupport::Inflector.inflections.singulars.empty?
assert ActiveSupport::Inflector.inflections.uncountables.empty?
ActiveSupport::Inflector.inflections.instance_variable_set :@plurals, cached_values[0]
ActiveSupport::Inflector.inflections.instance_variable_set :@singulars, cached_values[1]
ActiveSupport::Inflector.inflections.instance_variable_set :@uncountables, cached_values[2]
end
def test_clear_with_default
cached_values = Inflector.inflections.plurals, Inflector.inflections.singulars, Inflector.inflections.uncountables
Inflector.inflections.clear
assert Inflector.inflections.plurals.empty?
assert Inflector.inflections.singulars.empty?
assert Inflector.inflections.uncountables.empty?
Inflector.inflections.instance_variable_set :@plurals, cached_values[0]
Inflector.inflections.instance_variable_set :@singulars, cached_values[1]
Inflector.inflections.instance_variable_set :@uncountables, cached_values[2]
cached_values = ActiveSupport::Inflector.inflections.plurals, ActiveSupport::Inflector.inflections.singulars, ActiveSupport::Inflector.inflections.uncountables
ActiveSupport::Inflector.inflections.clear
assert ActiveSupport::Inflector.inflections.plurals.empty?
assert ActiveSupport::Inflector.inflections.singulars.empty?
assert ActiveSupport::Inflector.inflections.uncountables.empty?
ActiveSupport::Inflector.inflections.instance_variable_set :@plurals, cached_values[0]
ActiveSupport::Inflector.inflections.instance_variable_set :@singulars, cached_values[1]
ActiveSupport::Inflector.inflections.instance_variable_set :@uncountables, cached_values[2]
end
Irregularities.each do |irregularity|
singular, plural = *irregularity
Inflector.inflections do |inflect|
ActiveSupport::Inflector.inflections do |inflect|
define_method("test_irregularity_between_#{singular}_and_#{plural}") do
inflect.irregular(singular, plural)
assert_equal singular, Inflector.singularize(plural)
assert_equal plural, Inflector.pluralize(singular)
assert_equal singular, ActiveSupport::Inflector.singularize(plural)
assert_equal plural, ActiveSupport::Inflector.pluralize(singular)
end
end
end
[ :all, [] ].each do |scope|
Inflector.inflections do |inflect|
ActiveSupport::Inflector.inflections do |inflect|
define_method("test_clear_inflections_with_#{scope.kind_of?(Array) ? "no_arguments" : scope}") do
# save all the inflections
singulars, plurals, uncountables = inflect.singulars, inflect.plurals, inflect.uncountables
@@ -218,7 +218,7 @@ class InflectorTest < Test::Unit::TestCase
end
{ :singulars => :singular, :plurals => :plural, :uncountables => :uncountable }.each do |scope, method|
Inflector.inflections do |inflect|
ActiveSupport::Inflector.inflections do |inflect|
define_method("test_clear_inflections_with_#{scope}") do
# save the inflections
values = inflect.send(scope)

View File

@@ -42,4 +42,23 @@ class OrderedHashTest < Test::Unit::TestCase
assert_nil @ordered_hash.delete(bad_key)
end
def test_has_key
assert_equal true, @ordered_hash.has_key?('blue')
assert_equal true, @ordered_hash.key?('blue')
assert_equal true, @ordered_hash.include?('blue')
assert_equal true, @ordered_hash.member?('blue')
assert_equal false, @ordered_hash.has_key?('indigo')
assert_equal false, @ordered_hash.key?('indigo')
assert_equal false, @ordered_hash.include?('indigo')
assert_equal false, @ordered_hash.member?('indigo')
end
def test_has_value
assert_equal true, @ordered_hash.has_value?('000099')
assert_equal true, @ordered_hash.value?('000099')
assert_equal false, @ordered_hash.has_value?('ABCABC')
assert_equal false, @ordered_hash.value?('ABCABC')
end
end

View File

@@ -2,7 +2,7 @@ require 'abstract_unit'
class OrderedOptionsTest < Test::Unit::TestCase
def test_usage
a = OrderedOptions.new
a = ActiveSupport::OrderedOptions.new
assert_nil a[:not_set]
@@ -20,7 +20,7 @@ class OrderedOptionsTest < Test::Unit::TestCase
end
def test_looping
a = OrderedOptions.new
a = ActiveSupport::OrderedOptions.new
a[:allow_concurreny] = true
a["else_where"] = 56
@@ -34,7 +34,7 @@ class OrderedOptionsTest < Test::Unit::TestCase
end
def test_method_access
a = OrderedOptions.new
a = ActiveSupport::OrderedOptions.new
assert_nil a.not_set

View File

@@ -0,0 +1,15 @@
require 'abstract_unit'
class StringQuestioneerTest < Test::Unit::TestCase
def test_match
assert StringQuestioneer.new("production").production?
end
def test_miss
assert !StringQuestioneer.new("production").development?
end
def test_missing_question_mark
assert_raises(NoMethodError) { StringQuestioneer.new("production").production }
end
end

View File

@@ -1,10 +1,9 @@
require 'abstract_unit'
class TimeZoneTest < Test::Unit::TestCase
def test_utc_to_local
silence_warnings do # silence warnings raised by tzinfo gem
zone = TimeZone['Eastern Time (US & Canada)']
zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
assert_equal Time.utc(1999, 12, 31, 19), zone.utc_to_local(Time.utc(2000, 1)) # standard offset -0500
assert_equal Time.utc(2000, 6, 30, 20), zone.utc_to_local(Time.utc(2000, 7)) # dst offset -0400
end
@@ -12,41 +11,41 @@ class TimeZoneTest < Test::Unit::TestCase
def test_local_to_utc
silence_warnings do # silence warnings raised by tzinfo gem
zone = TimeZone['Eastern Time (US & Canada)']
zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
assert_equal Time.utc(2000, 1, 1, 5), zone.local_to_utc(Time.utc(2000, 1)) # standard offset -0500
assert_equal Time.utc(2000, 7, 1, 4), zone.local_to_utc(Time.utc(2000, 7)) # dst offset -0400
end
end
def test_period_for_local
silence_warnings do # silence warnings raised by tzinfo gem
zone = TimeZone['Eastern Time (US & Canada)']
zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
assert_instance_of TZInfo::TimezonePeriod, zone.period_for_local(Time.utc(2000))
end
end
TimeZone::MAPPING.keys.each do |name|
ActiveSupport::TimeZone::MAPPING.keys.each do |name|
define_method("test_map_#{name.downcase.gsub(/[^a-z]/, '_')}_to_tzinfo") do
silence_warnings do # silence warnings raised by tzinfo gem
zone = TimeZone[name]
zone = ActiveSupport::TimeZone[name]
assert zone.tzinfo.respond_to?(:period_for_local)
end
end
end
def test_from_integer_to_map
assert_instance_of TimeZone, TimeZone[-28800] # PST
assert_instance_of ActiveSupport::TimeZone, ActiveSupport::TimeZone[-28800] # PST
end
def test_from_duration_to_map
assert_instance_of TimeZone, TimeZone[-480.minutes] # PST
assert_instance_of ActiveSupport::TimeZone, ActiveSupport::TimeZone[-480.minutes] # PST
end
TimeZone.all.each do |zone|
ActiveSupport::TimeZone.all.each do |zone|
name = zone.name.downcase.gsub(/[^a-z]/, '_')
define_method("test_from_#{name}_to_map") do
silence_warnings do # silence warnings raised by tzinfo gem
assert_instance_of TimeZone, TimeZone[zone.name]
assert_instance_of ActiveSupport::TimeZone, ActiveSupport::TimeZone[zone.name]
end
end
@@ -62,62 +61,62 @@ class TimeZoneTest < Test::Unit::TestCase
def test_now
with_env_tz 'US/Eastern' do
Time.stubs(:now).returns(Time.local(2000))
zone = TimeZone['Eastern Time (US & Canada)']
zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
assert_instance_of ActiveSupport::TimeWithZone, zone.now
assert_equal Time.utc(2000,1,1,5), zone.now.utc
assert_equal Time.utc(2000), zone.now.time
assert_equal zone, zone.now.time_zone
end
end
def test_now_enforces_spring_dst_rules
with_env_tz 'US/Eastern' do
Time.stubs(:now).returns(Time.local(2006,4,2,2)) # 2AM springs forward to 3AM
zone = TimeZone['Eastern Time (US & Canada)']
zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
assert_equal Time.utc(2006,4,2,3), zone.now.time
assert_equal true, zone.now.dst?
end
end
def test_now_enforces_fall_dst_rules
with_env_tz 'US/Eastern' do
Time.stubs(:now).returns(Time.at(1162098000)) # equivalent to 1AM DST
zone = TimeZone['Eastern Time (US & Canada)']
zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
assert_equal Time.utc(2006,10,29,1), zone.now.time
assert_equal true, zone.now.dst?
end
end
def test_today
Time.stubs(:now).returns(Time.utc(2000, 1, 1, 4, 59, 59)) # 1 sec before midnight Jan 1 EST
assert_equal Date.new(1999, 12, 31), TimeZone['Eastern Time (US & Canada)'].today
assert_equal Date.new(1999, 12, 31), ActiveSupport::TimeZone['Eastern Time (US & Canada)'].today
Time.stubs(:now).returns(Time.utc(2000, 1, 1, 5)) # midnight Jan 1 EST
assert_equal Date.new(2000, 1, 1), TimeZone['Eastern Time (US & Canada)'].today
assert_equal Date.new(2000, 1, 1), ActiveSupport::TimeZone['Eastern Time (US & Canada)'].today
Time.stubs(:now).returns(Time.utc(2000, 1, 2, 4, 59, 59)) # 1 sec before midnight Jan 2 EST
assert_equal Date.new(2000, 1, 1), TimeZone['Eastern Time (US & Canada)'].today
assert_equal Date.new(2000, 1, 1), ActiveSupport::TimeZone['Eastern Time (US & Canada)'].today
Time.stubs(:now).returns(Time.utc(2000, 1, 2, 5)) # midnight Jan 2 EST
assert_equal Date.new(2000, 1, 2), TimeZone['Eastern Time (US & Canada)'].today
assert_equal Date.new(2000, 1, 2), ActiveSupport::TimeZone['Eastern Time (US & Canada)'].today
end
end
def test_local
silence_warnings do # silence warnings raised by tzinfo gem
time = TimeZone["Hawaii"].local(2007, 2, 5, 15, 30, 45)
time = ActiveSupport::TimeZone["Hawaii"].local(2007, 2, 5, 15, 30, 45)
assert_equal Time.utc(2007, 2, 5, 15, 30, 45), time.time
assert_equal TimeZone["Hawaii"], time.time_zone
assert_equal ActiveSupport::TimeZone["Hawaii"], time.time_zone
end
end
def test_local_with_old_date
silence_warnings do # silence warnings raised by tzinfo gem
time = TimeZone["Hawaii"].local(1850, 2, 5, 15, 30, 45)
time = ActiveSupport::TimeZone["Hawaii"].local(1850, 2, 5, 15, 30, 45)
assert_equal [45,30,15,5,2,1850], time.to_a[0,6]
assert_equal TimeZone["Hawaii"], time.time_zone
assert_equal ActiveSupport::TimeZone["Hawaii"], time.time_zone
end
end
def test_local_enforces_spring_dst_rules
zone = TimeZone['Eastern Time (US & Canada)']
zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
twz = zone.local(2006,4,2,1,59,59) # 1 second before DST start
assert_equal Time.utc(2006,4,2,1,59,59), twz.time
assert_equal Time.utc(2006,4,2,6,59,59), twz.utc
@@ -138,16 +137,16 @@ class TimeZoneTest < Test::Unit::TestCase
def test_local_enforces_fall_dst_rules
# 1AM during fall DST transition is ambiguous, it could be either DST or non-DST 1AM
# Mirroring Time.local behavior, this method selects the DST time
zone = TimeZone['Eastern Time (US & Canada)']
zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
twz = zone.local(2006,10,29,1)
assert_equal Time.utc(2006,10,29,1), twz.time
assert_equal Time.utc(2006,10,29,5), twz.utc
assert_equal true, twz.dst?
assert_equal true, twz.dst?
assert_equal 'EDT', twz.zone
end
def test_at
zone = TimeZone['Eastern Time (US & Canada)']
zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
secs = 946684800.0
twz = zone.at(secs)
assert_equal Time.utc(1999,12,31,19), twz.time
@@ -157,7 +156,7 @@ class TimeZoneTest < Test::Unit::TestCase
end
def test_at_with_old_date
zone = TimeZone['Eastern Time (US & Canada)']
zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
secs = DateTime.civil(1850).to_f
twz = zone.at(secs)
assert_equal [1850, 1, 1, 0], [twz.utc.year, twz.utc.mon, twz.utc.day, twz.utc.hour]
@@ -166,7 +165,7 @@ class TimeZoneTest < Test::Unit::TestCase
end
def test_parse
zone = TimeZone['Eastern Time (US & Canada)']
zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
twz = zone.parse('1999-12-31 19:00:00')
assert_equal Time.utc(1999,12,31,19), twz.time
assert_equal Time.utc(2000), twz.utc
@@ -175,7 +174,7 @@ class TimeZoneTest < Test::Unit::TestCase
def test_parse_string_with_timezone
(-11..13).each do |timezone_offset|
zone = TimeZone[timezone_offset]
zone = ActiveSupport::TimeZone[timezone_offset]
twz = zone.parse('1999-12-31 19:00:00')
assert_equal twz, zone.parse(twz.to_s)
end
@@ -183,25 +182,25 @@ class TimeZoneTest < Test::Unit::TestCase
def test_parse_with_old_date
silence_warnings do # silence warnings raised by tzinfo gem
zone = TimeZone['Eastern Time (US & Canada)']
zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
twz = zone.parse('1850-12-31 19:00:00')
assert_equal [0,0,19,31,12,1850], twz.to_a[0,6]
assert_equal zone, twz.time_zone
end
end
def test_parse_far_future_date_with_time_zone_offset_in_string
silence_warnings do # silence warnings raised by tzinfo gem
zone = TimeZone['Eastern Time (US & Canada)']
zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
twz = zone.parse('2050-12-31 19:00:00 -10:00') # i.e., 2050-01-01 05:00:00 UTC
assert_equal [0,0,0,1,1,2051], twz.to_a[0,6]
assert_equal zone, twz.time_zone
end
end
def test_parse_returns_nil_when_string_without_date_information_is_passed_in
silence_warnings do # silence warnings raised by tzinfo gem
zone = TimeZone['Eastern Time (US & Canada)']
zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
assert_nil zone.parse('foobar')
assert_nil zone.parse(' ')
end
@@ -209,80 +208,80 @@ class TimeZoneTest < Test::Unit::TestCase
uses_mocha 'TestParseWithIncompleteDate' do
def test_parse_with_incomplete_date
zone = TimeZone['Eastern Time (US & Canada)']
zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
zone.stubs(:now).returns zone.local(1999,12,31)
twz = zone.parse('19:00:00')
assert_equal Time.utc(1999,12,31,19), twz.time
end
end
def test_utc_offset_lazy_loaded_from_tzinfo_when_not_passed_in_to_initialize
silence_warnings do # silence warnings raised by tzinfo gem
tzinfo = TZInfo::Timezone.get('America/New_York')
zone = TimeZone.create(tzinfo.name, nil, tzinfo)
zone = ActiveSupport::TimeZone.create(tzinfo.name, nil, tzinfo)
assert_equal nil, zone.instance_variable_get('@utc_offset')
assert_equal(-18_000, zone.utc_offset)
end
end
def test_formatted_offset_positive
zone = TimeZone['Moscow']
zone = ActiveSupport::TimeZone['Moscow']
assert_equal "+03:00", zone.formatted_offset
assert_equal "+0300", zone.formatted_offset(false)
end
def test_formatted_offset_negative
zone = TimeZone['Eastern Time (US & Canada)']
zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
assert_equal "-05:00", zone.formatted_offset
assert_equal "-0500", zone.formatted_offset(false)
end
def test_formatted_offset_zero
zone = TimeZone['London']
zone = ActiveSupport::TimeZone['London']
assert_equal "+00:00", zone.formatted_offset
assert_equal "UTC", zone.formatted_offset(true, 'UTC')
end
def test_zone_compare
zone1 = TimeZone['Central Time (US & Canada)'] # offset -0600
zone2 = TimeZone['Eastern Time (US & Canada)'] # offset -0500
zone1 = ActiveSupport::TimeZone['Central Time (US & Canada)'] # offset -0600
zone2 = ActiveSupport::TimeZone['Eastern Time (US & Canada)'] # offset -0500
assert zone1 < zone2
assert zone2 > zone1
assert zone1 == zone1
end
def test_to_s
assert_equal "(GMT+03:00) Moscow", TimeZone['Moscow'].to_s
assert_equal "(GMT+03:00) Moscow", ActiveSupport::TimeZone['Moscow'].to_s
end
def test_all_sorted
all = TimeZone.all
all = ActiveSupport::TimeZone.all
1.upto( all.length-1 ) do |i|
assert all[i-1] < all[i]
end
end
def test_index
assert_nil TimeZone["bogus"]
assert_instance_of TimeZone, TimeZone["Central Time (US & Canada)"]
assert_instance_of TimeZone, TimeZone[8]
assert_raises(ArgumentError) { TimeZone[false] }
assert_nil ActiveSupport::TimeZone["bogus"]
assert_instance_of ActiveSupport::TimeZone, ActiveSupport::TimeZone["Central Time (US & Canada)"]
assert_instance_of ActiveSupport::TimeZone, ActiveSupport::TimeZone[8]
assert_raises(ArgumentError) { ActiveSupport::TimeZone[false] }
end
def test_new
assert_equal TimeZone["Central Time (US & Canada)"], TimeZone.new("Central Time (US & Canada)")
assert_equal ActiveSupport::TimeZone["Central Time (US & Canada)"], ActiveSupport::TimeZone.new("Central Time (US & Canada)")
end
def test_us_zones
assert TimeZone.us_zones.include?(TimeZone["Hawaii"])
assert !TimeZone.us_zones.include?(TimeZone["Kuala Lumpur"])
end
assert ActiveSupport::TimeZone.us_zones.include?(ActiveSupport::TimeZone["Hawaii"])
assert !ActiveSupport::TimeZone.us_zones.include?(ActiveSupport::TimeZone["Kuala Lumpur"])
end
protected
def with_env_tz(new_tz = 'US/Eastern')
old_tz, ENV['TZ'] = ENV['TZ'], new_tz
yield
ensure
old_tz ? ENV['TZ'] = old_tz : ENV.delete('TZ')
end
end
end

View File

@@ -1,5 +1,7 @@
*Edge*
* Wrapped Rails.env in StringQuestioneer so you can do Rails.env.development? [DHH]
* Fixed that RailsInfoController wasn't considering all requests local in development mode (Edgard Castro) [#310 state:resolved]

View File

@@ -37,7 +37,7 @@ module Rails
end
def env
RAILS_ENV
StringQuestioneer.new(RAILS_ENV)
end
def cache
@@ -204,10 +204,10 @@ module Rails
# Set the paths from which Rails will automatically load source files, and
# the load_once paths.
def set_autoload_paths
Dependencies.load_paths = configuration.load_paths.uniq
Dependencies.load_once_paths = configuration.load_once_paths.uniq
ActiveSupport::Dependencies.load_paths = configuration.load_paths.uniq
ActiveSupport::Dependencies.load_once_paths = configuration.load_once_paths.uniq
extra = Dependencies.load_once_paths - Dependencies.load_paths
extra = ActiveSupport::Dependencies.load_once_paths - ActiveSupport::Dependencies.load_paths
unless extra.empty?
abort <<-end_error
load_once_paths must be a subset of the load_paths.
@@ -234,7 +234,7 @@ module Rails
end
# Adds all load paths from plugins to the global set of load paths, so that
# code from plugins can be required (explicitly or automatically via Dependencies).
# code from plugins can be required (explicitly or automatically via ActiveSupport::Dependencies).
def add_plugin_load_paths
plugin_loader.add_plugin_load_paths
end
@@ -416,7 +416,7 @@ module Rails
# Sets the dependency loading mechanism based on the value of
# Configuration#cache_classes.
def initialize_dependency_mechanism
Dependencies.mechanism = configuration.cache_classes ? :require : :load
ActiveSupport::Dependencies.mechanism = configuration.cache_classes ? :require : :load
end
# Loads support for "whiny nil" (noisy warnings when methods are invoked
@@ -602,12 +602,12 @@ module Rails
# If <tt>reload_plugins?</tt> is false, add this to your plugin's <tt>init.rb</tt>
# to make it reloadable:
#
# Dependencies.load_once_paths.delete lib_path
# ActiveSupport::Dependencies.load_once_paths.delete lib_path
#
# If <tt>reload_plugins?</tt> is true, add this to your plugin's <tt>init.rb</tt>
# to only load it once:
#
# Dependencies.load_once_paths << lib_path
# ActiveSupport::Dependencies.load_once_paths << lib_path
#
attr_accessor :reload_plugins

View File

@@ -45,9 +45,9 @@ module Rails
plugins.each do |plugin|
plugin.load_paths.each do |path|
$LOAD_PATH.insert(application_lib_index + 1, path)
Dependencies.load_paths << path
ActiveSupport::Dependencies.load_paths << path
unless Rails.configuration.reload_plugins?
Dependencies.load_once_paths << path
ActiveSupport::Dependencies.load_once_paths << path
end
end
end