diff options
102 files changed, 3210 insertions, 3747 deletions
diff --git a/actionmailer/lib/action_mailer/version.rb b/actionmailer/lib/action_mailer/version.rb index c35b648baf..9728d1b4db 100644 --- a/actionmailer/lib/action_mailer/version.rb +++ b/actionmailer/lib/action_mailer/version.rb @@ -1,7 +1,7 @@ module ActionMailer module VERSION #:nodoc: MAJOR = 2 - MINOR = 1 + MINOR = 2 TINY = 0 STRING = [MAJOR, MINOR, TINY].join('.') diff --git a/actionpack/CHANGELOG b/actionpack/CHANGELOG index 3743e3e8fe..54ea93fb72 100644 --- a/actionpack/CHANGELOG +++ b/actionpack/CHANGELOG @@ -1,5 +1,7 @@ *Edge* +* Set HttpOnly for the cookie session store's cookie. #1046 + * Added FormTagHelper#image_submit_tag confirm option #784 [Alastair Brunton] * Fixed FormTagHelper#submit_tag with :disable_with option wouldn't submit the button's value when was clicked #633 [Jose Fernandez] diff --git a/actionpack/lib/action_controller/cgi_ext/session.rb b/actionpack/lib/action_controller/cgi_ext/session.rb index a01f17f9ce..d3f85e3705 100644 --- a/actionpack/lib/action_controller/cgi_ext/session.rb +++ b/actionpack/lib/action_controller/cgi_ext/session.rb @@ -6,28 +6,8 @@ class CGI #:nodoc: # * Expose the CGI instance to session stores. # * Don't require 'digest/md5' whenever a new session id is generated. class Session #:nodoc: - begin - require 'securerandom' - - # Generate a 32-character unique id using SecureRandom. - # This is used to generate session ids but may be reused elsewhere. - def self.generate_unique_id(constant = nil) - SecureRandom.hex(16) - end - rescue LoadError - # Generate an 32-character unique id based on a hash of the current time, - # a random number, the process id, and a constant string. This is used - # to generate session ids but may be reused elsewhere. - def self.generate_unique_id(constant = 'foobar') - md5 = Digest::MD5.new - now = Time.now - md5 << now.to_s - md5 << String(now.usec) - md5 << String(rand(0)) - md5 << String($$) - md5 << constant - md5.hexdigest - end + def self.generate_unique_id(constant = nil) + ActiveSupport::SecureRandom.hex(16) end # Make the CGI instance available to session stores. diff --git a/actionpack/lib/action_controller/cgi_process.rb b/actionpack/lib/action_controller/cgi_process.rb index d381af1b84..fabacd9b83 100644 --- a/actionpack/lib/action_controller/cgi_process.rb +++ b/actionpack/lib/action_controller/cgi_process.rb @@ -42,7 +42,8 @@ module ActionController #:nodoc: :prefix => "ruby_sess.", # prefix session file names :session_path => "/", # available to all paths in app :session_key => "_session_id", - :cookie_only => true + :cookie_only => true, + :session_http_only=> true } def initialize(cgi, session_options = {}) diff --git a/actionpack/lib/action_controller/rack_process.rb b/actionpack/lib/action_controller/rack_process.rb index 1ace16da07..e8ea3704a8 100644 --- a/actionpack/lib/action_controller/rack_process.rb +++ b/actionpack/lib/action_controller/rack_process.rb @@ -14,7 +14,8 @@ module ActionController #:nodoc: :prefix => "ruby_sess.", # prefix session file names :session_path => "/", # available to all paths in app :session_key => "_session_id", - :cookie_only => true + :cookie_only => true, + :session_http_only=> true } def initialize(env, session_options = DEFAULT_SESSION_OPTIONS) diff --git a/actionpack/lib/action_controller/session/cookie_store.rb b/actionpack/lib/action_controller/session/cookie_store.rb index 5bf7503f04..f2fb200950 100644 --- a/actionpack/lib/action_controller/session/cookie_store.rb +++ b/actionpack/lib/action_controller/session/cookie_store.rb @@ -70,7 +70,8 @@ class CGI::Session::CookieStore 'path' => options['session_path'], 'domain' => options['session_domain'], 'expires' => options['session_expires'], - 'secure' => options['session_secure'] + 'secure' => options['session_secure'], + 'http_only' => options['session_http_only'] } # Set no_hidden and no_cookies since the session id is unused and we diff --git a/actionpack/lib/action_controller/session_management.rb b/actionpack/lib/action_controller/session_management.rb index f5a1155a46..fd3d94ed97 100644 --- a/actionpack/lib/action_controller/session_management.rb +++ b/actionpack/lib/action_controller/session_management.rb @@ -60,6 +60,10 @@ module ActionController #:nodoc: # # the session will only work over HTTPS, but only for the foo action # session :only => :foo, :session_secure => true # + # # the session by default uses HttpOnly sessions for security reasons. + # # this can be switched off. + # session :only => :foo, :session_http_only => false + # # # the session will only be disabled for 'foo', and only if it is # # requested as a web service # session :off, :only => :foo, diff --git a/actionpack/lib/action_pack/version.rb b/actionpack/lib/action_pack/version.rb index c67654d9a8..288b62778e 100644 --- a/actionpack/lib/action_pack/version.rb +++ b/actionpack/lib/action_pack/version.rb @@ -1,7 +1,7 @@ module ActionPack #:nodoc: module VERSION #:nodoc: MAJOR = 2 - MINOR = 1 + MINOR = 2 TINY = 0 STRING = [MAJOR, MINOR, TINY].join('.') diff --git a/actionpack/lib/action_view.rb b/actionpack/lib/action_view.rb index 0ed69f29bf..7cd9b633ac 100644 --- a/actionpack/lib/action_view.rb +++ b/actionpack/lib/action_view.rb @@ -43,7 +43,7 @@ require 'action_view/base' require 'action_view/partials' require 'action_view/template_error' -I18n.load_translations "#{File.dirname(__FILE__)}/action_view/locale/en-US.yml" +I18n.load_path << "#{File.dirname(__FILE__)}/action_view/locale/en-US.yml" require 'action_view/helpers' diff --git a/actionpack/lib/action_view/helpers.rb b/actionpack/lib/action_view/helpers.rb index 05e1cf990a..ff97df204c 100644 --- a/actionpack/lib/action_view/helpers.rb +++ b/actionpack/lib/action_view/helpers.rb @@ -21,7 +21,6 @@ module ActionView #:nodoc: include CaptureHelper include DateHelper include DebugHelper - include FormCountryHelper include FormHelper include FormOptionsHelper include FormTagHelper diff --git a/actionpack/lib/action_view/helpers/asset_tag_helper.rb b/actionpack/lib/action_view/helpers/asset_tag_helper.rb index a926599e25..63ccde393a 100644 --- a/actionpack/lib/action_view/helpers/asset_tag_helper.rb +++ b/actionpack/lib/action_view/helpers/asset_tag_helper.rb @@ -151,7 +151,7 @@ module ActionView # javascript_path "http://www.railsapplication.com/js/xmlhr" # => http://www.railsapplication.com/js/xmlhr.js # javascript_path "http://www.railsapplication.com/js/xmlhr.js" # => http://www.railsapplication.com/js/xmlhr.js def javascript_path(source) - compute_public_path(source, 'javascripts', 'js') + JavaScriptTag.create(self, @controller, source).public_path end alias_method :path_to_javascript, :javascript_path # aliased to avoid conflicts with a javascript_path named route @@ -249,15 +249,17 @@ module ActionView joined_javascript_name = (cache == true ? "all" : cache) + ".js" joined_javascript_path = File.join(JAVASCRIPTS_DIR, joined_javascript_name) - write_asset_file_contents(joined_javascript_path, compute_javascript_paths(sources, recursive)) unless File.exists?(joined_javascript_path) + unless File.exists?(joined_javascript_path) + JavaScriptSources.create(self, @controller, sources, recursive).write_asset_file_contents(joined_javascript_path) + end javascript_src_tag(joined_javascript_name, options) else - expand_javascript_sources(sources, recursive).collect { |source| javascript_src_tag(source, options) }.join("\n") + JavaScriptSources.create(self, @controller, sources, recursive).expand_sources.collect { |source| + javascript_src_tag(source, options) + }.join("\n") end end - @@javascript_expansions = { :defaults => JAVASCRIPT_DEFAULT_SOURCES.dup } - # Register one or more javascript files to be included when <tt>symbol</tt> # is passed to <tt>javascript_include_tag</tt>. This method is typically intended # to be called from plugin initialization to register javascript files @@ -270,11 +272,9 @@ module ActionView # <script type="text/javascript" src="/javascripts/body.js"></script> # <script type="text/javascript" src="/javascripts/tail.js"></script> def self.register_javascript_expansion(expansions) - @@javascript_expansions.merge!(expansions) + JavaScriptSources.expansions.merge!(expansions) end - @@stylesheet_expansions = {} - # Register one or more stylesheet files to be included when <tt>symbol</tt> # is passed to <tt>stylesheet_link_tag</tt>. This method is typically intended # to be called from plugin initialization to register stylesheet files @@ -287,7 +287,7 @@ module ActionView # <link href="/stylesheets/body.css" media="screen" rel="stylesheet" type="text/css" /> # <link href="/stylesheets/tail.css" media="screen" rel="stylesheet" type="text/css" /> def self.register_stylesheet_expansion(expansions) - @@stylesheet_expansions.merge!(expansions) + StylesheetSources.expansions.merge!(expansions) end # Register one or more additional JavaScript files to be included when @@ -295,11 +295,11 @@ module ActionView # typically intended to be called from plugin initialization to register additional # .js files that the plugin installed in <tt>public/javascripts</tt>. def self.register_javascript_include_default(*sources) - @@javascript_expansions[:defaults].concat(sources) + JavaScriptSources.expansions[:defaults].concat(sources) end def self.reset_javascript_include_default #:nodoc: - @@javascript_expansions[:defaults] = JAVASCRIPT_DEFAULT_SOURCES.dup + JavaScriptSources.expansions[:defaults] = JAVASCRIPT_DEFAULT_SOURCES.dup end # Computes the path to a stylesheet asset in the public stylesheets directory. @@ -314,7 +314,7 @@ module ActionView # stylesheet_path "http://www.railsapplication.com/css/style" # => http://www.railsapplication.com/css/style.css # stylesheet_path "http://www.railsapplication.com/css/style.js" # => http://www.railsapplication.com/css/style.css def stylesheet_path(source) - compute_public_path(source, 'stylesheets', 'css') + StylesheetTag.create(self, @controller, source).public_path end alias_method :path_to_stylesheet, :stylesheet_path # aliased to avoid conflicts with a stylesheet_path named route @@ -389,10 +389,14 @@ module ActionView joined_stylesheet_name = (cache == true ? "all" : cache) + ".css" joined_stylesheet_path = File.join(STYLESHEETS_DIR, joined_stylesheet_name) - write_asset_file_contents(joined_stylesheet_path, compute_stylesheet_paths(sources, recursive)) unless File.exists?(joined_stylesheet_path) + unless File.exists?(joined_stylesheet_path) + StylesheetSources.create(self, @controller, sources, recursive).write_asset_file_contents(joined_stylesheet_path) + end stylesheet_tag(joined_stylesheet_name, options) else - expand_stylesheet_sources(sources, recursive).collect { |source| stylesheet_tag(source, options) }.join("\n") + StylesheetSources.create(self, @controller, sources, recursive).expand_sources.collect { |source| + stylesheet_tag(source, options) + }.join("\n") end end @@ -407,7 +411,7 @@ module ActionView # image_path("/icons/edit.png") # => /icons/edit.png # image_path("http://www.railsapplication.com/img/edit.png") # => http://www.railsapplication.com/img/edit.png def image_path(source) - compute_public_path(source, 'images') + ImageTag.create(self, @controller, source).public_path end alias_method :path_to_image, :image_path # aliased to avoid conflicts with an image_path named route @@ -463,180 +467,344 @@ module ActionView end private - COMPUTED_PUBLIC_PATHS = {} - COMPUTED_PUBLIC_PATHS_GUARD = Mutex.new - - # Add the the extension +ext+ if not present. Return full URLs otherwise untouched. - # Prefix with <tt>/dir/</tt> if lacking a leading +/+. Account for relative URL - # roots. Rewrite the asset path for cache-busting asset ids. Include - # asset host, if configured, with the correct request protocol. - def compute_public_path(source, dir, ext = nil, include_host = true) - has_request = @controller.respond_to?(:request) - - cache_key = - if has_request - [ @controller.request.protocol, - ActionController::Base.asset_host.to_s, - ActionController::Base.relative_url_root, - dir, source, ext, include_host ].join - else - [ ActionController::Base.asset_host.to_s, - dir, source, ext, include_host ].join - end + def javascript_src_tag(source, options) + content_tag("script", "", { "type" => Mime::JS, "src" => path_to_javascript(source) }.merge(options)) + end - COMPUTED_PUBLIC_PATHS_GUARD.synchronize do - source = COMPUTED_PUBLIC_PATHS[cache_key] ||= - begin - source += ".#{ext}" if ext && File.extname(source).blank? || File.exist?(File.join(ASSETS_DIR, dir, "#{source}.#{ext}")) + def stylesheet_tag(source, options) + tag("link", { "rel" => "stylesheet", "type" => Mime::CSS, "media" => "screen", "href" => html_escape(path_to_stylesheet(source)) }.merge(options), false, false) + end - if source =~ %r{^[-a-z]+://} - source - else - source = "/#{dir}/#{source}" unless source[0] == ?/ - if has_request - unless source =~ %r{^#{ActionController::Base.relative_url_root}/} - source = "#{ActionController::Base.relative_url_root}#{source}" - end - end + module ImageAsset + DIRECTORY = 'images'.freeze - rewrite_asset_path(source) - end - end + def directory + DIRECTORY end - if include_host && source !~ %r{^[-a-z]+://} - host = compute_asset_host(source) + def extension + nil + end + end - if has_request && !host.blank? && host !~ %r{^[-a-z]+://} - host = "#{@controller.request.protocol}#{host}" - end + module JavaScriptAsset + DIRECTORY = 'javascripts'.freeze + EXTENSION = 'js'.freeze + + def public_directory + JAVASCRIPTS_DIR + end + + def directory + DIRECTORY + end + + def extension + EXTENSION + end + end + + module StylesheetAsset + DIRECTORY = 'stylesheets'.freeze + EXTENSION = 'css'.freeze + + def public_directory + STYLESHEETS_DIR + end + + def directory + DIRECTORY + end - "#{host}#{source}" - else - source + def extension + EXTENSION end end - # Pick an asset host for this source. Returns +nil+ if no host is set, - # the host if no wildcard is set, the host interpolated with the - # numbers 0-3 if it contains <tt>%d</tt> (the number is the source hash mod 4), - # or the value returned from invoking the proc if it's a proc. - def compute_asset_host(source) - if host = ActionController::Base.asset_host - if host.is_a?(Proc) - case host.arity - when 2 - host.call(source, @controller.request) + class AssetTag + extend ActiveSupport::Memoizable + + Cache = {} + CacheGuard = Mutex.new + + def self.create(template, controller, source, include_host = true) + CacheGuard.synchronize do + key = if controller.respond_to?(:request) + [self, controller.request.protocol, + ActionController::Base.asset_host, + ActionController::Base.relative_url_root, + source, include_host] else - host.call(source) + [self, ActionController::Base.asset_host, source, include_host] end - else - (host =~ /%d/) ? host % (source.hash % 4) : host + Cache[key] ||= new(template, controller, source, include_host).freeze end end - end - # Use the RAILS_ASSET_ID environment variable or the source's - # modification time as its cache-busting asset id. - def rails_asset_id(source) - if asset_id = ENV["RAILS_ASSET_ID"] - asset_id - else - path = File.join(ASSETS_DIR, source) + ProtocolRegexp = %r{^[-a-z]+://}.freeze - if File.exist?(path) - File.mtime(path).to_i.to_s - else - '' - end + def initialize(template, controller, source, include_host = true) + # NOTE: The template arg is temporarily needed for a legacy plugin + # hook that is expected to call rewrite_asset_path on the + # template. This should eventually be removed. + @template = template + @controller = controller + @source = source + @include_host = include_host end - end - # Break out the asset path rewrite in case plugins wish to put the asset id - # someplace other than the query string. - def rewrite_asset_path(source) - asset_id = rails_asset_id(source) - if asset_id.blank? - source - else - source + "?#{asset_id}" + def public_path + compute_public_path(@source) end - end + memoize :public_path - def javascript_src_tag(source, options) - content_tag("script", "", { "type" => Mime::JS, "src" => path_to_javascript(source) }.merge(options)) + def asset_file_path + File.join(ASSETS_DIR, public_path.split('?').first) + end + memoize :asset_file_path + + def contents + File.read(asset_file_path) + end + + def mtime + File.mtime(asset_file_path) + end + + private + def request + @controller.request + end + + def request? + @controller.respond_to?(:request) + end + + # Add the the extension +ext+ if not present. Return full URLs otherwise untouched. + # Prefix with <tt>/dir/</tt> if lacking a leading +/+. Account for relative URL + # roots. Rewrite the asset path for cache-busting asset ids. Include + # asset host, if configured, with the correct request protocol. + def compute_public_path(source) + source += ".#{extension}" if missing_extension?(source) + unless source =~ ProtocolRegexp + source = "/#{directory}/#{source}" unless source[0] == ?/ + source = prepend_relative_url_root(source) + source = rewrite_asset_path(source) + end + source = prepend_asset_host(source) + source + end + + def missing_extension?(source) + extension && File.extname(source).blank? || File.exist?(File.join(ASSETS_DIR, directory, "#{source}.#{extension}")) + end + + def prepend_relative_url_root(source) + relative_url_root = ActionController::Base.relative_url_root + if request? && @include_host && source !~ %r{^#{relative_url_root}/} + "#{relative_url_root}#{source}" + else + source + end + end + + def prepend_asset_host(source) + if @include_host && source !~ ProtocolRegexp + host = compute_asset_host(source) + if request? && !host.blank? && host !~ ProtocolRegexp + host = "#{request.protocol}#{host}" + end + "#{host}#{source}" + else + source + end + end + + # Pick an asset host for this source. Returns +nil+ if no host is set, + # the host if no wildcard is set, the host interpolated with the + # numbers 0-3 if it contains <tt>%d</tt> (the number is the source hash mod 4), + # or the value returned from invoking the proc if it's a proc. + def compute_asset_host(source) + if host = ActionController::Base.asset_host + if host.is_a?(Proc) + case host.arity + when 2 + host.call(source, request) + else + host.call(source) + end + else + (host =~ /%d/) ? host % (source.hash % 4) : host + end + end + end + + # Use the RAILS_ASSET_ID environment variable or the source's + # modification time as its cache-busting asset id. + def rails_asset_id(source) + if asset_id = ENV["RAILS_ASSET_ID"] + asset_id + else + path = File.join(ASSETS_DIR, source) + + if File.exist?(path) + File.mtime(path).to_i.to_s + else + '' + end + end + end + + # Break out the asset path rewrite in case plugins wish to put the asset id + # someplace other than the query string. + def rewrite_asset_path(source) + if @template.respond_to?(:rewrite_asset_path) + # DEPRECATE: This way to override rewrite_asset_path + @template.send(:rewrite_asset_path, source) + else + asset_id = rails_asset_id(source) + if asset_id.blank? + source + else + "#{source}?#{asset_id}" + end + end + end end - def stylesheet_tag(source, options) - tag("link", { "rel" => "stylesheet", "type" => Mime::CSS, "media" => "screen", "href" => html_escape(path_to_stylesheet(source)) }.merge(options), false, false) + class ImageTag < AssetTag + include ImageAsset end - def compute_javascript_paths(*args) - expand_javascript_sources(*args).collect { |source| compute_public_path(source, 'javascripts', 'js', false) } + class JavaScriptTag < AssetTag + include JavaScriptAsset end - def compute_stylesheet_paths(*args) - expand_stylesheet_sources(*args).collect { |source| compute_public_path(source, 'stylesheets', 'css', false) } + class StylesheetTag < AssetTag + include StylesheetAsset end - def expand_javascript_sources(sources, recursive = false) - if sources.include?(:all) - all_javascript_files = collect_asset_files(JAVASCRIPTS_DIR, ('**' if recursive), '*.js') - @@all_javascript_sources ||= {} - @@all_javascript_sources[recursive] ||= ((determine_source(:defaults, @@javascript_expansions).dup & all_javascript_files) + all_javascript_files).uniq - else - expanded_sources = sources.collect do |source| - determine_source(source, @@javascript_expansions) - end.flatten - expanded_sources << "application" if sources.include?(:defaults) && File.exist?(File.join(JAVASCRIPTS_DIR, "application.js")) - expanded_sources + class AssetCollection + extend ActiveSupport::Memoizable + + Cache = {} + CacheGuard = Mutex.new + + def self.create(template, controller, sources, recursive) + CacheGuard.synchronize do + key = [self, sources, recursive] + Cache[key] ||= new(template, controller, sources, recursive).freeze + end end - end - def expand_stylesheet_sources(sources, recursive) - if sources.first == :all - @@all_stylesheet_sources ||= {} - @@all_stylesheet_sources[recursive] ||= collect_asset_files(STYLESHEETS_DIR, ('**' if recursive), '*.css') - else - sources.collect do |source| - determine_source(source, @@stylesheet_expansions) - end.flatten + def initialize(template, controller, sources, recursive) + # NOTE: The template arg is temporarily needed for a legacy plugin + # hook. See NOTE under AssetTag#initialize for more details + @template = template + @controller = controller + @sources = sources + @recursive = recursive end - end - def determine_source(source, collection) - case source - when Symbol - collection[source] || raise(ArgumentError, "No expansion found for #{source.inspect}") - else - source + def write_asset_file_contents(joined_asset_path) + FileUtils.mkdir_p(File.dirname(joined_asset_path)) + File.open(joined_asset_path, "w+") { |cache| cache.write(joined_contents) } + mt = latest_mtime + File.utime(mt, mt, joined_asset_path) end - end - def join_asset_file_contents(paths) - paths.collect { |path| File.read(asset_file_path(path)) }.join("\n\n") - end + private + def determine_source(source, collection) + case source + when Symbol + collection[source] || raise(ArgumentError, "No expansion found for #{source.inspect}") + else + source + end + end + + def validate_sources! + @sources.collect { |source| determine_source(source, self.class.expansions) }.flatten + end + + def all_asset_files + path = [public_directory, ('**' if @recursive), "*.#{extension}"].compact + Dir[File.join(*path)].collect { |file| + file[-(file.size - public_directory.size - 1)..-1].sub(/\.\w+$/, '') + }.sort + end + + def tag_sources + expand_sources.collect { |source| tag_class.create(@template, @controller, source, false) } + end - def write_asset_file_contents(joined_asset_path, asset_paths) - FileUtils.mkdir_p(File.dirname(joined_asset_path)) - File.open(joined_asset_path, "w+") { |cache| cache.write(join_asset_file_contents(asset_paths)) } + def joined_contents + tag_sources.collect { |source| source.contents }.join("\n\n") + end - # Set mtime to the latest of the combined files to allow for - # consistent ETag without a shared filesystem. - mt = asset_paths.map { |p| File.mtime(asset_file_path(p)) }.max - File.utime(mt, mt, joined_asset_path) + # Set mtime to the latest of the combined files to allow for + # consistent ETag without a shared filesystem. + def latest_mtime + tag_sources.map { |source| source.mtime }.max + end end - def asset_file_path(path) - File.join(ASSETS_DIR, path.split('?').first) + class JavaScriptSources < AssetCollection + include JavaScriptAsset + + EXPANSIONS = { :defaults => JAVASCRIPT_DEFAULT_SOURCES.dup } + + def self.expansions + EXPANSIONS + end + + APPLICATION_JS = "application".freeze + APPLICATION_FILE = "application.js".freeze + + def expand_sources + if @sources.include?(:all) + assets = all_asset_files + ((defaults.dup & assets) + assets).uniq! + else + expanded_sources = validate_sources! + expanded_sources << APPLICATION_JS if include_application? + expanded_sources + end + end + memoize :expand_sources + + private + def tag_class + JavaScriptTag + end + + def defaults + determine_source(:defaults, self.class.expansions) + end + + def include_application? + @sources.include?(:defaults) && File.exist?(File.join(JAVASCRIPTS_DIR, APPLICATION_FILE)) + end end - def collect_asset_files(*path) - dir = path.first + class StylesheetSources < AssetCollection + include StylesheetAsset + + EXPANSIONS = {} + + def self.expansions + EXPANSIONS + end - Dir[File.join(*path.compact)].collect do |file| - file[-(file.size - dir.size - 1)..-1].sub(/\.\w+$/, '') - end.sort + def expand_sources + @sources.first == :all ? all_asset_files : validate_sources! + end + memoize :expand_sources + + private + def tag_class + StylesheetTag + end end end end diff --git a/actionpack/lib/action_view/helpers/form_country_helper.rb b/actionpack/lib/action_view/helpers/form_country_helper.rb deleted file mode 100644 index 84e811f61d..0000000000 --- a/actionpack/lib/action_view/helpers/form_country_helper.rb +++ /dev/null @@ -1,92 +0,0 @@ -require 'action_view/helpers/form_options_helper' - -module ActionView - module Helpers - module FormCountryHelper - - # Return select and option tags for the given object and method, using country_options_for_select to generate the list of option tags. - def country_select(object, method, priority_countries = nil, options = {}, html_options = {}) - InstanceTag.new(object, method, self, options.delete(:object)).to_country_select_tag(priority_countries, options, html_options) - end - - # Returns a string of option tags for pretty much any country in the world. Supply a country name as +selected+ to - # have it marked as the selected option tag. You can also supply an array of countries as +priority_countries+, so - # that they will be listed above the rest of the (long) list. - # - # NOTE: Only the option tags are returned, you have to wrap this call in a regular HTML select tag. - def country_options_for_select(selected = nil, priority_countries = nil) - country_options = "" - - if priority_countries - country_options += options_for_select(priority_countries, selected) - country_options += "<option value=\"\" disabled=\"disabled\">-------------</option>\n" - end - - return country_options + options_for_select(COUNTRIES, selected) - end - - private - - # All the countries included in the country_options output. - COUNTRIES = ["Afghanistan", "Aland Islands", "Albania", "Algeria", "American Samoa", "Andorra", "Angola", - "Anguilla", "Antarctica", "Antigua And Barbuda", "Argentina", "Armenia", "Aruba", "Australia", "Austria", - "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", - "Bermuda", "Bhutan", "Bolivia", "Bosnia and Herzegowina", "Botswana", "Bouvet Island", "Brazil", - "British Indian Ocean Territory", "Brunei Darussalam", "Bulgaria", "Burkina Faso", "Burundi", "Cambodia", - "Cameroon", "Canada", "Cape Verde", "Cayman Islands", "Central African Republic", "Chad", "Chile", "China", - "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo", - "Congo, the Democratic Republic of the", "Cook Islands", "Costa Rica", "Cote d'Ivoire", "Croatia", "Cuba", - "Cyprus", "Czech Republic", "Denmark", "Djibouti", "Dominica", "Dominican Republic", "Ecuador", "Egypt", - "El Salvador", "Equatorial Guinea", "Eritrea", "Estonia", "Ethiopia", "Falkland Islands (Malvinas)", - "Faroe Islands", "Fiji", "Finland", "France", "French Guiana", "French Polynesia", - "French Southern Territories", "Gabon", "Gambia", "Georgia", "Germany", "Ghana", "Gibraltar", "Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guernsey", "Guinea", - "Guinea-Bissau", "Guyana", "Haiti", "Heard and McDonald Islands", "Holy See (Vatican City State)", - "Honduras", "Hong Kong", "Hungary", "Iceland", "India", "Indonesia", "Iran, Islamic Republic of", "Iraq", - "Ireland", "Isle of Man", "Israel", "Italy", "Jamaica", "Japan", "Jersey", "Jordan", "Kazakhstan", "Kenya", - "Kiribati", "Korea, Democratic People's Republic of", "Korea, Republic of", "Kuwait", "Kyrgyzstan", - "Lao People's Democratic Republic", "Latvia", "Lebanon", "Lesotho", "Liberia", "Libyan Arab Jamahiriya", - "Liechtenstein", "Lithuania", "Luxembourg", "Macao", "Macedonia, The Former Yugoslav Republic Of", - "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands", "Martinique", - "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia, Federated States of", "Moldova, Republic of", - "Monaco", "Mongolia", "Montenegro", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia", "Nauru", - "Nepal", "Netherlands", "Netherlands Antilles", "New Caledonia", "New Zealand", "Nicaragua", "Niger", - "Nigeria", "Niue", "Norfolk Island", "Northern Mariana Islands", "Norway", "Oman", "Pakistan", "Palau", - "Palestinian Territory, Occupied", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines", - "Pitcairn", "Poland", "Portugal", "Puerto Rico", "Qatar", "Reunion", "Romania", "Russian Federation", - "Rwanda", "Saint Barthelemy", "Saint Helena", "Saint Kitts and Nevis", "Saint Lucia", - "Saint Pierre and Miquelon", "Saint Vincent and the Grenadines", "Samoa", "San Marino", - "Sao Tome and Principe", "Saudi Arabia", "Senegal", "Serbia", "Seychelles", "Sierra Leone", "Singapore", - "Slovakia", "Slovenia", "Solomon Islands", "Somalia", "South Africa", - "South Georgia and the South Sandwich Islands", "Spain", "Sri Lanka", "Sudan", "Suriname", - "Svalbard and Jan Mayen", "Swaziland", "Sweden", "Switzerland", "Syrian Arab Republic", - "Taiwan, Province of China", "Tajikistan", "Tanzania, United Republic of", "Thailand", "Timor-Leste", - "Togo", "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey", "Turkmenistan", - "Turks and Caicos Islands", "Tuvalu", "Uganda", "Ukraine", "United Arab Emirates", "United Kingdom", - "United States", "United States Minor Outlying Islands", "Uruguay", "Uzbekistan", "Vanuatu", "Venezuela", - "Viet Nam", "Virgin Islands, British", "Virgin Islands, U.S.", "Wallis and Futuna", "Western Sahara", - "Yemen", "Zambia", "Zimbabwe"] unless const_defined?("COUNTRIES") - end - - class InstanceTag #:nodoc: - include FormCountryHelper - - def to_country_select_tag(priority_countries, options, html_options) - html_options = html_options.stringify_keys - add_default_name_and_id(html_options) - value = value(object) - content_tag("select", - add_options( - country_options_for_select(value, priority_countries), - options, value - ), html_options - ) - end - end - - class FormBuilder - def country_select(method, priority_countries = nil, options = {}, html_options = {}) - @template.country_select(@object_name, method, priority_countries, objectify_options(options), @default_options.merge(html_options)) - end - end - end -end
\ No newline at end of file diff --git a/actionpack/lib/action_view/helpers/form_options_helper.rb b/actionpack/lib/action_view/helpers/form_options_helper.rb index 9aae945408..33f8aaf9ed 100644 --- a/actionpack/lib/action_view/helpers/form_options_helper.rb +++ b/actionpack/lib/action_view/helpers/form_options_helper.rb @@ -324,9 +324,6 @@ module ActionView value == selected end end - - # All the countries included in the country_options output. - COUNTRIES = ActiveSupport::Deprecation::DeprecatedConstantProxy.new 'COUNTRIES', 'ActionView::Helpers::FormCountryHelper::COUNTRIES' end class InstanceTag #:nodoc: diff --git a/actionpack/lib/action_view/helpers/text_helper.rb b/actionpack/lib/action_view/helpers/text_helper.rb index ab1fdc80bc..3af7440400 100644 --- a/actionpack/lib/action_view/helpers/text_helper.rb +++ b/actionpack/lib/action_view/helpers/text_helper.rb @@ -42,65 +42,46 @@ module ActionView output_buffer << string end - if RUBY_VERSION < '1.9' - # Truncates a given +text+ after a given <tt>:length</tt> if +text+ is longer than <tt>:length</tt> - # (defaults to 30). The last characters will be replaced with the <tt>:omission</tt> (defaults to "..."). - # - # ==== Examples - # - # truncate("Once upon a time in a world far far away") - # # => Once upon a time in a world f... - # - # truncate("Once upon a time in a world far far away", :length => 14) - # # => Once upon a... - # - # truncate("And they found that many people were sleeping better.", :length => 25, "(clipped)") - # # => And they found that many (clipped) - # - # truncate("And they found that many people were sleeping better.", :omission => "... (continued)", :length => 15) - # # => And they found... (continued) - # - # You can still use <tt>truncate</tt> with the old API that accepts the - # +length+ as its optional second and the +ellipsis+ as its - # optional third parameter: - # truncate("Once upon a time in a world far far away", 14) - # # => Once upon a time in a world f... - # - # truncate("And they found that many people were sleeping better.", 15, "... (continued)") - # # => And they found... (continued) - def truncate(text, *args) - options = args.extract_options! - unless args.empty? - ActiveSupport::Deprecation.warn('truncate takes an option hash instead of separate ' + - 'length and omission arguments', caller) - - options[:length] = args[0] || 30 - options[:omission] = args[1] || "..." - end - options.reverse_merge!(:length => 30, :omission => "...") + # Truncates a given +text+ after a given <tt>:length</tt> if +text+ is longer than <tt>:length</tt> + # (defaults to 30). The last characters will be replaced with the <tt>:omission</tt> (defaults to "..."). + # + # ==== Examples + # + # truncate("Once upon a time in a world far far away") + # # => Once upon a time in a world f... + # + # truncate("Once upon a time in a world far far away", :length => 14) + # # => Once upon a... + # + # truncate("And they found that many people were sleeping better.", :length => 25, "(clipped)") + # # => And they found that many (clipped) + # + # truncate("And they found that many people were sleeping better.", :omission => "... (continued)", :length => 15) + # # => And they found... (continued) + # + # You can still use <tt>truncate</tt> with the old API that accepts the + # +length+ as its optional second and the +ellipsis+ as its + # optional third parameter: + # truncate("Once upon a time in a world far far away", 14) + # # => Once upon a time in a world f... + # + # truncate("And they found that many people were sleeping better.", 15, "... (continued)") + # # => And they found... (continued) + def truncate(text, *args) + options = args.extract_options! + unless args.empty? + ActiveSupport::Deprecation.warn('truncate takes an option hash instead of separate ' + + 'length and omission arguments', caller) - if text - l = options[:length] - options[:omission].chars.length - chars = text.chars - (chars.length > options[:length] ? chars[0...l] + options[:omission] : text).to_s - end + options[:length] = args[0] || 30 + options[:omission] = args[1] || "..." end - else - def truncate(text, *args) #:nodoc: - options = args.extract_options! - unless args.empty? - ActiveSupport::Deprecation.warn('truncate takes an option hash instead of separate ' + - 'length and omission arguments', caller) - - options[:length] = args[0] || 30 - options[:omission] = args[1] || "..." - end - options.reverse_merge!(:length => 30, :omission => "...") + options.reverse_merge!(:length => 30, :omission => "...") - if text - l = options[:length].to_i - options[:omission].length - (text.length > options[:length].to_i ? text[0...l] + options[:omission] : text).to_s - end + if text + l = options[:length] - options[:omission].mb_chars.length + chars = text.mb_chars + (chars.length > options[:length] ? chars[0...l] + options[:omission] : text).to_s end end @@ -140,81 +121,54 @@ module ActionView end end - if RUBY_VERSION < '1.9' - # Extracts an excerpt from +text+ that matches the first instance of +phrase+. - # The <tt>:radius</tt> option expands the excerpt on each side of the first occurrence of +phrase+ by the number of characters - # defined in <tt>:radius</tt> (which defaults to 100). If the excerpt radius overflows the beginning or end of the +text+, - # then the <tt>:omission</tt> option (which defaults to "...") will be prepended/appended accordingly. The resulting string - # will be stripped in any case. If the +phrase+ isn't found, nil is returned. - # - # ==== Examples - # excerpt('This is an example', 'an', :radius => 5) - # # => ...s is an exam... - # - # excerpt('This is an example', 'is', :radius => 5) - # # => This is a... - # - # excerpt('This is an example', 'is') - # # => This is an example - # - # excerpt('This next thing is an example', 'ex', :radius => 2) - # # => ...next... - # - # excerpt('This is also an example', 'an', :radius => 8, :omission => '<chop> ') - # # => <chop> is also an example - # - # You can still use <tt>excerpt</tt> with the old API that accepts the - # +radius+ as its optional third and the +ellipsis+ as its - # optional forth parameter: - # excerpt('This is an example', 'an', 5) # => ...s is an exam... - # excerpt('This is also an example', 'an', 8, '<chop> ') # => <chop> is also an example - def excerpt(text, phrase, *args) - options = args.extract_options! - unless args.empty? - options[:radius] = args[0] || 100 - options[:omission] = args[1] || "..." - end - options.reverse_merge!(:radius => 100, :omission => "...") - - if text && phrase - phrase = Regexp.escape(phrase) - - if found_pos = text.chars =~ /(#{phrase})/i - start_pos = [ found_pos - options[:radius], 0 ].max - end_pos = [ [ found_pos + phrase.chars.length + options[:radius] - 1, 0].max, text.chars.length ].min - - prefix = start_pos > 0 ? options[:omission] : "" - postfix = end_pos < text.chars.length - 1 ? options[:omission] : "" - - prefix + text.chars[start_pos..end_pos].strip + postfix - else - nil - end - end + # Extracts an excerpt from +text+ that matches the first instance of +phrase+. + # The <tt>:radius</tt> option expands the excerpt on each side of the first occurrence of +phrase+ by the number of characters + # defined in <tt>:radius</tt> (which defaults to 100). If the excerpt radius overflows the beginning or end of the +text+, + # then the <tt>:omission</tt> option (which defaults to "...") will be prepended/appended accordingly. The resulting string + # will be stripped in any case. If the +phrase+ isn't found, nil is returned. + # + # ==== Examples + # excerpt('This is an example', 'an', :radius => 5) + # # => ...s is an exam... + # + # excerpt('This is an example', 'is', :radius => 5) + # # => This is a... + # + # excerpt('This is an example', 'is') + # # => This is an example + # + # excerpt('This next thing is an example', 'ex', :radius => 2) + # # => ...next... + # + # excerpt('This is also an example', 'an', :radius => 8, :omission => '<chop> ') + # # => <chop> is also an example + # + # You can still use <tt>excerpt</tt> with the old API that accepts the + # +radius+ as its optional third and the +ellipsis+ as its + # optional forth parameter: + # excerpt('This is an example', 'an', 5) # => ...s is an exam... + # excerpt('This is also an example', 'an', 8, '<chop> ') # => <chop> is also an example + def excerpt(text, phrase, *args) + options = args.extract_options! + unless args.empty? + options[:radius] = args[0] || 100 + options[:omission] = args[1] || "..." end - else - def excerpt(text, phrase, *args) #:nodoc: - options = args.extract_options! - unless args.empty? - options[:radius] = args[0] || 100 - options[:omission] = args[1] || "..." - end - options.reverse_merge!(:radius => 100, :omission => "...") + options.reverse_merge!(:radius => 100, :omission => "...") - if text && phrase - phrase = Regexp.escape(phrase) + if text && phrase + phrase = Regexp.escape(phrase) - if found_pos = text =~ /(#{phrase})/i - start_pos = [ found_pos - options[:radius], 0 ].max - end_pos = [ [ found_pos + phrase.length + options[:radius] - 1, 0].max, text.length ].min + if found_pos = text.mb_chars =~ /(#{phrase})/i + start_pos = [ found_pos - options[:radius], 0 ].max + end_pos = [ [ found_pos + phrase.mb_chars.length + options[:radius] - 1, 0].max, text.mb_chars.length ].min - prefix = start_pos > 0 ? options[:omission] : "" - postfix = end_pos < text.length - 1 ? options[:omission] : "" + prefix = start_pos > 0 ? options[:omission] : "" + postfix = end_pos < text.mb_chars.length - 1 ? options[:omission] : "" - prefix + text[start_pos..end_pos].strip + postfix - else - nil - end + prefix + text.mb_chars[start_pos..end_pos].strip + postfix + else + nil end end end diff --git a/actionpack/lib/action_view/template.rb b/actionpack/lib/action_view/template.rb index 64597b3d39..12808581a3 100644 --- a/actionpack/lib/action_view/template.rb +++ b/actionpack/lib/action_view/template.rb @@ -52,15 +52,20 @@ module ActionView #:nodoc: end memoize :path_without_format_and_extension + def relative_path + path = File.expand_path(filename) + path.sub!(/^#{Regexp.escape(File.expand_path(RAILS_ROOT))}\//, '') if defined?(RAILS_ROOT) + path + end + memoize :relative_path + def source File.read(filename) end memoize :source def method_segment - segment = File.expand_path(filename) - segment.sub!(/^#{Regexp.escape(File.expand_path(RAILS_ROOT))}/, '') if defined?(RAILS_ROOT) - segment.gsub!(/([^a-zA-Z0-9_])/) { $1.ord } + relative_path.to_s.gsub(/([^a-zA-Z0-9_])/) { $1.ord } end memoize :method_segment @@ -69,7 +74,7 @@ module ActionView #:nodoc: rescue Exception => e raise e unless filename if TemplateError === e - e.sub_template_of(filename) + e.sub_template_of(self) raise e else raise TemplateError.new(self, view.assigns, e) diff --git a/actionpack/lib/action_view/template_error.rb b/actionpack/lib/action_view/template_error.rb index 2368662f31..bcce331773 100644 --- a/actionpack/lib/action_view/template_error.rb +++ b/actionpack/lib/action_view/template_error.rb @@ -7,12 +7,14 @@ module ActionView attr_reader :original_exception def initialize(template, assigns, original_exception) - @base_path = template.base_path.to_s - @assigns, @source, @original_exception = assigns.dup, template.source, original_exception - @file_path = template.filename + @template, @assigns, @original_exception = template, assigns.dup, original_exception @backtrace = compute_backtrace end + def file_name + @template.relative_path + end + def message ActiveSupport::Deprecation.silence { original_exception.message } end @@ -24,7 +26,7 @@ module ActionView def sub_template_message if @sub_templates "Trace of template inclusion: " + - @sub_templates.collect { |template| strip_base_path(template) }.join(", ") + @sub_templates.collect { |template| template.relative_path }.join(", ") else "" end @@ -34,18 +36,18 @@ module ActionView return unless num = line_number num = num.to_i - source_code = IO.readlines(@file_path) + source_code = @template.source.split("\n") start_on_line = [ num - SOURCE_CODE_RADIUS - 1, 0 ].max end_on_line = [ num + SOURCE_CODE_RADIUS - 1, source_code.length].min indent = ' ' * indentation line_counter = start_on_line - return unless source_code = source_code[start_on_line..end_on_line] - + return unless source_code = source_code[start_on_line..end_on_line] + source_code.sum do |line| line_counter += 1 - "#{indent}#{line_counter}: #{line}" + "#{indent}#{line_counter}: #{line}\n" end end @@ -63,12 +65,6 @@ module ActionView end end - def file_name - stripped = strip_base_path(@file_path) - stripped.slice!(0,1) if stripped[0] == ?/ - stripped - end - def to_s "\n\n#{self.class} (#{message}) #{source_location}:\n" + "#{source_extract}\n #{clean_backtrace.join("\n ")}\n\n" @@ -88,12 +84,6 @@ module ActionView ] end - def strip_base_path(path) - stripped_path = File.expand_path(path).gsub(@base_path, "") - stripped_path.gsub!(/^#{Regexp.escape File.expand_path(RAILS_ROOT)}/, '') if defined?(RAILS_ROOT) - stripped_path - end - def source_location if line_number "on line ##{line_number} of " diff --git a/actionpack/test/controller/session/cookie_store_test.rb b/actionpack/test/controller/session/cookie_store_test.rb index 5adaeaf5c5..010c00fa14 100644 --- a/actionpack/test/controller/session/cookie_store_test.rb +++ b/actionpack/test/controller/session/cookie_store_test.rb @@ -36,7 +36,9 @@ class CookieStoreTest < Test::Unit::TestCase 'session_key' => '_myapp_session', 'secret' => 'Keep it secret; keep it safe.', 'no_cookies' => true, - 'no_hidden' => true } + 'no_hidden' => true, + 'session_http_only' => true + } end def self.cookies @@ -149,6 +151,48 @@ class CookieStoreTest < Test::Unit::TestCase assert_equal 1, session.cgi.output_cookies.size cookie = session.cgi.output_cookies.first assert_cookie cookie, cookie_value(:flashed) + assert_http_only_cookie cookie + assert_secure_cookie cookie, false + end + end + + def test_writes_non_secure_cookie_by_default + set_cookie! cookie_value(:typical) + new_session do |session| + session['flash'] = {} + session.close + cookie = session.cgi.output_cookies.first + assert_secure_cookie cookie,false + end + end + + def test_writes_secure_cookie + set_cookie! cookie_value(:typical) + new_session('session_secure'=>true) do |session| + session['flash'] = {} + session.close + cookie = session.cgi.output_cookies.first + assert_secure_cookie cookie + end + end + + def test_http_only_cookie_by_default + set_cookie! cookie_value(:typical) + new_session do |session| + session['flash'] = {} + session.close + cookie = session.cgi.output_cookies.first + assert_http_only_cookie cookie + end + end + + def test_overides_http_only_cookie + set_cookie! cookie_value(:typical) + new_session('session_http_only'=>false) do |session| + session['flash'] = {} + session.close + cookie = session.cgi.output_cookies.first + assert_http_only_cookie cookie, false end end @@ -195,6 +239,13 @@ class CookieStoreTest < Test::Unit::TestCase assert_equal expires, cookie.expires ? cookie.expires.to_date : cookie.expires, message end + def assert_secure_cookie(cookie,value=true) + assert cookie.secure==value + end + + def assert_http_only_cookie(cookie,value=true) + assert cookie.http_only==value + end def cookies(*which) self.class.cookies.values_at(*which) diff --git a/actionpack/test/fixtures/test/sub_template_raise.html.erb b/actionpack/test/fixtures/test/sub_template_raise.html.erb new file mode 100644 index 0000000000..f38c0bda90 --- /dev/null +++ b/actionpack/test/fixtures/test/sub_template_raise.html.erb @@ -0,0 +1 @@ +<%= render :partial => "test/raise" %>
\ No newline at end of file diff --git a/actionpack/test/template/asset_tag_helper_test.rb b/actionpack/test/template/asset_tag_helper_test.rb index 7e40a55dc5..aaf9fe2ebf 100644 --- a/actionpack/test/template/asset_tag_helper_test.rb +++ b/actionpack/test/template/asset_tag_helper_test.rb @@ -38,7 +38,8 @@ class AssetTagHelperTest < ActionView::TestCase @controller.request = @request ActionView::Helpers::AssetTagHelper::reset_javascript_include_default - COMPUTED_PUBLIC_PATHS.clear + AssetTag::Cache.clear + AssetCollection::Cache.clear end def teardown @@ -155,12 +156,12 @@ class AssetTagHelperTest < ActionView::TestCase PathToJavascriptToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) } end - def test_javascript_include_tag + def test_javascript_include_tag_with_blank_asset_id ENV["RAILS_ASSET_ID"] = "" JavascriptIncludeToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) } + end - COMPUTED_PUBLIC_PATHS.clear - + def test_javascript_include_tag_with_given_asset_id ENV["RAILS_ASSET_ID"] = "1" assert_dom_equal(%(<script src="/javascripts/prototype.js?1" type="text/javascript"></script>\n<script src="/javascripts/effects.js?1" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js?1" type="text/javascript"></script>\n<script src="/javascripts/controls.js?1" type="text/javascript"></script>\n<script src="/javascripts/application.js?1" type="text/javascript"></script>), javascript_include_tag(:defaults)) end @@ -169,6 +170,11 @@ class AssetTagHelperTest < ActionView::TestCase ENV["RAILS_ASSET_ID"] = "" ActionView::Helpers::AssetTagHelper::register_javascript_include_default 'slider' assert_dom_equal %(<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/slider.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>), javascript_include_tag(:defaults) + end + + def test_register_javascript_include_default_mixed_defaults + ENV["RAILS_ASSET_ID"] = "" + ActionView::Helpers::AssetTagHelper::register_javascript_include_default 'slider' ActionView::Helpers::AssetTagHelper::register_javascript_include_default 'lib1', '/elsewhere/blub/lib2' assert_dom_equal %(<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/slider.js" type="text/javascript"></script>\n<script src="/javascripts/lib1.js" type="text/javascript"></script>\n<script src="/elsewhere/blub/lib2.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>), javascript_include_tag(:defaults) end @@ -386,6 +392,31 @@ class AssetTagHelperTest < ActionView::TestCase FileUtils.rm_f(File.join(ActionView::Helpers::AssetTagHelper::JAVASCRIPTS_DIR, 'combined.js')) end + def test_caching_javascript_include_tag_with_relative_url_root + ENV["RAILS_ASSET_ID"] = "" + ActionController::Base.relative_url_root = "/collaboration/hieraki" + ActionController::Base.perform_caching = true + + assert_dom_equal( + %(<script src="/collaboration/hieraki/javascripts/all.js" type="text/javascript"></script>), + javascript_include_tag(:all, :cache => true) + ) + + assert File.exist?(File.join(ActionView::Helpers::AssetTagHelper::JAVASCRIPTS_DIR, 'all.js')) + + assert_dom_equal( + %(<script src="/collaboration/hieraki/javascripts/money.js" type="text/javascript"></script>), + javascript_include_tag(:all, :cache => "money") + ) + + assert File.exist?(File.join(ActionView::Helpers::AssetTagHelper::JAVASCRIPTS_DIR, 'money.js')) + + ensure + ActionController::Base.relative_url_root = nil + FileUtils.rm_f(File.join(ActionView::Helpers::AssetTagHelper::JAVASCRIPTS_DIR, 'all.js')) + FileUtils.rm_f(File.join(ActionView::Helpers::AssetTagHelper::JAVASCRIPTS_DIR, 'money.js')) + end + def test_caching_javascript_include_tag_when_caching_off ENV["RAILS_ASSET_ID"] = "" ActionController::Base.perform_caching = false @@ -456,6 +487,31 @@ class AssetTagHelperTest < ActionView::TestCase FileUtils.rm_f(File.join(ActionView::Helpers::AssetTagHelper::STYLESHEETS_DIR, 'styles.css')) end + def test_caching_stylesheet_link_tag_with_relative_url_root + ENV["RAILS_ASSET_ID"] = "" + ActionController::Base.relative_url_root = "/collaboration/hieraki" + ActionController::Base.perform_caching = true + + assert_dom_equal( + %(<link href="/collaboration/hieraki/stylesheets/all.css" media="screen" rel="stylesheet" type="text/css" />), + stylesheet_link_tag(:all, :cache => true) + ) + + expected = Dir["#{ActionView::Helpers::AssetTagHelper::STYLESHEETS_DIR}/*.css"].map { |p| File.mtime(p) }.max + assert_equal expected, File.mtime(File.join(ActionView::Helpers::AssetTagHelper::STYLESHEETS_DIR, 'all.css')) + + assert_dom_equal( + %(<link href="/collaboration/hieraki/stylesheets/money.css" media="screen" rel="stylesheet" type="text/css" />), + stylesheet_link_tag(:all, :cache => "money") + ) + + assert File.exist?(File.join(ActionView::Helpers::AssetTagHelper::STYLESHEETS_DIR, 'money.css')) + ensure + ActionController::Base.relative_url_root = nil + FileUtils.rm_f(File.join(ActionView::Helpers::AssetTagHelper::STYLESHEETS_DIR, 'all.css')) + FileUtils.rm_f(File.join(ActionView::Helpers::AssetTagHelper::STYLESHEETS_DIR, 'money.css')) + end + def test_caching_stylesheet_include_tag_when_caching_off ENV["RAILS_ASSET_ID"] = "" ActionController::Base.perform_caching = false diff --git a/actionpack/test/template/form_country_helper_test.rb b/actionpack/test/template/form_country_helper_test.rb deleted file mode 100644 index 8862e08222..0000000000 --- a/actionpack/test/template/form_country_helper_test.rb +++ /dev/null @@ -1,1549 +0,0 @@ -require 'abstract_unit' - -class FormCountryHelperTest < ActionView::TestCase - tests ActionView::Helpers::FormCountryHelper - - silence_warnings do - Post = Struct.new('Post', :title, :author_name, :body, :secret, :written_on, :category, :origin) - end - - def test_country_select - @post = Post.new - @post.origin = "Denmark" - expected_select = <<-COUNTRIES -<select id="post_origin" name="post[origin]"><option value="Afghanistan">Afghanistan</option> -<option value="Aland Islands">Aland Islands</option> -<option value="Albania">Albania</option> -<option value="Algeria">Algeria</option> -<option value="American Samoa">American Samoa</option> -<option value="Andorra">Andorra</option> -<option value="Angola">Angola</option> -<option value="Anguilla">Anguilla</option> -<option value="Antarctica">Antarctica</option> -<option value="Antigua And Barbuda">Antigua And Barbuda</option> -<option value="Argentina">Argentina</option> -<option value="Armenia">Armenia</option> -<option value="Aruba">Aruba</option> -<option value="Australia">Australia</option> -<option value="Austria">Austria</option> -<option value="Azerbaijan">Azerbaijan</option> -<option value="Bahamas">Bahamas</option> -<option value="Bahrain">Bahrain</option> -<option value="Bangladesh">Bangladesh</option> -<option value="Barbados">Barbados</option> -<option value="Belarus">Belarus</option> -<option value="Belgium">Belgium</option> -<option value="Belize">Belize</option> -<option value="Benin">Benin</option> -<option value="Bermuda">Bermuda</option> -<option value="Bhutan">Bhutan</option> -<option value="Bolivia">Bolivia</option> -<option value="Bosnia and Herzegowina">Bosnia and Herzegowina</option> -<option value="Botswana">Botswana</option> -<option value="Bouvet Island">Bouvet Island</option> -<option value="Brazil">Brazil</option> -<option value="British Indian Ocean Territory">British Indian Ocean Territory</option> -<option value="Brunei Darussalam">Brunei Darussalam</option> -<option value="Bulgaria">Bulgaria</option> -<option value="Burkina Faso">Burkina Faso</option> -<option value="Burundi">Burundi</option> -<option value="Cambodia">Cambodia</option> -<option value="Cameroon">Cameroon</option> -<option value="Canada">Canada</option> -<option value="Cape Verde">Cape Verde</option> -<option value="Cayman Islands">Cayman Islands</option> -<option value="Central African Republic">Central African Republic</option> -<option value="Chad">Chad</option> -<option value="Chile">Chile</option> -<option value="China">China</option> -<option value="Christmas Island">Christmas Island</option> -<option value="Cocos (Keeling) Islands">Cocos (Keeling) Islands</option> -<option value="Colombia">Colombia</option> -<option value="Comoros">Comoros</option> -<option value="Congo">Congo</option> -<option value="Congo, the Democratic Republic of the">Congo, the Democratic Republic of the</option> -<option value="Cook Islands">Cook Islands</option> -<option value="Costa Rica">Costa Rica</option> -<option value="Cote d'Ivoire">Cote d'Ivoire</option> -<option value="Croatia">Croatia</option> -<option value="Cuba">Cuba</option> -<option value="Cyprus">Cyprus</option> -<option value="Czech Republic">Czech Republic</option> -<option selected="selected" value="Denmark">Denmark</option> -<option value="Djibouti">Djibouti</option> -<option value="Dominica">Dominica</option> -<option value="Dominican Republic">Dominican Republic</option> -<option value="Ecuador">Ecuador</option> -<option value="Egypt">Egypt</option> -<option value="El Salvador">El Salvador</option> -<option value="Equatorial Guinea">Equatorial Guinea</option> -<option value="Eritrea">Eritrea</option> -<option value="Estonia">Estonia</option> -<option value="Ethiopia">Ethiopia</option> -<option value="Falkland Islands (Malvinas)">Falkland Islands (Malvinas)</option> -<option value="Faroe Islands">Faroe Islands</option> -<option value="Fiji">Fiji</option> -<option value="Finland">Finland</option> -<option value="France">France</option> -<option value="French Guiana">French Guiana</option> -<option value="French Polynesia">French Polynesia</option> -<option value="French Southern Territories">French Southern Territories</option> -<option value="Gabon">Gabon</option> -<option value="Gambia">Gambia</option> -<option value="Georgia">Georgia</option> -<option value="Germany">Germany</option> -<option value="Ghana">Ghana</option> -<option value="Gibraltar">Gibraltar</option> -<option value="Greece">Greece</option> -<option value="Greenland">Greenland</option> -<option value="Grenada">Grenada</option> -<option value="Guadeloupe">Guadeloupe</option> -<option value="Guam">Guam</option> -<option value="Guatemala">Guatemala</option> -<option value="Guernsey">Guernsey</option> -<option value="Guinea">Guinea</option> -<option value="Guinea-Bissau">Guinea-Bissau</option> -<option value="Guyana">Guyana</option> -<option value="Haiti">Haiti</option> -<option value="Heard and McDonald Islands">Heard and McDonald Islands</option> -<option value="Holy See (Vatican City State)">Holy See (Vatican City State)</option> -<option value="Honduras">Honduras</option> -<option value="Hong Kong">Hong Kong</option> -<option value="Hungary">Hungary</option> -<option value="Iceland">Iceland</option> -<option value="India">India</option> -<option value="Indonesia">Indonesia</option> -<option value="Iran, Islamic Republic of">Iran, Islamic Republic of</option> -<option value="Iraq">Iraq</option> -<option value="Ireland">Ireland</option> -<option value="Isle of Man">Isle of Man</option> -<option value="Israel">Israel</option> -<option value="Italy">Italy</option> -<option value="Jamaica">Jamaica</option> -<option value="Japan">Japan</option> -<option value="Jersey">Jersey</option> -<option value="Jordan">Jordan</option> -<option value="Kazakhstan">Kazakhstan</option> -<option value="Kenya">Kenya</option> -<option value="Kiribati">Kiribati</option> -<option value="Korea, Democratic People's Republic of">Korea, Democratic People's Republic of</option> -<option value="Korea, Republic of">Korea, Republic of</option> -<option value="Kuwait">Kuwait</option> -<option value="Kyrgyzstan">Kyrgyzstan</option> -<option value="Lao People's Democratic Republic">Lao People's Democratic Republic</option> -<option value="Latvia">Latvia</option> -<option value="Lebanon">Lebanon</option> -<option value="Lesotho">Lesotho</option> -<option value="Liberia">Liberia</option> -<option value="Libyan Arab Jamahiriya">Libyan Arab Jamahiriya</option> -<option value="Liechtenstein">Liechtenstein</option> -<option value="Lithuania">Lithuania</option> -<option value="Luxembourg">Luxembourg</option> -<option value="Macao">Macao</option> -<option value="Macedonia, The Former Yugoslav Republic Of">Macedonia, The Former Yugoslav Republic Of</option> -<option value="Madagascar">Madagascar</option> -<option value="Malawi">Malawi</option> -<option value="Malaysia">Malaysia</option> -<option value="Maldives">Maldives</option> -<option value="Mali">Mali</option> -<option value="Malta">Malta</option> -<option value="Marshall Islands">Marshall Islands</option> -<option value="Martinique">Martinique</option> -<option value="Mauritania">Mauritania</option> -<option value="Mauritius">Mauritius</option> -<option value="Mayotte">Mayotte</option> -<option value="Mexico">Mexico</option> -<option value="Micronesia, Federated States of">Micronesia, Federated States of</option> -<option value="Moldova, Republic of">Moldova, Republic of</option> -<option value="Monaco">Monaco</option> -<option value="Mongolia">Mongolia</option> -<option value="Montenegro">Montenegro</option> -<option value="Montserrat">Montserrat</option> -<option value="Morocco">Morocco</option> -<option value="Mozambique">Mozambique</option> -<option value="Myanmar">Myanmar</option> -<option value="Namibia">Namibia</option> -<option value="Nauru">Nauru</option> -<option value="Nepal">Nepal</option> -<option value="Netherlands">Netherlands</option> -<option value="Netherlands Antilles">Netherlands Antilles</option> -<option value="New Caledonia">New Caledonia</option> -<option value="New Zealand">New Zealand</option> -<option value="Nicaragua">Nicaragua</option> -<option value="Niger">Niger</option> -<option value="Nigeria">Nigeria</option> -<option value="Niue">Niue</option> -<option value="Norfolk Island">Norfolk Island</option> -<option value="Northern Mariana Islands">Northern Mariana Islands</option> -<option value="Norway">Norway</option> -<option value="Oman">Oman</option> -<option value="Pakistan">Pakistan</option> -<option value="Palau">Palau</option> -<option value="Palestinian Territory, Occupied">Palestinian Territory, Occupied</option> -<option value="Panama">Panama</option> -<option value="Papua New Guinea">Papua New Guinea</option> -<option value="Paraguay">Paraguay</option> -<option value="Peru">Peru</option> -<option value="Philippines">Philippines</option> -<option value="Pitcairn">Pitcairn</option> -<option value="Poland">Poland</option> -<option value="Portugal">Portugal</option> -<option value="Puerto Rico">Puerto Rico</option> -<option value="Qatar">Qatar</option> -<option value="Reunion">Reunion</option> -<option value="Romania">Romania</option> -<option value="Russian Federation">Russian Federation</option> -<option value="Rwanda">Rwanda</option> -<option value="Saint Barthelemy">Saint Barthelemy</option> -<option value="Saint Helena">Saint Helena</option> -<option value="Saint Kitts and Nevis">Saint Kitts and Nevis</option> -<option value="Saint Lucia">Saint Lucia</option> -<option value="Saint Pierre and Miquelon">Saint Pierre and Miquelon</option> -<option value="Saint Vincent and the Grenadines">Saint Vincent and the Grenadines</option> -<option value="Samoa">Samoa</option> -<option value="San Marino">San Marino</option> -<option value="Sao Tome and Principe">Sao Tome and Principe</option> -<option value="Saudi Arabia">Saudi Arabia</option> -<option value="Senegal">Senegal</option> -<option value="Serbia">Serbia</option> -<option value="Seychelles">Seychelles</option> -<option value="Sierra Leone">Sierra Leone</option> -<option value="Singapore">Singapore</option> -<option value="Slovakia">Slovakia</option> -<option value="Slovenia">Slovenia</option> -<option value="Solomon Islands">Solomon Islands</option> -<option value="Somalia">Somalia</option> -<option value="South Africa">South Africa</option> -<option value="South Georgia and the South Sandwich Islands">South Georgia and the South Sandwich Islands</option> -<option value="Spain">Spain</option> -<option value="Sri Lanka">Sri Lanka</option> -<option value="Sudan">Sudan</option> -<option value="Suriname">Suriname</option> -<option value="Svalbard and Jan Mayen">Svalbard and Jan Mayen</option> -<option value="Swaziland">Swaziland</option> -<option value="Sweden">Sweden</option> -<option value="Switzerland">Switzerland</option> -<option value="Syrian Arab Republic">Syrian Arab Republic</option> -<option value="Taiwan, Province of China">Taiwan, Province of China</option> -<option value="Tajikistan">Tajikistan</option> -<option value="Tanzania, United Republic of">Tanzania, United Republic of</option> -<option value="Thailand">Thailand</option> -<option value="Timor-Leste">Timor-Leste</option> -<option value="Togo">Togo</option> -<option value="Tokelau">Tokelau</option> -<option value="Tonga">Tonga</option> -<option value="Trinidad and Tobago">Trinidad and Tobago</option> -<option value="Tunisia">Tunisia</option> -<option value="Turkey">Turkey</option> -<option value="Turkmenistan">Turkmenistan</option> -<option value="Turks and Caicos Islands">Turks and Caicos Islands</option> -<option value="Tuvalu">Tuvalu</option> -<option value="Uganda">Uganda</option> -<option value="Ukraine">Ukraine</option> -<option value="United Arab Emirates">United Arab Emirates</option> -<option value="United Kingdom">United Kingdom</option> -<option value="United States">United States</option> -<option value="United States Minor Outlying Islands">United States Minor Outlying Islands</option> -<option value="Uruguay">Uruguay</option> -<option value="Uzbekistan">Uzbekistan</option> -<option value="Vanuatu">Vanuatu</option> -<option value="Venezuela">Venezuela</option> -<option value="Viet Nam">Viet Nam</option> -<option value="Virgin Islands, British">Virgin Islands, British</option> -<option value="Virgin Islands, U.S.">Virgin Islands, U.S.</option> -<option value="Wallis and Futuna">Wallis and Futuna</option> -<option value="Western Sahara">Western Sahara</option> -<option value="Yemen">Yemen</option> -<option value="Zambia">Zambia</option> -<option value="Zimbabwe">Zimbabwe</option></select> -COUNTRIES - assert_dom_equal(expected_select[0..-2], country_select("post", "origin")) - end - - def test_country_select_with_priority_countries - @post = Post.new - @post.origin = "Denmark" - expected_select = <<-COUNTRIES -<select id="post_origin" name="post[origin]"><option value="New Zealand">New Zealand</option> -<option value="Nicaragua">Nicaragua</option><option value="" disabled="disabled">-------------</option> -<option value="Afghanistan">Afghanistan</option> -<option value="Aland Islands">Aland Islands</option> -<option value="Albania">Albania</option> -<option value="Algeria">Algeria</option> -<option value="American Samoa">American Samoa</option> -<option value="Andorra">Andorra</option> -<option value="Angola">Angola</option> -<option value="Anguilla">Anguilla</option> -<option value="Antarctica">Antarctica</option> -<option value="Antigua And Barbuda">Antigua And Barbuda</option> -<option value="Argentina">Argentina</option> -<option value="Armenia">Armenia</option> -<option value="Aruba">Aruba</option> -<option value="Australia">Australia</option> -<option value="Austria">Austria</option> -<option value="Azerbaijan">Azerbaijan</option> -<option value="Bahamas">Bahamas</option> -<option value="Bahrain">Bahrain</option> -<option value="Bangladesh">Bangladesh</option> -<option value="Barbados">Barbados</option> -<option value="Belarus">Belarus</option> -<option value="Belgium">Belgium</option> -<option value="Belize">Belize</option> -<option value="Benin">Benin</option> -<option value="Bermuda">Bermuda</option> -<option value="Bhutan">Bhutan</option> -<option value="Bolivia">Bolivia</option> -<option value="Bosnia and Herzegowina">Bosnia and Herzegowina</option> -<option value="Botswana">Botswana</option> -<option value="Bouvet Island">Bouvet Island</option> -<option value="Brazil">Brazil</option> -<option value="British Indian Ocean Territory">British Indian Ocean Territory</option> -<option value="Brunei Darussalam">Brunei Darussalam</option> -<option value="Bulgaria">Bulgaria</option> -<option value="Burkina Faso">Burkina Faso</option> -<option value="Burundi">Burundi</option> -<option value="Cambodia">Cambodia</option> -<option value="Cameroon">Cameroon</option> -<option value="Canada">Canada</option> -<option value="Cape Verde">Cape Verde</option> -<option value="Cayman Islands">Cayman Islands</option> -<option value="Central African Republic">Central African Republic</option> -<option value="Chad">Chad</option> -<option value="Chile">Chile</option> -<option value="China">China</option> -<option value="Christmas Island">Christmas Island</option> -<option value="Cocos (Keeling) Islands">Cocos (Keeling) Islands</option> -<option value="Colombia">Colombia</option> -<option value="Comoros">Comoros</option> -<option value="Congo">Congo</option> -<option value="Congo, the Democratic Republic of the">Congo, the Democratic Republic of the</option> -<option value="Cook Islands">Cook Islands</option> -<option value="Costa Rica">Costa Rica</option> -<option value="Cote d'Ivoire">Cote d'Ivoire</option> -<option value="Croatia">Croatia</option> -<option value="Cuba">Cuba</option> -<option value="Cyprus">Cyprus</option> -<option value="Czech Republic">Czech Republic</option> -<option selected="selected" value="Denmark">Denmark</option> -<option value="Djibouti">Djibouti</option> -<option value="Dominica">Dominica</option> -<option value="Dominican Republic">Dominican Republic</option> -<option value="Ecuador">Ecuador</option> -<option value="Egypt">Egypt</option> -<option value="El Salvador">El Salvador</option> -<option value="Equatorial Guinea">Equatorial Guinea</option> -<option value="Eritrea">Eritrea</option> -<option value="Estonia">Estonia</option> -<option value="Ethiopia">Ethiopia</option> -<option value="Falkland Islands (Malvinas)">Falkland Islands (Malvinas)</option> -<option value="Faroe Islands">Faroe Islands</option> -<option value="Fiji">Fiji</option> -<option value="Finland">Finland</option> -<option value="France">France</option> -<option value="French Guiana">French Guiana</option> -<option value="French Polynesia">French Polynesia</option> -<option value="French Southern Territories">French Southern Territories</option> -<option value="Gabon">Gabon</option> -<option value="Gambia">Gambia</option> -<option value="Georgia">Georgia</option> -<option value="Germany">Germany</option> -<option value="Ghana">Ghana</option> -<option value="Gibraltar">Gibraltar</option> -<option value="Greece">Greece</option> -<option value="Greenland">Greenland</option> -<option value="Grenada">Grenada</option> -<option value="Guadeloupe">Guadeloupe</option> -<option value="Guam">Guam</option> -<option value="Guatemala">Guatemala</option> -<option value="Guernsey">Guernsey</option> -<option value="Guinea">Guinea</option> -<option value="Guinea-Bissau">Guinea-Bissau</option> -<option value="Guyana">Guyana</option> -<option value="Haiti">Haiti</option> -<option value="Heard and McDonald Islands">Heard and McDonald Islands</option> -<option value="Holy See (Vatican City State)">Holy See (Vatican City State)</option> -<option value="Honduras">Honduras</option> -<option value="Hong Kong">Hong Kong</option> -<option value="Hungary">Hungary</option> -<option value="Iceland">Iceland</option> -<option value="India">India</option> -<option value="Indonesia">Indonesia</option> -<option value="Iran, Islamic Republic of">Iran, Islamic Republic of</option> -<option value="Iraq">Iraq</option> -<option value="Ireland">Ireland</option> -<option value="Isle of Man">Isle of Man</option> -<option value="Israel">Israel</option> -<option value="Italy">Italy</option> -<option value="Jamaica">Jamaica</option> -<option value="Japan">Japan</option> -<option value="Jersey">Jersey</option> -<option value="Jordan">Jordan</option> -<option value="Kazakhstan">Kazakhstan</option> -<option value="Kenya">Kenya</option> -<option value="Kiribati">Kiribati</option> -<option value="Korea, Democratic People's Republic of">Korea, Democratic People's Republic of</option> -<option value="Korea, Republic of">Korea, Republic of</option> -<option value="Kuwait">Kuwait</option> -<option value="Kyrgyzstan">Kyrgyzstan</option> -<option value="Lao People's Democratic Republic">Lao People's Democratic Republic</option> -<option value="Latvia">Latvia</option> -<option value="Lebanon">Lebanon</option> -<option value="Lesotho">Lesotho</option> -<option value="Liberia">Liberia</option> -<option value="Libyan Arab Jamahiriya">Libyan Arab Jamahiriya</option> -<option value="Liechtenstein">Liechtenstein</option> -<option value="Lithuania">Lithuania</option> -<option value="Luxembourg">Luxembourg</option> -<option value="Macao">Macao</option> -<option value="Macedonia, The Former Yugoslav Republic Of">Macedonia, The Former Yugoslav Republic Of</option> -<option value="Madagascar">Madagascar</option> -<option value="Malawi">Malawi</option> -<option value="Malaysia">Malaysia</option> -<option value="Maldives">Maldives</option> -<option value="Mali">Mali</option> -<option value="Malta">Malta</option> -<option value="Marshall Islands">Marshall Islands</option> -<option value="Martinique">Martinique</option> -<option value="Mauritania">Mauritania</option> -<option value="Mauritius">Mauritius</option> -<option value="Mayotte">Mayotte</option> -<option value="Mexico">Mexico</option> -<option value="Micronesia, Federated States of">Micronesia, Federated States of</option> -<option value="Moldova, Republic of">Moldova, Republic of</option> -<option value="Monaco">Monaco</option> -<option value="Mongolia">Mongolia</option> -<option value="Montenegro">Montenegro</option> -<option value="Montserrat">Montserrat</option> -<option value="Morocco">Morocco</option> -<option value="Mozambique">Mozambique</option> -<option value="Myanmar">Myanmar</option> -<option value="Namibia">Namibia</option> -<option value="Nauru">Nauru</option> -<option value="Nepal">Nepal</option> -<option value="Netherlands">Netherlands</option> -<option value="Netherlands Antilles">Netherlands Antilles</option> -<option value="New Caledonia">New Caledonia</option> -<option value="New Zealand">New Zealand</option> -<option value="Nicaragua">Nicaragua</option> -<option value="Niger">Niger</option> -<option value="Nigeria">Nigeria</option> -<option value="Niue">Niue</option> -<option value="Norfolk Island">Norfolk Island</option> -<option value="Northern Mariana Islands">Northern Mariana Islands</option> -<option value="Norway">Norway</option> -<option value="Oman">Oman</option> -<option value="Pakistan">Pakistan</option> -<option value="Palau">Palau</option> -<option value="Palestinian Territory, Occupied">Palestinian Territory, Occupied</option> -<option value="Panama">Panama</option> -<option value="Papua New Guinea">Papua New Guinea</option> -<option value="Paraguay">Paraguay</option> -<option value="Peru">Peru</option> -<option value="Philippines">Philippines</option> -<option value="Pitcairn">Pitcairn</option> -<option value="Poland">Poland</option> -<option value="Portugal">Portugal</option> -<option value="Puerto Rico">Puerto Rico</option> -<option value="Qatar">Qatar</option> -<option value="Reunion">Reunion</option> -<option value="Romania">Romania</option> -<option value="Russian Federation">Russian Federation</option> -<option value="Rwanda">Rwanda</option> -<option value="Saint Barthelemy">Saint Barthelemy</option> -<option value="Saint Helena">Saint Helena</option> -<option value="Saint Kitts and Nevis">Saint Kitts and Nevis</option> -<option value="Saint Lucia">Saint Lucia</option> -<option value="Saint Pierre and Miquelon">Saint Pierre and Miquelon</option> -<option value="Saint Vincent and the Grenadines">Saint Vincent and the Grenadines</option> -<option value="Samoa">Samoa</option> -<option value="San Marino">San Marino</option> -<option value="Sao Tome and Principe">Sao Tome and Principe</option> -<option value="Saudi Arabia">Saudi Arabia</option> -<option value="Senegal">Senegal</option> -<option value="Serbia">Serbia</option> -<option value="Seychelles">Seychelles</option> -<option value="Sierra Leone">Sierra Leone</option> -<option value="Singapore">Singapore</option> -<option value="Slovakia">Slovakia</option> -<option value="Slovenia">Slovenia</option> -<option value="Solomon Islands">Solomon Islands</option> -<option value="Somalia">Somalia</option> -<option value="South Africa">South Africa</option> -<option value="South Georgia and the South Sandwich Islands">South Georgia and the South Sandwich Islands</option> -<option value="Spain">Spain</option> -<option value="Sri Lanka">Sri Lanka</option> -<option value="Sudan">Sudan</option> -<option value="Suriname">Suriname</option> -<option value="Svalbard and Jan Mayen">Svalbard and Jan Mayen</option> -<option value="Swaziland">Swaziland</option> -<option value="Sweden">Sweden</option> -<option value="Switzerland">Switzerland</option> -<option value="Syrian Arab Republic">Syrian Arab Republic</option> -<option value="Taiwan, Province of China">Taiwan, Province of China</option> -<option value="Tajikistan">Tajikistan</option> -<option value="Tanzania, United Republic of">Tanzania, United Republic of</option> -<option value="Thailand">Thailand</option> -<option value="Timor-Leste">Timor-Leste</option> -<option value="Togo">Togo</option> -<option value="Tokelau">Tokelau</option> -<option value="Tonga">Tonga</option> -<option value="Trinidad and Tobago">Trinidad and Tobago</option> -<option value="Tunisia">Tunisia</option> -<option value="Turkey">Turkey</option> -<option value="Turkmenistan">Turkmenistan</option> -<option value="Turks and Caicos Islands">Turks and Caicos Islands</option> -<option value="Tuvalu">Tuvalu</option> -<option value="Uganda">Uganda</option> -<option value="Ukraine">Ukraine</option> -<option value="United Arab Emirates">United Arab Emirates</option> -<option value="United Kingdom">United Kingdom</option> -<option value="United States">United States</option> -<option value="United States Minor Outlying Islands">United States Minor Outlying Islands</option> -<option value="Uruguay">Uruguay</option> -<option value="Uzbekistan">Uzbekistan</option> -<option value="Vanuatu">Vanuatu</option> -<option value="Venezuela">Venezuela</option> -<option value="Viet Nam">Viet Nam</option> -<option value="Virgin Islands, British">Virgin Islands, British</option> -<option value="Virgin Islands, U.S.">Virgin Islands, U.S.</option> -<option value="Wallis and Futuna">Wallis and Futuna</option> -<option value="Western Sahara">Western Sahara</option> -<option value="Yemen">Yemen</option> -<option value="Zambia">Zambia</option> -<option value="Zimbabwe">Zimbabwe</option></select> -COUNTRIES - assert_dom_equal(expected_select[0..-2], country_select("post", "origin", ["New Zealand", "Nicaragua"])) - end - - def test_country_select_with_selected_priority_country - @post = Post.new - @post.origin = "New Zealand" - expected_select = <<-COUNTRIES -<select id="post_origin" name="post[origin]"><option selected="selected" value="New Zealand">New Zealand</option> -<option value="Nicaragua">Nicaragua</option><option value="" disabled="disabled">-------------</option> -<option value="Afghanistan">Afghanistan</option> -<option value="Aland Islands">Aland Islands</option> -<option value="Albania">Albania</option> -<option value="Algeria">Algeria</option> -<option value="American Samoa">American Samoa</option> -<option value="Andorra">Andorra</option> -<option value="Angola">Angola</option> -<option value="Anguilla">Anguilla</option> -<option value="Antarctica">Antarctica</option> -<option value="Antigua And Barbuda">Antigua And Barbuda</option> -<option value="Argentina">Argentina</option> -<option value="Armenia">Armenia</option> -<option value="Aruba">Aruba</option> -<option value="Australia">Australia</option> -<option value="Austria">Austria</option> -<option value="Azerbaijan">Azerbaijan</option> -<option value="Bahamas">Bahamas</option> -<option value="Bahrain">Bahrain</option> -<option value="Bangladesh">Bangladesh</option> -<option value="Barbados">Barbados</option> -<option value="Belarus">Belarus</option> -<option value="Belgium">Belgium</option> -<option value="Belize">Belize</option> -<option value="Benin">Benin</option> -<option value="Bermuda">Bermuda</option> -<option value="Bhutan">Bhutan</option> -<option value="Bolivia">Bolivia</option> -<option value="Bosnia and Herzegowina">Bosnia and Herzegowina</option> -<option value="Botswana">Botswana</option> -<option value="Bouvet Island">Bouvet Island</option> -<option value="Brazil">Brazil</option> -<option value="British Indian Ocean Territory">British Indian Ocean Territory</option> -<option value="Brunei Darussalam">Brunei Darussalam</option> -<option value="Bulgaria">Bulgaria</option> -<option value="Burkina Faso">Burkina Faso</option> -<option value="Burundi">Burundi</option> -<option value="Cambodia">Cambodia</option> -<option value="Cameroon">Cameroon</option> -<option value="Canada">Canada</option> -<option value="Cape Verde">Cape Verde</option> -<option value="Cayman Islands">Cayman Islands</option> -<option value="Central African Republic">Central African Republic</option> -<option value="Chad">Chad</option> -<option value="Chile">Chile</option> -<option value="China">China</option> -<option value="Christmas Island">Christmas Island</option> -<option value="Cocos (Keeling) Islands">Cocos (Keeling) Islands</option> -<option value="Colombia">Colombia</option> -<option value="Comoros">Comoros</option> -<option value="Congo">Congo</option> -<option value="Congo, the Democratic Republic of the">Congo, the Democratic Republic of the</option> -<option value="Cook Islands">Cook Islands</option> -<option value="Costa Rica">Costa Rica</option> -<option value="Cote d'Ivoire">Cote d'Ivoire</option> -<option value="Croatia">Croatia</option> -<option value="Cuba">Cuba</option> -<option value="Cyprus">Cyprus</option> -<option value="Czech Republic">Czech Republic</option> -<option value="Denmark">Denmark</option> -<option value="Djibouti">Djibouti</option> -<option value="Dominica">Dominica</option> -<option value="Dominican Republic">Dominican Republic</option> -<option value="Ecuador">Ecuador</option> -<option value="Egypt">Egypt</option> -<option value="El Salvador">El Salvador</option> -<option value="Equatorial Guinea">Equatorial Guinea</option> -<option value="Eritrea">Eritrea</option> -<option value="Estonia">Estonia</option> -<option value="Ethiopia">Ethiopia</option> -<option value="Falkland Islands (Malvinas)">Falkland Islands (Malvinas)</option> -<option value="Faroe Islands">Faroe Islands</option> -<option value="Fiji">Fiji</option> -<option value="Finland">Finland</option> -<option value="France">France</option> -<option value="French Guiana">French Guiana</option> -<option value="French Polynesia">French Polynesia</option> -<option value="French Southern Territories">French Southern Territories</option> -<option value="Gabon">Gabon</option> -<option value="Gambia">Gambia</option> -<option value="Georgia">Georgia</option> -<option value="Germany">Germany</option> -<option value="Ghana">Ghana</option> -<option value="Gibraltar">Gibraltar</option> -<option value="Greece">Greece</option> -<option value="Greenland">Greenland</option> -<option value="Grenada">Grenada</option> -<option value="Guadeloupe">Guadeloupe</option> -<option value="Guam">Guam</option> -<option value="Guatemala">Guatemala</option> -<option value="Guernsey">Guernsey</option> -<option value="Guinea">Guinea</option> -<option value="Guinea-Bissau">Guinea-Bissau</option> -<option value="Guyana">Guyana</option> -<option value="Haiti">Haiti</option> -<option value="Heard and McDonald Islands">Heard and McDonald Islands</option> -<option value="Holy See (Vatican City State)">Holy See (Vatican City State)</option> -<option value="Honduras">Honduras</option> -<option value="Hong Kong">Hong Kong</option> -<option value="Hungary">Hungary</option> -<option value="Iceland">Iceland</option> -<option value="India">India</option> -<option value="Indonesia">Indonesia</option> -<option value="Iran, Islamic Republic of">Iran, Islamic Republic of</option> -<option value="Iraq">Iraq</option> -<option value="Ireland">Ireland</option> -<option value="Isle of Man">Isle of Man</option> -<option value="Israel">Israel</option> -<option value="Italy">Italy</option> -<option value="Jamaica">Jamaica</option> -<option value="Japan">Japan</option> -<option value="Jersey">Jersey</option> -<option value="Jordan">Jordan</option> -<option value="Kazakhstan">Kazakhstan</option> -<option value="Kenya">Kenya</option> -<option value="Kiribati">Kiribati</option> -<option value="Korea, Democratic People's Republic of">Korea, Democratic People's Republic of</option> -<option value="Korea, Republic of">Korea, Republic of</option> -<option value="Kuwait">Kuwait</option> -<option value="Kyrgyzstan">Kyrgyzstan</option> -<option value="Lao People's Democratic Republic">Lao People's Democratic Republic</option> -<option value="Latvia">Latvia</option> -<option value="Lebanon">Lebanon</option> -<option value="Lesotho">Lesotho</option> -<option value="Liberia">Liberia</option> -<option value="Libyan Arab Jamahiriya">Libyan Arab Jamahiriya</option> -<option value="Liechtenstein">Liechtenstein</option> -<option value="Lithuania">Lithuania</option> -<option value="Luxembourg">Luxembourg</option> -<option value="Macao">Macao</option> -<option value="Macedonia, The Former Yugoslav Republic Of">Macedonia, The Former Yugoslav Republic Of</option> -<option value="Madagascar">Madagascar</option> -<option value="Malawi">Malawi</option> -<option value="Malaysia">Malaysia</option> -<option value="Maldives">Maldives</option> -<option value="Mali">Mali</option> -<option value="Malta">Malta</option> -<option value="Marshall Islands">Marshall Islands</option> -<option value="Martinique">Martinique</option> -<option value="Mauritania">Mauritania</option> -<option value="Mauritius">Mauritius</option> -<option value="Mayotte">Mayotte</option> -<option value="Mexico">Mexico</option> -<option value="Micronesia, Federated States of">Micronesia, Federated States of</option> -<option value="Moldova, Republic of">Moldova, Republic of</option> -<option value="Monaco">Monaco</option> -<option value="Mongolia">Mongolia</option> -<option value="Montenegro">Montenegro</option> -<option value="Montserrat">Montserrat</option> -<option value="Morocco">Morocco</option> -<option value="Mozambique">Mozambique</option> -<option value="Myanmar">Myanmar</option> -<option value="Namibia">Namibia</option> -<option value="Nauru">Nauru</option> -<option value="Nepal">Nepal</option> -<option value="Netherlands">Netherlands</option> -<option value="Netherlands Antilles">Netherlands Antilles</option> -<option value="New Caledonia">New Caledonia</option> -<option selected="selected" value="New Zealand">New Zealand</option> -<option value="Nicaragua">Nicaragua</option> -<option value="Niger">Niger</option> -<option value="Nigeria">Nigeria</option> -<option value="Niue">Niue</option> -<option value="Norfolk Island">Norfolk Island</option> -<option value="Northern Mariana Islands">Northern Mariana Islands</option> -<option value="Norway">Norway</option> -<option value="Oman">Oman</option> -<option value="Pakistan">Pakistan</option> -<option value="Palau">Palau</option> -<option value="Palestinian Territory, Occupied">Palestinian Territory, Occupied</option> -<option value="Panama">Panama</option> -<option value="Papua New Guinea">Papua New Guinea</option> -<option value="Paraguay">Paraguay</option> -<option value="Peru">Peru</option> -<option value="Philippines">Philippines</option> -<option value="Pitcairn">Pitcairn</option> -<option value="Poland">Poland</option> -<option value="Portugal">Portugal</option> -<option value="Puerto Rico">Puerto Rico</option> -<option value="Qatar">Qatar</option> -<option value="Reunion">Reunion</option> -<option value="Romania">Romania</option> -<option value="Russian Federation">Russian Federation</option> -<option value="Rwanda">Rwanda</option> -<option value="Saint Barthelemy">Saint Barthelemy</option> -<option value="Saint Helena">Saint Helena</option> -<option value="Saint Kitts and Nevis">Saint Kitts and Nevis</option> -<option value="Saint Lucia">Saint Lucia</option> -<option value="Saint Pierre and Miquelon">Saint Pierre and Miquelon</option> -<option value="Saint Vincent and the Grenadines">Saint Vincent and the Grenadines</option> -<option value="Samoa">Samoa</option> -<option value="San Marino">San Marino</option> -<option value="Sao Tome and Principe">Sao Tome and Principe</option> -<option value="Saudi Arabia">Saudi Arabia</option> -<option value="Senegal">Senegal</option> -<option value="Serbia">Serbia</option> -<option value="Seychelles">Seychelles</option> -<option value="Sierra Leone">Sierra Leone</option> -<option value="Singapore">Singapore</option> -<option value="Slovakia">Slovakia</option> -<option value="Slovenia">Slovenia</option> -<option value="Solomon Islands">Solomon Islands</option> -<option value="Somalia">Somalia</option> -<option value="South Africa">South Africa</option> -<option value="South Georgia and the South Sandwich Islands">South Georgia and the South Sandwich Islands</option> -<option value="Spain">Spain</option> -<option value="Sri Lanka">Sri Lanka</option> -<option value="Sudan">Sudan</option> -<option value="Suriname">Suriname</option> -<option value="Svalbard and Jan Mayen">Svalbard and Jan Mayen</option> -<option value="Swaziland">Swaziland</option> -<option value="Sweden">Sweden</option> -<option value="Switzerland">Switzerland</option> -<option value="Syrian Arab Republic">Syrian Arab Republic</option> -<option value="Taiwan, Province of China">Taiwan, Province of China</option> -<option value="Tajikistan">Tajikistan</option> -<option value="Tanzania, United Republic of">Tanzania, United Republic of</option> -<option value="Thailand">Thailand</option> -<option value="Timor-Leste">Timor-Leste</option> -<option value="Togo">Togo</option> -<option value="Tokelau">Tokelau</option> -<option value="Tonga">Tonga</option> -<option value="Trinidad and Tobago">Trinidad and Tobago</option> -<option value="Tunisia">Tunisia</option> -<option value="Turkey">Turkey</option> -<option value="Turkmenistan">Turkmenistan</option> -<option value="Turks and Caicos Islands">Turks and Caicos Islands</option> -<option value="Tuvalu">Tuvalu</option> -<option value="Uganda">Uganda</option> -<option value="Ukraine">Ukraine</option> -<option value="United Arab Emirates">United Arab Emirates</option> -<option value="United Kingdom">United Kingdom</option> -<option value="United States">United States</option> -<option value="United States Minor Outlying Islands">United States Minor Outlying Islands</option> -<option value="Uruguay">Uruguay</option> -<option value="Uzbekistan">Uzbekistan</option> -<option value="Vanuatu">Vanuatu</option> -<option value="Venezuela">Venezuela</option> -<option value="Viet Nam">Viet Nam</option> -<option value="Virgin Islands, British">Virgin Islands, British</option> -<option value="Virgin Islands, U.S.">Virgin Islands, U.S.</option> -<option value="Wallis and Futuna">Wallis and Futuna</option> -<option value="Western Sahara">Western Sahara</option> -<option value="Yemen">Yemen</option> -<option value="Zambia">Zambia</option> -<option value="Zimbabwe">Zimbabwe</option></select> -COUNTRIES - assert_dom_equal(expected_select[0..-2], country_select("post", "origin", ["New Zealand", "Nicaragua"])) - end - - def test_country_select_under_fields_for - @post = Post.new - @post.origin = "Australia" - expected_select = <<-COUNTRIES -<select id="post_origin" name="post[origin]"><option value="Afghanistan">Afghanistan</option> -<option value="Aland Islands">Aland Islands</option> -<option value="Albania">Albania</option> -<option value="Algeria">Algeria</option> -<option value="American Samoa">American Samoa</option> -<option value="Andorra">Andorra</option> -<option value="Angola">Angola</option> -<option value="Anguilla">Anguilla</option> -<option value="Antarctica">Antarctica</option> -<option value="Antigua And Barbuda">Antigua And Barbuda</option> -<option value="Argentina">Argentina</option> -<option value="Armenia">Armenia</option> -<option value="Aruba">Aruba</option> -<option selected="selected" value="Australia">Australia</option> -<option value="Austria">Austria</option> -<option value="Azerbaijan">Azerbaijan</option> -<option value="Bahamas">Bahamas</option> -<option value="Bahrain">Bahrain</option> -<option value="Bangladesh">Bangladesh</option> -<option value="Barbados">Barbados</option> -<option value="Belarus">Belarus</option> -<option value="Belgium">Belgium</option> -<option value="Belize">Belize</option> -<option value="Benin">Benin</option> -<option value="Bermuda">Bermuda</option> -<option value="Bhutan">Bhutan</option> -<option value="Bolivia">Bolivia</option> -<option value="Bosnia and Herzegowina">Bosnia and Herzegowina</option> -<option value="Botswana">Botswana</option> -<option value="Bouvet Island">Bouvet Island</option> -<option value="Brazil">Brazil</option> -<option value="British Indian Ocean Territory">British Indian Ocean Territory</option> -<option value="Brunei Darussalam">Brunei Darussalam</option> -<option value="Bulgaria">Bulgaria</option> -<option value="Burkina Faso">Burkina Faso</option> -<option value="Burundi">Burundi</option> -<option value="Cambodia">Cambodia</option> -<option value="Cameroon">Cameroon</option> -<option value="Canada">Canada</option> -<option value="Cape Verde">Cape Verde</option> -<option value="Cayman Islands">Cayman Islands</option> -<option value="Central African Republic">Central African Republic</option> -<option value="Chad">Chad</option> -<option value="Chile">Chile</option> -<option value="China">China</option> -<option value="Christmas Island">Christmas Island</option> -<option value="Cocos (Keeling) Islands">Cocos (Keeling) Islands</option> -<option value="Colombia">Colombia</option> -<option value="Comoros">Comoros</option> -<option value="Congo">Congo</option> -<option value="Congo, the Democratic Republic of the">Congo, the Democratic Republic of the</option> -<option value="Cook Islands">Cook Islands</option> -<option value="Costa Rica">Costa Rica</option> -<option value="Cote d'Ivoire">Cote d'Ivoire</option> -<option value="Croatia">Croatia</option> -<option value="Cuba">Cuba</option> -<option value="Cyprus">Cyprus</option> -<option value="Czech Republic">Czech Republic</option> -<option value="Denmark">Denmark</option> -<option value="Djibouti">Djibouti</option> -<option value="Dominica">Dominica</option> -<option value="Dominican Republic">Dominican Republic</option> -<option value="Ecuador">Ecuador</option> -<option value="Egypt">Egypt</option> -<option value="El Salvador">El Salvador</option> -<option value="Equatorial Guinea">Equatorial Guinea</option> -<option value="Eritrea">Eritrea</option> -<option value="Estonia">Estonia</option> -<option value="Ethiopia">Ethiopia</option> -<option value="Falkland Islands (Malvinas)">Falkland Islands (Malvinas)</option> -<option value="Faroe Islands">Faroe Islands</option> -<option value="Fiji">Fiji</option> -<option value="Finland">Finland</option> -<option value="France">France</option> -<option value="French Guiana">French Guiana</option> -<option value="French Polynesia">French Polynesia</option> -<option value="French Southern Territories">French Southern Territories</option> -<option value="Gabon">Gabon</option> -<option value="Gambia">Gambia</option> -<option value="Georgia">Georgia</option> -<option value="Germany">Germany</option> -<option value="Ghana">Ghana</option> -<option value="Gibraltar">Gibraltar</option> -<option value="Greece">Greece</option> -<option value="Greenland">Greenland</option> -<option value="Grenada">Grenada</option> -<option value="Guadeloupe">Guadeloupe</option> -<option value="Guam">Guam</option> -<option value="Guatemala">Guatemala</option> -<option value="Guernsey">Guernsey</option> -<option value="Guinea">Guinea</option> -<option value="Guinea-Bissau">Guinea-Bissau</option> -<option value="Guyana">Guyana</option> -<option value="Haiti">Haiti</option> -<option value="Heard and McDonald Islands">Heard and McDonald Islands</option> -<option value="Holy See (Vatican City State)">Holy See (Vatican City State)</option> -<option value="Honduras">Honduras</option> -<option value="Hong Kong">Hong Kong</option> -<option value="Hungary">Hungary</option> -<option value="Iceland">Iceland</option> -<option value="India">India</option> -<option value="Indonesia">Indonesia</option> -<option value="Iran, Islamic Republic of">Iran, Islamic Republic of</option> -<option value="Iraq">Iraq</option> -<option value="Ireland">Ireland</option> -<option value="Isle of Man">Isle of Man</option> -<option value="Israel">Israel</option> -<option value="Italy">Italy</option> -<option value="Jamaica">Jamaica</option> -<option value="Japan">Japan</option> -<option value="Jersey">Jersey</option> -<option value="Jordan">Jordan</option> -<option value="Kazakhstan">Kazakhstan</option> -<option value="Kenya">Kenya</option> -<option value="Kiribati">Kiribati</option> -<option value="Korea, Democratic People's Republic of">Korea, Democratic People's Republic of</option> -<option value="Korea, Republic of">Korea, Republic of</option> -<option value="Kuwait">Kuwait</option> -<option value="Kyrgyzstan">Kyrgyzstan</option> -<option value="Lao People's Democratic Republic">Lao People's Democratic Republic</option> -<option value="Latvia">Latvia</option> -<option value="Lebanon">Lebanon</option> -<option value="Lesotho">Lesotho</option> -<option value="Liberia">Liberia</option> -<option value="Libyan Arab Jamahiriya">Libyan Arab Jamahiriya</option> -<option value="Liechtenstein">Liechtenstein</option> -<option value="Lithuania">Lithuania</option> -<option value="Luxembourg">Luxembourg</option> -<option value="Macao">Macao</option> -<option value="Macedonia, The Former Yugoslav Republic Of">Macedonia, The Former Yugoslav Republic Of</option> -<option value="Madagascar">Madagascar</option> -<option value="Malawi">Malawi</option> -<option value="Malaysia">Malaysia</option> -<option value="Maldives">Maldives</option> -<option value="Mali">Mali</option> -<option value="Malta">Malta</option> -<option value="Marshall Islands">Marshall Islands</option> -<option value="Martinique">Martinique</option> -<option value="Mauritania">Mauritania</option> -<option value="Mauritius">Mauritius</option> -<option value="Mayotte">Mayotte</option> -<option value="Mexico">Mexico</option> -<option value="Micronesia, Federated States of">Micronesia, Federated States of</option> -<option value="Moldova, Republic of">Moldova, Republic of</option> -<option value="Monaco">Monaco</option> -<option value="Mongolia">Mongolia</option> -<option value="Montenegro">Montenegro</option> -<option value="Montserrat">Montserrat</option> -<option value="Morocco">Morocco</option> -<option value="Mozambique">Mozambique</option> -<option value="Myanmar">Myanmar</option> -<option value="Namibia">Namibia</option> -<option value="Nauru">Nauru</option> -<option value="Nepal">Nepal</option> -<option value="Netherlands">Netherlands</option> -<option value="Netherlands Antilles">Netherlands Antilles</option> -<option value="New Caledonia">New Caledonia</option> -<option value="New Zealand">New Zealand</option> -<option value="Nicaragua">Nicaragua</option> -<option value="Niger">Niger</option> -<option value="Nigeria">Nigeria</option> -<option value="Niue">Niue</option> -<option value="Norfolk Island">Norfolk Island</option> -<option value="Northern Mariana Islands">Northern Mariana Islands</option> -<option value="Norway">Norway</option> -<option value="Oman">Oman</option> -<option value="Pakistan">Pakistan</option> -<option value="Palau">Palau</option> -<option value="Palestinian Territory, Occupied">Palestinian Territory, Occupied</option> -<option value="Panama">Panama</option> -<option value="Papua New Guinea">Papua New Guinea</option> -<option value="Paraguay">Paraguay</option> -<option value="Peru">Peru</option> -<option value="Philippines">Philippines</option> -<option value="Pitcairn">Pitcairn</option> -<option value="Poland">Poland</option> -<option value="Portugal">Portugal</option> -<option value="Puerto Rico">Puerto Rico</option> -<option value="Qatar">Qatar</option> -<option value="Reunion">Reunion</option> -<option value="Romania">Romania</option> -<option value="Russian Federation">Russian Federation</option> -<option value="Rwanda">Rwanda</option> -<option value="Saint Barthelemy">Saint Barthelemy</option> -<option value="Saint Helena">Saint Helena</option> -<option value="Saint Kitts and Nevis">Saint Kitts and Nevis</option> -<option value="Saint Lucia">Saint Lucia</option> -<option value="Saint Pierre and Miquelon">Saint Pierre and Miquelon</option> -<option value="Saint Vincent and the Grenadines">Saint Vincent and the Grenadines</option> -<option value="Samoa">Samoa</option> -<option value="San Marino">San Marino</option> -<option value="Sao Tome and Principe">Sao Tome and Principe</option> -<option value="Saudi Arabia">Saudi Arabia</option> -<option value="Senegal">Senegal</option> -<option value="Serbia">Serbia</option> -<option value="Seychelles">Seychelles</option> -<option value="Sierra Leone">Sierra Leone</option> -<option value="Singapore">Singapore</option> -<option value="Slovakia">Slovakia</option> -<option value="Slovenia">Slovenia</option> -<option value="Solomon Islands">Solomon Islands</option> -<option value="Somalia">Somalia</option> -<option value="South Africa">South Africa</option> -<option value="South Georgia and the South Sandwich Islands">South Georgia and the South Sandwich Islands</option> -<option value="Spain">Spain</option> -<option value="Sri Lanka">Sri Lanka</option> -<option value="Sudan">Sudan</option> -<option value="Suriname">Suriname</option> -<option value="Svalbard and Jan Mayen">Svalbard and Jan Mayen</option> -<option value="Swaziland">Swaziland</option> -<option value="Sweden">Sweden</option> -<option value="Switzerland">Switzerland</option> -<option value="Syrian Arab Republic">Syrian Arab Republic</option> -<option value="Taiwan, Province of China">Taiwan, Province of China</option> -<option value="Tajikistan">Tajikistan</option> -<option value="Tanzania, United Republic of">Tanzania, United Republic of</option> -<option value="Thailand">Thailand</option> -<option value="Timor-Leste">Timor-Leste</option> -<option value="Togo">Togo</option> -<option value="Tokelau">Tokelau</option> -<option value="Tonga">Tonga</option> -<option value="Trinidad and Tobago">Trinidad and Tobago</option> -<option value="Tunisia">Tunisia</option> -<option value="Turkey">Turkey</option> -<option value="Turkmenistan">Turkmenistan</option> -<option value="Turks and Caicos Islands">Turks and Caicos Islands</option> -<option value="Tuvalu">Tuvalu</option> -<option value="Uganda">Uganda</option> -<option value="Ukraine">Ukraine</option> -<option value="United Arab Emirates">United Arab Emirates</option> -<option value="United Kingdom">United Kingdom</option> -<option value="United States">United States</option> -<option value="United States Minor Outlying Islands">United States Minor Outlying Islands</option> -<option value="Uruguay">Uruguay</option> -<option value="Uzbekistan">Uzbekistan</option> -<option value="Vanuatu">Vanuatu</option> -<option value="Venezuela">Venezuela</option> -<option value="Viet Nam">Viet Nam</option> -<option value="Virgin Islands, British">Virgin Islands, British</option> -<option value="Virgin Islands, U.S.">Virgin Islands, U.S.</option> -<option value="Wallis and Futuna">Wallis and Futuna</option> -<option value="Western Sahara">Western Sahara</option> -<option value="Yemen">Yemen</option> -<option value="Zambia">Zambia</option> -<option value="Zimbabwe">Zimbabwe</option></select> -COUNTRIES - - fields_for :post, @post do |f| - concat f.country_select("origin") - end - - assert_dom_equal(expected_select[0..-2], output_buffer) - end - - def test_country_select_under_fields_for_with_index - @post = Post.new - @post.origin = "United States" - expected_select = <<-COUNTRIES -<select id="post_325_origin" name="post[325][origin]"><option value="Afghanistan">Afghanistan</option> -<option value="Aland Islands">Aland Islands</option> -<option value="Albania">Albania</option> -<option value="Algeria">Algeria</option> -<option value="American Samoa">American Samoa</option> -<option value="Andorra">Andorra</option> -<option value="Angola">Angola</option> -<option value="Anguilla">Anguilla</option> -<option value="Antarctica">Antarctica</option> -<option value="Antigua And Barbuda">Antigua And Barbuda</option> -<option value="Argentina">Argentina</option> -<option value="Armenia">Armenia</option> -<option value="Aruba">Aruba</option> -<option value="Australia">Australia</option> -<option value="Austria">Austria</option> -<option value="Azerbaijan">Azerbaijan</option> -<option value="Bahamas">Bahamas</option> -<option value="Bahrain">Bahrain</option> -<option value="Bangladesh">Bangladesh</option> -<option value="Barbados">Barbados</option> -<option value="Belarus">Belarus</option> -<option value="Belgium">Belgium</option> -<option value="Belize">Belize</option> -<option value="Benin">Benin</option> -<option value="Bermuda">Bermuda</option> -<option value="Bhutan">Bhutan</option> -<option value="Bolivia">Bolivia</option> -<option value="Bosnia and Herzegowina">Bosnia and Herzegowina</option> -<option value="Botswana">Botswana</option> -<option value="Bouvet Island">Bouvet Island</option> -<option value="Brazil">Brazil</option> -<option value="British Indian Ocean Territory">British Indian Ocean Territory</option> -<option value="Brunei Darussalam">Brunei Darussalam</option> -<option value="Bulgaria">Bulgaria</option> -<option value="Burkina Faso">Burkina Faso</option> -<option value="Burundi">Burundi</option> -<option value="Cambodia">Cambodia</option> -<option value="Cameroon">Cameroon</option> -<option value="Canada">Canada</option> -<option value="Cape Verde">Cape Verde</option> -<option value="Cayman Islands">Cayman Islands</option> -<option value="Central African Republic">Central African Republic</option> -<option value="Chad">Chad</option> -<option value="Chile">Chile</option> -<option value="China">China</option> -<option value="Christmas Island">Christmas Island</option> -<option value="Cocos (Keeling) Islands">Cocos (Keeling) Islands</option> -<option value="Colombia">Colombia</option> -<option value="Comoros">Comoros</option> -<option value="Congo">Congo</option> -<option value="Congo, the Democratic Republic of the">Congo, the Democratic Republic of the</option> -<option value="Cook Islands">Cook Islands</option> -<option value="Costa Rica">Costa Rica</option> -<option value="Cote d'Ivoire">Cote d'Ivoire</option> -<option value="Croatia">Croatia</option> -<option value="Cuba">Cuba</option> -<option value="Cyprus">Cyprus</option> -<option value="Czech Republic">Czech Republic</option> -<option value="Denmark">Denmark</option> -<option value="Djibouti">Djibouti</option> -<option value="Dominica">Dominica</option> -<option value="Dominican Republic">Dominican Republic</option> -<option value="Ecuador">Ecuador</option> -<option value="Egypt">Egypt</option> -<option value="El Salvador">El Salvador</option> -<option value="Equatorial Guinea">Equatorial Guinea</option> -<option value="Eritrea">Eritrea</option> -<option value="Estonia">Estonia</option> -<option value="Ethiopia">Ethiopia</option> -<option value="Falkland Islands (Malvinas)">Falkland Islands (Malvinas)</option> -<option value="Faroe Islands">Faroe Islands</option> -<option value="Fiji">Fiji</option> -<option value="Finland">Finland</option> -<option value="France">France</option> -<option value="French Guiana">French Guiana</option> -<option value="French Polynesia">French Polynesia</option> -<option value="French Southern Territories">French Southern Territories</option> -<option value="Gabon">Gabon</option> -<option value="Gambia">Gambia</option> -<option value="Georgia">Georgia</option> -<option value="Germany">Germany</option> -<option value="Ghana">Ghana</option> -<option value="Gibraltar">Gibraltar</option> -<option value="Greece">Greece</option> -<option value="Greenland">Greenland</option> -<option value="Grenada">Grenada</option> -<option value="Guadeloupe">Guadeloupe</option> -<option value="Guam">Guam</option> -<option value="Guatemala">Guatemala</option> -<option value="Guernsey">Guernsey</option> -<option value="Guinea">Guinea</option> -<option value="Guinea-Bissau">Guinea-Bissau</option> -<option value="Guyana">Guyana</option> -<option value="Haiti">Haiti</option> -<option value="Heard and McDonald Islands">Heard and McDonald Islands</option> -<option value="Holy See (Vatican City State)">Holy See (Vatican City State)</option> -<option value="Honduras">Honduras</option> -<option value="Hong Kong">Hong Kong</option> -<option value="Hungary">Hungary</option> -<option value="Iceland">Iceland</option> -<option value="India">India</option> -<option value="Indonesia">Indonesia</option> -<option value="Iran, Islamic Republic of">Iran, Islamic Republic of</option> -<option value="Iraq">Iraq</option> -<option value="Ireland">Ireland</option> -<option value="Isle of Man">Isle of Man</option> -<option value="Israel">Israel</option> -<option value="Italy">Italy</option> -<option value="Jamaica">Jamaica</option> -<option value="Japan">Japan</option> -<option value="Jersey">Jersey</option> -<option value="Jordan">Jordan</option> -<option value="Kazakhstan">Kazakhstan</option> -<option value="Kenya">Kenya</option> -<option value="Kiribati">Kiribati</option> -<option value="Korea, Democratic People's Republic of">Korea, Democratic People's Republic of</option> -<option value="Korea, Republic of">Korea, Republic of</option> -<option value="Kuwait">Kuwait</option> -<option value="Kyrgyzstan">Kyrgyzstan</option> -<option value="Lao People's Democratic Republic">Lao People's Democratic Republic</option> -<option value="Latvia">Latvia</option> -<option value="Lebanon">Lebanon</option> -<option value="Lesotho">Lesotho</option> -<option value="Liberia">Liberia</option> -<option value="Libyan Arab Jamahiriya">Libyan Arab Jamahiriya</option> -<option value="Liechtenstein">Liechtenstein</option> -<option value="Lithuania">Lithuania</option> -<option value="Luxembourg">Luxembourg</option> -<option value="Macao">Macao</option> -<option value="Macedonia, The Former Yugoslav Republic Of">Macedonia, The Former Yugoslav Republic Of</option> -<option value="Madagascar">Madagascar</option> -<option value="Malawi">Malawi</option> -<option value="Malaysia">Malaysia</option> -<option value="Maldives">Maldives</option> -<option value="Mali">Mali</option> -<option value="Malta">Malta</option> -<option value="Marshall Islands">Marshall Islands</option> -<option value="Martinique">Martinique</option> -<option value="Mauritania">Mauritania</option> -<option value="Mauritius">Mauritius</option> -<option value="Mayotte">Mayotte</option> -<option value="Mexico">Mexico</option> -<option value="Micronesia, Federated States of">Micronesia, Federated States of</option> -<option value="Moldova, Republic of">Moldova, Republic of</option> -<option value="Monaco">Monaco</option> -<option value="Mongolia">Mongolia</option> -<option value="Montenegro">Montenegro</option> -<option value="Montserrat">Montserrat</option> -<option value="Morocco">Morocco</option> -<option value="Mozambique">Mozambique</option> -<option value="Myanmar">Myanmar</option> -<option value="Namibia">Namibia</option> -<option value="Nauru">Nauru</option> -<option value="Nepal">Nepal</option> -<option value="Netherlands">Netherlands</option> -<option value="Netherlands Antilles">Netherlands Antilles</option> -<option value="New Caledonia">New Caledonia</option> -<option value="New Zealand">New Zealand</option> -<option value="Nicaragua">Nicaragua</option> -<option value="Niger">Niger</option> -<option value="Nigeria">Nigeria</option> -<option value="Niue">Niue</option> -<option value="Norfolk Island">Norfolk Island</option> -<option value="Northern Mariana Islands">Northern Mariana Islands</option> -<option value="Norway">Norway</option> -<option value="Oman">Oman</option> -<option value="Pakistan">Pakistan</option> -<option value="Palau">Palau</option> -<option value="Palestinian Territory, Occupied">Palestinian Territory, Occupied</option> -<option value="Panama">Panama</option> -<option value="Papua New Guinea">Papua New Guinea</option> -<option value="Paraguay">Paraguay</option> -<option value="Peru">Peru</option> -<option value="Philippines">Philippines</option> -<option value="Pitcairn">Pitcairn</option> -<option value="Poland">Poland</option> -<option value="Portugal">Portugal</option> -<option value="Puerto Rico">Puerto Rico</option> -<option value="Qatar">Qatar</option> -<option value="Reunion">Reunion</option> -<option value="Romania">Romania</option> -<option value="Russian Federation">Russian Federation</option> -<option value="Rwanda">Rwanda</option> -<option value="Saint Barthelemy">Saint Barthelemy</option> -<option value="Saint Helena">Saint Helena</option> -<option value="Saint Kitts and Nevis">Saint Kitts and Nevis</option> -<option value="Saint Lucia">Saint Lucia</option> -<option value="Saint Pierre and Miquelon">Saint Pierre and Miquelon</option> -<option value="Saint Vincent and the Grenadines">Saint Vincent and the Grenadines</option> -<option value="Samoa">Samoa</option> -<option value="San Marino">San Marino</option> -<option value="Sao Tome and Principe">Sao Tome and Principe</option> -<option value="Saudi Arabia">Saudi Arabia</option> -<option value="Senegal">Senegal</option> -<option value="Serbia">Serbia</option> -<option value="Seychelles">Seychelles</option> -<option value="Sierra Leone">Sierra Leone</option> -<option value="Singapore">Singapore</option> -<option value="Slovakia">Slovakia</option> -<option value="Slovenia">Slovenia</option> -<option value="Solomon Islands">Solomon Islands</option> -<option value="Somalia">Somalia</option> -<option value="South Africa">South Africa</option> -<option value="South Georgia and the South Sandwich Islands">South Georgia and the South Sandwich Islands</option> -<option value="Spain">Spain</option> -<option value="Sri Lanka">Sri Lanka</option> -<option value="Sudan">Sudan</option> -<option value="Suriname">Suriname</option> -<option value="Svalbard and Jan Mayen">Svalbard and Jan Mayen</option> -<option value="Swaziland">Swaziland</option> -<option value="Sweden">Sweden</option> -<option value="Switzerland">Switzerland</option> -<option value="Syrian Arab Republic">Syrian Arab Republic</option> -<option value="Taiwan, Province of China">Taiwan, Province of China</option> -<option value="Tajikistan">Tajikistan</option> -<option value="Tanzania, United Republic of">Tanzania, United Republic of</option> -<option value="Thailand">Thailand</option> -<option value="Timor-Leste">Timor-Leste</option> -<option value="Togo">Togo</option> -<option value="Tokelau">Tokelau</option> -<option value="Tonga">Tonga</option> -<option value="Trinidad and Tobago">Trinidad and Tobago</option> -<option value="Tunisia">Tunisia</option> -<option value="Turkey">Turkey</option> -<option value="Turkmenistan">Turkmenistan</option> -<option value="Turks and Caicos Islands">Turks and Caicos Islands</option> -<option value="Tuvalu">Tuvalu</option> -<option value="Uganda">Uganda</option> -<option value="Ukraine">Ukraine</option> -<option value="United Arab Emirates">United Arab Emirates</option> -<option value="United Kingdom">United Kingdom</option> -<option selected="selected" value="United States">United States</option> -<option value="United States Minor Outlying Islands">United States Minor Outlying Islands</option> -<option value="Uruguay">Uruguay</option> -<option value="Uzbekistan">Uzbekistan</option> -<option value="Vanuatu">Vanuatu</option> -<option value="Venezuela">Venezuela</option> -<option value="Viet Nam">Viet Nam</option> -<option value="Virgin Islands, British">Virgin Islands, British</option> -<option value="Virgin Islands, U.S.">Virgin Islands, U.S.</option> -<option value="Wallis and Futuna">Wallis and Futuna</option> -<option value="Western Sahara">Western Sahara</option> -<option value="Yemen">Yemen</option> -<option value="Zambia">Zambia</option> -<option value="Zimbabwe">Zimbabwe</option></select> -COUNTRIES - - fields_for :post, @post, :index => 325 do |f| - concat f.country_select("origin") - end - - assert_dom_equal(expected_select[0..-2], output_buffer) - end - - def test_country_select_under_fields_for_with_auto_index - @post = Post.new - @post.origin = "Iraq" - def @post.to_param; 325; end - - expected_select = <<-COUNTRIES -<select id="post_325_origin" name="post[325][origin]"><option value="Afghanistan">Afghanistan</option> -<option value="Aland Islands">Aland Islands</option> -<option value="Albania">Albania</option> -<option value="Algeria">Algeria</option> -<option value="American Samoa">American Samoa</option> -<option value="Andorra">Andorra</option> -<option value="Angola">Angola</option> -<option value="Anguilla">Anguilla</option> -<option value="Antarctica">Antarctica</option> -<option value="Antigua And Barbuda">Antigua And Barbuda</option> -<option value="Argentina">Argentina</option> -<option value="Armenia">Armenia</option> -<option value="Aruba">Aruba</option> -<option value="Australia">Australia</option> -<option value="Austria">Austria</option> -<option value="Azerbaijan">Azerbaijan</option> -<option value="Bahamas">Bahamas</option> -<option value="Bahrain">Bahrain</option> -<option value="Bangladesh">Bangladesh</option> -<option value="Barbados">Barbados</option> -<option value="Belarus">Belarus</option> -<option value="Belgium">Belgium</option> -<option value="Belize">Belize</option> -<option value="Benin">Benin</option> -<option value="Bermuda">Bermuda</option> -<option value="Bhutan">Bhutan</option> -<option value="Bolivia">Bolivia</option> -<option value="Bosnia and Herzegowina">Bosnia and Herzegowina</option> -<option value="Botswana">Botswana</option> -<option value="Bouvet Island">Bouvet Island</option> -<option value="Brazil">Brazil</option> -<option value="British Indian Ocean Territory">British Indian Ocean Territory</option> -<option value="Brunei Darussalam">Brunei Darussalam</option> -<option value="Bulgaria">Bulgaria</option> -<option value="Burkina Faso">Burkina Faso</option> -<option value="Burundi">Burundi</option> -<option value="Cambodia">Cambodia</option> -<option value="Cameroon">Cameroon</option> -<option value="Canada">Canada</option> -<option value="Cape Verde">Cape Verde</option> -<option value="Cayman Islands">Cayman Islands</option> -<option value="Central African Republic">Central African Republic</option> -<option value="Chad">Chad</option> -<option value="Chile">Chile</option> -<option value="China">China</option> -<option value="Christmas Island">Christmas Island</option> -<option value="Cocos (Keeling) Islands">Cocos (Keeling) Islands</option> -<option value="Colombia">Colombia</option> -<option value="Comoros">Comoros</option> -<option value="Congo">Congo</option> -<option value="Congo, the Democratic Republic of the">Congo, the Democratic Republic of the</option> -<option value="Cook Islands">Cook Islands</option> -<option value="Costa Rica">Costa Rica</option> -<option value="Cote d'Ivoire">Cote d'Ivoire</option> -<option value="Croatia">Croatia</option> -<option value="Cuba">Cuba</option> -<option value="Cyprus">Cyprus</option> -<option value="Czech Republic">Czech Republic</option> -<option value="Denmark">Denmark</option> -<option value="Djibouti">Djibouti</option> -<option value="Dominica">Dominica</option> -<option value="Dominican Republic">Dominican Republic</option> -<option value="Ecuador">Ecuador</option> -<option value="Egypt">Egypt</option> -<option value="El Salvador">El Salvador</option> -<option value="Equatorial Guinea">Equatorial Guinea</option> -<option value="Eritrea">Eritrea</option> -<option value="Estonia">Estonia</option> -<option value="Ethiopia">Ethiopia</option> -<option value="Falkland Islands (Malvinas)">Falkland Islands (Malvinas)</option> -<option value="Faroe Islands">Faroe Islands</option> -<option value="Fiji">Fiji</option> -<option value="Finland">Finland</option> -<option value="France">France</option> -<option value="French Guiana">French Guiana</option> -<option value="French Polynesia">French Polynesia</option> -<option value="French Southern Territories">French Southern Territories</option> -<option value="Gabon">Gabon</option> -<option value="Gambia">Gambia</option> -<option value="Georgia">Georgia</option> -<option value="Germany">Germany</option> -<option value="Ghana">Ghana</option> -<option value="Gibraltar">Gibraltar</option> -<option value="Greece">Greece</option> -<option value="Greenland">Greenland</option> -<option value="Grenada">Grenada</option> -<option value="Guadeloupe">Guadeloupe</option> -<option value="Guam">Guam</option> -<option value="Guatemala">Guatemala</option> -<option value="Guernsey">Guernsey</option> -<option value="Guinea">Guinea</option> -<option value="Guinea-Bissau">Guinea-Bissau</option> -<option value="Guyana">Guyana</option> -<option value="Haiti">Haiti</option> -<option value="Heard and McDonald Islands">Heard and McDonald Islands</option> -<option value="Holy See (Vatican City State)">Holy See (Vatican City State)</option> -<option value="Honduras">Honduras</option> -<option value="Hong Kong">Hong Kong</option> -<option value="Hungary">Hungary</option> -<option value="Iceland">Iceland</option> -<option value="India">India</option> -<option value="Indonesia">Indonesia</option> -<option value="Iran, Islamic Republic of">Iran, Islamic Republic of</option> -<option selected="selected" value="Iraq">Iraq</option> -<option value="Ireland">Ireland</option> -<option value="Isle of Man">Isle of Man</option> -<option value="Israel">Israel</option> -<option value="Italy">Italy</option> -<option value="Jamaica">Jamaica</option> -<option value="Japan">Japan</option> -<option value="Jersey">Jersey</option> -<option value="Jordan">Jordan</option> -<option value="Kazakhstan">Kazakhstan</option> -<option value="Kenya">Kenya</option> -<option value="Kiribati">Kiribati</option> -<option value="Korea, Democratic People's Republic of">Korea, Democratic People's Republic of</option> -<option value="Korea, Republic of">Korea, Republic of</option> -<option value="Kuwait">Kuwait</option> -<option value="Kyrgyzstan">Kyrgyzstan</option> -<option value="Lao People's Democratic Republic">Lao People's Democratic Republic</option> -<option value="Latvia">Latvia</option> -<option value="Lebanon">Lebanon</option> -<option value="Lesotho">Lesotho</option> -<option value="Liberia">Liberia</option> -<option value="Libyan Arab Jamahiriya">Libyan Arab Jamahiriya</option> -<option value="Liechtenstein">Liechtenstein</option> -<option value="Lithuania">Lithuania</option> -<option value="Luxembourg">Luxembourg</option> -<option value="Macao">Macao</option> -<option value="Macedonia, The Former Yugoslav Republic Of">Macedonia, The Former Yugoslav Republic Of</option> -<option value="Madagascar">Madagascar</option> -<option value="Malawi">Malawi</option> -<option value="Malaysia">Malaysia</option> -<option value="Maldives">Maldives</option> -<option value="Mali">Mali</option> -<option value="Malta">Malta</option> -<option value="Marshall Islands">Marshall Islands</option> -<option value="Martinique">Martinique</option> -<option value="Mauritania">Mauritania</option> -<option value="Mauritius">Mauritius</option> -<option value="Mayotte">Mayotte</option> -<option value="Mexico">Mexico</option> -<option value="Micronesia, Federated States of">Micronesia, Federated States of</option> -<option value="Moldova, Republic of">Moldova, Republic of</option> -<option value="Monaco">Monaco</option> -<option value="Mongolia">Mongolia</option> -<option value="Montenegro">Montenegro</option> -<option value="Montserrat">Montserrat</option> -<option value="Morocco">Morocco</option> -<option value="Mozambique">Mozambique</option> -<option value="Myanmar">Myanmar</option> -<option value="Namibia">Namibia</option> -<option value="Nauru">Nauru</option> -<option value="Nepal">Nepal</option> -<option value="Netherlands">Netherlands</option> -<option value="Netherlands Antilles">Netherlands Antilles</option> -<option value="New Caledonia">New Caledonia</option> -<option value="New Zealand">New Zealand</option> -<option value="Nicaragua">Nicaragua</option> -<option value="Niger">Niger</option> -<option value="Nigeria">Nigeria</option> -<option value="Niue">Niue</option> -<option value="Norfolk Island">Norfolk Island</option> -<option value="Northern Mariana Islands">Northern Mariana Islands</option> -<option value="Norway">Norway</option> -<option value="Oman">Oman</option> -<option value="Pakistan">Pakistan</option> -<option value="Palau">Palau</option> -<option value="Palestinian Territory, Occupied">Palestinian Territory, Occupied</option> -<option value="Panama">Panama</option> -<option value="Papua New Guinea">Papua New Guinea</option> -<option value="Paraguay">Paraguay</option> -<option value="Peru">Peru</option> -<option value="Philippines">Philippines</option> -<option value="Pitcairn">Pitcairn</option> -<option value="Poland">Poland</option> -<option value="Portugal">Portugal</option> -<option value="Puerto Rico">Puerto Rico</option> -<option value="Qatar">Qatar</option> -<option value="Reunion">Reunion</option> -<option value="Romania">Romania</option> -<option value="Russian Federation">Russian Federation</option> -<option value="Rwanda">Rwanda</option> -<option value="Saint Barthelemy">Saint Barthelemy</option> -<option value="Saint Helena">Saint Helena</option> -<option value="Saint Kitts and Nevis">Saint Kitts and Nevis</option> -<option value="Saint Lucia">Saint Lucia</option> -<option value="Saint Pierre and Miquelon">Saint Pierre and Miquelon</option> -<option value="Saint Vincent and the Grenadines">Saint Vincent and the Grenadines</option> -<option value="Samoa">Samoa</option> -<option value="San Marino">San Marino</option> -<option value="Sao Tome and Principe">Sao Tome and Principe</option> -<option value="Saudi Arabia">Saudi Arabia</option> -<option value="Senegal">Senegal</option> -<option value="Serbia">Serbia</option> -<option value="Seychelles">Seychelles</option> -<option value="Sierra Leone">Sierra Leone</option> -<option value="Singapore">Singapore</option> -<option value="Slovakia">Slovakia</option> -<option value="Slovenia">Slovenia</option> -<option value="Solomon Islands">Solomon Islands</option> -<option value="Somalia">Somalia</option> -<option value="South Africa">South Africa</option> -<option value="South Georgia and the South Sandwich Islands">South Georgia and the South Sandwich Islands</option> -<option value="Spain">Spain</option> -<option value="Sri Lanka">Sri Lanka</option> -<option value="Sudan">Sudan</option> -<option value="Suriname">Suriname</option> -<option value="Svalbard and Jan Mayen">Svalbard and Jan Mayen</option> -<option value="Swaziland">Swaziland</option> -<option value="Sweden">Sweden</option> -<option value="Switzerland">Switzerland</option> -<option value="Syrian Arab Republic">Syrian Arab Republic</option> -<option value="Taiwan, Province of China">Taiwan, Province of China</option> -<option value="Tajikistan">Tajikistan</option> -<option value="Tanzania, United Republic of">Tanzania, United Republic of</option> -<option value="Thailand">Thailand</option> -<option value="Timor-Leste">Timor-Leste</option> -<option value="Togo">Togo</option> -<option value="Tokelau">Tokelau</option> -<option value="Tonga">Tonga</option> -<option value="Trinidad and Tobago">Trinidad and Tobago</option> -<option value="Tunisia">Tunisia</option> -<option value="Turkey">Turkey</option> -<option value="Turkmenistan">Turkmenistan</option> -<option value="Turks and Caicos Islands">Turks and Caicos Islands</option> -<option value="Tuvalu">Tuvalu</option> -<option value="Uganda">Uganda</option> -<option value="Ukraine">Ukraine</option> -<option value="United Arab Emirates">United Arab Emirates</option> -<option value="United Kingdom">United Kingdom</option> -<option value="United States">United States</option> -<option value="United States Minor Outlying Islands">United States Minor Outlying Islands</option> -<option value="Uruguay">Uruguay</option> -<option value="Uzbekistan">Uzbekistan</option> -<option value="Vanuatu">Vanuatu</option> -<option value="Venezuela">Venezuela</option> -<option value="Viet Nam">Viet Nam</option> -<option value="Virgin Islands, British">Virgin Islands, British</option> -<option value="Virgin Islands, U.S.">Virgin Islands, U.S.</option> -<option value="Wallis and Futuna">Wallis and Futuna</option> -<option value="Western Sahara">Western Sahara</option> -<option value="Yemen">Yemen</option> -<option value="Zambia">Zambia</option> -<option value="Zimbabwe">Zimbabwe</option></select> -COUNTRIES - - fields_for "post[]", @post do |f| - concat f.country_select("origin") - end - - assert_dom_equal(expected_select[0..-2], output_buffer) - end - -end
\ No newline at end of file diff --git a/actionpack/test/template/render_test.rb b/actionpack/test/template/render_test.rb index f3c8dbcae9..a4ea22ddcb 100644 --- a/actionpack/test/template/render_test.rb +++ b/actionpack/test/template/render_test.rb @@ -70,7 +70,23 @@ class ViewRenderTest < Test::Unit::TestCase end def test_render_partial_with_errors - assert_raise(ActionView::TemplateError) { @view.render(:partial => "test/raise") } + @view.render(:partial => "test/raise") + flunk "Render did not raise TemplateError" + rescue ActionView::TemplateError => e + assert_match "undefined local variable or method `doesnt_exist'", e.message + assert_equal "", e.sub_template_message + assert_equal "1", e.line_number + assert_equal File.expand_path("#{FIXTURE_LOAD_PATH}/test/_raise.html.erb"), e.file_name + end + + def test_render_sub_template_with_errors + @view.render(:file => "test/sub_template_raise") + flunk "Render did not raise TemplateError" + rescue ActionView::TemplateError => e + assert_match "undefined local variable or method `doesnt_exist'", e.message + assert_equal "Trace of template inclusion: #{File.expand_path("#{FIXTURE_LOAD_PATH}/test/sub_template_raise.html.erb")}", e.sub_template_message + assert_equal "1", e.line_number + assert_equal File.expand_path("#{FIXTURE_LOAD_PATH}/test/_raise.html.erb"), e.file_name end def test_render_partial_collection diff --git a/activerecord/CHANGELOG b/activerecord/CHANGELOG index 5bcc7ad3a9..6479cc5a9b 100644 --- a/activerecord/CHANGELOG +++ b/activerecord/CHANGELOG @@ -1,5 +1,13 @@ *Edge* +* Add Model#delete instance method, similar to Model.delete class method. #1086 [Hongli Lai] + +* MySQL: cope with quirky default values for not-null text columns. #1043 [Frederick Cheung] + +* Multiparameter attributes skip time zone conversion for time-only columns [#1030 state:resolved] [Geoff Buesing] + +* Base.skip_time_zone_conversion_for_attributes uses class_inheritable_accessor, so that subclasses don't overwrite Base [#346 state:resolved] [miloops] + * Added find_last_by dynamic finder #762 [miloops] * Internal API: configurable association options and build_association method for reflections so plugins may extend and override. #985 [Hongli Lai] diff --git a/activerecord/lib/active_record.rb b/activerecord/lib/active_record.rb index a6bbd6fc82..219cd30f94 100644 --- a/activerecord/lib/active_record.rb +++ b/activerecord/lib/active_record.rb @@ -77,5 +77,5 @@ require 'active_record/connection_adapters/abstract_adapter' require 'active_record/schema_dumper' -I18n.load_translations File.dirname(__FILE__) + '/active_record/locale/en-US.yml' - +require 'active_record/i18n_interpolation_deprecation' +I18n.load_path << File.dirname(__FILE__) + '/active_record/locale/en-US.yml' diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb index 33457822ff..4d36216c34 100755 --- a/activerecord/lib/active_record/associations.rb +++ b/activerecord/lib/active_record/associations.rb @@ -1026,7 +1026,7 @@ module ActiveRecord # Create the callbacks to update counter cache if options[:counter_cache] cache_column = options[:counter_cache] == true ? - "#{self.to_s.underscore.pluralize}_count" : + "#{self.to_s.demodulize.underscore.pluralize}_count" : options[:counter_cache] method_name = "belongs_to_counter_cache_after_create_for_#{reflection.name}".to_sym @@ -1268,7 +1268,11 @@ module ActiveRecord if association_proxy_class == BelongsToAssociation define_method("#{reflection.primary_key_name}=") do |target_id| - instance_variable_get(ivar).reset if instance_variable_defined?(ivar) + if instance_variable_defined?(ivar) + if association = instance_variable_get(ivar) + association.reset + end + end write_attribute(reflection.primary_key_name, target_id) end end @@ -1424,15 +1428,23 @@ module ActiveRecord [] end + # Creates before_destroy callback methods that nullify, delete or destroy + # has_many associated objects, according to the defined :dependent rule. + # # See HasManyAssociation#delete_records. Dependent associations # delete children, otherwise foreign key is set to NULL. - def configure_dependency_for_has_many(reflection) + # + # The +extra_conditions+ parameter, which is not used within the main + # Active Record codebase, is meant to allow plugins to define extra + # finder conditions. + def configure_dependency_for_has_many(reflection, extra_conditions = nil) if reflection.options.include?(:dependent) # Add polymorphic type if the :as option is present dependent_conditions = [] dependent_conditions << "#{reflection.primary_key_name} = \#{record.quoted_id}" dependent_conditions << "#{reflection.options[:as]}_type = '#{base_class.name}'" if reflection.options[:as] dependent_conditions << sanitize_sql(reflection.options[:conditions]) if reflection.options[:conditions] + dependent_conditions << extra_conditions if extra_conditions dependent_conditions = dependent_conditions.collect {|where| "(#{where})" }.join(" AND ") case reflection.options[:dependent] @@ -1443,9 +1455,24 @@ module ActiveRecord end before_destroy method_name when :delete_all - module_eval "before_destroy { |record| #{reflection.class_name}.delete_all(%(#{dependent_conditions})) }" + module_eval %Q{ + before_destroy do |record| + delete_all_has_many_dependencies(record, + "#{reflection.name}", + #{reflection.class_name}, + "#{dependent_conditions}") + end + } when :nullify - module_eval "before_destroy { |record| #{reflection.class_name}.update_all(%(#{reflection.primary_key_name} = NULL), %(#{dependent_conditions})) }" + module_eval %Q{ + before_destroy do |record| + nullify_has_many_dependencies(record, + "#{reflection.name}", + #{reflection.class_name}, + "#{reflection.primary_key_name}", + "#{dependent_conditions}") + end + } else raise ArgumentError, "The :dependent option expects either :destroy, :delete_all, or :nullify (#{reflection.options[:dependent].inspect})" end @@ -1472,7 +1499,7 @@ module ActiveRecord # with foreign keys pointing to this object, and we only want # to delete the correct one, not all of them. association = send(reflection.name) - association.class.delete(association.id) unless association.nil? + association.delete unless association.nil? end before_destroy method_name when :nullify @@ -1502,7 +1529,7 @@ module ActiveRecord method_name = "belongs_to_dependent_delete_for_#{reflection.name}".to_sym define_method(method_name) do association = send(reflection.name) - association.class.delete(association.id) unless association.nil? + association.delete unless association.nil? end before_destroy method_name else @@ -1511,6 +1538,14 @@ module ActiveRecord end end + def delete_all_has_many_dependencies(record, reflection_name, association_class, dependent_conditions) + association_class.delete_all(dependent_conditions) + end + + def nullify_has_many_dependencies(record, reflection_name, association_class, primary_key_name, dependent_conditions) + association_class.update_all("#{primary_key_name} = NULL", dependent_conditions) + end + mattr_accessor :valid_keys_for_has_many_association @@valid_keys_for_has_many_association = [ :class_name, :table_name, :foreign_key, :primary_key, @@ -1757,12 +1792,12 @@ module ActiveRecord def create_extension_modules(association_id, block_extension, extensions) if block_extension - extension_module_name = "#{self.to_s}#{association_id.to_s.camelize}AssociationExtension" + extension_module_name = "#{self.to_s.demodulize}#{association_id.to_s.camelize}AssociationExtension" silence_warnings do - Object.const_set(extension_module_name, Module.new(&block_extension)) + self.parent.const_set(extension_module_name, Module.new(&block_extension)) end - Array(extensions).push(extension_module_name.constantize) + Array(extensions).push("#{self.parent}::#{extension_module_name}".constantize) else Array(extensions) end diff --git a/activerecord/lib/active_record/associations/association_collection.rb b/activerecord/lib/active_record/associations/association_collection.rb index 8de528f638..463de9d819 100644 --- a/activerecord/lib/active_record/associations/association_collection.rb +++ b/activerecord/lib/active_record/associations/association_collection.rb @@ -63,7 +63,7 @@ module ActiveRecord # Fetches the first one using SQL if possible. def first(*args) - if fetch_first_or_last_using_find? args + if fetch_first_or_last_using_find?(args) find(:first, *args) else load_target unless loaded? @@ -73,7 +73,7 @@ module ActiveRecord # Fetches the last one using SQL if possible. def last(*args) - if fetch_first_or_last_using_find? args + if fetch_first_or_last_using_find?(args) find(:last, *args) else load_target unless loaded? @@ -108,7 +108,7 @@ module ActiveRecord result = true load_target if @owner.new_record? - @owner.transaction do + transaction do flatten_deeper(records).each do |record| raise_on_type_mismatch(record) add_record_to_target_with_callbacks(record) do |r| @@ -123,6 +123,21 @@ module ActiveRecord alias_method :push, :<< alias_method :concat, :<< + # Starts a transaction in the association class's database connection. + # + # class Author < ActiveRecord::Base + # has_many :books + # end + # + # Author.find(:first).books.transaction do + # # same effect as calling Book.transaction + # end + def transaction(*args) + @reflection.klass.transaction(*args) do + yield + end + end + # Remove all records from this association def delete_all load_target @@ -173,7 +188,7 @@ module ActiveRecord records = flatten_deeper(records) records.each { |record| raise_on_type_mismatch(record) } - @owner.transaction do + transaction do records.each { |record| callback(:before_remove, record) } old_records = records.reject {|r| r.new_record? } @@ -200,7 +215,7 @@ module ActiveRecord end def destroy_all - @owner.transaction do + transaction do each { |record| record.destroy } end @@ -238,6 +253,8 @@ module ActiveRecord def size if @owner.new_record? || (loaded? && !@reflection.options[:uniq]) @target.size + elsif !loaded? && @reflection.options[:group] + load_target.size elsif !loaded? && !@reflection.options[:uniq] && @target.is_a?(Array) unsaved_records = @target.select { |r| r.new_record? } unsaved_records.size + count_records @@ -290,7 +307,7 @@ module ActiveRecord other = other_array.size < 100 ? other_array : other_array.to_set current = @target.size < 100 ? @target : @target.to_set - @owner.transaction do + transaction do delete(@target.select { |v| !other.include?(v) }) concat(other_array.select { |v| !current.include?(v) }) end @@ -418,7 +435,8 @@ module ActiveRecord end def fetch_first_or_last_using_find?(args) - args.first.kind_of?(Hash) || !(loaded? || @owner.new_record? || @reflection.options[:finder_sql] || !@target.blank? || args.first.kind_of?(Integer)) + args.first.kind_of?(Hash) || !(loaded? || @owner.new_record? || @reflection.options[:finder_sql] || + @target.any? { |record| record.new_record? } || args.first.kind_of?(Integer)) end end end diff --git a/activerecord/lib/active_record/associations/has_many_association.rb b/activerecord/lib/active_record/associations/has_many_association.rb index dda22668c6..3b2f306637 100644 --- a/activerecord/lib/active_record/associations/has_many_association.rb +++ b/activerecord/lib/active_record/associations/has_many_association.rb @@ -17,7 +17,10 @@ module ActiveRecord # Returns the number of records in this collection. # # If the association has a counter cache it gets that value. Otherwise - # a count via SQL is performed, bounded to <tt>:limit</tt> if there's one. + # it will attempt to do a count via SQL, bounded to <tt>:limit</tt> if + # there's one. Some configuration options like :group make it impossible + # to do a SQL count, in those cases the array count will be used. + # # That does not depend on whether the collection has already been loaded # or not. The +size+ method is the one that takes the loaded flag into # account and delegates to +count_records+ if needed. diff --git a/activerecord/lib/active_record/associations/has_many_through_association.rb b/activerecord/lib/active_record/associations/has_many_through_association.rb index ebd2bf768c..3171665e19 100644 --- a/activerecord/lib/active_record/associations/has_many_through_association.rb +++ b/activerecord/lib/active_record/associations/has_many_through_association.rb @@ -9,14 +9,14 @@ module ActiveRecord alias_method :new, :build def create!(attrs = nil) - @reflection.klass.transaction do + transaction do self << (object = attrs ? @reflection.klass.send(:with_scope, :create => attrs) { @reflection.create_association! } : @reflection.create_association!) object end end def create(attrs = nil) - @reflection.klass.transaction do + transaction do self << (object = attrs ? @reflection.klass.send(:with_scope, :create => attrs) { @reflection.create_association } : @reflection.create_association) object end diff --git a/activerecord/lib/active_record/attribute_methods.rb b/activerecord/lib/active_record/attribute_methods.rb index 0a1baff87d..e5486738f0 100644 --- a/activerecord/lib/active_record/attribute_methods.rb +++ b/activerecord/lib/active_record/attribute_methods.rb @@ -10,7 +10,7 @@ module ActiveRecord base.attribute_types_cached_by_default = ATTRIBUTE_TYPES_CACHED_BY_DEFAULT base.cattr_accessor :time_zone_aware_attributes, :instance_writer => false base.time_zone_aware_attributes = false - base.cattr_accessor :skip_time_zone_conversion_for_attributes, :instance_writer => false + base.class_inheritable_accessor :skip_time_zone_conversion_for_attributes, :instance_writer => false base.skip_time_zone_conversion_for_attributes = [] end @@ -232,6 +232,10 @@ module ActiveRecord def method_missing(method_id, *args, &block) method_name = method_id.to_s + if self.class.private_method_defined?(method_name) + raise NoMethodError("Attempt to call private method", method_name, args) + end + # If we haven't generated any methods yet, generate them, then # see if we've created the method we're looking for. if !self.class.generated_methods? @@ -334,10 +338,12 @@ module ActiveRecord # <tt>person.respond_to?(:name=)</tt>, and <tt>person.respond_to?(:name?)</tt> # which will all return +true+. alias :respond_to_without_attributes? :respond_to? - def respond_to?(method, include_priv = false) + def respond_to?(method, include_private_methods = false) method_name = method.to_s if super return true + elsif self.private_methods.include?(method_name) && !include_private_methods + return false elsif !self.class.generated_methods? self.class.define_attribute_methods if self.class.generated_methods.include?(method_name) diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb index c0c9b8a9b3..ac15eed408 100755 --- a/activerecord/lib/active_record/base.rb +++ b/activerecord/lib/active_record/base.rb @@ -1632,19 +1632,19 @@ module ActiveRecord #:nodoc: (safe_to_array(first) + safe_to_array(second)).uniq end - def merge_joins(first, second) - if first.is_a?(String) && second.is_a?(String) - "#{first} #{second}" - elsif first.is_a?(String) || second.is_a?(String) - if first.is_a?(String) - join_dependency = ActiveRecord::Associations::ClassMethods::InnerJoinDependency.new(self, second, nil) - "#{first} #{join_dependency.join_associations.collect { |assoc| assoc.association_join }.join}" - else - join_dependency = ActiveRecord::Associations::ClassMethods::InnerJoinDependency.new(self, first, nil) - "#{join_dependency.join_associations.collect { |assoc| assoc.association_join }.join} #{second}" + def merge_joins(*joins) + if joins.any?{|j| j.is_a?(String) || array_of_strings?(j) } + joins = joins.collect do |join| + join = [join] if join.is_a?(String) + unless array_of_strings?(join) + join_dependency = ActiveRecord::Associations::ClassMethods::InnerJoinDependency.new(self, join, nil) + join = join_dependency.join_associations.collect { |assoc| assoc.association_join } + end + join end + joins.flatten.uniq else - (safe_to_array(first) + safe_to_array(second)).uniq + joins.collect{|j| safe_to_array(j)}.flatten.uniq end end @@ -1660,6 +1660,10 @@ module ActiveRecord #:nodoc: end end + def array_of_strings?(o) + o.is_a?(Array) && o.all?{|obj| obj.is_a?(String)} + end + def add_order!(sql, order, scope = :auto) scope = scope(:find) if :auto == scope scoped_order = scope[:order] if scope @@ -1708,8 +1712,12 @@ module ActiveRecord #:nodoc: merged_joins = scope && scope[:joins] && joins ? merge_joins(scope[:joins], joins) : (joins || scope && scope[:joins]) case merged_joins when Symbol, Hash, Array - join_dependency = ActiveRecord::Associations::ClassMethods::InnerJoinDependency.new(self, merged_joins, nil) - sql << " #{join_dependency.join_associations.collect { |assoc| assoc.association_join }.join} " + if array_of_strings?(merged_joins) + sql << merged_joins.join(' ') + " " + else + join_dependency = ActiveRecord::Associations::ClassMethods::InnerJoinDependency.new(self, merged_joins, nil) + sql << " #{join_dependency.join_associations.collect { |assoc| assoc.association_join }.join} " + end when String sql << " #{merged_joins} " end @@ -2387,8 +2395,18 @@ module ActiveRecord #:nodoc: # Deletes the record in the database and freezes this instance to reflect that no changes should # be made (since they can't be persisted). # + # Unlike #destroy, this method doesn't run any +before_delete+ and +after_delete+ + # callbacks, nor will it enforce any association +:dependent+ rules. + # # In addition to deleting this record, any defined +before_delete+ and +after_delete+ # callbacks are run, and +:dependent+ rules defined on associations are run. + def delete + self.class.delete(id) unless new_record? + freeze + end + + # Deletes the record in the database and freezes this instance to reflect that no changes should + # be made (since they can't be persisted). def destroy unless new_record? connection.delete <<-end_sql, "#{self.class.name} Destroy" @@ -2828,7 +2846,7 @@ module ActiveRecord #:nodoc: end def instantiate_time_object(name, values) - if self.class.time_zone_aware_attributes && !self.class.skip_time_zone_conversion_for_attributes.include?(name.to_sym) + if self.class.send(:create_time_zone_conversion_attribute?, name, column_for_attribute(name)) Time.zone.local(*values) else Time.time_with_datetime_fallback(@@default_timezone, *values) diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb index 22304edfc9..58992f91da 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb @@ -40,6 +40,10 @@ module ActiveRecord type == :integer || type == :float || type == :decimal end + def has_default? + !default.nil? + end + # Returns the Ruby class that corresponds to the abstract data type. def klass case type diff --git a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb index c2a0fb72bf..a26fd02b90 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb @@ -80,7 +80,7 @@ module ActiveRecord def extract_default(default) if type == :binary || type == :text if default.blank? - nil + return null ? nil : '' else raise ArgumentError, "#{type} columns cannot have a default value: #{default.inspect}" end @@ -91,6 +91,11 @@ module ActiveRecord end end + def has_default? + return false if type == :binary || type == :text #mysql forbids defaults on blob and text columns + super + end + private def simplified_type(field_type) return :boolean if MysqlAdapter.emulate_booleans && field_type.downcase.index("tinyint(1)") diff --git a/activerecord/lib/active_record/i18n_interpolation_deprecation.rb b/activerecord/lib/active_record/i18n_interpolation_deprecation.rb new file mode 100644 index 0000000000..cd634e1b8d --- /dev/null +++ b/activerecord/lib/active_record/i18n_interpolation_deprecation.rb @@ -0,0 +1,26 @@ +# Deprecates the use of the former message interpolation syntax in activerecord +# as in "must have %d characters". The new syntax uses explicit variable names +# as in "{{value}} must have {{count}} characters". + +require 'i18n/backend/simple' +module I18n + module Backend + class Simple + DEPRECATED_INTERPOLATORS = { '%d' => '{{count}}', '%s' => '{{value}}' } + + protected + def interpolate_with_deprecated_syntax(locale, string, values = {}) + return string unless string.is_a?(String) + + string = string.gsub(/%d|%s/) do |s| + instead = DEPRECATED_INTERPOLATORS[s] + ActiveSupport::Deprecation.warn "using #{s} in messages is deprecated; use #{instead} instead." + instead + end + + interpolate_without_deprecated_syntax(locale, string, values) + end + alias_method_chain :interpolate, :deprecated_syntax + end + end +end
\ No newline at end of file diff --git a/activerecord/lib/active_record/schema_dumper.rb b/activerecord/lib/active_record/schema_dumper.rb index b90ed88c6b..4f96e225c1 100644 --- a/activerecord/lib/active_record/schema_dumper.rb +++ b/activerecord/lib/active_record/schema_dumper.rb @@ -102,7 +102,7 @@ HEADER spec[:precision] = column.precision.inspect if !column.precision.nil? spec[:scale] = column.scale.inspect if !column.scale.nil? spec[:null] = 'false' if !column.null - spec[:default] = default_string(column.default) if !column.default.nil? + spec[:default] = default_string(column.default) if column.has_default? (spec.keys - [:name, :type]).each{ |k| spec[k].insert(0, "#{k.inspect} => ")} spec end.compact diff --git a/activerecord/lib/active_record/validations.rb b/activerecord/lib/active_record/validations.rb index 8481706074..9220eae4d1 100644 --- a/activerecord/lib/active_record/validations.rb +++ b/activerecord/lib/active_record/validations.rb @@ -472,7 +472,7 @@ module ActiveRecord db_cols = begin column_names - rescue ActiveRecord::StatementInvalid + rescue Exception # To ignore both statement and connection errors [] end names = attr_names.reject { |name| db_cols.include?(name.to_s) } @@ -738,7 +738,7 @@ module ActiveRecord condition_params = [value] else condition_sql = "LOWER(#{sql_attribute}) #{comparison_operator}" - condition_params = [value.chars.downcase] + condition_params = [value.mb_chars.downcase] end if scope = configuration[:scope] diff --git a/activerecord/lib/active_record/version.rb b/activerecord/lib/active_record/version.rb index aaadef9979..2479b75789 100644 --- a/activerecord/lib/active_record/version.rb +++ b/activerecord/lib/active_record/version.rb @@ -1,7 +1,7 @@ module ActiveRecord module VERSION #:nodoc: MAJOR = 2 - MINOR = 1 + MINOR = 2 TINY = 0 STRING = [MAJOR, MINOR, TINY].join('.') diff --git a/activerecord/test/cases/associations/extension_test.rb b/activerecord/test/cases/associations/extension_test.rb index 5c01c3c1f5..9390633d5b 100644 --- a/activerecord/test/cases/associations/extension_test.rb +++ b/activerecord/test/cases/associations/extension_test.rb @@ -3,6 +3,7 @@ require 'models/post' require 'models/comment' require 'models/project' require 'models/developer' +require 'models/company_in_module' class AssociationsExtensionsTest < ActiveRecord::TestCase fixtures :projects, :developers, :developers_projects, :comments, :posts @@ -44,4 +45,18 @@ class AssociationsExtensionsTest < ActiveRecord::TestCase david = Marshal.load(Marshal.dump(david)) assert_equal projects(:action_controller), david.projects_extended_by_name.find_most_recent end + + + def test_extension_name + extension = Proc.new {} + name = :association_name + + assert_equal 'DeveloperAssociationNameAssociationExtension', Developer.send(:create_extension_modules, name, extension, []).first.name + assert_equal 'MyApplication::Business::DeveloperAssociationNameAssociationExtension', +MyApplication::Business::Developer.send(:create_extension_modules, name, extension, []).first.name + assert_equal 'MyApplication::Business::DeveloperAssociationNameAssociationExtension', MyApplication::Business::Developer.send(:create_extension_modules, name, extension, []).first.name + assert_equal 'MyApplication::Business::DeveloperAssociationNameAssociationExtension', MyApplication::Business::Developer.send(:create_extension_modules, name, extension, []).first.name + end + + end diff --git a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb index 9981f4c5d5..2949f1d304 100644 --- a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb @@ -253,7 +253,7 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase assert !devel.projects.loaded? assert_equal devel.projects.last, proj - assert devel.projects.loaded? + assert !devel.projects.loaded? assert !proj.new_record? assert_equal Developer.find(1).projects.sort_by(&:id).last, proj # prove join table is updated @@ -738,4 +738,13 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase # Array#count in Ruby >=1.8.7, which would raise an ArgumentError assert_nothing_raised { david.projects.count(:all, :conditions => '1=1') } end + + uses_mocha 'mocking Post.transaction' do + def test_association_proxy_transaction_method_starts_transaction_in_association_class + Post.expects(:transaction) + Category.find(:first).posts.transaction do + # nothing + end + end + end end diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index 5bcbc5eb5b..315d77de07 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -249,7 +249,9 @@ class HasManyAssociationsTest < ActiveRecord::TestCase end def test_find_scoped_grouped + assert_equal 1, companies(:first_firm).clients_grouped_by_firm_id.size assert_equal 1, companies(:first_firm).clients_grouped_by_firm_id.length + assert_equal 2, companies(:first_firm).clients_grouped_by_name.size assert_equal 2, companies(:first_firm).clients_grouped_by_name.length end @@ -1007,6 +1009,19 @@ class HasManyAssociationsTest < ActiveRecord::TestCase assert firm.clients.loaded? end + def test_calling_first_or_last_on_existing_record_with_create_should_not_load_association + firm = companies(:first_firm) + firm.clients.create(:name => 'Foo') + assert !firm.clients.loaded? + + assert_queries 2 do + firm.clients.first + firm.clients.last + end + + assert !firm.clients.loaded? + end + def test_calling_first_or_last_on_new_record_should_not_run_queries firm = Firm.new @@ -1056,4 +1071,13 @@ class HasManyAssociationsTest < ActiveRecord::TestCase ActiveRecord::Base.store_full_sti_class = old end + uses_mocha 'mocking Comment.transaction' do + def test_association_proxy_transaction_method_starts_transaction_in_association_class + Comment.expects(:transaction) + Post.find(:first).comments.transaction do + # nothing + end + end + end + end diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb index 0be050ec81..12cce98c26 100644 --- a/activerecord/test/cases/associations/has_many_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb @@ -220,4 +220,13 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase assert_equal [posts(:welcome).id, posts(:authorless).id].sort, person.post_ids.sort assert !person.posts.loaded? end + + uses_mocha 'mocking Tag.transaction' do + def test_association_proxy_transaction_method_starts_transaction_in_association_class + Tag.expects(:transaction) + Post.find(:first).tags.transaction do + # nothing + end + end + end end diff --git a/activerecord/test/cases/associations_test.rb b/activerecord/test/cases/associations_test.rb index 2050d16179..cde451de0e 100644 --- a/activerecord/test/cases/associations_test.rb +++ b/activerecord/test/cases/associations_test.rb @@ -194,6 +194,14 @@ class AssociationProxyTest < ActiveRecord::TestCase assert_equal david, welcome.author end + def test_assigning_association_id_after_reload + welcome = posts(:welcome) + welcome.reload + assert_nothing_raised do + welcome.author_id = authors(:david).id + end + end + def test_reload_returns_assocition david = developers(:david) assert_nothing_raised do diff --git a/activerecord/test/cases/attribute_methods_test.rb b/activerecord/test/cases/attribute_methods_test.rb index 7999e29264..160716f944 100644 --- a/activerecord/test/cases/attribute_methods_test.rb +++ b/activerecord/test/cases/attribute_methods_test.rb @@ -1,5 +1,6 @@ require "cases/helper" require 'models/topic' +require 'models/minimalistic' class AttributeMethodsTest < ActiveRecord::TestCase fixtures :topics @@ -57,19 +58,19 @@ class AttributeMethodsTest < ActiveRecord::TestCase def test_kernel_methods_not_implemented_in_activerecord %w(test name display y).each do |method| - assert_equal false, ActiveRecord::Base.instance_method_already_implemented?(method), "##{method} is defined" + assert !ActiveRecord::Base.instance_method_already_implemented?(method), "##{method} is defined" end end def test_primary_key_implemented - assert_equal true, Class.new(ActiveRecord::Base).instance_method_already_implemented?('id') + assert Class.new(ActiveRecord::Base).instance_method_already_implemented?('id') end def test_defined_kernel_methods_implemented_in_model %w(test name display y).each do |method| klass = Class.new ActiveRecord::Base klass.class_eval "def #{method}() 'defined #{method}' end" - assert_equal true, klass.instance_method_already_implemented?(method), "##{method} is not defined" + assert klass.instance_method_already_implemented?(method), "##{method} is not defined" end end @@ -79,7 +80,7 @@ class AttributeMethodsTest < ActiveRecord::TestCase abstract.class_eval "def #{method}() 'defined #{method}' end" abstract.abstract_class = true klass = Class.new abstract - assert_equal true, klass.instance_method_already_implemented?(method), "##{method} is not defined" + assert klass.instance_method_already_implemented?(method), "##{method} is not defined" end end @@ -219,6 +220,48 @@ class AttributeMethodsTest < ActiveRecord::TestCase end end + def test_setting_time_zone_conversion_for_attributes_should_write_value_on_class_variable + Topic.skip_time_zone_conversion_for_attributes = [:field_a] + Minimalistic.skip_time_zone_conversion_for_attributes = [:field_b] + + assert_equal [:field_a], Topic.skip_time_zone_conversion_for_attributes + assert_equal [:field_b], Minimalistic.skip_time_zone_conversion_for_attributes + end + + def test_read_attributes_respect_access_control + privatize("title") + + topic = @target.new(:title => "The pros and cons of programming naked.") + assert !topic.respond_to?(:title) + assert_raise(NoMethodError) { topic.title } + topic.send(:title) + end + + def test_write_attributes_respect_access_control + privatize("title=(value)") + + topic = @target.new + assert !topic.respond_to?(:title=) + assert_raise(NoMethodError) { topic.title = "Pants"} + topic.send(:title=, "Very large pants") + end + + def test_question_attributes_respect_access_control + privatize("title?") + + topic = @target.new(:title => "Isaac Newton's pants") + assert !topic.respond_to?(:title?) + assert_raise(NoMethodError) { topic.title? } + assert topic.send(:title?) + end + + def test_bulk_update_respects_access_control + privatize("title=(value)") + + assert_raise(ActiveRecord::UnknownAttributeError) { topic = @target.new(:title => "Rants about pants") } + assert_raise(ActiveRecord::UnknownAttributeError) { @target.new.attributes = { :title => "Ants in pants" } } + end + private def time_related_columns_on_topic Topic.columns.select{|c| [:time, :date, :datetime, :timestamp].include?(c.type)}.map(&:name) @@ -235,4 +278,13 @@ class AttributeMethodsTest < ActiveRecord::TestCase Time.zone = old_zone ActiveRecord::Base.time_zone_aware_attributes = old_tz end + + def privatize(method_signature) + @target.class_eval <<-private_method + private + def #{method_signature} + "I'm private" + end + private_method + end end diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb index bda6f346f0..d512834237 100644..100755 --- a/activerecord/test/cases/base_test.rb +++ b/activerecord/test/cases/base_test.rb @@ -472,6 +472,18 @@ class BasicsTest < ActiveRecord::TestCase assert topic.instance_variable_get("@custom_approved") end + def test_delete + topic = Topic.find(1) + assert_equal topic, topic.delete, 'topic.delete did not return self' + assert topic.frozen?, 'topic not frozen after delete' + assert_raise(ActiveRecord::RecordNotFound) { Topic.find(topic.id) } + end + + def test_delete_doesnt_run_callbacks + Topic.find(1).delete + assert_not_nil Topic.find(2) + end + def test_destroy topic = Topic.find(1) assert_equal topic, topic.destroy, 'topic.destroy did not return self' @@ -820,6 +832,20 @@ class BasicsTest < ActiveRecord::TestCase assert_equal [ Topic.find(1) ], [ Topic.find(2).topic ] & [ Topic.find(1) ] end + def test_delete_new_record + client = Client.new + client.delete + assert client.frozen? + end + + def test_delete_record_with_associations + client = Client.find(3) + client.delete + assert client.frozen? + assert_kind_of Firm, client.firm + assert_raises(ActiveSupport::FrozenObjectError) { client.name = "something else" } + end + def test_destroy_new_record client = Client.new client.destroy @@ -1084,6 +1110,24 @@ class BasicsTest < ActiveRecord::TestCase Time.zone = nil Topic.skip_time_zone_conversion_for_attributes = [] end + + def test_multiparameter_attributes_on_time_only_column_with_time_zone_aware_attributes_does_not_do_time_zone_conversion + ActiveRecord::Base.time_zone_aware_attributes = true + ActiveRecord::Base.default_timezone = :utc + Time.zone = ActiveSupport::TimeZone[-28800] + attributes = { + "bonus_time(1i)" => "2000", "bonus_time(2i)" => "1", "bonus_time(3i)" => "1", + "bonus_time(4i)" => "16", "bonus_time(5i)" => "24" + } + topic = Topic.find(1) + topic.attributes = attributes + assert_equal Time.utc(2000, 1, 1, 16, 24, 0), topic.bonus_time + assert topic.bonus_time.utc? + ensure + ActiveRecord::Base.time_zone_aware_attributes = false + ActiveRecord::Base.default_timezone = :local + Time.zone = nil + end def test_multiparameter_attributes_on_time_with_empty_seconds attributes = { @@ -1420,15 +1464,17 @@ class BasicsTest < ActiveRecord::TestCase if RUBY_VERSION < '1.9' def test_quote_chars - str = 'The Narrator' - topic = Topic.create(:author_name => str) - assert_equal str, topic.author_name + with_kcode('UTF8') do + str = 'The Narrator' + topic = Topic.create(:author_name => str) + assert_equal str, topic.author_name - assert_kind_of ActiveSupport::Multibyte::Chars, str.chars - topic = Topic.find_by_author_name(str.chars) + assert_kind_of ActiveSupport::Multibyte.proxy_class, str.mb_chars + topic = Topic.find_by_author_name(str.mb_chars) - assert_kind_of Topic, topic - assert_equal str, topic.author_name, "The right topic should have been found by name even with name passed as Chars" + assert_kind_of Topic, topic + assert_equal str, topic.author_name, "The right topic should have been found by name even with name passed as Chars" + end end end @@ -2021,4 +2067,18 @@ class BasicsTest < ActiveRecord::TestCase ensure ActiveRecord::Base.logger = original_logger end + + private + def with_kcode(kcode) + if RUBY_VERSION < '1.9' + orig_kcode, $KCODE = $KCODE, kcode + begin + yield + ensure + $KCODE = orig_kcode + end + else + yield + end + end end diff --git a/activerecord/test/cases/defaults_test.rb b/activerecord/test/cases/defaults_test.rb index 3473b846a0..ee84cb8af8 100644 --- a/activerecord/test/cases/defaults_test.rb +++ b/activerecord/test/cases/defaults_test.rb @@ -19,6 +19,37 @@ class DefaultTest < ActiveRecord::TestCase end if current_adapter?(:MysqlAdapter) + + #MySQL 5 and higher is quirky with not null text/blob columns. + #With MySQL Text/blob columns cannot have defaults. If the column is not null MySQL will report that the column has a null default + #but it behaves as though the column had a default of '' + def test_mysql_text_not_null_defaults + klass = Class.new(ActiveRecord::Base) + klass.table_name = 'test_mysql_text_not_null_defaults' + klass.connection.create_table klass.table_name do |t| + t.column :non_null_text, :text, :null => false + t.column :non_null_blob, :blob, :null => false + t.column :null_text, :text, :null => true + t.column :null_blob, :blob, :null => true + end + assert_equal '', klass.columns_hash['non_null_blob'].default + assert_equal '', klass.columns_hash['non_null_text'].default + + assert_equal nil, klass.columns_hash['null_blob'].default + assert_equal nil, klass.columns_hash['null_text'].default + + assert_nothing_raised do + instance = klass.create! + assert_equal '', instance.non_null_text + assert_equal '', instance.non_null_blob + assert_nil instance.null_text + assert_nil instance.null_blob + end + ensure + klass.connection.drop_table(klass.table_name) rescue nil + end + + # MySQL uses an implicit default 0 rather than NULL unless in strict mode. # We use an implicit NULL so schema.rb is compatible with other databases. def test_mysql_integer_not_null_defaults diff --git a/activerecord/test/cases/finder_test.rb b/activerecord/test/cases/finder_test.rb index cbdff382fe..292b88edbc 100644 --- a/activerecord/test/cases/finder_test.rb +++ b/activerecord/test/cases/finder_test.rb @@ -465,8 +465,8 @@ class FinderTest < ActiveRecord::TestCase quoted_bambi_and_thumper = ActiveRecord::Base.connection.quote("Bambi\nand\nThumper") assert_equal "name=#{quoted_bambi}", bind('name=?', "Bambi") assert_equal "name=#{quoted_bambi_and_thumper}", bind('name=?', "Bambi\nand\nThumper") - assert_equal "name=#{quoted_bambi}", bind('name=?', "Bambi".chars) - assert_equal "name=#{quoted_bambi_and_thumper}", bind('name=?', "Bambi\nand\nThumper".chars) + assert_equal "name=#{quoted_bambi}", bind('name=?', "Bambi".mb_chars) + assert_equal "name=#{quoted_bambi_and_thumper}", bind('name=?', "Bambi\nand\nThumper".mb_chars) end def test_bind_record @@ -935,6 +935,17 @@ class FinderTest < ActiveRecord::TestCase assert_equal 1, first.id end + def test_joins_with_string_array + person_with_reader_and_post = Post.find( + :all, + :joins => [ + "INNER JOIN categorizations ON categorizations.post_id = posts.id", + "INNER JOIN categories ON categories.id = categorizations.category_id AND categories.type = 'SpecialCategory'" + ] + ) + assert_equal 1, person_with_reader_and_post.size + end + def test_find_by_id_with_conditions_with_or assert_nothing_raised do Post.find([1,2,3], diff --git a/activerecord/test/cases/helper.rb b/activerecord/test/cases/helper.rb index f30d58546e..f7bdac8013 100644 --- a/activerecord/test/cases/helper.rb +++ b/activerecord/test/cases/helper.rb @@ -46,3 +46,17 @@ end class << ActiveRecord::Base public :with_scope, :with_exclusive_scope end + +unless ENV['FIXTURE_DEBUG'] + module Test #:nodoc: + module Unit #:nodoc: + class << TestCase #:nodoc: + def try_to_load_dependency_with_silence(*args) + ActiveRecord::Base.logger.silence { try_to_load_dependency_without_silence(*args)} + end + + alias_method_chain :try_to_load_dependency, :silence + end + end + end +end
\ No newline at end of file diff --git a/activerecord/test/cases/method_scoping_test.rb b/activerecord/test/cases/method_scoping_test.rb index af6fcd32ad..ff10bfaf3e 100644 --- a/activerecord/test/cases/method_scoping_test.rb +++ b/activerecord/test/cases/method_scoping_test.rb @@ -138,6 +138,36 @@ class MethodScopingTest < ActiveRecord::TestCase assert_equal authors(:david).attributes, scoped_authors.first.attributes end + def test_scoped_find_merges_string_array_style_and_string_style_joins + scoped_authors = Author.with_scope(:find => { :joins => ["INNER JOIN posts ON posts.author_id = authors.id"]}) do + Author.find(:all, :select => 'DISTINCT authors.*', :joins => 'INNER JOIN comments ON posts.id = comments.post_id', :conditions => 'comments.id = 1') + end + assert scoped_authors.include?(authors(:david)) + assert !scoped_authors.include?(authors(:mary)) + assert_equal 1, scoped_authors.size + assert_equal authors(:david).attributes, scoped_authors.first.attributes + end + + def test_scoped_find_merges_string_array_style_and_hash_style_joins + scoped_authors = Author.with_scope(:find => { :joins => :posts}) do + Author.find(:all, :select => 'DISTINCT authors.*', :joins => ['INNER JOIN comments ON posts.id = comments.post_id'], :conditions => 'comments.id = 1') + end + assert scoped_authors.include?(authors(:david)) + assert !scoped_authors.include?(authors(:mary)) + assert_equal 1, scoped_authors.size + assert_equal authors(:david).attributes, scoped_authors.first.attributes + end + + def test_scoped_find_merges_joins_and_eliminates_duplicate_string_joins + scoped_authors = Author.with_scope(:find => { :joins => 'INNER JOIN posts ON posts.author_id = authors.id'}) do + Author.find(:all, :select => 'DISTINCT authors.*', :joins => ["INNER JOIN posts ON posts.author_id = authors.id", "INNER JOIN comments ON posts.id = comments.post_id"], :conditions => 'comments.id = 1') + end + assert scoped_authors.include?(authors(:david)) + assert !scoped_authors.include?(authors(:mary)) + assert_equal 1, scoped_authors.size + assert_equal authors(:david).attributes, scoped_authors.first.attributes + end + def test_scoped_count_include # with the include, will retrieve only developers for the given project Developer.with_scope(:find => { :include => :projects }) do diff --git a/activerecord/test/cases/migration_test.rb b/activerecord/test/cases/migration_test.rb index c1a8da2270..ac44dd7ffe 100644 --- a/activerecord/test/cases/migration_test.rb +++ b/activerecord/test/cases/migration_test.rb @@ -1133,7 +1133,11 @@ if ActiveRecord::Base.connection.supports_migrations? columns = Person.connection.columns(:binary_testings) data_column = columns.detect { |c| c.name == "data" } - assert_nil data_column.default + if current_adapter?(:MysqlAdapter) + assert_equal '', data_column.default + else + assert_nil data_column.default + end Person.connection.drop_table :binary_testings rescue nil end diff --git a/activerecord/test/cases/named_scope_test.rb b/activerecord/test/cases/named_scope_test.rb index 444debd255..64e899780c 100644 --- a/activerecord/test/cases/named_scope_test.rb +++ b/activerecord/test/cases/named_scope_test.rb @@ -271,4 +271,10 @@ class NamedScopeTest < ActiveRecord::TestCase topics.size # use loaded (no query) end end + + def test_chaining_with_duplicate_joins + join = "INNER JOIN comments ON comments.post_id = posts.id" + post = Post.find(1) + assert_equal post.comments.size, Post.scoped(:joins => join).scoped(:joins => join, :conditions => "posts.id = #{post.id}").size + end end diff --git a/activerecord/test/cases/sanitize_test.rb b/activerecord/test/cases/sanitize_test.rb index 0106572ced..817897ceac 100644 --- a/activerecord/test/cases/sanitize_test.rb +++ b/activerecord/test/cases/sanitize_test.rb @@ -8,18 +8,18 @@ class SanitizeTest < ActiveRecord::TestCase def test_sanitize_sql_array_handles_string_interpolation quoted_bambi = ActiveRecord::Base.connection.quote_string("Bambi") assert_equal "name=#{quoted_bambi}", Binary.send(:sanitize_sql_array, ["name=%s", "Bambi"]) - assert_equal "name=#{quoted_bambi}", Binary.send(:sanitize_sql_array, ["name=%s", "Bambi".chars]) + assert_equal "name=#{quoted_bambi}", Binary.send(:sanitize_sql_array, ["name=%s", "Bambi".mb_chars]) quoted_bambi_and_thumper = ActiveRecord::Base.connection.quote_string("Bambi\nand\nThumper") assert_equal "name=#{quoted_bambi_and_thumper}",Binary.send(:sanitize_sql_array, ["name=%s", "Bambi\nand\nThumper"]) - assert_equal "name=#{quoted_bambi_and_thumper}",Binary.send(:sanitize_sql_array, ["name=%s", "Bambi\nand\nThumper".chars]) + assert_equal "name=#{quoted_bambi_and_thumper}",Binary.send(:sanitize_sql_array, ["name=%s", "Bambi\nand\nThumper".mb_chars]) end def test_sanitize_sql_array_handles_bind_variables quoted_bambi = ActiveRecord::Base.connection.quote("Bambi") assert_equal "name=#{quoted_bambi}", Binary.send(:sanitize_sql_array, ["name=?", "Bambi"]) - assert_equal "name=#{quoted_bambi}", Binary.send(:sanitize_sql_array, ["name=?", "Bambi".chars]) + assert_equal "name=#{quoted_bambi}", Binary.send(:sanitize_sql_array, ["name=?", "Bambi".mb_chars]) quoted_bambi_and_thumper = ActiveRecord::Base.connection.quote("Bambi\nand\nThumper") assert_equal "name=#{quoted_bambi_and_thumper}", Binary.send(:sanitize_sql_array, ["name=?", "Bambi\nand\nThumper"]) - assert_equal "name=#{quoted_bambi_and_thumper}", Binary.send(:sanitize_sql_array, ["name=?", "Bambi\nand\nThumper".chars]) + assert_equal "name=#{quoted_bambi_and_thumper}", Binary.send(:sanitize_sql_array, ["name=?", "Bambi\nand\nThumper".mb_chars]) end end diff --git a/activerecord/test/cases/validations_i18n_test.rb b/activerecord/test/cases/validations_i18n_test.rb index e34890ef19..42246f18b6 100644 --- a/activerecord/test/cases/validations_i18n_test.rb +++ b/activerecord/test/cases/validations_i18n_test.rb @@ -6,12 +6,16 @@ class ActiveRecordValidationsI18nTests < Test::Unit::TestCase def setup reset_callbacks Topic @topic = Topic.new + @old_load_path, @old_backend = I18n.load_path, I18n.backend + I18n.load_path.clear + I18n.backend = I18n::Backend::Simple.new I18n.backend.store_translations('en-US', :activerecord => {:errors => {:messages => {:custom => nil}}}) end def teardown reset_callbacks Topic - I18n.load_translations File.dirname(__FILE__) + '/../../lib/active_record/locale/en-US.yml' + I18n.load_path.replace @old_load_path + I18n.backend = @old_backend end def unique_topic diff --git a/activeresource/lib/active_resource/connection.rb b/activeresource/lib/active_resource/connection.rb index fe9c2d57fe..273fee3286 100644 --- a/activeresource/lib/active_resource/connection.rb +++ b/activeresource/lib/active_resource/connection.rb @@ -199,7 +199,7 @@ module ActiveResource # Builds headers for request to remote service. def build_request_headers(headers, http_method=nil) - authorization_header.update(default_header).update(headers).update(http_format_header(http_method)) + authorization_header.update(default_header).update(http_format_header(http_method)).update(headers) end # Sets authorization header diff --git a/activeresource/test/connection_test.rb b/activeresource/test/connection_test.rb index 06f31f1b57..84bcf69219 100644 --- a/activeresource/test/connection_test.rb +++ b/activeresource/test/connection_test.rb @@ -168,12 +168,20 @@ class ConnectionTest < Test::Unit::TestCase assert_equal 200, response.code end - uses_mocha('test_timeout') do + uses_mocha('test_timeout, test_accept_http_header') do def test_timeout @http = mock('new Net::HTTP') @conn.expects(:http).returns(@http) @http.expects(:get).raises(Timeout::Error, 'execution expired') - assert_raises(ActiveResource::TimeoutError) { @conn.get('/people_timeout.xml') } + assert_raise(ActiveResource::TimeoutError) { @conn.get('/people_timeout.xml') } + end + + def test_accept_http_header + @http = mock('new Net::HTTP') + @conn.expects(:http).returns(@http) + path = '/people/1.xml' + @http.expects(:get).with(path, {'Accept' => 'application/xhtml+xml'}).returns(ActiveResource::Response.new(@matz, 200, {'Content-Type' => 'text/xhtml'})) + assert_nothing_raised(Mocha::ExpectationError) { @conn.get(path, {'Accept' => 'application/xhtml+xml'}) } end end diff --git a/activesupport/CHANGELOG b/activesupport/CHANGELOG index 7d7a6920e2..9700a11531 100644 --- a/activesupport/CHANGELOG +++ b/activesupport/CHANGELOG @@ -1,5 +1,13 @@ *Edge* +* Switch from String#chars to String#mb_chars for the unicode proxy. [Manfred Stienstra] + + This helps with 1.8.7 compatibility and also improves performance for some operations by reducing indirection. + +* TimeWithZone #wday, #yday and #to_date avoid trip through #method_missing [Geoff Buesing] + +* Added Time, Date, DateTime and TimeWithZone #past?, #future? and #today? #720 [Clemens Kofler, Geoff Buesing] + * Fixed Sri Jayawardenepura time zone to map to Asia/Colombo [Jamis Buck] * Added Inflector#parameterize for easy slug generation ("Donald E. Knuth".parameterize => "donald-e-knuth") #713 [Matt Darby] diff --git a/activesupport/bin/generate_tables b/activesupport/bin/generate_tables new file mode 100755 index 0000000000..f8e032139f --- /dev/null +++ b/activesupport/bin/generate_tables @@ -0,0 +1,147 @@ +#!/usr/bin/env ruby + +begin + $:.unshift(File.expand_path(File.dirname(__FILE__) + '/../lib')) + require 'active_support' +rescue IOError +end + +require 'open-uri' +require 'tmpdir' + +module ActiveSupport + module Multibyte + class UnicodeDatabase + def load; end + end + + class UnicodeDatabaseGenerator + BASE_URI = "http://www.unicode.org/Public/#{ActiveSupport::Multibyte::UNICODE_VERSION}/ucd/" + SOURCES = { + :codepoints => BASE_URI + 'UnicodeData.txt', + :composition_exclusion => BASE_URI + 'CompositionExclusions.txt', + :grapheme_break_property => BASE_URI + 'auxiliary/GraphemeBreakProperty.txt', + :cp1252 => 'http://unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP1252.TXT' + } + + def initialize + @ucd = UnicodeDatabase.new + + default = Codepoint.new + default.combining_class = 0 + default.uppercase_mapping = 0 + default.lowercase_mapping = 0 + @ucd.codepoints = Hash.new(default) + end + + def parse_codepoints(line) + codepoint = Codepoint.new + raise "Could not parse input." unless line =~ /^ + ([0-9A-F]+); # code + ([^;]+); # name + ([A-Z]+); # general category + ([0-9]+); # canonical combining class + ([A-Z]+); # bidi class + (<([A-Z]*)>)? # decomposition type + ((\ ?[0-9A-F]+)*); # decompomposition mapping + ([0-9]*); # decimal digit + ([0-9]*); # digit + ([^;]*); # numeric + ([YN]*); # bidi mirrored + ([^;]*); # unicode 1.0 name + ([^;]*); # iso comment + ([0-9A-F]*); # simple uppercase mapping + ([0-9A-F]*); # simple lowercase mapping + ([0-9A-F]*)$/ix # simple titlecase mapping + codepoint.code = $1.hex + #codepoint.name = $2 + #codepoint.category = $3 + codepoint.combining_class = Integer($4) + #codepoint.bidi_class = $5 + codepoint.decomp_type = $7 + codepoint.decomp_mapping = ($8=='') ? nil : $8.split.collect { |element| element.hex } + #codepoint.bidi_mirrored = ($13=='Y') ? true : false + codepoint.uppercase_mapping = ($16=='') ? 0 : $16.hex + codepoint.lowercase_mapping = ($17=='') ? 0 : $17.hex + #codepoint.titlecase_mapping = ($18=='') ? nil : $18.hex + @ucd.codepoints[codepoint.code] = codepoint + end + + def parse_grapheme_break_property(line) + if line =~ /^([0-9A-F\.]+)\s*;\s*([\w]+)\s*#/ + type = $2.downcase.intern + @ucd.boundary[type] ||= [] + if $1.include? '..' + parts = $1.split '..' + @ucd.boundary[type] << (parts[0].hex..parts[1].hex) + else + @ucd.boundary[type] << $1.hex + end + end + end + + def parse_composition_exclusion(line) + if line =~ /^([0-9A-F]+)/i + @ucd.composition_exclusion << $1.hex + end + end + + def parse_cp1252(line) + if line =~ /^([0-9A-Fx]+)\s([0-9A-Fx]+)/i + @ucd.cp1252[$1.hex] = $2.hex + end + end + + def create_composition_map + @ucd.codepoints.each do |_, cp| + if !cp.nil? and cp.combining_class == 0 and cp.decomp_type.nil? and !cp.decomp_mapping.nil? and cp.decomp_mapping.length == 2 and @ucd.codepoints[cp.decomp_mapping[0]].combining_class == 0 and !@ucd.composition_exclusion.include?(cp.code) + @ucd.composition_map[cp.decomp_mapping[0]] ||= {} + @ucd.composition_map[cp.decomp_mapping[0]][cp.decomp_mapping[1]] = cp.code + end + end + end + + def normalize_boundary_map + @ucd.boundary.each do |k,v| + if [:lf, :cr].include? k + @ucd.boundary[k] = v[0] + end + end + end + + def parse + SOURCES.each do |type, url| + filename = File.join(Dir.tmpdir, "#{url.split('/').last}") + unless File.exist?(filename) + $stderr.puts "Downloading #{url.split('/').last}" + File.open(filename, 'wb') do |target| + open(url) do |source| + source.each_line { |line| target.write line } + end + end + end + File.open(filename) do |file| + file.each_line { |line| send "parse_#{type}".intern, line } + end + end + create_composition_map + normalize_boundary_map + end + + def dump_to(filename) + File.open(filename, 'wb') do |f| + f.write Marshal.dump([@ucd.codepoints, @ucd.composition_exclusion, @ucd.composition_map, @ucd.boundary, @ucd.cp1252]) + end + end + end + end +end + +if __FILE__ == $0 + filename = ActiveSupport::Multibyte::UnicodeDatabase.filename + generator = ActiveSupport::Multibyte::UnicodeDatabaseGenerator.new + generator.parse + print "Writing to: #{filename}" + generator.dump_to filename + puts " (#{File.size(filename)} bytes)" +end diff --git a/activesupport/lib/active_support.rb b/activesupport/lib/active_support.rb index 7e34a871e3..b30faff06d 100644 --- a/activesupport/lib/active_support.rb +++ b/activesupport/lib/active_support.rb @@ -56,7 +56,7 @@ require 'active_support/time_with_zone' require 'active_support/secure_random' -I18n.load_translations File.dirname(__FILE__) + '/active_support/locale/en-US.yml' +I18n.load_path << File.dirname(__FILE__) + '/active_support/locale/en-US.yml' Inflector = ActiveSupport::Deprecation::DeprecatedConstantProxy.new('Inflector', 'ActiveSupport::Inflector') Dependencies = ActiveSupport::Deprecation::DeprecatedConstantProxy.new('Dependencies', 'ActiveSupport::Dependencies') diff --git a/activesupport/lib/active_support/buffered_logger.rb b/activesupport/lib/active_support/buffered_logger.rb index 6553d72b4f..77e0b1d33f 100644 --- a/activesupport/lib/active_support/buffered_logger.rb +++ b/activesupport/lib/active_support/buffered_logger.rb @@ -116,7 +116,7 @@ module ActiveSupport end def clear_buffer - @buffer[Thread.current] = [] + @buffer.delete(Thread.current) end end end diff --git a/activesupport/lib/active_support/core_ext/date/calculations.rb b/activesupport/lib/active_support/core_ext/date/calculations.rb index b5180c9592..43d70c7013 100644 --- a/activesupport/lib/active_support/core_ext/date/calculations.rb +++ b/activesupport/lib/active_support/core_ext/date/calculations.rb @@ -20,18 +20,33 @@ module ActiveSupport #:nodoc: def yesterday ::Date.today.yesterday end - + # Returns a new Date representing the date 1 day after today (i.e. tomorrow's date). def tomorrow ::Date.today.tomorrow end - + # Returns Time.zone.today when config.time_zone is set, otherwise just returns Date.today. def current ::Time.zone_default ? ::Time.zone.today : ::Date.today end end - + + # Tells whether the Date object's date lies in the past + def past? + self < ::Date.current + end + + # Tells whether the Date object's date is today + def today? + self.to_date == ::Date.current # we need the to_date because of DateTime + end + + # Tells whether the Date object's date lies in the future + def future? + self > ::Date.current + end + # Converts Date to a Time (or DateTime if necessary) with the time portion set to the beginning of the day (0:00) # and then subtracts the specified number of seconds def ago(seconds) @@ -57,7 +72,7 @@ module ActiveSupport #:nodoc: def end_of_day to_time.end_of_day end - + def plus_with_duration(other) #:nodoc: if ActiveSupport::Duration === other other.since(self) @@ -65,7 +80,7 @@ module ActiveSupport #:nodoc: plus_without_duration(other) end end - + def minus_with_duration(other) #:nodoc: if ActiveSupport::Duration === other plus_with_duration(-other) @@ -73,8 +88,8 @@ module ActiveSupport #:nodoc: minus_without_duration(other) end end - - # Provides precise Date calculations for years, months, and days. The +options+ parameter takes a hash with + + # Provides precise Date calculations for years, months, and days. The +options+ parameter takes a hash with # any of these keys: <tt>:years</tt>, <tt>:months</tt>, <tt>:weeks</tt>, <tt>:days</tt>. def advance(options) d = self @@ -98,7 +113,7 @@ module ActiveSupport #:nodoc: options[:day] || self.day ) end - + # Returns a new Date/DateTime representing the time a number of specified months ago def months_ago(months) advance(:months => -months) @@ -161,7 +176,7 @@ module ActiveSupport #:nodoc: days_into_week = { :monday => 0, :tuesday => 1, :wednesday => 2, :thursday => 3, :friday => 4, :saturday => 5, :sunday => 6} result = (self + 7).beginning_of_week + days_into_week[day] self.acts_like?(:time) ? result.change(:hour => 0) : result - end + end # Returns a new ; DateTime objects will have time set to 0:00DateTime representing the start of the month (1st of the month; DateTime objects will have time set to 0:00) def beginning_of_month diff --git a/activesupport/lib/active_support/core_ext/date_time/calculations.rb b/activesupport/lib/active_support/core_ext/date_time/calculations.rb index 155c961a91..0099431e9d 100644 --- a/activesupport/lib/active_support/core_ext/date_time/calculations.rb +++ b/activesupport/lib/active_support/core_ext/date_time/calculations.rb @@ -7,7 +7,7 @@ module ActiveSupport #:nodoc: module Calculations def self.included(base) #:nodoc: base.extend ClassMethods - + base.class_eval do alias_method :compare_without_coercion, :<=> alias_method :<=>, :compare_with_coercion @@ -19,6 +19,20 @@ module ActiveSupport #:nodoc: def local_offset ::Time.local(2007).utc_offset.to_r / 86400 end + + def current + ::Time.zone_default ? ::Time.zone.now.to_datetime : ::Time.now.to_datetime + end + end + + # Tells whether the DateTime object's datetime lies in the past + def past? + self < ::DateTime.current + end + + # Tells whether the DateTime object's datetime lies in the future + def future? + self > ::DateTime.current end # Seconds since midnight: DateTime.now.seconds_since_midnight @@ -78,7 +92,7 @@ module ActiveSupport #:nodoc: def end_of_day change(:hour => 23, :min => 59, :sec => 59) end - + # Adjusts DateTime to UTC by adding its offset value; offset is set to 0 # # Example: @@ -89,17 +103,17 @@ module ActiveSupport #:nodoc: new_offset(0) end alias_method :getutc, :utc - + # Returns true if offset == 0 def utc? offset == 0 end - + # Returns the offset value in seconds def utc_offset (offset * 86400).to_i end - + # Layers additional behavior on DateTime#<=> so that Time and ActiveSupport::TimeWithZone instances can be compared with a DateTime def compare_with_coercion(other) other = other.comparable_time if other.respond_to?(:comparable_time) diff --git a/activesupport/lib/active_support/core_ext/file/atomic.rb b/activesupport/lib/active_support/core_ext/file/atomic.rb index 4d3cf5423f..f988eff3d9 100644 --- a/activesupport/lib/active_support/core_ext/file/atomic.rb +++ b/activesupport/lib/active_support/core_ext/file/atomic.rb @@ -28,7 +28,7 @@ module ActiveSupport #:nodoc: rescue Errno::ENOENT # No old permissions, write a temp file to determine the defaults check_name = ".permissions_check.#{Thread.current.object_id}.#{Process.pid}.#{rand(1000000)}" - new(check_name, "w") + open(check_name, "w") { } old_stat = stat(check_name) unlink(check_name) end diff --git a/activesupport/lib/active_support/core_ext/hash/slice.rb b/activesupport/lib/active_support/core_ext/hash/slice.rb index 3f14470f36..88df49a69f 100644 --- a/activesupport/lib/active_support/core_ext/hash/slice.rb +++ b/activesupport/lib/active_support/core_ext/hash/slice.rb @@ -18,7 +18,7 @@ module ActiveSupport #:nodoc: # Returns a new hash with only the given keys. def slice(*keys) keys = keys.map! { |key| convert_key(key) } if respond_to?(:convert_key) - hash = {} + hash = self.class.new keys.each { |k| hash[k] = self[k] if has_key?(k) } hash end diff --git a/activesupport/lib/active_support/core_ext/string.rb b/activesupport/lib/active_support/core_ext/string.rb index 7ff2f11eff..16c544a577 100644 --- a/activesupport/lib/active_support/core_ext/string.rb +++ b/activesupport/lib/active_support/core_ext/string.rb @@ -1,9 +1,11 @@ +# encoding: utf-8 + require 'active_support/core_ext/string/inflections' require 'active_support/core_ext/string/conversions' require 'active_support/core_ext/string/access' require 'active_support/core_ext/string/starts_ends_with' require 'active_support/core_ext/string/iterators' -require 'active_support/core_ext/string/unicode' +require 'active_support/core_ext/string/multibyte' require 'active_support/core_ext/string/xchar' require 'active_support/core_ext/string/filters' require 'active_support/core_ext/string/behavior' @@ -15,6 +17,6 @@ class String #:nodoc: include ActiveSupport::CoreExtensions::String::Inflections include ActiveSupport::CoreExtensions::String::StartsEndsWith include ActiveSupport::CoreExtensions::String::Iterators - include ActiveSupport::CoreExtensions::String::Unicode include ActiveSupport::CoreExtensions::String::Behavior + include ActiveSupport::CoreExtensions::String::Multibyte end diff --git a/activesupport/lib/active_support/core_ext/string/access.rb b/activesupport/lib/active_support/core_ext/string/access.rb index 1a949c0b77..7fb21fa4dd 100644 --- a/activesupport/lib/active_support/core_ext/string/access.rb +++ b/activesupport/lib/active_support/core_ext/string/access.rb @@ -11,7 +11,7 @@ module ActiveSupport #:nodoc: # "hello".at(4) # => "o" # "hello".at(10) # => nil def at(position) - chars[position, 1].to_s + mb_chars[position, 1].to_s end # Returns the remaining of the string from the +position+ treating the string as an array (where 0 is the first character). @@ -21,7 +21,7 @@ module ActiveSupport #:nodoc: # "hello".from(2) # => "llo" # "hello".from(10) # => nil def from(position) - chars[position..-1].to_s + mb_chars[position..-1].to_s end # Returns the beginning of the string up to the +position+ treating the string as an array (where 0 is the first character). @@ -31,7 +31,7 @@ module ActiveSupport #:nodoc: # "hello".to(2) # => "hel" # "hello".to(10) # => "hello" def to(position) - chars[0..position].to_s + mb_chars[0..position].to_s end # Returns the first character of the string or the first +limit+ characters. @@ -41,7 +41,7 @@ module ActiveSupport #:nodoc: # "hello".first(2) # => "he" # "hello".first(10) # => "hello" def first(limit = 1) - chars[0..(limit - 1)].to_s + mb_chars[0..(limit - 1)].to_s end # Returns the last character of the string or the last +limit+ characters. @@ -51,7 +51,7 @@ module ActiveSupport #:nodoc: # "hello".last(2) # => "lo" # "hello".last(10) # => "hello" def last(limit = 1) - (chars[(-limit)..-1] || self).to_s + (mb_chars[(-limit)..-1] || self).to_s end end else diff --git a/activesupport/lib/active_support/core_ext/string/multibyte.rb b/activesupport/lib/active_support/core_ext/string/multibyte.rb new file mode 100644 index 0000000000..a4caa83b74 --- /dev/null +++ b/activesupport/lib/active_support/core_ext/string/multibyte.rb @@ -0,0 +1,81 @@ +# encoding: utf-8 + +module ActiveSupport #:nodoc: + module CoreExtensions #:nodoc: + module String #:nodoc: + # Implements multibyte methods for easier access to multibyte characters in a String instance. + module Multibyte + unless '1.9'.respond_to?(:force_encoding) + # == Multibyte proxy + # + # +mb_chars+ is a multibyte safe proxy for string methods. + # + # In Ruby 1.8 and older it creates and returns an instance of the ActiveSupport::Multibyte::Chars class which + # encapsulates the original string. A Unicode safe version of all the String methods are defined on this proxy + # class. If the proxy class doesn't respond to a certain method, it's forwarded to the encapsuled string. + # + # name = 'Claus Müller' + # name.reverse #=> "rell??M sualC" + # name.length #=> 13 + # + # name.mb_chars.reverse.to_s #=> "rellüM sualC" + # name.mb_chars.length #=> 12 + # + # In Ruby 1.9 and newer +mb_chars+ returns +self+ because String is (mostly) encoding aware. This means that + # it becomes easy to run one version of your code on multiple Ruby versions. + # + # == Method chaining + # + # All the methods on the Chars proxy which normally return a string will return a Chars object. This allows + # method chaining on the result of any of these methods. + # + # name.mb_chars.reverse.length #=> 12 + # + # == Interoperability and configuration + # + # The Chars object tries to be as interchangeable with String objects as possible: sorting and comparing between + # String and Char work like expected. The bang! methods change the internal string representation in the Chars + # object. Interoperability problems can be resolved easily with a +to_s+ call. + # + # For more information about the methods defined on the Chars proxy see ActiveSupport::Multibyte::Chars. For + # information about how to change the default Multibyte behaviour see ActiveSupport::Multibyte. + def mb_chars + if ActiveSupport::Multibyte.proxy_class.wants?(self) + ActiveSupport::Multibyte.proxy_class.new(self) + else + self + end + end + + # Returns true if the string has UTF-8 semantics (a String used for purely byte resources is unlikely to have + # them), returns false otherwise. + def is_utf8? + ActiveSupport::Multibyte::Chars.consumes?(self) + end + + unless '1.8.7 and later'.respond_to?(:chars) + def chars + ActiveSupport::Deprecation.warn('String#chars has been deprecated in favor of String#mb_chars.', caller) + mb_chars + end + end + else + def mb_chars #:nodoc + self + end + + def is_utf8? #:nodoc + case encoding + when Encoding::UTF_8 + valid_encoding? + when Encoding::ASCII_8BIT, Encoding::US_ASCII + dup.force_encoding(Encoding::UTF_8).valid_encoding? + else + false + end + end + end + end + end + end +end diff --git a/activesupport/lib/active_support/core_ext/string/unicode.rb b/activesupport/lib/active_support/core_ext/string/unicode.rb deleted file mode 100644 index 666f7bcb65..0000000000 --- a/activesupport/lib/active_support/core_ext/string/unicode.rb +++ /dev/null @@ -1,66 +0,0 @@ -module ActiveSupport #:nodoc: - module CoreExtensions #:nodoc: - module String #:nodoc: - # Define methods for handling unicode data. - module Unicode - def self.append_features(base) - if '1.8.7 and later'.respond_to?(:chars) - base.class_eval { remove_method :chars } - end - super - end - - unless '1.9'.respond_to?(:force_encoding) - # +chars+ is a Unicode safe proxy for string methods. It creates and returns an instance of the - # ActiveSupport::Multibyte::Chars class which encapsulates the original string. A Unicode safe version of all - # the String methods are defined on this proxy class. Undefined methods are forwarded to String, so all of the - # string overrides can also be called through the +chars+ proxy. - # - # name = 'Claus Müller' - # name.reverse # => "rell??M sualC" - # name.length # => 13 - # - # name.chars.reverse.to_s # => "rellüM sualC" - # name.chars.length # => 12 - # - # - # All the methods on the chars proxy which normally return a string will return a Chars object. This allows - # method chaining on the result of any of these methods. - # - # name.chars.reverse.length # => 12 - # - # The Char object tries to be as interchangeable with String objects as possible: sorting and comparing between - # String and Char work like expected. The bang! methods change the internal string representation in the Chars - # object. Interoperability problems can be resolved easily with a +to_s+ call. - # - # For more information about the methods defined on the Chars proxy see ActiveSupport::Multibyte::Chars and - # ActiveSupport::Multibyte::Handlers::UTF8Handler. - def chars - ActiveSupport::Multibyte::Chars.new(self) - end - - # Returns true if the string has UTF-8 semantics (a String used for purely byte resources is unlikely to have - # them), returns false otherwise. - def is_utf8? - ActiveSupport::Multibyte::Handlers::UTF8Handler.consumes?(self) - end - else - def chars #:nodoc: - self - end - - def is_utf8? #:nodoc: - case encoding - when Encoding::UTF_8 - valid_encoding? - when Encoding::ASCII_8BIT - dup.force_encoding('UTF-8').valid_encoding? - else - false - end - end - end - end - end - end -end diff --git a/activesupport/lib/active_support/core_ext/time/calculations.rb b/activesupport/lib/active_support/core_ext/time/calculations.rb index cd234c9b89..3cc6d59907 100644 --- a/activesupport/lib/active_support/core_ext/time/calculations.rb +++ b/activesupport/lib/active_support/core_ext/time/calculations.rb @@ -9,13 +9,13 @@ module ActiveSupport #:nodoc: base.class_eval do alias_method :plus_without_duration, :+ alias_method :+, :plus_with_duration - + alias_method :minus_without_duration, :- alias_method :-, :minus_with_duration - + alias_method :minus_without_coercion, :- alias_method :-, :minus_with_coercion - + alias_method :compare_without_coercion, :<=> alias_method :<=>, :compare_with_coercion end @@ -28,9 +28,9 @@ module ActiveSupport #:nodoc: def ===(other) other.is_a?(::Time) end - - # Return the number of days in the given month. - # If no year is specified, it will use the current year. + + # Return the number of days in the given month. + # If no year is specified, it will use the current year. def days_in_month(month, year = now.year) return 29 if month == 2 && ::Date.gregorian_leap?(year) COMMON_YEAR_DAYS_IN_MONTH[month] @@ -57,6 +57,21 @@ module ActiveSupport #:nodoc: end end + # Tells whether the Time object's time lies in the past + def past? + self < ::Time.current + end + + # Tells whether the Time object's time is today + def today? + self.to_date == ::Date.current + end + + # Tells whether the Time object's time lies in the future + def future? + self > ::Time.current + end + # Seconds since midnight: Time.now.seconds_since_midnight def seconds_since_midnight self.to_i - self.change(:hour => 0).to_i + (self.usec/1.0e+6) @@ -106,7 +121,7 @@ module ActiveSupport #:nodoc: (seconds.abs >= 86400 && initial_dst != final_dst) ? f + (initial_dst - final_dst).hours : f end rescue - self.to_datetime.since(seconds) + self.to_datetime.since(seconds) end alias :in :since @@ -199,7 +214,7 @@ module ActiveSupport #:nodoc: change(:day => last_day, :hour => 23, :min => 59, :sec => 59, :usec => 0) end alias :at_end_of_month :end_of_month - + # Returns a new Time representing the start of the quarter (1st of january, april, july, october, 0:00) def beginning_of_quarter beginning_of_month.change(:month => [10, 7, 4, 1].detect { |m| m <= self.month }) @@ -208,7 +223,7 @@ module ActiveSupport #:nodoc: # Returns a new Time representing the end of the quarter (last day of march, june, september, december, 23:59:59) def end_of_quarter - change(:month => [3, 6, 9, 12].detect { |m| m >= self.month }).end_of_month + beginning_of_month.change(:month => [3, 6, 9, 12].detect { |m| m >= self.month }).end_of_month end alias :at_end_of_quarter :end_of_quarter @@ -249,7 +264,7 @@ module ActiveSupport #:nodoc: minus_without_duration(other) end end - + # Time#- can also be used to determine the number of seconds between two Time instances. # We're layering on additional behavior so that ActiveSupport::TimeWithZone instances # are coerced into values that Time#- will recognize @@ -257,7 +272,7 @@ module ActiveSupport #:nodoc: other = other.comparable_time if other.respond_to?(:comparable_time) minus_without_coercion(other) end - + # Layers additional behavior on Time#<=> so that DateTime and ActiveSupport::TimeWithZone instances # can be chronologically compared with a Time def compare_with_coercion(other) diff --git a/activesupport/lib/active_support/inflector.rb b/activesupport/lib/active_support/inflector.rb index 8a917a9eb2..89a93f4a5f 100644 --- a/activesupport/lib/active_support/inflector.rb +++ b/activesupport/lib/active_support/inflector.rb @@ -240,9 +240,9 @@ module ActiveSupport def demodulize(class_name_in_module) class_name_in_module.to_s.gsub(/^.*::/, '') end - + # Replaces special characters in a string so that it may be used as part of a 'pretty' URL. - # + # # ==== Examples # # class Person @@ -250,14 +250,20 @@ module ActiveSupport # "#{id}-#{name.parameterize}" # end # end - # + # # @person = Person.find(1) # # => #<Person id: 1, name: "Donald E. Knuth"> - # + # # <%= link_to(@person.name, person_path %> # # => <a href="/person/1-donald-e-knuth">Donald E. Knuth</a> def parameterize(string, sep = '-') - string.chars.normalize(:kd).to_s.gsub(/[^\x00-\x7F]+/, '').gsub(/[^a-z0-9_\-]+/i, sep).downcase + re_sep = Regexp.escape(sep) + string.mb_chars.normalize(:kd). # Decompose accented characters + gsub(/[^\x00-\x7F]+/, ''). # Remove anything non-ASCII entirely (e.g. diacritics). + gsub(/[^a-z0-9\-_\+]+/i, sep). # Turn unwanted chars into the separator. + squeeze(sep). # No more than one of the separator in a row. + gsub(/^#{re_sep}|#{re_sep}$/i, ''). # Remove leading/trailing separator. + downcase end # Create the name of a table like Rails does for models to table names. This method diff --git a/activesupport/lib/active_support/multibyte.rb b/activesupport/lib/active_support/multibyte.rb index 27c0d180a5..018aafe607 100644 --- a/activesupport/lib/active_support/multibyte.rb +++ b/activesupport/lib/active_support/multibyte.rb @@ -1,9 +1,33 @@ -module ActiveSupport - module Multibyte #:nodoc: - DEFAULT_NORMALIZATION_FORM = :kc +# encoding: utf-8 + +require 'active_support/multibyte/chars' +require 'active_support/multibyte/exceptions' +require 'active_support/multibyte/unicode_database' + +module ActiveSupport #:nodoc: + module Multibyte + # A list of all available normalization forms. See http://www.unicode.org/reports/tr15/tr15-29.html for more + # information about normalization. NORMALIZATIONS_FORMS = [:c, :kc, :d, :kd] - UNICODE_VERSION = '5.0.0' + + # The Unicode version that is supported by the implementation + UNICODE_VERSION = '5.1.0' + + # The default normalization used for operations that require normalization. It can be set to any of the + # normalizations in NORMALIZATIONS_FORMS. + # + # Example: + # ActiveSupport::Multibyte.default_normalization_form = :c + mattr_accessor :default_normalization_form + self.default_normalization_form = :kc + + # The proxy class returned when calling mb_chars. You can use this accessor to configure your own proxy + # class so you can support other encodings. See the ActiveSupport::Multibyte::Chars implementation for + # an example how to do this. + # + # Example: + # ActiveSupport::Multibyte.proxy_class = CharsForUTF32 + mattr_accessor :proxy_class + self.proxy_class = ActiveSupport::Multibyte::Chars end end - -require 'active_support/multibyte/chars' diff --git a/activesupport/lib/active_support/multibyte/chars.rb b/activesupport/lib/active_support/multibyte/chars.rb index de2c83f8d1..5184026c63 100644 --- a/activesupport/lib/active_support/multibyte/chars.rb +++ b/activesupport/lib/active_support/multibyte/chars.rb @@ -1,142 +1,679 @@ -require 'active_support/multibyte/handlers/utf8_handler' -require 'active_support/multibyte/handlers/passthru_handler' - -# Encapsulates all the functionality related to the Chars proxy. -module ActiveSupport::Multibyte #:nodoc: - # Chars enables you to work transparently with multibyte encodings in the Ruby String class without having extensive - # knowledge about the encoding. A Chars object accepts a string upon initialization and proxies String methods in an - # encoding safe manner. All the normal String methods are also implemented on the proxy. - # - # String methods are proxied through the Chars object, and can be accessed through the +chars+ method. Methods - # which would normally return a String object now return a Chars object so methods can be chained. - # - # "The Perfect String ".chars.downcase.strip.normalize # => "the perfect string" - # - # Chars objects are perfectly interchangeable with String objects as long as no explicit class checks are made. - # If certain methods do explicitly check the class, call +to_s+ before you pass chars objects to them. - # - # bad.explicit_checking_method "T".chars.downcase.to_s - # - # The actual operations on the string are delegated to handlers. Theoretically handlers can be implemented for - # any encoding, but the default handler handles UTF-8. This handler is set during initialization, if you want to - # use you own handler, you can set it on the Chars class. Look at the UTF8Handler source for an example how to - # implement your own handler. If you your own handler to work on anything but UTF-8 you probably also - # want to override Chars#handler. - # - # ActiveSupport::Multibyte::Chars.handler = MyHandler - # - # Note that a few methods are defined on Chars instead of the handler because they are defined on Object or Kernel - # and method_missing can't catch them. - class Chars - - attr_reader :string # The contained string - alias_method :to_s, :string - - include Comparable - - # The magic method to make String and Chars comparable - def to_str - # Using any other ways of overriding the String itself will lead you all the way from infinite loops to - # core dumps. Don't go there. - @string - end +# encoding: utf-8 + +module ActiveSupport #:nodoc: + module Multibyte #:nodoc: + # Chars enables you to work transparently with UTF-8 encoding in the Ruby String class without having extensive + # knowledge about the encoding. A Chars object accepts a string upon initialization and proxies String methods in an + # encoding safe manner. All the normal String methods are also implemented on the proxy. + # + # String methods are proxied through the Chars object, and can be accessed through the +mb_chars+ method. Methods + # which would normally return a String object now return a Chars object so methods can be chained. + # + # "The Perfect String ".mb_chars.downcase.strip.normalize #=> "the perfect string" + # + # Chars objects are perfectly interchangeable with String objects as long as no explicit class checks are made. + # If certain methods do explicitly check the class, call +to_s+ before you pass chars objects to them. + # + # bad.explicit_checking_method "T".mb_chars.downcase.to_s + # + # The default Chars implementation assumes that the encoding of the string is UTF-8, if you want to handle different + # encodings you can write your own multibyte string handler and configure it through + # ActiveSupport::Multibyte.proxy_class. + # + # class CharsForUTF32 + # def size + # @wrapped_string.size / 4 + # end + # + # def self.accepts?(string) + # string.length % 4 == 0 + # end + # end + # + # ActiveSupport::Multibyte.proxy_class = CharsForUTF32 + class Chars + # Hangul character boundaries and properties + HANGUL_SBASE = 0xAC00 + HANGUL_LBASE = 0x1100 + HANGUL_VBASE = 0x1161 + HANGUL_TBASE = 0x11A7 + HANGUL_LCOUNT = 19 + HANGUL_VCOUNT = 21 + HANGUL_TCOUNT = 28 + HANGUL_NCOUNT = HANGUL_VCOUNT * HANGUL_TCOUNT + HANGUL_SCOUNT = 11172 + HANGUL_SLAST = HANGUL_SBASE + HANGUL_SCOUNT + HANGUL_JAMO_FIRST = 0x1100 + HANGUL_JAMO_LAST = 0x11FF + + # All the unicode whitespace + UNICODE_WHITESPACE = [ + (0x0009..0x000D).to_a, # White_Space # Cc [5] <control-0009>..<control-000D> + 0x0020, # White_Space # Zs SPACE + 0x0085, # White_Space # Cc <control-0085> + 0x00A0, # White_Space # Zs NO-BREAK SPACE + 0x1680, # White_Space # Zs OGHAM SPACE MARK + 0x180E, # White_Space # Zs MONGOLIAN VOWEL SEPARATOR + (0x2000..0x200A).to_a, # White_Space # Zs [11] EN QUAD..HAIR SPACE + 0x2028, # White_Space # Zl LINE SEPARATOR + 0x2029, # White_Space # Zp PARAGRAPH SEPARATOR + 0x202F, # White_Space # Zs NARROW NO-BREAK SPACE + 0x205F, # White_Space # Zs MEDIUM MATHEMATICAL SPACE + 0x3000, # White_Space # Zs IDEOGRAPHIC SPACE + ].flatten.freeze + + # BOM (byte order mark) can also be seen as whitespace, it's a non-rendering character used to distinguish + # between little and big endian. This is not an issue in utf-8, so it must be ignored. + UNICODE_LEADERS_AND_TRAILERS = UNICODE_WHITESPACE + [65279] # ZERO-WIDTH NO-BREAK SPACE aka BOM + + # Returns a regular expression pattern that matches the passed Unicode codepoints + def self.codepoints_to_pattern(array_of_codepoints) #:nodoc: + array_of_codepoints.collect{ |e| [e].pack 'U*' }.join('|') + end + UNICODE_TRAILERS_PAT = /(#{codepoints_to_pattern(UNICODE_LEADERS_AND_TRAILERS)})+\Z/ + UNICODE_LEADERS_PAT = /\A(#{codepoints_to_pattern(UNICODE_LEADERS_AND_TRAILERS)})+/ + + # Borrowed from the Kconv library by Shinji KONO - (also as seen on the W3C site) + UTF8_PAT = /\A(?: + [\x00-\x7f] | + [\xc2-\xdf] [\x80-\xbf] | + \xe0 [\xa0-\xbf] [\x80-\xbf] | + [\xe1-\xef] [\x80-\xbf] [\x80-\xbf] | + \xf0 [\x90-\xbf] [\x80-\xbf] [\x80-\xbf] | + [\xf1-\xf3] [\x80-\xbf] [\x80-\xbf] [\x80-\xbf] | + \xf4 [\x80-\x8f] [\x80-\xbf] [\x80-\xbf] + )*\z/xn + + attr_reader :wrapped_string + alias to_s wrapped_string + alias to_str wrapped_string + + if '1.9'.respond_to?(:force_encoding) + # Creates a new Chars instance by wrapping _string_. + def initialize(string) + @wrapped_string = string + @wrapped_string.force_encoding(Encoding::UTF_8) unless @wrapped_string.frozen? + end + else + def initialize(string) #:nodoc: + @wrapped_string = string + end + end + + # Forward all undefined methods to the wrapped string. + def method_missing(method, *args, &block) + if method.to_s =~ /!$/ + @wrapped_string.__send__(method, *args, &block) + self + else + result = @wrapped_string.__send__(method, *args, &block) + result.kind_of?(String) ? chars(result) : result + end + end + + # Returns +true+ if _obj_ responds to the given method. Private methods are included in the search + # only if the optional second parameter evaluates to +true+. + def respond_to?(method, include_private=false) + super || @wrapped_string.respond_to?(method, include_private) || false + end + + # Enable more predictable duck-typing on String-like classes. See Object#acts_like?. + def acts_like_string? + true + end + + # Returns +true+ if the Chars class can and should act as a proxy for the string _string_. Returns + # +false+ otherwise. + def self.wants?(string) + $KCODE == 'UTF8' && consumes?(string) + end - # Make duck-typing with String possible - def respond_to?(method, include_priv = false) - super || @string.respond_to?(method, include_priv) || - handler.respond_to?(method, include_priv) || - (method.to_s =~ /(.*)!/ && handler.respond_to?($1, include_priv)) || + # Returns +true+ when the proxy class can handle the string. Returns +false+ otherwise. + def self.consumes?(string) + # Unpack is a little bit faster than regular expressions. + string.unpack('U*') + true + rescue ArgumentError false - end + end - # Enable more predictable duck-typing on String-like classes. See Object#acts_like?. - def acts_like_string? - true - end + include Comparable - # Create a new Chars instance. - def initialize(str) - @string = str.respond_to?(:string) ? str.string : str - end - - # Returns -1, 0 or +1 depending on whether the Chars object is to be sorted before, equal or after the - # object on the right side of the operation. It accepts any object that implements +to_s+. See String.<=> - # for more details. - def <=>(other); @string <=> other.to_s; end - - # Works just like String#split, with the exception that the items in the resulting list are Chars - # instances instead of String. This makes chaining methods easier. - def split(*args) - @string.split(*args).map { |i| i.chars } - end - - # Gsub works exactly the same as gsub on a normal string. - def gsub(*a, &b); @string.gsub(*a, &b).chars; end - - # Like String.=~ only it returns the character offset (in codepoints) instead of the byte offset. - def =~(other) - handler.translate_offset(@string, @string =~ other) - end - - # Try to forward all undefined methods to the handler, when a method is not defined on the handler, send it to - # the contained string. Method_missing is also responsible for making the bang! methods destructive. - def method_missing(m, *a, &b) - begin - # Simulate methods with a ! at the end because we can't touch the enclosed string from the handlers. - if m.to_s =~ /^(.*)\!$/ && handler.respond_to?($1) - result = handler.send($1, @string, *a, &b) - if result == @string - result = nil + # Returns <tt>-1</tt>, <tt>0</tt> or <tt>+1</tt> depending on whether the Chars object is to be sorted before, + # equal or after the object on the right side of the operation. It accepts any object that implements +to_s+. + # See <tt>String#<=></tt> for more details. + # + # Example: + # 'é'.mb_chars <=> 'ü'.mb_chars #=> -1 + def <=>(other) + @wrapped_string <=> other.to_s + end + + # Returns a new Chars object containing the _other_ object concatenated to the string. + # + # Example: + # ('Café'.mb_chars + ' périferôl').to_s #=> "Café périferôl" + def +(other) + self << other + end + + # Like <tt>String#=~</tt> only it returns the character offset (in codepoints) instead of the byte offset. + # + # Example: + # 'Café périferôl'.mb_chars =~ /ô/ #=> 12 + def =~(other) + translate_offset(@wrapped_string =~ other) + end + + # Works just like <tt>String#split</tt>, with the exception that the items in the resulting list are Chars + # instances instead of String. This makes chaining methods easier. + # + # Example: + # 'Café périferôl'.mb_chars.split(/é/).map { |part| part.upcase.to_s } #=> ["CAF", " P", "RIFERÔL"] + def split(*args) + @wrapped_string.split(*args).map { |i| i.mb_chars } + end + + # Inserts the passed string at specified codepoint offsets. + # + # Example: + # 'Café'.mb_chars.insert(4, ' périferôl').to_s #=> "Café périferôl" + def insert(offset, fragment) + unpacked = self.class.u_unpack(@wrapped_string) + unless offset > unpacked.length + @wrapped_string.replace( + self.class.u_unpack(@wrapped_string).insert(offset, *self.class.u_unpack(fragment)).pack('U*') + ) + else + raise IndexError, "index #{offset} out of string" + end + self + end + + # Returns +true+ if contained string contains _other_. Returns +false+ otherwise. + # + # Example: + # 'Café'.mb_chars.include?('é') #=> true + def include?(other) + # We have to redefine this method because Enumerable defines it. + @wrapped_string.include?(other) + end + + # Returns the position _needle_ in the string, counting in codepoints. Returns +nil+ if _needle_ isn't found. + # + # Example: + # 'Café périferôl'.mb_chars.index('ô') #=> 12 + # 'Café périferôl'.mb_chars.index(/\w/u) #=> 0 + def index(needle, offset=0) + index = @wrapped_string.index(needle, offset) + index ? (self.class.u_unpack(@wrapped_string.slice(0...index)).size) : nil + end + + # Like <tt>String#[]=</tt>, except instead of byte offsets you specify character offsets. + # + # Example: + # + # s = "Müller" + # s.mb_chars[2] = "e" # Replace character with offset 2 + # s + # #=> "Müeler" + # + # s = "Müller" + # s.mb_chars[1, 2] = "ö" # Replace 2 characters at character offset 1 + # s + # #=> "Möler" + def []=(*args) + replace_by = args.pop + # Indexed replace with regular expressions already works + if args.first.is_a?(Regexp) + @wrapped_string[*args] = replace_by + else + result = self.class.u_unpack(@wrapped_string) + if args[0].is_a?(Fixnum) + raise IndexError, "index #{args[0]} out of string" if args[0] >= result.length + min = args[0] + max = args[1].nil? ? min : (min + args[1] - 1) + range = Range.new(min, max) + replace_by = [replace_by].pack('U') if replace_by.is_a?(Fixnum) + elsif args.first.is_a?(Range) + raise RangeError, "#{args[0]} out of range" if args[0].min >= result.length + range = args[0] else - @string.replace result + needle = args[0].to_s + min = index(needle) + max = min + self.class.u_unpack(needle).length - 1 + range = Range.new(min, max) end - elsif handler.respond_to?(m) - result = handler.send(m, @string, *a, &b) - else - result = @string.send(m, *a, &b) + result[range] = self.class.u_unpack(replace_by) + @wrapped_string.replace(result.pack('U*')) end - rescue Handlers::EncodingError - @string.replace handler.tidy_bytes(@string) - retry end - - if result.kind_of?(String) - result.chars - else - result + + # Works just like <tt>String#rjust</tt>, only integer specifies characters instead of bytes. + # + # Example: + # + # "¾ cup".mb_chars.rjust(8).to_s + # #=> " ¾ cup" + # + # "¾ cup".mb_chars.rjust(8, " ").to_s # Use non-breaking whitespace + # #=> " ¾ cup" + def rjust(integer, padstr=' ') + justify(integer, :right, padstr) end - end - - # Set the handler class for the Char objects. - def self.handler=(klass) - @@handler = klass - end - # Returns the proper handler for the contained string depending on $KCODE and the encoding of the string. This - # method is used internally to always redirect messages to the proper classes depending on the context. - def handler - if utf8_pragma? - @@handler - else - ActiveSupport::Multibyte::Handlers::PassthruHandler + # Works just like <tt>String#ljust</tt>, only integer specifies characters instead of bytes. + # + # Example: + # + # "¾ cup".mb_chars.rjust(8).to_s + # #=> "¾ cup " + # + # "¾ cup".mb_chars.rjust(8, " ").to_s # Use non-breaking whitespace + # #=> "¾ cup " + def ljust(integer, padstr=' ') + justify(integer, :left, padstr) + end + + # Works just like <tt>String#center</tt>, only integer specifies characters instead of bytes. + # + # Example: + # + # "¾ cup".mb_chars.center(8).to_s + # #=> " ¾ cup " + # + # "¾ cup".mb_chars.center(8, " ").to_s # Use non-breaking whitespace + # #=> " ¾ cup " + def center(integer, padstr=' ') + justify(integer, :center, padstr) end - end - private + # Strips entire range of Unicode whitespace from the right of the string. + def rstrip + chars(@wrapped_string.gsub(UNICODE_TRAILERS_PAT, '')) + end + + # Strips entire range of Unicode whitespace from the left of the string. + def lstrip + chars(@wrapped_string.gsub(UNICODE_LEADERS_PAT, '')) + end + + # Strips entire range of Unicode whitespace from the right and left of the string. + def strip + rstrip.lstrip + end + + # Returns the number of codepoints in the string + def size + self.class.u_unpack(@wrapped_string).size + end + alias_method :length, :size - # +utf8_pragma+ checks if it can send this string to the handlers. It makes sure @string isn't nil and $KCODE is - # set to 'UTF8'. - def utf8_pragma? - !@string.nil? && ($KCODE == 'UTF8') + # Reverses all characters in the string. + # + # Example: + # 'Café'.mb_chars.reverse.to_s #=> 'éfaC' + def reverse + chars(self.class.u_unpack(@wrapped_string).reverse.pack('U*')) end + + # Implements Unicode-aware slice with codepoints. Slicing on one point returns the codepoints for that + # character. + # + # Example: + # 'こにちわ'.mb_chars.slice(2..3).to_s #=> "ちわ" + def slice(*args) + if args.size > 2 + raise ArgumentError, "wrong number of arguments (#{args.size} for 1)" # Do as if we were native + elsif (args.size == 2 && !(args.first.is_a?(Numeric) || args.first.is_a?(Regexp))) + raise TypeError, "cannot convert #{args.first.class} into Integer" # Do as if we were native + elsif (args.size == 2 && !args[1].is_a?(Numeric)) + raise TypeError, "cannot convert #{args[1].class} into Integer" # Do as if we were native + elsif args[0].kind_of? Range + cps = self.class.u_unpack(@wrapped_string).slice(*args) + result = cps.nil? ? nil : cps.pack('U*') + elsif args[0].kind_of? Regexp + result = @wrapped_string.slice(*args) + elsif args.size == 1 && args[0].kind_of?(Numeric) + character = self.class.u_unpack(@wrapped_string)[args[0]] + result = character.nil? ? nil : [character].pack('U') + else + result = self.class.u_unpack(@wrapped_string).slice(*args).pack('U*') + end + result.nil? ? nil : chars(result) + end + alias_method :[], :slice + + # Convert characters in the string to uppercase. + # + # Example: + # 'Laurent, òu sont les tests?'.mb_chars.upcase.to_s #=> "LAURENT, ÒU SONT LES TESTS?" + def upcase + apply_mapping :uppercase_mapping + end + + # Convert characters in the string to lowercase. + # + # Example: + # 'VĚDA A VÝZKUM'.mb_chars.downcase.to_s #=> "věda a výzkum" + def downcase + apply_mapping :lowercase_mapping + end + + # Converts the first character to uppercase and the remainder to lowercase. + # + # Example: + # 'über'.mb_chars.capitalize.to_s #=> "Über" + def capitalize + (slice(0) || chars('')).upcase + (slice(1..-1) || chars('')).downcase + end + + # Returns the KC normalization of the string by default. NFKC is considered the best normalization form for + # passing strings to databases and validations. + # + # * <tt>str</tt> - The string to perform normalization on. + # * <tt>form</tt> - The form you want to normalize in. Should be one of the following: + # <tt>:c</tt>, <tt>:kc</tt>, <tt>:d</tt>, or <tt>:kd</tt>. Default is + # ActiveSupport::Multibyte.default_normalization_form + def normalize(form=ActiveSupport::Multibyte.default_normalization_form) + # See http://www.unicode.org/reports/tr15, Table 1 + codepoints = self.class.u_unpack(@wrapped_string) + chars(case form + when :d + self.class.reorder_characters(self.class.decompose_codepoints(:canonical, codepoints)) + when :c + self.class.compose_codepoints(self.class.reorder_characters(self.class.decompose_codepoints(:canonical, codepoints))) + when :kd + self.class.reorder_characters(self.class.decompose_codepoints(:compatability, codepoints)) + when :kc + self.class.compose_codepoints(self.class.reorder_characters(self.class.decompose_codepoints(:compatability, codepoints))) + else + raise ArgumentError, "#{form} is not a valid normalization variant", caller + end.pack('U*')) + end + + # Performs canonical decomposition on all the characters. + # + # Example: + # 'é'.length #=> 2 + # 'é'.mb_chars.decompose.to_s.length #=> 3 + def decompose + chars(self.class.decompose_codepoints(:canonical, self.class.u_unpack(@wrapped_string)).pack('U*')) + end + + # Performs composition on all the characters. + # + # Example: + # 'é'.length #=> 3 + # 'é'.mb_chars.compose.to_s.length #=> 2 + def compose + chars(self.class.compose_codepoints(self.class.u_unpack(@wrapped_string)).pack('U*')) + end + + # Returns the number of grapheme clusters in the string. + # + # Example: + # 'क्षि'.mb_chars.length #=> 4 + # 'क्षि'.mb_chars.g_length #=> 3 + def g_length + self.class.g_unpack(@wrapped_string).length + end + + # Replaces all ISO-8859-1 or CP1252 characters by their UTF-8 equivalent resulting in a valid UTF-8 string. + def tidy_bytes + chars(self.class.tidy_bytes(@wrapped_string)) + end + + %w(lstrip rstrip strip reverse upcase downcase slice tidy_bytes capitalize).each do |method| + define_method("#{method}!") do |*args| + unless args.nil? + @wrapped_string = send(method, *args).to_s + else + @wrapped_string = send(method).to_s + end + self + end + end + + class << self + + # Unpack the string at codepoints boundaries. Raises an EncodingError when the encoding of the string isn't + # valid UTF-8. + # + # Example: + # Chars.u_unpack('Café') #=> [67, 97, 102, 233] + def u_unpack(string) + begin + string.unpack 'U*' + rescue ArgumentError + raise EncodingError, 'malformed UTF-8 character' + end + end + + # Detect whether the codepoint is in a certain character class. Returns +true+ when it's in the specified + # character class and +false+ otherwise. Valid character classes are: <tt>:cr</tt>, <tt>:lf</tt>, <tt>:l</tt>, + # <tt>:v</tt>, <tt>:lv</tt>, <tt>:lvt</tt> and <tt>:t</tt>. + # + # Primarily used by the grapheme cluster support. + def in_char_class?(codepoint, classes) + classes.detect { |c| UCD.boundary[c] === codepoint } ? true : false + end + + # Unpack the string at grapheme boundaries. Returns a list of character lists. + # + # Example: + # Chars.g_unpack('क्षि') #=> [[2325, 2381], [2359], [2367]] + # Chars.g_unpack('Café') #=> [[67], [97], [102], [233]] + def g_unpack(string) + codepoints = u_unpack(string) + unpacked = [] + pos = 0 + marker = 0 + eoc = codepoints.length + while(pos < eoc) + pos += 1 + previous = codepoints[pos-1] + current = codepoints[pos] + if ( + # CR X LF + one = ( previous == UCD.boundary[:cr] and current == UCD.boundary[:lf] ) or + # L X (L|V|LV|LVT) + two = ( UCD.boundary[:l] === previous and in_char_class?(current, [:l,:v,:lv,:lvt]) ) or + # (LV|V) X (V|T) + three = ( in_char_class?(previous, [:lv,:v]) and in_char_class?(current, [:v,:t]) ) or + # (LVT|T) X (T) + four = ( in_char_class?(previous, [:lvt,:t]) and UCD.boundary[:t] === current ) or + # X Extend + five = (UCD.boundary[:extend] === current) + ) + else + unpacked << codepoints[marker..pos-1] + marker = pos + end + end + unpacked + end + + # Reverse operation of g_unpack. + # + # Example: + # Chars.g_pack(Chars.g_unpack('क्षि')) #=> 'क्षि' + def g_pack(unpacked) + (unpacked.flatten).pack('U*') + end + + def padding(padsize, padstr=' ') #:nodoc: + if padsize != 0 + new(padstr * ((padsize / u_unpack(padstr).size) + 1)).slice(0, padsize) + else + '' + end + end + + # Re-order codepoints so the string becomes canonical. + def reorder_characters(codepoints) + length = codepoints.length- 1 + pos = 0 + while pos < length do + cp1, cp2 = UCD.codepoints[codepoints[pos]], UCD.codepoints[codepoints[pos+1]] + if (cp1.combining_class > cp2.combining_class) && (cp2.combining_class > 0) + codepoints[pos..pos+1] = cp2.code, cp1.code + pos += (pos > 0 ? -1 : 1) + else + pos += 1 + end + end + codepoints + end + + # Decompose composed characters to the decomposed form. + def decompose_codepoints(type, codepoints) + codepoints.inject([]) do |decomposed, cp| + # if it's a hangul syllable starter character + if HANGUL_SBASE <= cp and cp < HANGUL_SLAST + sindex = cp - HANGUL_SBASE + ncp = [] # new codepoints + ncp << HANGUL_LBASE + sindex / HANGUL_NCOUNT + ncp << HANGUL_VBASE + (sindex % HANGUL_NCOUNT) / HANGUL_TCOUNT + tindex = sindex % HANGUL_TCOUNT + ncp << (HANGUL_TBASE + tindex) unless tindex == 0 + decomposed.concat ncp + # if the codepoint is decomposable in with the current decomposition type + elsif (ncp = UCD.codepoints[cp].decomp_mapping) and (!UCD.codepoints[cp].decomp_type || type == :compatability) + decomposed.concat decompose_codepoints(type, ncp.dup) + else + decomposed << cp + end + end + end + + # Compose decomposed characters to the composed form. + def compose_codepoints(codepoints) + pos = 0 + eoa = codepoints.length - 1 + starter_pos = 0 + starter_char = codepoints[0] + previous_combining_class = -1 + while pos < eoa + pos += 1 + lindex = starter_char - HANGUL_LBASE + # -- Hangul + if 0 <= lindex and lindex < HANGUL_LCOUNT + vindex = codepoints[starter_pos+1] - HANGUL_VBASE rescue vindex = -1 + if 0 <= vindex and vindex < HANGUL_VCOUNT + tindex = codepoints[starter_pos+2] - HANGUL_TBASE rescue tindex = -1 + if 0 <= tindex and tindex < HANGUL_TCOUNT + j = starter_pos + 2 + eoa -= 2 + else + tindex = 0 + j = starter_pos + 1 + eoa -= 1 + end + codepoints[starter_pos..j] = (lindex * HANGUL_VCOUNT + vindex) * HANGUL_TCOUNT + tindex + HANGUL_SBASE + end + starter_pos += 1 + starter_char = codepoints[starter_pos] + # -- Other characters + else + current_char = codepoints[pos] + current = UCD.codepoints[current_char] + if current.combining_class > previous_combining_class + if ref = UCD.composition_map[starter_char] + composition = ref[current_char] + else + composition = nil + end + unless composition.nil? + codepoints[starter_pos] = composition + starter_char = composition + codepoints.delete_at pos + eoa -= 1 + pos -= 1 + previous_combining_class = -1 + else + previous_combining_class = current.combining_class + end + else + previous_combining_class = current.combining_class + end + if current.combining_class == 0 + starter_pos = pos + starter_char = codepoints[pos] + end + end + end + codepoints + end + + # Replaces all ISO-8859-1 or CP1252 characters by their UTF-8 equivalent resulting in a valid UTF-8 string. + def tidy_bytes(string) + string.split(//u).map do |c| + if !UTF8_PAT.match(c) + n = c.unpack('C')[0] + n < 128 ? n.chr : + n < 160 ? [UCD.cp1252[n] || n].pack('U') : + n < 192 ? "\xC2" + n.chr : "\xC3" + (n-64).chr + else + c + end + end.join + end + end + + protected + + def translate_offset(byte_offset) #:nodoc: + return nil if byte_offset.nil? + return 0 if @wrapped_string == '' + chunk = @wrapped_string[0..byte_offset] + begin + begin + chunk.unpack('U*').length - 1 + rescue ArgumentError => e + chunk = @wrapped_string[0..(byte_offset+=1)] + # Stop retrying at the end of the string + raise e unless byte_offset < chunk.length + # We damaged a character, retry + retry + end + # Catch the ArgumentError so we can throw our own + rescue ArgumentError + raise EncodingError, 'malformed UTF-8 character' + end + end + + def justify(integer, way, padstr=' ') #:nodoc: + raise ArgumentError, "zero width padding" if padstr.length == 0 + padsize = integer - size + padsize = padsize > 0 ? padsize : 0 + case way + when :right + result = @wrapped_string.dup.insert(0, self.class.padding(padsize, padstr)) + when :left + result = @wrapped_string.dup.insert(-1, self.class.padding(padsize, padstr)) + when :center + lpad = self.class.padding((padsize / 2.0).floor, padstr) + rpad = self.class.padding((padsize / 2.0).ceil, padstr) + result = @wrapped_string.dup.insert(0, lpad).insert(-1, rpad) + end + chars(result) + end + + def apply_mapping(mapping) #:nodoc: + chars(self.class.u_unpack(@wrapped_string).map do |codepoint| + cp = UCD.codepoints[codepoint] + if cp and (ncp = cp.send(mapping)) and ncp > 0 + ncp + else + codepoint + end + end.pack('U*')) + end + + def chars(string) #:nodoc: + self.class.new(string) + end + end end -end - -# When we can load the utf8proc library, override normalization with the faster methods -begin - require 'utf8proc_native' - require 'active_support/multibyte/handlers/utf8_handler_proc' - ActiveSupport::Multibyte::Chars.handler = ActiveSupport::Multibyte::Handlers::UTF8HandlerProc -rescue LoadError - ActiveSupport::Multibyte::Chars.handler = ActiveSupport::Multibyte::Handlers::UTF8Handler -end +end
\ No newline at end of file diff --git a/activesupport/lib/active_support/multibyte/exceptions.rb b/activesupport/lib/active_support/multibyte/exceptions.rb new file mode 100644 index 0000000000..62066e3c71 --- /dev/null +++ b/activesupport/lib/active_support/multibyte/exceptions.rb @@ -0,0 +1,8 @@ +# encoding: utf-8 + +module ActiveSupport #:nodoc: + module Multibyte #:nodoc: + # Raised when a problem with the encoding was found. + class EncodingError < StandardError; end + end +end
\ No newline at end of file diff --git a/activesupport/lib/active_support/multibyte/generators/generate_tables.rb b/activesupport/lib/active_support/multibyte/generators/generate_tables.rb deleted file mode 100755 index 7f807585c5..0000000000 --- a/activesupport/lib/active_support/multibyte/generators/generate_tables.rb +++ /dev/null @@ -1,149 +0,0 @@ -#!/usr/bin/env ruby -begin - require File.dirname(__FILE__) + '/../../../active_support' -rescue IOError -end -require 'open-uri' -require 'tmpdir' - -module ActiveSupport::Multibyte::Handlers #:nodoc: - class UnicodeDatabase #:nodoc: - def self.load - [Hash.new(Codepoint.new),[],{},{}] - end - end - - class UnicodeTableGenerator #:nodoc: - BASE_URI = "http://www.unicode.org/Public/#{ActiveSupport::Multibyte::UNICODE_VERSION}/ucd/" - SOURCES = { - :codepoints => BASE_URI + 'UnicodeData.txt', - :composition_exclusion => BASE_URI + 'CompositionExclusions.txt', - :grapheme_break_property => BASE_URI + 'auxiliary/GraphemeBreakProperty.txt', - :cp1252 => 'http://unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP1252.TXT' - } - - def initialize - @ucd = UnicodeDatabase.new - - default = Codepoint.new - default.combining_class = 0 - default.uppercase_mapping = 0 - default.lowercase_mapping = 0 - @ucd.codepoints = Hash.new(default) - - @ucd.composition_exclusion = [] - @ucd.composition_map = {} - @ucd.boundary = {} - @ucd.cp1252 = {} - end - - def parse_codepoints(line) - codepoint = Codepoint.new - raise "Could not parse input." unless line =~ /^ - ([0-9A-F]+); # code - ([^;]+); # name - ([A-Z]+); # general category - ([0-9]+); # canonical combining class - ([A-Z]+); # bidi class - (<([A-Z]*)>)? # decomposition type - ((\ ?[0-9A-F]+)*); # decompomposition mapping - ([0-9]*); # decimal digit - ([0-9]*); # digit - ([^;]*); # numeric - ([YN]*); # bidi mirrored - ([^;]*); # unicode 1.0 name - ([^;]*); # iso comment - ([0-9A-F]*); # simple uppercase mapping - ([0-9A-F]*); # simple lowercase mapping - ([0-9A-F]*)$/ix # simple titlecase mapping - codepoint.code = $1.hex - #codepoint.name = $2 - #codepoint.category = $3 - codepoint.combining_class = Integer($4) - #codepoint.bidi_class = $5 - codepoint.decomp_type = $7 - codepoint.decomp_mapping = ($8=='') ? nil : $8.split.collect { |element| element.hex } - #codepoint.bidi_mirrored = ($13=='Y') ? true : false - codepoint.uppercase_mapping = ($16=='') ? 0 : $16.hex - codepoint.lowercase_mapping = ($17=='') ? 0 : $17.hex - #codepoint.titlecase_mapping = ($18=='') ? nil : $18.hex - @ucd.codepoints[codepoint.code] = codepoint - end - - def parse_grapheme_break_property(line) - if line =~ /^([0-9A-F\.]+)\s*;\s*([\w]+)\s*#/ - type = $2.downcase.intern - @ucd.boundary[type] ||= [] - if $1.include? '..' - parts = $1.split '..' - @ucd.boundary[type] << (parts[0].hex..parts[1].hex) - else - @ucd.boundary[type] << $1.hex - end - end - end - - def parse_composition_exclusion(line) - if line =~ /^([0-9A-F]+)/i - @ucd.composition_exclusion << $1.hex - end - end - - def parse_cp1252(line) - if line =~ /^([0-9A-Fx]+)\s([0-9A-Fx]+)/i - @ucd.cp1252[$1.hex] = $2.hex - end - end - - def create_composition_map - @ucd.codepoints.each do |_, cp| - if !cp.nil? and cp.combining_class == 0 and cp.decomp_type.nil? and !cp.decomp_mapping.nil? and cp.decomp_mapping.length == 2 and @ucd[cp.decomp_mapping[0]].combining_class == 0 and !@ucd.composition_exclusion.include?(cp.code) - @ucd.composition_map[cp.decomp_mapping[0]] ||= {} - @ucd.composition_map[cp.decomp_mapping[0]][cp.decomp_mapping[1]] = cp.code - end - end - end - - def normalize_boundary_map - @ucd.boundary.each do |k,v| - if [:lf, :cr].include? k - @ucd.boundary[k] = v[0] - end - end - end - - def parse - SOURCES.each do |type, url| - filename = File.join(Dir.tmpdir, "#{url.split('/').last}") - unless File.exist?(filename) - $stderr.puts "Downloading #{url.split('/').last}" - File.open(filename, 'wb') do |target| - open(url) do |source| - source.each_line { |line| target.write line } - end - end - end - File.open(filename) do |file| - file.each_line { |line| send "parse_#{type}".intern, line } - end - end - create_composition_map - normalize_boundary_map - end - - def dump_to(filename) - File.open(filename, 'wb') do |f| - f.write Marshal.dump([@ucd.codepoints, @ucd.composition_exclusion, @ucd.composition_map, @ucd.boundary, @ucd.cp1252]) - end - end - end -end - -if __FILE__ == $0 - filename = ActiveSupport::Multibyte::Handlers::UnicodeDatabase.filename - generator = ActiveSupport::Multibyte::Handlers::UnicodeTableGenerator.new - generator.parse - print "Writing to: #{filename}" - generator.dump_to filename - puts " (#{File.size(filename)} bytes)" -end diff --git a/activesupport/lib/active_support/multibyte/handlers/passthru_handler.rb b/activesupport/lib/active_support/multibyte/handlers/passthru_handler.rb deleted file mode 100644 index 916215c2ce..0000000000 --- a/activesupport/lib/active_support/multibyte/handlers/passthru_handler.rb +++ /dev/null @@ -1,9 +0,0 @@ -# Chars uses this handler when $KCODE is not set to 'UTF8'. Because this handler doesn't define any methods all call -# will be forwarded to String. -class ActiveSupport::Multibyte::Handlers::PassthruHandler #:nodoc: - - # Return the original byteoffset - def self.translate_offset(string, byte_offset) #:nodoc: - byte_offset - end -end
\ No newline at end of file diff --git a/activesupport/lib/active_support/multibyte/handlers/utf8_handler.rb b/activesupport/lib/active_support/multibyte/handlers/utf8_handler.rb deleted file mode 100644 index aa9c16f575..0000000000 --- a/activesupport/lib/active_support/multibyte/handlers/utf8_handler.rb +++ /dev/null @@ -1,564 +0,0 @@ -# Contains all the handlers and helper classes -module ActiveSupport::Multibyte::Handlers #:nodoc: - class EncodingError < ArgumentError #:nodoc: - end - - class Codepoint #:nodoc: - attr_accessor :code, :combining_class, :decomp_type, :decomp_mapping, :uppercase_mapping, :lowercase_mapping - end - - class UnicodeDatabase #:nodoc: - attr_writer :codepoints, :composition_exclusion, :composition_map, :boundary, :cp1252 - - # self-expiring methods that lazily load the Unicode database and then return the value. - [:codepoints, :composition_exclusion, :composition_map, :boundary, :cp1252].each do |attr_name| - class_eval(<<-EOS, __FILE__, __LINE__) - def #{attr_name} - load - @#{attr_name} - end - EOS - end - - # Shortcut to ucd.codepoints[] - def [](index); codepoints[index]; end - - # Returns the directory in which the data files are stored - def self.dirname - File.dirname(__FILE__) + '/../../values/' - end - - # Returns the filename for the data file for this version - def self.filename - File.expand_path File.join(dirname, "unicode_tables.dat") - end - - # Loads the unicode database and returns all the internal objects of UnicodeDatabase - # Once the values have been loaded, define attr_reader methods for the instance variables. - def load - begin - @codepoints, @composition_exclusion, @composition_map, @boundary, @cp1252 = File.open(self.class.filename, 'rb') { |f| Marshal.load f.read } - rescue Exception => e - raise IOError.new("Couldn't load the unicode tables for UTF8Handler (#{e.message}), handler is unusable") - end - @codepoints ||= Hash.new(Codepoint.new) - @composition_exclusion ||= [] - @composition_map ||= {} - @boundary ||= {} - @cp1252 ||= {} - - # Redefine the === method so we can write shorter rules for grapheme cluster breaks - @boundary.each do |k,_| - @boundary[k].instance_eval do - def ===(other) - detect { |i| i === other } ? true : false - end - end if @boundary[k].kind_of?(Array) - end - - # define attr_reader methods for the instance variables - class << self - attr_reader :codepoints, :composition_exclusion, :composition_map, :boundary, :cp1252 - end - end - end - - # UTF8Handler implements Unicode aware operations for strings, these operations will be used by the Chars - # proxy when $KCODE is set to 'UTF8'. - class UTF8Handler - # Hangul character boundaries and properties - HANGUL_SBASE = 0xAC00 - HANGUL_LBASE = 0x1100 - HANGUL_VBASE = 0x1161 - HANGUL_TBASE = 0x11A7 - HANGUL_LCOUNT = 19 - HANGUL_VCOUNT = 21 - HANGUL_TCOUNT = 28 - HANGUL_NCOUNT = HANGUL_VCOUNT * HANGUL_TCOUNT - HANGUL_SCOUNT = 11172 - HANGUL_SLAST = HANGUL_SBASE + HANGUL_SCOUNT - HANGUL_JAMO_FIRST = 0x1100 - HANGUL_JAMO_LAST = 0x11FF - - # All the unicode whitespace - UNICODE_WHITESPACE = [ - (0x0009..0x000D).to_a, # White_Space # Cc [5] <control-0009>..<control-000D> - 0x0020, # White_Space # Zs SPACE - 0x0085, # White_Space # Cc <control-0085> - 0x00A0, # White_Space # Zs NO-BREAK SPACE - 0x1680, # White_Space # Zs OGHAM SPACE MARK - 0x180E, # White_Space # Zs MONGOLIAN VOWEL SEPARATOR - (0x2000..0x200A).to_a, # White_Space # Zs [11] EN QUAD..HAIR SPACE - 0x2028, # White_Space # Zl LINE SEPARATOR - 0x2029, # White_Space # Zp PARAGRAPH SEPARATOR - 0x202F, # White_Space # Zs NARROW NO-BREAK SPACE - 0x205F, # White_Space # Zs MEDIUM MATHEMATICAL SPACE - 0x3000, # White_Space # Zs IDEOGRAPHIC SPACE - ].flatten.freeze - - # BOM (byte order mark) can also be seen as whitespace, it's a non-rendering character used to distinguish - # between little and big endian. This is not an issue in utf-8, so it must be ignored. - UNICODE_LEADERS_AND_TRAILERS = UNICODE_WHITESPACE + [65279] # ZERO-WIDTH NO-BREAK SPACE aka BOM - - # Borrowed from the Kconv library by Shinji KONO - (also as seen on the W3C site) - UTF8_PAT = /\A(?: - [\x00-\x7f] | - [\xc2-\xdf] [\x80-\xbf] | - \xe0 [\xa0-\xbf] [\x80-\xbf] | - [\xe1-\xef] [\x80-\xbf] [\x80-\xbf] | - \xf0 [\x90-\xbf] [\x80-\xbf] [\x80-\xbf] | - [\xf1-\xf3] [\x80-\xbf] [\x80-\xbf] [\x80-\xbf] | - \xf4 [\x80-\x8f] [\x80-\xbf] [\x80-\xbf] - )*\z/xn - - # Returns a regular expression pattern that matches the passed Unicode codepoints - def self.codepoints_to_pattern(array_of_codepoints) #:nodoc: - array_of_codepoints.collect{ |e| [e].pack 'U*' }.join('|') - end - UNICODE_TRAILERS_PAT = /(#{codepoints_to_pattern(UNICODE_LEADERS_AND_TRAILERS)})+\Z/ - UNICODE_LEADERS_PAT = /\A(#{codepoints_to_pattern(UNICODE_LEADERS_AND_TRAILERS)})+/ - - class << self - - # /// - # /// BEGIN String method overrides - # /// - - # Inserts the passed string at specified codepoint offsets - def insert(str, offset, fragment) - str.replace( - u_unpack(str).insert( - offset, - u_unpack(fragment) - ).flatten.pack('U*') - ) - end - - # Returns the position of the passed argument in the string, counting in codepoints - def index(str, *args) - bidx = str.index(*args) - bidx ? (u_unpack(str.slice(0...bidx)).size) : nil - end - - # Works just like the indexed replace method on string, except instead of byte offsets you specify - # character offsets. - # - # Example: - # - # s = "Müller" - # s.chars[2] = "e" # Replace character with offset 2 - # s # => "Müeler" - # - # s = "Müller" - # s.chars[1, 2] = "ö" # Replace 2 characters at character offset 1 - # s # => "Möler" - def []=(str, *args) - replace_by = args.pop - # Indexed replace with regular expressions already works - return str[*args] = replace_by if args.first.is_a?(Regexp) - result = u_unpack(str) - if args[0].is_a?(Fixnum) - raise IndexError, "index #{args[0]} out of string" if args[0] >= result.length - min = args[0] - max = args[1].nil? ? min : (min + args[1] - 1) - range = Range.new(min, max) - replace_by = [replace_by].pack('U') if replace_by.is_a?(Fixnum) - elsif args.first.is_a?(Range) - raise RangeError, "#{args[0]} out of range" if args[0].min >= result.length - range = args[0] - else - needle = args[0].to_s - min = index(str, needle) - max = min + length(needle) - 1 - range = Range.new(min, max) - end - result[range] = u_unpack(replace_by) - str.replace(result.pack('U*')) - end - - # Works just like String#rjust, only integer specifies characters instead of bytes. - # - # Example: - # - # "¾ cup".chars.rjust(8).to_s - # # => " ¾ cup" - # - # "¾ cup".chars.rjust(8, " ").to_s # Use non-breaking whitespace - # # => " ¾ cup" - def rjust(str, integer, padstr=' ') - justify(str, integer, :right, padstr) - end - - # Works just like String#ljust, only integer specifies characters instead of bytes. - # - # Example: - # - # "¾ cup".chars.rjust(8).to_s - # # => "¾ cup " - # - # "¾ cup".chars.rjust(8, " ").to_s # Use non-breaking whitespace - # # => "¾ cup " - def ljust(str, integer, padstr=' ') - justify(str, integer, :left, padstr) - end - - # Works just like String#center, only integer specifies characters instead of bytes. - # - # Example: - # - # "¾ cup".chars.center(8).to_s - # # => " ¾ cup " - # - # "¾ cup".chars.center(8, " ").to_s # Use non-breaking whitespace - # # => " ¾ cup " - def center(str, integer, padstr=' ') - justify(str, integer, :center, padstr) - end - - # Does Unicode-aware rstrip - def rstrip(str) - str.gsub(UNICODE_TRAILERS_PAT, '') - end - - # Does Unicode-aware lstrip - def lstrip(str) - str.gsub(UNICODE_LEADERS_PAT, '') - end - - # Removed leading and trailing whitespace - def strip(str) - str.gsub(UNICODE_LEADERS_PAT, '').gsub(UNICODE_TRAILERS_PAT, '') - end - - # Returns the number of codepoints in the string - def size(str) - u_unpack(str).size - end - alias_method :length, :size - - # Reverses codepoints in the string. - def reverse(str) - u_unpack(str).reverse.pack('U*') - end - - # Implements Unicode-aware slice with codepoints. Slicing on one point returns the codepoints for that - # character. - def slice(str, *args) - if args.size > 2 - raise ArgumentError, "wrong number of arguments (#{args.size} for 1)" # Do as if we were native - elsif (args.size == 2 && !(args.first.is_a?(Numeric) || args.first.is_a?(Regexp))) - raise TypeError, "cannot convert #{args.first.class} into Integer" # Do as if we were native - elsif (args.size == 2 && !args[1].is_a?(Numeric)) - raise TypeError, "cannot convert #{args[1].class} into Integer" # Do as if we were native - elsif args[0].kind_of? Range - cps = u_unpack(str).slice(*args) - cps.nil? ? nil : cps.pack('U*') - elsif args[0].kind_of? Regexp - str.slice(*args) - elsif args.size == 1 && args[0].kind_of?(Numeric) - u_unpack(str)[args[0]] - else - u_unpack(str).slice(*args).pack('U*') - end - end - alias_method :[], :slice - - # Convert characters in the string to uppercase - def upcase(str); to_case :uppercase_mapping, str; end - - # Convert characters in the string to lowercase - def downcase(str); to_case :lowercase_mapping, str; end - - # Returns a copy of +str+ with the first character converted to uppercase and the remainder to lowercase - def capitalize(str) - upcase(slice(str, 0..0)) + downcase(slice(str, 1..-1) || '') - end - - # /// - # /// Extra String methods for unicode operations - # /// - - # Returns the KC normalization of the string by default. NFKC is considered the best normalization form for - # passing strings to databases and validations. - # - # * <tt>str</tt> - The string to perform normalization on. - # * <tt>form</tt> - The form you want to normalize in. Should be one of the following: - # <tt>:c</tt>, <tt>:kc</tt>, <tt>:d</tt>, or <tt>:kd</tt>. Default is - # ActiveSupport::Multibyte::DEFAULT_NORMALIZATION_FORM. - def normalize(str, form=ActiveSupport::Multibyte::DEFAULT_NORMALIZATION_FORM) - # See http://www.unicode.org/reports/tr15, Table 1 - codepoints = u_unpack(str) - case form - when :d - reorder_characters(decompose_codepoints(:canonical, codepoints)) - when :c - compose_codepoints reorder_characters(decompose_codepoints(:canonical, codepoints)) - when :kd - reorder_characters(decompose_codepoints(:compatability, codepoints)) - when :kc - compose_codepoints reorder_characters(decompose_codepoints(:compatability, codepoints)) - else - raise ArgumentError, "#{form} is not a valid normalization variant", caller - end.pack('U*') - end - - # Perform decomposition on the characters in the string - def decompose(str) - decompose_codepoints(:canonical, u_unpack(str)).pack('U*') - end - - # Perform composition on the characters in the string - def compose(str) - compose_codepoints u_unpack(str).pack('U*') - end - - # /// - # /// BEGIN Helper methods for unicode operation - # /// - - # Used to translate an offset from bytes to characters, for instance one received from a regular expression match - def translate_offset(str, byte_offset) - return nil if byte_offset.nil? - return 0 if str == '' - chunk = str[0..byte_offset] - begin - begin - chunk.unpack('U*').length - 1 - rescue ArgumentError => e - chunk = str[0..(byte_offset+=1)] - # Stop retrying at the end of the string - raise e unless byte_offset < chunk.length - # We damaged a character, retry - retry - end - # Catch the ArgumentError so we can throw our own - rescue ArgumentError - raise EncodingError.new('malformed UTF-8 character') - end - end - - # Checks if the string is valid UTF8. - def consumes?(str) - # Unpack is a little bit faster than regular expressions - begin - str.unpack('U*') - true - rescue ArgumentError - false - end - end - - # Returns the number of grapheme clusters in the string. This method is very likely to be moved or renamed - # in future versions. - def g_length(str) - g_unpack(str).length - end - - # Replaces all the non-utf-8 bytes by their iso-8859-1 or cp1252 equivalent resulting in a valid utf-8 string - def tidy_bytes(str) - str.split(//u).map do |c| - if !UTF8_PAT.match(c) - n = c.unpack('C')[0] - n < 128 ? n.chr : - n < 160 ? [UCD.cp1252[n] || n].pack('U') : - n < 192 ? "\xC2" + n.chr : "\xC3" + (n-64).chr - else - c - end - end.join - end - - protected - - # Detect whether the codepoint is in a certain character class. Primarily used by the - # grapheme cluster support. - def in_char_class?(codepoint, classes) - classes.detect { |c| UCD.boundary[c] === codepoint } ? true : false - end - - # Unpack the string at codepoints boundaries - def u_unpack(str) - begin - str.unpack 'U*' - rescue ArgumentError - raise EncodingError.new('malformed UTF-8 character') - end - end - - # Unpack the string at grapheme boundaries instead of codepoint boundaries - def g_unpack(str) - codepoints = u_unpack(str) - unpacked = [] - pos = 0 - marker = 0 - eoc = codepoints.length - while(pos < eoc) - pos += 1 - previous = codepoints[pos-1] - current = codepoints[pos] - if ( - # CR X LF - one = ( previous == UCD.boundary[:cr] and current == UCD.boundary[:lf] ) or - # L X (L|V|LV|LVT) - two = ( UCD.boundary[:l] === previous and in_char_class?(current, [:l,:v,:lv,:lvt]) ) or - # (LV|V) X (V|T) - three = ( in_char_class?(previous, [:lv,:v]) and in_char_class?(current, [:v,:t]) ) or - # (LVT|T) X (T) - four = ( in_char_class?(previous, [:lvt,:t]) and UCD.boundary[:t] === current ) or - # X Extend - five = (UCD.boundary[:extend] === current) - ) - else - unpacked << codepoints[marker..pos-1] - marker = pos - end - end - unpacked - end - - # Reverse operation of g_unpack - def g_pack(unpacked) - unpacked.flatten - end - - # Justifies a string in a certain way. Valid values for <tt>way</tt> are <tt>:right</tt>, <tt>:left</tt> and - # <tt>:center</tt>. Is primarily used as a helper method by <tt>rjust</tt>, <tt>ljust</tt> and <tt>center</tt>. - def justify(str, integer, way, padstr=' ') - raise ArgumentError, "zero width padding" if padstr.length == 0 - padsize = integer - size(str) - padsize = padsize > 0 ? padsize : 0 - case way - when :right - str.dup.insert(0, padding(padsize, padstr)) - when :left - str.dup.insert(-1, padding(padsize, padstr)) - when :center - lpad = padding((padsize / 2.0).floor, padstr) - rpad = padding((padsize / 2.0).ceil, padstr) - str.dup.insert(0, lpad).insert(-1, rpad) - end - end - - # Generates a padding string of a certain size. - def padding(padsize, padstr=' ') - if padsize != 0 - slice(padstr * ((padsize / size(padstr)) + 1), 0, padsize) - else - '' - end - end - - # Convert characters to a different case - def to_case(way, str) - u_unpack(str).map do |codepoint| - cp = UCD[codepoint] - unless cp.nil? - ncp = cp.send(way) - ncp > 0 ? ncp : codepoint - else - codepoint - end - end.pack('U*') - end - - # Re-order codepoints so the string becomes canonical - def reorder_characters(codepoints) - length = codepoints.length- 1 - pos = 0 - while pos < length do - cp1, cp2 = UCD[codepoints[pos]], UCD[codepoints[pos+1]] - if (cp1.combining_class > cp2.combining_class) && (cp2.combining_class > 0) - codepoints[pos..pos+1] = cp2.code, cp1.code - pos += (pos > 0 ? -1 : 1) - else - pos += 1 - end - end - codepoints - end - - # Decompose composed characters to the decomposed form - def decompose_codepoints(type, codepoints) - codepoints.inject([]) do |decomposed, cp| - # if it's a hangul syllable starter character - if HANGUL_SBASE <= cp and cp < HANGUL_SLAST - sindex = cp - HANGUL_SBASE - ncp = [] # new codepoints - ncp << HANGUL_LBASE + sindex / HANGUL_NCOUNT - ncp << HANGUL_VBASE + (sindex % HANGUL_NCOUNT) / HANGUL_TCOUNT - tindex = sindex % HANGUL_TCOUNT - ncp << (HANGUL_TBASE + tindex) unless tindex == 0 - decomposed.concat ncp - # if the codepoint is decomposable in with the current decomposition type - elsif (ncp = UCD[cp].decomp_mapping) and (!UCD[cp].decomp_type || type == :compatability) - decomposed.concat decompose_codepoints(type, ncp.dup) - else - decomposed << cp - end - end - end - - # Compose decomposed characters to the composed form - def compose_codepoints(codepoints) - pos = 0 - eoa = codepoints.length - 1 - starter_pos = 0 - starter_char = codepoints[0] - previous_combining_class = -1 - while pos < eoa - pos += 1 - lindex = starter_char - HANGUL_LBASE - # -- Hangul - if 0 <= lindex and lindex < HANGUL_LCOUNT - vindex = codepoints[starter_pos+1] - HANGUL_VBASE rescue vindex = -1 - if 0 <= vindex and vindex < HANGUL_VCOUNT - tindex = codepoints[starter_pos+2] - HANGUL_TBASE rescue tindex = -1 - if 0 <= tindex and tindex < HANGUL_TCOUNT - j = starter_pos + 2 - eoa -= 2 - else - tindex = 0 - j = starter_pos + 1 - eoa -= 1 - end - codepoints[starter_pos..j] = (lindex * HANGUL_VCOUNT + vindex) * HANGUL_TCOUNT + tindex + HANGUL_SBASE - end - starter_pos += 1 - starter_char = codepoints[starter_pos] - # -- Other characters - else - current_char = codepoints[pos] - current = UCD[current_char] - if current.combining_class > previous_combining_class - if ref = UCD.composition_map[starter_char] - composition = ref[current_char] - else - composition = nil - end - unless composition.nil? - codepoints[starter_pos] = composition - starter_char = composition - codepoints.delete_at pos - eoa -= 1 - pos -= 1 - previous_combining_class = -1 - else - previous_combining_class = current.combining_class - end - else - previous_combining_class = current.combining_class - end - if current.combining_class == 0 - starter_pos = pos - starter_char = codepoints[pos] - end - end - end - codepoints - end - - # UniCode Database - UCD = UnicodeDatabase.new - end - end -end diff --git a/activesupport/lib/active_support/multibyte/handlers/utf8_handler_proc.rb b/activesupport/lib/active_support/multibyte/handlers/utf8_handler_proc.rb deleted file mode 100644 index f10eecc622..0000000000 --- a/activesupport/lib/active_support/multibyte/handlers/utf8_handler_proc.rb +++ /dev/null @@ -1,43 +0,0 @@ -# Methods in this handler call functions in the utf8proc ruby extension. These are significantly faster than the -# pure ruby versions. Chars automatically uses this handler when it can load the utf8proc extension. For -# documentation on handler methods see UTF8Handler. -class ActiveSupport::Multibyte::Handlers::UTF8HandlerProc < ActiveSupport::Multibyte::Handlers::UTF8Handler #:nodoc: - class << self - def normalize(str, form=ActiveSupport::Multibyte::DEFAULT_NORMALIZATION_FORM) #:nodoc: - codepoints = str.unpack('U*') - case form - when :d - utf8map(str, :stable) - when :c - utf8map(str, :stable, :compose) - when :kd - utf8map(str, :stable, :compat) - when :kc - utf8map(str, :stable, :compose, :compat) - else - raise ArgumentError, "#{form} is not a valid normalization variant", caller - end - end - - def decompose(str) #:nodoc: - utf8map(str, :stable) - end - - def downcase(str) #:nodoc:c - utf8map(str, :casefold) - end - - protected - - def utf8map(str, *option_array) #:nodoc: - options = 0 - option_array.each do |option| - flag = Utf8Proc::Options[option] - raise ArgumentError, "Unknown argument given to utf8map." unless - flag - options |= flag - end - return Utf8Proc::utf8map(str, options) - end - end -end diff --git a/activesupport/lib/active_support/multibyte/unicode_database.rb b/activesupport/lib/active_support/multibyte/unicode_database.rb new file mode 100644 index 0000000000..3b8cf8f9eb --- /dev/null +++ b/activesupport/lib/active_support/multibyte/unicode_database.rb @@ -0,0 +1,71 @@ +# encoding: utf-8 + +module ActiveSupport #:nodoc: + module Multibyte #:nodoc: + # Holds data about a codepoint in the Unicode database + class Codepoint + attr_accessor :code, :combining_class, :decomp_type, :decomp_mapping, :uppercase_mapping, :lowercase_mapping + end + + # Holds static data from the Unicode database + class UnicodeDatabase + ATTRIBUTES = :codepoints, :composition_exclusion, :composition_map, :boundary, :cp1252 + + attr_writer(*ATTRIBUTES) + + def initialize + @codepoints = Hash.new(Codepoint.new) + @composition_exclusion = [] + @composition_map = {} + @boundary = {} + @cp1252 = {} + end + + # Lazy load the Unicode database so it's only loaded when it's actually used + ATTRIBUTES.each do |attr_name| + class_eval(<<-EOS, __FILE__, __LINE__) + def #{attr_name} + load + @#{attr_name} + end + EOS + end + + # Loads the Unicode database and returns all the internal objects of UnicodeDatabase. + def load + begin + @codepoints, @composition_exclusion, @composition_map, @boundary, @cp1252 = File.open(self.class.filename, 'rb') { |f| Marshal.load f.read } + rescue Exception => e + raise IOError.new("Couldn't load the Unicode tables for UTF8Handler (#{e.message}), ActiveSupport::Multibyte is unusable") + end + + # Redefine the === method so we can write shorter rules for grapheme cluster breaks + @boundary.each do |k,_| + @boundary[k].instance_eval do + def ===(other) + detect { |i| i === other } ? true : false + end + end if @boundary[k].kind_of?(Array) + end + + # define attr_reader methods for the instance variables + class << self + attr_reader(*ATTRIBUTES) + end + end + + # Returns the directory in which the data files are stored + def self.dirname + File.dirname(__FILE__) + '/../values/' + end + + # Returns the filename for the data file for this version + def self.filename + File.expand_path File.join(dirname, "unicode_tables.dat") + end + end + + # UniCode Database + UCD = UnicodeDatabase.new + end +end
\ No newline at end of file diff --git a/activesupport/lib/active_support/test_case.rb b/activesupport/lib/active_support/test_case.rb index 0f531b0c79..197e73b3e8 100644 --- a/activesupport/lib/active_support/test_case.rb +++ b/activesupport/lib/active_support/test_case.rb @@ -12,7 +12,13 @@ module ActiveSupport test_name = "test_#{name.gsub(/\s+/,'_')}".to_sym defined = instance_method(test_name) rescue false raise "#{test_name} is already defined in #{self}" if defined - define_method(test_name, &block) + if block_given? + define_method(test_name, &block) + else + define_method(test_name) do + flunk "No implementation provided for #{name}" + end + end end end end diff --git a/activesupport/lib/active_support/time_with_zone.rb b/activesupport/lib/active_support/time_with_zone.rb index 75591b7c34..b7b8807c6d 100644 --- a/activesupport/lib/active_support/time_with_zone.rb +++ b/activesupport/lib/active_support/time_with_zone.rb @@ -1,6 +1,6 @@ require 'tzinfo' module ActiveSupport - # A Time-like class that can represent a time in any time zone. Necessary because standard Ruby Time instances are + # A Time-like class that can represent a time in any time zone. Necessary because standard Ruby Time instances are # limited to UTC and the system's <tt>ENV['TZ']</tt> zone. # # You shouldn't ever need to create a TimeWithZone instance directly via <tt>new</tt> -- instead, Rails provides the methods @@ -32,12 +32,12 @@ module ActiveSupport class TimeWithZone include Comparable attr_reader :time_zone - + def initialize(utc_time, time_zone, local_time = nil, period = nil) @utc, @time_zone, @time = utc_time, time_zone, local_time @period = @utc ? period : get_period_and_ensure_valid_local_time end - + # Returns a Time or DateTime instance that represents the time in +time_zone+. def time @time ||= period.to_local(@utc) @@ -51,7 +51,7 @@ module ActiveSupport alias_method :getgm, :utc alias_method :getutc, :utc alias_method :gmtime, :utc - + # Returns the underlying TZInfo::TimezonePeriod. def period @period ||= time_zone.period_for_utc(@utc) @@ -62,38 +62,38 @@ module ActiveSupport return self if time_zone == new_zone utc.in_time_zone(new_zone) end - + # Returns a <tt>Time.local()</tt> instance of the simultaneous time in your system's <tt>ENV['TZ']</tt> zone def localtime utc.getlocal end alias_method :getlocal, :localtime - + def dst? period.dst? end alias_method :isdst, :dst? - + def utc? time_zone.name == 'UTC' end alias_method :gmt?, :utc? - + def utc_offset period.utc_total_offset end alias_method :gmt_offset, :utc_offset alias_method :gmtoff, :utc_offset - + def formatted_offset(colon = true, alternate_utc_string = nil) utc? && alternate_utc_string || utc_offset.to_utc_offset_s(colon) end - + # Time uses +zone+ to display the time zone abbreviation, so we're duck-typing it. def zone period.zone_identifier.to_s end - + def inspect "#{time.strftime('%a, %d %b %Y %H:%M:%S')} #{zone} #{formatted_offset}" end @@ -122,7 +122,7 @@ module ActiveSupport %("#{time.strftime("%Y/%m/%d %H:%M:%S")} #{formatted_offset(false)}") end end - + def to_yaml(options = {}) if options.kind_of?(YAML::Emitter) utc.to_yaml(options) @@ -130,19 +130,19 @@ module ActiveSupport time.to_yaml(options).gsub('Z', formatted_offset(true, 'Z')) end end - + def httpdate utc.httpdate end - + def rfc2822 to_s(:rfc822) end alias_method :rfc822, :rfc2822 - + # <tt>:db</tt> format outputs time in UTC; all others output time in local. # Uses TimeWithZone's +strftime+, so <tt>%Z</tt> and <tt>%z</tt> work correctly. - def to_s(format = :default) + def to_s(format = :default) return utc.to_s(format) if format == :db if formatter = ::Time::DATE_FORMATS[format] formatter.respond_to?(:call) ? formatter.call(self).to_s : strftime(formatter) @@ -150,27 +150,39 @@ module ActiveSupport "#{time.strftime("%Y-%m-%d %H:%M:%S")} #{formatted_offset(false, 'UTC')}" # mimicking Ruby 1.9 Time#to_s format end end - + # Replaces <tt>%Z</tt> and <tt>%z</tt> directives with +zone+ and +formatted_offset+, respectively, before passing to # Time#strftime, so that zone information is correct def strftime(format) format = format.gsub('%Z', zone).gsub('%z', formatted_offset(false)) time.strftime(format) end - + # Use the time in UTC for comparisons. def <=>(other) utc <=> other end - + def between?(min, max) utc.between?(min, max) end - + + def past? + utc.past? + end + + def today? + time.today? + end + + def future? + utc.future? + end + def eql?(other) utc == other end - + def +(other) # If we're adding a Duration of variable length (i.e., years, months, days), move forward from #time, # otherwise move forward from #utc, for accuracy when moving across DST boundaries @@ -194,7 +206,7 @@ module ActiveSupport result.in_time_zone(time_zone) end end - + def since(other) # If we're adding a Duration of variable length (i.e., years, months, days), move forward from #time, # otherwise move forward from #utc, for accuracy when moving across DST boundaries @@ -204,7 +216,7 @@ module ActiveSupport utc.since(other).in_time_zone(time_zone) end end - + def ago(other) since(-other) end @@ -218,53 +230,53 @@ module ActiveSupport utc.advance(options).in_time_zone(time_zone) end end - - %w(year mon month day mday hour min sec).each do |method_name| + + %w(year mon month day mday wday yday hour min sec to_date).each do |method_name| class_eval <<-EOV def #{method_name} time.#{method_name} end EOV end - + def usec time.respond_to?(:usec) ? time.usec : 0 end - + def to_a [time.sec, time.min, time.hour, time.day, time.mon, time.year, time.wday, time.yday, dst?, zone] end - + def to_f utc.to_f - end - + end + def to_i utc.to_i end alias_method :hash, :to_i alias_method :tv_sec, :to_i - + # A TimeWithZone acts like a Time, so just return +self+. def to_time self end - + def to_datetime utc.to_datetime.new_offset(Rational(utc_offset, 86_400)) end - + # So that +self+ <tt>acts_like?(:time)</tt>. def acts_like_time? true end - + # Say we're a Time to thwart type checking. def is_a?(klass) klass == ::Time || super end alias_method :kind_of?, :is_a? - + # Neuter freeze because freezing can cause problems with lazy loading of attributes. def freeze self @@ -273,7 +285,7 @@ module ActiveSupport def marshal_dump [utc, time_zone.name, time] end - + def marshal_load(variables) initialize(variables[0].utc, ::Time.__send__(:get_zone, variables[1]), variables[2].utc) end @@ -290,10 +302,10 @@ module ActiveSupport result = time.__send__(sym, *args, &block) result.acts_like?(:time) ? self.class.new(nil, time_zone, result) : result end - - private + + private def get_period_and_ensure_valid_local_time - # we don't want a Time.local instance enforcing its own DST rules as well, + # we don't want a Time.local instance enforcing its own DST rules as well, # so transfer time values to a utc constructor if necessary @time = transfer_time_values_to_utc_constructor(@time) unless @time.utc? begin @@ -304,11 +316,11 @@ module ActiveSupport retry end end - + def transfer_time_values_to_utc_constructor(time) ::Time.utc_time(time.year, time.month, time.day, time.hour, time.min, time.sec, time.respond_to?(:usec) ? time.usec : 0) end - + def duration_of_variable_length?(obj) ActiveSupport::Duration === obj && obj.parts.flatten.detect {|p| [:years, :months, :days].include? p } end diff --git a/activesupport/lib/active_support/values/unicode_tables.dat b/activesupport/lib/active_support/values/unicode_tables.dat Binary files differindex 35edb148c3..74b333d416 100644 --- a/activesupport/lib/active_support/values/unicode_tables.dat +++ b/activesupport/lib/active_support/values/unicode_tables.dat diff --git a/activesupport/lib/active_support/vendor/i18n-0.0.1/i18n.rb b/activesupport/lib/active_support/vendor/i18n-0.0.1/i18n.rb index 0988ea8f44..344c77aecf 100755 --- a/activesupport/lib/active_support/vendor/i18n-0.0.1/i18n.rb +++ b/activesupport/lib/active_support/vendor/i18n-0.0.1/i18n.rb @@ -10,7 +10,8 @@ require 'i18n/exceptions' module I18n @@backend = nil - @@default_locale = 'en-US' + @@load_path = nil + @@default_locale = :'en-US' @@exception_handler = :default_exception_handler class << self @@ -49,14 +50,22 @@ module I18n @@exception_handler = exception_handler end - # Allows client libraries to pass arguments that specify a source for - # translation data to be loaded by the backend. The backend defines - # acceptable sources. + # Allow clients to register paths providing translation data sources. The + # backend defines acceptable sources. + # # E.g. the provided SimpleBackend accepts a list of paths to translation # files which are either named *.rb and contain plain Ruby Hashes or are - # named *.yml and contain YAML data.) - def load_translations(*args) - backend.load_translations(*args) + # named *.yml and contain YAML data. So for the SimpleBackend clients may + # register translation files like this: + # I18n.load_path << 'path/to/locale/en-US.yml' + def load_path + @@load_path ||= [] + end + + # Sets the load path instance. Custom implementations are expected to + # behave like a Ruby Array. + def load_path=(load_path) + @@load_path = load_path end # Translates, pluralizes and interpolates a given key using a given locale, @@ -175,6 +184,4 @@ module I18n keys.flatten.map{|k| k.to_sym} end end -end - - +end
\ No newline at end of file diff --git a/activesupport/lib/active_support/vendor/i18n-0.0.1/i18n/backend/simple.rb b/activesupport/lib/active_support/vendor/i18n-0.0.1/i18n/backend/simple.rb index e2d19cdd45..2dbaf8a405 100644 --- a/activesupport/lib/active_support/vendor/i18n-0.0.1/i18n/backend/simple.rb +++ b/activesupport/lib/active_support/vendor/i18n-0.0.1/i18n/backend/simple.rb @@ -1,10 +1,9 @@ -require 'strscan' +require 'yaml' module I18n module Backend class Simple INTERPOLATION_RESERVED_KEYS = %w(scope default) - DEPRECATED_INTERPOLATORS = { '%d' => '{{count}}', '%s' => '{{value}}' } MATCH = /(\\\\)?\{\{([^\}]+)\}\}/ # Accepts a list of paths to translation files. Loads translations from @@ -60,7 +59,16 @@ module I18n object.strftime(format) end + def initialized? + @initialized ||= false + end + protected + + def init_translations + load_translations(*I18n.load_path) + @initialized = true + end def translations @translations ||= {} @@ -73,6 +81,7 @@ module I18n # <tt>%w(currency format)</tt>. def lookup(locale, key, scope = []) return unless key + init_translations unless initialized? keys = I18n.send :normalize_translation_keys, locale, key, scope keys.inject(translations){|result, k| result[k.to_sym] or return nil } end @@ -95,7 +104,7 @@ module I18n rescue MissingTranslationData nil end - + # Picks a translation from an array according to English pluralization # rules. It will pick the first translation if count is not equal to 1 # and the second translation if it is equal to 1. Other backends can @@ -120,12 +129,6 @@ module I18n def interpolate(locale, string, values = {}) return string unless string.is_a?(String) - string = string.gsub(/%d|%s/) do |s| - instead = DEPRECATED_INTERPOLATORS[s] - ActiveSupport::Deprecation.warn "using #{s} in messages is deprecated; use #{instead} instead." - instead - end - if string.respond_to?(:force_encoding) original_encoding = string.encoding string.force_encoding(Encoding::BINARY) diff --git a/activesupport/lib/active_support/version.rb b/activesupport/lib/active_support/version.rb index b346459a9b..8f5395fca6 100644 --- a/activesupport/lib/active_support/version.rb +++ b/activesupport/lib/active_support/version.rb @@ -1,7 +1,7 @@ module ActiveSupport module VERSION #:nodoc: MAJOR = 2 - MINOR = 1 + MINOR = 2 TINY = 0 STRING = [MAJOR, MINOR, TINY].join('.') diff --git a/activesupport/test/abstract_unit.rb b/activesupport/test/abstract_unit.rb index cce8d5d220..a698beaa0e 100644 --- a/activesupport/test/abstract_unit.rb +++ b/activesupport/test/abstract_unit.rb @@ -1,9 +1,15 @@ +# encoding: utf-8 + require 'test/unit' $:.unshift "#{File.dirname(__FILE__)}/../lib" $:.unshift File.dirname(__FILE__) require 'active_support' +if RUBY_VERSION < '1.9' + $KCODE = 'UTF8' +end + def uses_gem(gem_name, test_name, version = '> 0') require 'rubygems' gem gem_name.to_s, version @@ -22,3 +28,16 @@ end # Show backtraces for deprecated behavior for quicker cleanup. ActiveSupport::Deprecation.debug = true + +def with_kcode(code) + if RUBY_VERSION < '1.9' + begin + old_kcode, $KCODE = $KCODE, code + yield + ensure + $KCODE = old_kcode + end + else + yield + end +end
\ No newline at end of file diff --git a/activesupport/test/core_ext/date_ext_test.rb b/activesupport/test/core_ext/date_ext_test.rb index 0f3cf4c75c..b53c754780 100644 --- a/activesupport/test/core_ext/date_ext_test.rb +++ b/activesupport/test/core_ext/date_ext_test.rb @@ -210,6 +210,29 @@ class DateExtCalculationsTest < Test::Unit::TestCase end end + uses_mocha 'past?, today? and future?' do + def test_today + Date.stubs(:current).returns(Date.new(2000, 1, 1)) + assert_equal false, Date.new(1999, 12, 31).today? + assert_equal true, Date.new(2000,1,1).today? + assert_equal false, Date.new(2000,1,2).today? + end + + def test_past + Date.stubs(:current).returns(Date.new(2000, 1, 1)) + assert_equal true, Date.new(1999, 12, 31).past? + assert_equal false, Date.new(2000,1,1).past? + assert_equal false, Date.new(2000,1,2).past? + end + + def test_future + Date.stubs(:current).returns(Date.new(2000, 1, 1)) + assert_equal false, Date.new(1999, 12, 31).future? + assert_equal false, Date.new(2000,1,1).future? + assert_equal true, Date.new(2000,1,2).future? + end + end + uses_mocha 'TestDateCurrent' do def test_current_returns_date_today_when_zone_default_not_set with_env_tz 'US/Central' do diff --git a/activesupport/test/core_ext/date_time_ext_test.rb b/activesupport/test/core_ext/date_time_ext_test.rb index 854a3a05e1..be3cd8b5d6 100644 --- a/activesupport/test/core_ext/date_time_ext_test.rb +++ b/activesupport/test/core_ext/date_time_ext_test.rb @@ -207,6 +207,81 @@ class DateTimeExtCalculationsTest < Test::Unit::TestCase assert_match(/^2080-02-28T15:15:10-06:?00$/, DateTime.civil(2080, 2, 28, 15, 15, 10, -0.25).xmlschema) end + uses_mocha 'Test DateTime past?, today? and future?' do + def test_today_with_offset + Date.stubs(:current).returns(Date.new(2000, 1, 1)) + assert_equal false, DateTime.civil(1999,12,31,23,59,59, Rational(-18000, 86400)).today? + assert_equal true, DateTime.civil(2000,1,1,0,0,0, Rational(-18000, 86400)).today? + assert_equal true, DateTime.civil(2000,1,1,23,59,59, Rational(-18000, 86400)).today? + assert_equal false, DateTime.civil(2000,1,2,0,0,0, Rational(-18000, 86400)).today? + end + + def test_today_without_offset + Date.stubs(:current).returns(Date.new(2000, 1, 1)) + assert_equal false, DateTime.civil(1999,12,31,23,59,59).today? + assert_equal true, DateTime.civil(2000,1,1,0).today? + assert_equal true, DateTime.civil(2000,1,1,23,59,59).today? + assert_equal false, DateTime.civil(2000,1,2,0).today? + end + + def test_past_with_offset + DateTime.stubs(:current).returns(DateTime.civil(2005,2,10,15,30,45, Rational(-18000, 86400))) + assert_equal true, DateTime.civil(2005,2,10,15,30,44, Rational(-18000, 86400)).past? + assert_equal false, DateTime.civil(2005,2,10,15,30,45, Rational(-18000, 86400)).past? + assert_equal false, DateTime.civil(2005,2,10,15,30,46, Rational(-18000, 86400)).past? + end + + def test_past_without_offset + DateTime.stubs(:current).returns(DateTime.civil(2005,2,10,15,30,45, Rational(-18000, 86400))) + assert_equal true, DateTime.civil(2005,2,10,20,30,44).past? + assert_equal false, DateTime.civil(2005,2,10,20,30,45).past? + assert_equal false, DateTime.civil(2005,2,10,20,30,46).past? + end + + def test_future_with_offset + DateTime.stubs(:current).returns(DateTime.civil(2005,2,10,15,30,45, Rational(-18000, 86400))) + assert_equal false, DateTime.civil(2005,2,10,15,30,44, Rational(-18000, 86400)).future? + assert_equal false, DateTime.civil(2005,2,10,15,30,45, Rational(-18000, 86400)).future? + assert_equal true, DateTime.civil(2005,2,10,15,30,46, Rational(-18000, 86400)).future? + end + + def test_future_without_offset + DateTime.stubs(:current).returns(DateTime.civil(2005,2,10,15,30,45, Rational(-18000, 86400))) + assert_equal false, DateTime.civil(2005,2,10,20,30,44).future? + assert_equal false, DateTime.civil(2005,2,10,20,30,45).future? + assert_equal true, DateTime.civil(2005,2,10,20,30,46).future? + end + end + + uses_mocha 'TestDateTimeCurrent' do + def test_current_returns_date_today_when_zone_default_not_set + with_env_tz 'US/Eastern' do + Time.stubs(:now).returns Time.local(1999, 12, 31, 23, 59, 59) + assert_equal DateTime.new(1999, 12, 31, 23, 59, 59, Rational(-18000, 86400)), DateTime.current + end + end + + def test_current_returns_time_zone_today_when_zone_default_set + Time.zone_default = ActiveSupport::TimeZone['Eastern Time (US & Canada)'] + with_env_tz 'US/Eastern' do + Time.stubs(:now).returns Time.local(1999, 12, 31, 23, 59, 59) + assert_equal DateTime.new(1999, 12, 31, 23, 59, 59, Rational(-18000, 86400)), DateTime.current + end + ensure + Time.zone_default = nil + end + end + + def test_current_without_time_zone + assert DateTime.current.is_a?(DateTime) + end + + def test_current_with_time_zone + with_env_tz 'US/Eastern' do + assert DateTime.current.is_a?(DateTime) + end + end + def test_acts_like_time assert DateTime.new.acts_like_time? end diff --git a/activesupport/test/core_ext/hash_ext_test.rb b/activesupport/test/core_ext/hash_ext_test.rb index 44d48e7577..9537f486cb 100644 --- a/activesupport/test/core_ext/hash_ext_test.rb +++ b/activesupport/test/core_ext/hash_ext_test.rb @@ -329,6 +329,16 @@ class HashExtTest < Test::Unit::TestCase end end + def test_indifferent_slice_access_with_symbols + original = {'login' => 'bender', 'password' => 'shiny', 'stuff' => 'foo'} + original = original.with_indifferent_access + + slice = original.slice(:login, :password) + + assert_equal 'bender', slice[:login] + assert_equal 'bender', slice['login'] + end + def test_except original = { :a => 'x', :b => 'y', :c => 10 } expected = { :a => 'x', :b => 'y' } diff --git a/activesupport/test/core_ext/string_ext_test.rb b/activesupport/test/core_ext/string_ext_test.rb index c0decf2c3f..b086c957fe 100644 --- a/activesupport/test/core_ext/string_ext_test.rb +++ b/activesupport/test/core_ext/string_ext_test.rb @@ -191,13 +191,12 @@ class StringInflectionsTest < Test::Unit::TestCase if RUBY_VERSION < '1.9' def test_each_char_with_utf8_string_when_kcode_is_utf8 - old_kcode, $KCODE = $KCODE, 'UTF8' - '€2.99'.each_char do |char| - assert_not_equal 1, char.length - break + with_kcode('UTF8') do + '€2.99'.each_char do |char| + assert_not_equal 1, char.length + break + end end - ensure - $KCODE = old_kcode end end end @@ -206,4 +205,52 @@ class StringBehaviourTest < Test::Unit::TestCase def test_acts_like_string assert 'Bambi'.acts_like_string? end +end + +class CoreExtStringMultibyteTest < Test::Unit::TestCase + UNICODE_STRING = 'こにちわ' + ASCII_STRING = 'ohayo' + BYTE_STRING = "\270\236\010\210\245" + + def test_core_ext_adds_mb_chars + assert UNICODE_STRING.respond_to?(:mb_chars) + end + + def test_string_should_recognize_utf8_strings + assert UNICODE_STRING.is_utf8? + assert ASCII_STRING.is_utf8? + assert !BYTE_STRING.is_utf8? + end + + if RUBY_VERSION < '1.8.7' + def test_core_ext_adds_chars + assert UNICODE_STRING.respond_to?(:chars) + end + + def test_chars_warns_about_deprecation + assert_deprecated("String#chars") do + ''.chars + end + end + end + + if RUBY_VERSION < '1.9' + def test_mb_chars_returns_self_when_kcode_not_set + with_kcode('none') do + assert UNICODE_STRING.mb_chars.kind_of?(String) + end + end + + def test_mb_chars_returns_an_instance_of_the_chars_proxy_when_kcode_utf8 + with_kcode('UTF8') do + assert UNICODE_STRING.mb_chars.kind_of?(ActiveSupport::Multibyte.proxy_class) + end + end + end + + if RUBY_VERSION >= '1.9' + def test_mb_chars_returns_string + assert UNICODE_STRING.mb_chars.kind_of?(String) + end + end end
\ No newline at end of file diff --git a/activesupport/test/core_ext/time_ext_test.rb b/activesupport/test/core_ext/time_ext_test.rb index c1bdee4ca9..8ceaedc7f4 100644 --- a/activesupport/test/core_ext/time_ext_test.rb +++ b/activesupport/test/core_ext/time_ext_test.rb @@ -117,6 +117,7 @@ class TimeExtCalculationsTest < Test::Unit::TestCase assert_equal Time.local(2007,3,31,23,59,59), Time.local(2007,3,31,0,0,0).end_of_quarter assert_equal Time.local(2007,12,31,23,59,59), Time.local(2007,12,21,10,10,10).end_of_quarter assert_equal Time.local(2007,6,30,23,59,59), Time.local(2007,4,1,0,0,0).end_of_quarter + assert_equal Time.local(2008,6,30,23,59,59), Time.local(2008,5,31,0,0,0).end_of_quarter end def test_end_of_year @@ -563,6 +564,74 @@ class TimeExtCalculationsTest < Test::Unit::TestCase assert_nothing_raised { Time.now.xmlschema } end + uses_mocha 'Test Time past?, today? and future?' do + def test_today_with_time_local + Date.stubs(:current).returns(Date.new(2000, 1, 1)) + assert_equal false, Time.local(1999,12,31,23,59,59).today? + assert_equal true, Time.local(2000,1,1,0).today? + assert_equal true, Time.local(2000,1,1,23,59,59).today? + assert_equal false, Time.local(2000,1,2,0).today? + end + + def test_today_with_time_utc + Date.stubs(:current).returns(Date.new(2000, 1, 1)) + assert_equal false, Time.utc(1999,12,31,23,59,59).today? + assert_equal true, Time.utc(2000,1,1,0).today? + assert_equal true, Time.utc(2000,1,1,23,59,59).today? + assert_equal false, Time.utc(2000,1,2,0).today? + end + + def test_past_with_time_current_as_time_local + with_env_tz 'US/Eastern' do + Time.stubs(:current).returns(Time.local(2005,2,10,15,30,45)) + assert_equal true, Time.local(2005,2,10,15,30,44).past? + assert_equal false, Time.local(2005,2,10,15,30,45).past? + assert_equal false, Time.local(2005,2,10,15,30,46).past? + assert_equal true, Time.utc(2005,2,10,20,30,44).past? + assert_equal false, Time.utc(2005,2,10,20,30,45).past? + assert_equal false, Time.utc(2005,2,10,20,30,46).past? + end + end + + def test_past_with_time_current_as_time_with_zone + with_env_tz 'US/Eastern' do + twz = Time.utc(2005,2,10,15,30,45).in_time_zone('Central Time (US & Canada)') + Time.stubs(:current).returns(twz) + assert_equal true, Time.local(2005,2,10,10,30,44).past? + assert_equal false, Time.local(2005,2,10,10,30,45).past? + assert_equal false, Time.local(2005,2,10,10,30,46).past? + assert_equal true, Time.utc(2005,2,10,15,30,44).past? + assert_equal false, Time.utc(2005,2,10,15,30,45).past? + assert_equal false, Time.utc(2005,2,10,15,30,46).past? + end + end + + def test_future_with_time_current_as_time_local + with_env_tz 'US/Eastern' do + Time.stubs(:current).returns(Time.local(2005,2,10,15,30,45)) + assert_equal false, Time.local(2005,2,10,15,30,44).future? + assert_equal false, Time.local(2005,2,10,15,30,45).future? + assert_equal true, Time.local(2005,2,10,15,30,46).future? + assert_equal false, Time.utc(2005,2,10,20,30,44).future? + assert_equal false, Time.utc(2005,2,10,20,30,45).future? + assert_equal true, Time.utc(2005,2,10,20,30,46).future? + end + end + + def test_future_with_time_current_as_time_with_zone + with_env_tz 'US/Eastern' do + twz = Time.utc(2005,2,10,15,30,45).in_time_zone('Central Time (US & Canada)') + Time.stubs(:current).returns(twz) + assert_equal false, Time.local(2005,2,10,10,30,44).future? + assert_equal false, Time.local(2005,2,10,10,30,45).future? + assert_equal true, Time.local(2005,2,10,10,30,46).future? + assert_equal false, Time.utc(2005,2,10,15,30,44).future? + assert_equal false, Time.utc(2005,2,10,15,30,45).future? + assert_equal true, Time.utc(2005,2,10,15,30,46).future? + end + end + end + def test_acts_like_time assert Time.new.acts_like_time? end @@ -640,24 +709,24 @@ class TimeExtMarshalingTest < Test::Unit::TestCase assert_equal t, unmarshaled assert_equal t.zone, unmarshaled.zone end - - def test_marshaling_with_local_instance + + def test_marshaling_with_local_instance t = Time.local(2000) marshaled = Marshal.dump t unmarshaled = Marshal.load marshaled assert_equal t, unmarshaled assert_equal t.zone, unmarshaled.zone end - - def test_marshaling_with_frozen_utc_instance + + def test_marshaling_with_frozen_utc_instance t = Time.utc(2000).freeze marshaled = Marshal.dump t unmarshaled = Marshal.load marshaled assert_equal t, unmarshaled assert_equal t.zone, unmarshaled.zone end - - def test_marshaling_with_frozen_local_instance + + def test_marshaling_with_frozen_local_instance t = Time.local(2000).freeze marshaled = Marshal.dump t unmarshaled = Marshal.load marshaled diff --git a/activesupport/test/core_ext/time_with_zone_test.rb b/activesupport/test/core_ext/time_with_zone_test.rb index dfe04485be..72b540efe0 100644 --- a/activesupport/test/core_ext/time_with_zone_test.rb +++ b/activesupport/test/core_ext/time_with_zone_test.rb @@ -152,6 +152,50 @@ class TimeWithZoneTest < Test::Unit::TestCase assert_equal false, @twz.between?(Time.utc(2000,1,1,0,0,1), Time.utc(2000,1,1,0,0,2)) end + uses_mocha 'TimeWithZone past?, today? and future?' do + def test_today + Date.stubs(:current).returns(Date.new(2000, 1, 1)) + assert_equal false, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.utc(1999,12,31,23,59,59) ).today? + assert_equal true, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.utc(2000,1,1,0) ).today? + assert_equal true, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.utc(2000,1,1,23,59,59) ).today? + assert_equal false, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.utc(2000,1,2,0) ).today? + end + + def test_past_with_time_current_as_time_local + with_env_tz 'US/Eastern' do + Time.stubs(:current).returns(Time.local(2005,2,10,15,30,45)) + assert_equal true, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,44)).past? + assert_equal false, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,45)).past? + assert_equal false, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,46)).past? + end + end + + def test_past_with_time_current_as_time_with_zone + twz = ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,45) ) + Time.stubs(:current).returns(twz) + assert_equal true, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,44)).past? + assert_equal false, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,45)).past? + assert_equal false, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,46)).past? + end + + def test_future_with_time_current_as_time_local + with_env_tz 'US/Eastern' do + Time.stubs(:current).returns(Time.local(2005,2,10,15,30,45)) + assert_equal false, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,44)).future? + assert_equal false, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,45)).future? + assert_equal true, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,46)).future? + end + end + + def future_with_time_current_as_time_with_zone + twz = ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,45) ) + Time.stubs(:current).returns(twz) + assert_equal false, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,44)).future? + assert_equal false, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,45)).future? + assert_equal true, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,46)).future? + end + end + def test_eql? assert @twz.eql?(Time.utc(2000)) assert @twz.eql?( ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone["Hawaii"]) ) @@ -353,7 +397,7 @@ class TimeWithZoneTest < Test::Unit::TestCase 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) - twz.stubs(:method_missing).returns(nil) #ensure these methods are defined directly on class + twz.expects(:method_missing).never assert_equal 1999, twz.year assert_equal 12, twz.month assert_equal 31, twz.day @@ -361,6 +405,8 @@ class TimeWithZoneTest < Test::Unit::TestCase assert_equal 18, twz.min assert_equal 17, twz.sec assert_equal 500, twz.usec + assert_equal 5, twz.wday + assert_equal 365, twz.yday end end end @@ -538,7 +584,7 @@ class TimeWithZoneTest < Test::Unit::TestCase assert_equal "Sun, 02 Apr 2006 10:30:01 EDT -04:00", twz.since(1.days + 1.second).inspect assert_equal "Sun, 02 Apr 2006 10:30:01 EDT -04:00", (twz + 1.days + 1.second).inspect end - + def test_advance_1_day_across_spring_dst_transition_backwards twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006,4,2,10,30)) # In 2006, spring DST transition occurred Apr 2 at 2AM; this day was only 23 hours long @@ -548,7 +594,7 @@ class TimeWithZoneTest < Test::Unit::TestCase assert_equal "Sat, 01 Apr 2006 10:30:00 EST -05:00", (twz - 1.days).inspect assert_equal "Sat, 01 Apr 2006 10:30:01 EST -05:00", twz.ago(1.days - 1.second).inspect end - + def test_advance_1_day_expressed_as_number_of_seconds_minutes_or_hours_across_spring_dst_transition twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006,4,1,10,30)) # In 2006, spring DST transition occurred Apr 2 at 2AM; this day was only 23 hours long @@ -565,7 +611,7 @@ class TimeWithZoneTest < Test::Unit::TestCase assert_equal "Sun, 02 Apr 2006 11:30:00 EDT -04:00", twz.since(24.hours).inspect assert_equal "Sun, 02 Apr 2006 11:30:00 EDT -04:00", twz.advance(:hours => 24).inspect end - + def test_advance_1_day_expressed_as_number_of_seconds_minutes_or_hours_across_spring_dst_transition_backwards twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006,4,2,11,30)) # In 2006, spring DST transition occurred Apr 2 at 2AM; this day was only 23 hours long @@ -582,7 +628,7 @@ class TimeWithZoneTest < Test::Unit::TestCase assert_equal "Sat, 01 Apr 2006 10:30:00 EST -05:00", twz.ago(24.hours).inspect assert_equal "Sat, 01 Apr 2006 10:30:00 EST -05:00", twz.advance(:hours => -24).inspect end - + def test_advance_1_day_across_fall_dst_transition twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006,10,28,10,30)) # In 2006, fall DST transition occurred Oct 29 at 2AM; this day was 25 hours long @@ -593,7 +639,7 @@ class TimeWithZoneTest < Test::Unit::TestCase assert_equal "Sun, 29 Oct 2006 10:30:01 EST -05:00", twz.since(1.days + 1.second).inspect assert_equal "Sun, 29 Oct 2006 10:30:01 EST -05:00", (twz + 1.days + 1.second).inspect end - + def test_advance_1_day_across_fall_dst_transition_backwards twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006,10,29,10,30)) # In 2006, fall DST transition occurred Oct 29 at 2AM; this day was 25 hours long @@ -603,7 +649,7 @@ class TimeWithZoneTest < Test::Unit::TestCase assert_equal "Sat, 28 Oct 2006 10:30:00 EDT -04:00", (twz - 1.days).inspect assert_equal "Sat, 28 Oct 2006 10:30:01 EDT -04:00", twz.ago(1.days - 1.second).inspect end - + def test_advance_1_day_expressed_as_number_of_seconds_minutes_or_hours_across_fall_dst_transition twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006,10,28,10,30)) # In 2006, fall DST transition occurred Oct 29 at 2AM; this day was 25 hours long @@ -620,7 +666,7 @@ class TimeWithZoneTest < Test::Unit::TestCase assert_equal "Sun, 29 Oct 2006 09:30:00 EST -05:00", twz.since(24.hours).inspect assert_equal "Sun, 29 Oct 2006 09:30:00 EST -05:00", twz.advance(:hours => 24).inspect end - + def test_advance_1_day_expressed_as_number_of_seconds_minutes_or_hours_across_fall_dst_transition_backwards twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006,10,29,9,30)) # In 2006, fall DST transition occurred Oct 29 at 2AM; this day was 25 hours long @@ -669,7 +715,7 @@ class TimeWithZoneTest < Test::Unit::TestCase assert_equal "Sat, 28 Oct 2006 10:30:00 EDT -04:00", twz.ago(1.month).inspect assert_equal "Sat, 28 Oct 2006 10:30:00 EDT -04:00", (twz - 1.month).inspect end - + def test_advance_1_year twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2008,2,15,10,30)) assert_equal "Sun, 15 Feb 2009 10:30:00 EST -05:00", twz.advance(:years => 1).inspect @@ -679,7 +725,7 @@ class TimeWithZoneTest < Test::Unit::TestCase assert_equal "Thu, 15 Feb 2007 10:30:00 EST -05:00", twz.years_ago(1).inspect assert_equal "Thu, 15 Feb 2007 10:30:00 EST -05:00", (twz - 1.year).inspect end - + def test_advance_1_year_during_dst twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2008,7,15,10,30)) assert_equal "Wed, 15 Jul 2009 10:30:00 EDT -04:00", twz.advance(:years => 1).inspect @@ -689,6 +735,14 @@ class TimeWithZoneTest < Test::Unit::TestCase assert_equal "Sun, 15 Jul 2007 10:30:00 EDT -04:00", twz.years_ago(1).inspect assert_equal "Sun, 15 Jul 2007 10:30:00 EDT -04:00", (twz - 1.year).inspect 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 class TimeWithZoneMethodsForTimeAndDateTimeTest < Test::Unit::TestCase diff --git a/activesupport/test/inflector_test.rb b/activesupport/test/inflector_test.rb index f304844e82..d30852c013 100644 --- a/activesupport/test/inflector_test.rb +++ b/activesupport/test/inflector_test.rb @@ -104,6 +104,12 @@ class InflectorTest < Test::Unit::TestCase end end + def test_parameterize_with_custom_separator + StringToParameterized.each do |some_string, parameterized_string| + assert_equal(parameterized_string.gsub('-', '_'), ActiveSupport::Inflector.parameterize(some_string, '_')) + end + end + def test_classify ClassNameToTableName.each do |class_name, table_name| assert_equal(class_name, ActiveSupport::Inflector.classify(table_name)) diff --git a/activesupport/test/inflector_test_cases.rb b/activesupport/test/inflector_test_cases.rb index 8057809dbd..fc7a35f859 100644 --- a/activesupport/test/inflector_test_cases.rb +++ b/activesupport/test/inflector_test_cases.rb @@ -147,7 +147,10 @@ module InflectorTestCases "Random text with *(bad)* characters" => "random-text-with-bad-characters", "Malmö" => "malmo", "Garçons" => "garcons", - "Allow_Under_Scores" => "allow_under_scores" + "Allow_Under_Scores" => "allow_under_scores", + "Trailing bad characters!@#" => "trailing-bad-characters", + "!@#Leading bad characters" => "leading-bad-characters", + "Squeeze separators" => "squeeze-separators" } UnderscoreToHuman = { diff --git a/activesupport/test/json/encoding_test.rb b/activesupport/test/json/encoding_test.rb index 38bb8f3e79..497f028369 100644 --- a/activesupport/test/json/encoding_test.rb +++ b/activesupport/test/json/encoding_test.rb @@ -101,18 +101,6 @@ class TestJSONEncoding < Test::Unit::TestCase end protected - def with_kcode(code) - if RUBY_VERSION < '1.9' - begin - old_kcode, $KCODE = $KCODE, 'UTF8' - yield - ensure - $KCODE = old_kcode - end - else - yield - end - end def object_keys(json_object) json_object[1..-2].scan(/([^{}:,\s]+):/).flatten.sort diff --git a/activesupport/test/multibyte_chars_test.rb b/activesupport/test/multibyte_chars_test.rb index a87309b038..ca2af9b986 100644 --- a/activesupport/test/multibyte_chars_test.rb +++ b/activesupport/test/multibyte_chars_test.rb @@ -1,186 +1,569 @@ # encoding: utf-8 + require 'abstract_unit' +require 'multibyte_test_helpers' -if RUBY_VERSION < '1.9' +class String + def __method_for_multibyte_testing_with_integer_result; 1; end + def __method_for_multibyte_testing; 'result'; end + def __method_for_multibyte_testing!; 'result'; end +end -$KCODE = 'UTF8' +class MultibyteCharsTest < Test::Unit::TestCase + include MultibyteTestHelpers -class CharsTest < Test::Unit::TestCase - def setup - @s = { - :utf8 => "Abcd Блå ffi блa 埋", - :ascii => "asci ias c iia s", - :bytes => "\270\236\010\210\245" - } + @proxy_class = ActiveSupport::Multibyte::Chars + @chars = @proxy_class.new UNICODE_STRING + end + + def test_wraps_the_original_string + assert_equal UNICODE_STRING, @chars.to_s + assert_equal UNICODE_STRING, @chars.wrapped_string end - - def test_sanity - @s.each do |t, s| - assert s.respond_to?(:chars), "All string should have the chars method (#{t})" - assert s.respond_to?(:to_s), "All string should have the to_s method (#{t})" - assert_kind_of ActiveSupport::Multibyte::Chars, s.chars, "#chars should return an instance of Chars (#{t})" + + def test_should_allow_method_calls_to_string + assert_nothing_raised do + @chars.__method_for_multibyte_testing + end + assert_raises NoMethodError do + @chars.__unknown_method end end - - def test_comparability - @s.each do |t, s| - assert_equal s, s.chars.to_s, "Chars#to_s should return enclosed string unchanged" + + def test_forwarded_method_calls_should_return_new_chars_instance + assert @chars.__method_for_multibyte_testing.kind_of?(@proxy_class) + assert_not_equal @chars.object_id, @chars.__method_for_multibyte_testing.object_id + end + + def test_forwarded_bang_method_calls_should_return_the_original_chars_instance + assert @chars.__method_for_multibyte_testing!.kind_of?(@proxy_class) + assert_equal @chars.object_id, @chars.__method_for_multibyte_testing!.object_id + end + + def test_methods_are_forwarded_to_wrapped_string_for_byte_strings + assert_equal BYTE_STRING.class, BYTE_STRING.mb_chars.class + end + + def test_forwarded_method_with_non_string_result_should_be_returned_vertabim + assert_equal ''.__method_for_multibyte_testing_with_integer_result, @chars.__method_for_multibyte_testing_with_integer_result + end + + def test_should_concatenate + assert_equal 'ab', 'a'.mb_chars + 'b' + assert_equal 'ab', 'a' + 'b'.mb_chars + assert_equal 'ab', 'a'.mb_chars + 'b'.mb_chars + + assert_equal 'ab', 'a'.mb_chars << 'b' + assert_equal 'ab', 'a' << 'b'.mb_chars + assert_equal 'ab', 'a'.mb_chars << 'b'.mb_chars + end + + def test_consumes_utf8_strings + assert @proxy_class.consumes?(UNICODE_STRING) + assert @proxy_class.consumes?(ASCII_STRING) + assert !@proxy_class.consumes?(BYTE_STRING) + end + + def test_unpack_utf8_strings + assert_equal 4, @proxy_class.u_unpack(UNICODE_STRING).length + assert_equal 5, @proxy_class.u_unpack(ASCII_STRING).length + end + + def test_unpack_raises_encoding_error_on_broken_strings + assert_raises(ActiveSupport::Multibyte::EncodingError) do + @proxy_class.u_unpack(BYTE_STRING) end - assert_nothing_raised do - assert_equal "a", "a", "Normal string comparisons should be unaffected" - assert_not_equal "a", "b", "Normal string comparisons should be unaffected" - assert_not_equal "a".chars, "b".chars, "Chars objects should be comparable" - assert_equal "a".chars, "A".downcase.chars, "Chars objects should be comparable to each other" - assert_equal "a".chars, "A".downcase, "Chars objects should be comparable to strings coming from elsewhere" - end - - assert !@s[:utf8].eql?(@s[:utf8].chars), "Strict comparison is not supported" - assert_equal @s[:utf8], @s[:utf8].chars, "Chars should be compared by their enclosed string" - - other_string = @s[:utf8].dup - assert_equal other_string, @s[:utf8].chars, "Chars should be compared by their enclosed string" - assert_equal other_string.chars, @s[:utf8].chars, "Chars should be compared by their enclosed string" - - strings = ['builder'.chars, 'armor'.chars, 'zebra'.chars] - strings.sort! - assert_equal ['armor', 'builder', 'zebra'], strings, "Chars should be sortable based on their enclosed string" - - # This leads to a StackLevelTooDeep exception if the comparison is not wired properly - assert_raise(NameError) do - Chars - end - end - - def test_utf8? - assert @s[:utf8].is_utf8?, "UTF-8 strings are UTF-8" - assert @s[:ascii].is_utf8?, "All ASCII strings are also valid UTF-8" - assert !@s[:bytes].is_utf8?, "This bytestring isn't UTF-8" - end - - # The test for the following methods are defined here because they can only be defined on the Chars class for - # various reasons - - def test_gsub - assert_equal 'éxa', 'éda'.chars.gsub(/d/, 'x') - with_kcode('none') do - assert_equal 'éxa', 'éda'.chars.gsub(/d/, 'x') - end - end - - def test_split - word = "efficient" - chars = ["e", "ffi", "c", "i", "e", "n", "t"] - assert_equal chars, word.split(//) - assert_equal chars, word.chars.split(//) - assert_kind_of ActiveSupport::Multibyte::Chars, word.chars.split(//).first, "Split should return Chars instances" - end - - def test_regexp - with_kcode('none') do - assert_equal 12, (@s[:utf8].chars =~ /ffi/), - "Regex matching should be bypassed to String" - end - with_kcode('UTF8') do - assert_equal 9, (@s[:utf8].chars =~ /ffi/), - "Regex matching should be unicode aware" - assert_nil((''.chars =~ /\d+/), - "Non-matching regular expressions should return nil") - end - end - - def test_pragma - if RUBY_VERSION < '1.9' - with_kcode('UTF8') do - assert " ".chars.send(:utf8_pragma?), "UTF8 pragma should be on because KCODE is UTF8" + end + + if RUBY_VERSION < '1.9' + def test_concatenation_should_return_a_proxy_class_instance + assert_equal ActiveSupport::Multibyte.proxy_class, ('a'.mb_chars + 'b').class + assert_equal ActiveSupport::Multibyte.proxy_class, ('a'.mb_chars << 'b').class + end + + def test_ascii_strings_are_treated_at_utf8_strings + assert_equal ActiveSupport::Multibyte.proxy_class, ASCII_STRING.mb_chars.class + end + + def test_concatenate_should_return_proxy_instance + assert(('a'.mb_chars + 'b').kind_of?(@proxy_class)) + assert(('a'.mb_chars + 'b'.mb_chars).kind_of?(@proxy_class)) + assert(('a'.mb_chars << 'b').kind_of?(@proxy_class)) + assert(('a'.mb_chars << 'b'.mb_chars).kind_of?(@proxy_class)) + end + end +end + +class MultibyteCharsUTF8BehaviourTest < Test::Unit::TestCase + include MultibyteTestHelpers + + def setup + @chars = UNICODE_STRING.dup.mb_chars + + # NEWLINE, SPACE, EM SPACE + @whitespace = "\n#{[32, 8195].pack('U*')}" + @whitespace.force_encoding(Encoding::UTF_8) if @whitespace.respond_to?(:force_encoding) + @byte_order_mark = [65279].pack('U') + end + + if RUBY_VERSION < '1.9' + def test_split_should_return_an_array_of_chars_instances + @chars.split(//).each do |character| + assert character.kind_of?(ActiveSupport::Multibyte.proxy_class) end - with_kcode('none') do - assert !" ".chars.send(:utf8_pragma?), "UTF8 pragma should be off because KCODE is not UTF8" + end + + def test_indexed_insert_accepts_fixnums + @chars[2] = 32 + assert_equal 'こに わ', @chars + end + + def test_overridden_bang_methods_return_self + [:rstrip!, :lstrip!, :strip!, :reverse!, :upcase!, :downcase!, :capitalize!].each do |method| + assert_equal @chars.object_id, @chars.send(method).object_id end - else - assert !" ".chars.send(:utf8_pragma?), "UTF8 pragma should be off in Ruby 1.9" - end - end - - def test_handler_setting - handler = ''.chars.handler - - ActiveSupport::Multibyte::Chars.handler = :first - assert_equal :first, ''.chars.handler - ActiveSupport::Multibyte::Chars.handler = :second - assert_equal :second, ''.chars.handler - assert_raise(NoMethodError) do - ''.chars.handler.split - end - - ActiveSupport::Multibyte::Chars.handler = handler - end - - def test_method_chaining - assert_kind_of ActiveSupport::Multibyte::Chars, ''.chars.downcase - assert_kind_of ActiveSupport::Multibyte::Chars, ''.chars.strip, "Strip should return a Chars object" - assert_kind_of ActiveSupport::Multibyte::Chars, ''.chars.downcase.strip, "The Chars object should be " + - "forwarded down the call path for chaining" - assert_equal 'foo', " FOO ".chars.normalize.downcase.strip, "The Chars that results from the " + - " operations should be comparable to the string value of the result" - end - - def test_passthrough_on_kcode - # The easiest way to check if the passthrough is in place is through #size - with_kcode('none') do - assert_equal 26, @s[:utf8].chars.size - end - with_kcode('UTF8') do - assert_equal 17, @s[:utf8].chars.size - end - end - - def test_destructiveness - # Note that we're testing the destructiveness here and not the correct behaviour of the methods - str = 'ac' - str.chars.insert(1, 'b') - assert_equal 'abc', str, 'Insert should be destructive for a string' - - str = 'ac' - str.chars.reverse! - assert_equal 'ca', str, 'reverse! should be destructive for a string' - end - - def test_resilience - assert_nothing_raised do - assert_equal 5, @s[:bytes].chars.size, "The sequence contains five interpretable bytes" + assert_equal @chars.object_id, @chars.slice!(1).object_id end - reversed = [0xb8, 0x17e, 0x8, 0x2c6, 0xa5].reverse.pack('U*') - assert_nothing_raised do - assert_equal reversed, @s[:bytes].chars.reverse.to_s, "Reversing the string should only yield interpretable bytes" + + def test_overridden_bang_methods_change_wrapped_string + [:rstrip!, :lstrip!, :strip!, :reverse!, :upcase!, :downcase!].each do |method| + original = ' Café ' + proxy = chars(original.dup) + proxy.send(method) + assert_not_equal original, proxy.to_s + end + proxy = chars('Café') + proxy.slice!(3) + assert_equal 'é', proxy.to_s + + proxy = chars('òu') + proxy.capitalize! + assert_equal 'Òu', proxy.to_s end - assert_nothing_raised do - @s[:bytes].chars.reverse! - assert_equal reversed, @s[:bytes].to_s, "Reversing the string should only yield interpretable bytes" + end + + if RUBY_VERSION >= '1.9' + def test_unicode_string_should_have_utf8_encoding + assert_equal Encoding::UTF_8, UNICODE_STRING.encoding end end - - def test_duck_typing - assert_equal true, 'test'.chars.respond_to?(:strip) - assert_equal true, 'test'.chars.respond_to?(:normalize) - assert_equal true, 'test'.chars.respond_to?(:normalize!) - assert_equal false, 'test'.chars.respond_to?(:a_method_that_doesnt_exist) + + def test_identity + assert_equal @chars, @chars + assert @chars.eql?(@chars) + if RUBY_VERSION <= '1.9' + assert !@chars.eql?(UNICODE_STRING) + else + assert @chars.eql?(UNICODE_STRING) + end end - - def test_acts_like_string - assert 'Bambi'.chars.acts_like_string? + + def test_string_methods_are_chainable + assert chars('').insert(0, '').kind_of?(ActiveSupport::Multibyte.proxy_class) + assert chars('').rjust(1).kind_of?(ActiveSupport::Multibyte.proxy_class) + assert chars('').ljust(1).kind_of?(ActiveSupport::Multibyte.proxy_class) + assert chars('').center(1).kind_of?(ActiveSupport::Multibyte.proxy_class) + assert chars('').rstrip.kind_of?(ActiveSupport::Multibyte.proxy_class) + assert chars('').lstrip.kind_of?(ActiveSupport::Multibyte.proxy_class) + assert chars('').strip.kind_of?(ActiveSupport::Multibyte.proxy_class) + assert chars('').reverse.kind_of?(ActiveSupport::Multibyte.proxy_class) + assert chars(' ').slice(0).kind_of?(ActiveSupport::Multibyte.proxy_class) + assert chars('').upcase.kind_of?(ActiveSupport::Multibyte.proxy_class) + assert chars('').downcase.kind_of?(ActiveSupport::Multibyte.proxy_class) + assert chars('').capitalize.kind_of?(ActiveSupport::Multibyte.proxy_class) + assert chars('').normalize.kind_of?(ActiveSupport::Multibyte.proxy_class) + assert chars('').decompose.kind_of?(ActiveSupport::Multibyte.proxy_class) + assert chars('').compose.kind_of?(ActiveSupport::Multibyte.proxy_class) + assert chars('').tidy_bytes.kind_of?(ActiveSupport::Multibyte.proxy_class) end - protected + def test_should_be_equal_to_the_wrapped_string + assert_equal UNICODE_STRING, @chars + assert_equal @chars, UNICODE_STRING + end - def with_kcode(kcode) - old_kcode, $KCODE = $KCODE, kcode - begin - yield - ensure - $KCODE = old_kcode + def test_should_not_be_equal_to_an_other_string + assert_not_equal @chars, 'other' + assert_not_equal 'other', @chars + end + + def test_sortability + words = %w(builder armor zebra).map(&:mb_chars).sort + assert_equal %w(armor builder zebra), words + end + + def test_should_return_character_offset_for_regexp_matches + assert_nil(@chars =~ /wrong/u) + assert_equal 0, (@chars =~ /こ/u) + assert_equal 1, (@chars =~ /に/u) + assert_equal 3, (@chars =~ /わ/u) + end + + def test_should_use_character_offsets_for_insert_offsets + assert_equal '', ''.mb_chars.insert(0, '') + assert_equal 'こわにちわ', @chars.insert(1, 'わ') + assert_equal 'こわわわにちわ', @chars.insert(2, 'わわ') + assert_equal 'わこわわわにちわ', @chars.insert(0, 'わ') + assert_equal 'わこわわわにちわ', @chars.wrapped_string if RUBY_VERSION < '1.9' + end + + def test_insert_should_be_destructive + @chars.insert(1, 'わ') + assert_equal 'こわにちわ', @chars + end + + def test_insert_throws_index_error + assert_raises(IndexError) { @chars.insert(-12, 'わ')} + assert_raises(IndexError) { @chars.insert(12, 'わ') } + end + + def test_should_know_if_one_includes_the_other + assert @chars.include?('') + assert @chars.include?('ち') + assert @chars.include?('わ') + assert !@chars.include?('こちわ') + assert !@chars.include?('a') + end + + def test_include_raises_type_error_when_nil_is_passed + assert_raises(TypeError) do + @chars.include?(nil) end end + + def test_index_should_return_character_offset + assert_nil @chars.index('u') + assert_equal 0, @chars.index('こに') + assert_equal 2, @chars.index('ち') + assert_equal 3, @chars.index('わ') + end + + def test_indexed_insert_should_take_character_offsets + @chars[2] = 'a' + assert_equal 'こにaわ', @chars + @chars[2] = 'ηη' + assert_equal 'こにηηわ', @chars + @chars[3, 2] = 'λλλ' + assert_equal 'こにηλλλ', @chars + @chars[1, 0] = "λ" + assert_equal 'こλにηλλλ', @chars + @chars[4..6] = "ηη" + assert_equal 'こλにηηη', @chars + @chars[/ηη/] = "λλλ" + assert_equal 'こλにλλλη', @chars + @chars[/(λλ)(.)/, 2] = "α" + assert_equal 'こλにλλαη', @chars + @chars["α"] = "¢" + assert_equal 'こλにλλ¢η', @chars + @chars["λλ"] = "ααα" + assert_equal 'こλにααα¢η', @chars + end + + def test_indexed_insert_should_raise_on_index_overflow + before = @chars.to_s + assert_raises(IndexError) { @chars[10] = 'a' } + assert_raises(IndexError) { @chars[10, 4] = 'a' } + assert_raises(IndexError) { @chars[/ii/] = 'a' } + assert_raises(IndexError) { @chars[/()/, 10] = 'a' } + assert_equal before, @chars + end + + def test_indexed_insert_should_raise_on_range_overflow + before = @chars.to_s + assert_raises(RangeError) { @chars[10..12] = 'a' } + assert_equal before, @chars + end + + def test_rjust_should_raise_argument_errors_on_bad_arguments + assert_raises(ArgumentError) { @chars.rjust(10, '') } + assert_raises(ArgumentError) { @chars.rjust } + end + + def test_rjust_should_count_characters_instead_of_bytes + assert_equal UNICODE_STRING, @chars.rjust(-3) + assert_equal UNICODE_STRING, @chars.rjust(0) + assert_equal UNICODE_STRING, @chars.rjust(4) + assert_equal " #{UNICODE_STRING}", @chars.rjust(5) + assert_equal " #{UNICODE_STRING}", @chars.rjust(7) + assert_equal "---#{UNICODE_STRING}", @chars.rjust(7, '-') + assert_equal "ααα#{UNICODE_STRING}", @chars.rjust(7, 'α') + assert_equal "aba#{UNICODE_STRING}", @chars.rjust(7, 'ab') + assert_equal "αηα#{UNICODE_STRING}", @chars.rjust(7, 'αη') + assert_equal "αηαη#{UNICODE_STRING}", @chars.rjust(8, 'αη') + end + + def test_ljust_should_raise_argument_errors_on_bad_arguments + assert_raises(ArgumentError) { @chars.ljust(10, '') } + assert_raises(ArgumentError) { @chars.ljust } + end + + def test_ljust_should_count_characters_instead_of_bytes + assert_equal UNICODE_STRING, @chars.ljust(-3) + assert_equal UNICODE_STRING, @chars.ljust(0) + assert_equal UNICODE_STRING, @chars.ljust(4) + assert_equal "#{UNICODE_STRING} ", @chars.ljust(5) + assert_equal "#{UNICODE_STRING} ", @chars.ljust(7) + assert_equal "#{UNICODE_STRING}---", @chars.ljust(7, '-') + assert_equal "#{UNICODE_STRING}ααα", @chars.ljust(7, 'α') + assert_equal "#{UNICODE_STRING}aba", @chars.ljust(7, 'ab') + assert_equal "#{UNICODE_STRING}αηα", @chars.ljust(7, 'αη') + assert_equal "#{UNICODE_STRING}αηαη", @chars.ljust(8, 'αη') + end + + def test_center_should_raise_argument_errors_on_bad_arguments + assert_raises(ArgumentError) { @chars.center(10, '') } + assert_raises(ArgumentError) { @chars.center } + end + + def test_center_should_count_charactes_instead_of_bytes + assert_equal UNICODE_STRING, @chars.center(-3) + assert_equal UNICODE_STRING, @chars.center(0) + assert_equal UNICODE_STRING, @chars.center(4) + assert_equal "#{UNICODE_STRING} ", @chars.center(5) + assert_equal " #{UNICODE_STRING} ", @chars.center(6) + assert_equal " #{UNICODE_STRING} ", @chars.center(7) + assert_equal "--#{UNICODE_STRING}--", @chars.center(8, '-') + assert_equal "--#{UNICODE_STRING}---", @chars.center(9, '-') + assert_equal "αα#{UNICODE_STRING}αα", @chars.center(8, 'α') + assert_equal "αα#{UNICODE_STRING}ααα", @chars.center(9, 'α') + assert_equal "a#{UNICODE_STRING}ab", @chars.center(7, 'ab') + assert_equal "ab#{UNICODE_STRING}ab", @chars.center(8, 'ab') + assert_equal "abab#{UNICODE_STRING}abab", @chars.center(12, 'ab') + assert_equal "α#{UNICODE_STRING}αη", @chars.center(7, 'αη') + assert_equal "αη#{UNICODE_STRING}αη", @chars.center(8, 'αη') + end + + def test_lstrip_strips_whitespace_from_the_left_of_the_string + assert_equal UNICODE_STRING, UNICODE_STRING.mb_chars.lstrip + assert_equal UNICODE_STRING, (@whitespace + UNICODE_STRING).mb_chars.lstrip + assert_equal UNICODE_STRING + @whitespace, (@whitespace + UNICODE_STRING + @whitespace).mb_chars.lstrip + end + + def test_rstrip_strips_whitespace_from_the_right_of_the_string + assert_equal UNICODE_STRING, UNICODE_STRING.mb_chars.rstrip + assert_equal UNICODE_STRING, (UNICODE_STRING + @whitespace).mb_chars.rstrip + assert_equal @whitespace + UNICODE_STRING, (@whitespace + UNICODE_STRING + @whitespace).mb_chars.rstrip + end + + def test_strip_strips_whitespace + assert_equal UNICODE_STRING, UNICODE_STRING.mb_chars.strip + assert_equal UNICODE_STRING, (@whitespace + UNICODE_STRING).mb_chars.strip + assert_equal UNICODE_STRING, (UNICODE_STRING + @whitespace).mb_chars.strip + assert_equal UNICODE_STRING, (@whitespace + UNICODE_STRING + @whitespace).mb_chars.strip + end + + def test_stripping_whitespace_leaves_whitespace_within_the_string_intact + string_with_whitespace = UNICODE_STRING + @whitespace + UNICODE_STRING + assert_equal string_with_whitespace, string_with_whitespace.mb_chars.strip + assert_equal string_with_whitespace, string_with_whitespace.mb_chars.lstrip + assert_equal string_with_whitespace, string_with_whitespace.mb_chars.rstrip + end + + def test_size_returns_characters_instead_of_bytes + assert_equal 0, ''.mb_chars.size + assert_equal 4, @chars.size + assert_equal 4, @chars.length + assert_equal 5, ASCII_STRING.mb_chars.size + end + + def test_reverse_reverses_characters + assert_equal '', ''.mb_chars.reverse + assert_equal 'わちにこ', @chars.reverse + end + + def test_slice_should_take_character_offsets + assert_equal nil, ''.mb_chars.slice(0) + assert_equal 'こ', @chars.slice(0) + assert_equal 'わ', @chars.slice(3) + assert_equal nil, ''.mb_chars.slice(-1..1) + assert_equal '', ''.mb_chars.slice(0..10) + assert_equal 'にちわ', @chars.slice(1..3) + assert_equal 'にちわ', @chars.slice(1, 3) + assert_equal 'こ', @chars.slice(0, 1) + assert_equal 'ちわ', @chars.slice(2..10) + assert_equal '', @chars.slice(4..10) + assert_equal 'に', @chars.slice(/に/u) + assert_equal 'にち', @chars.slice(/に\w/u) + assert_equal nil, @chars.slice(/unknown/u) + assert_equal 'にち', @chars.slice(/(にち)/u, 1) + assert_equal nil, @chars.slice(/(にち)/u, 2) + assert_equal nil, @chars.slice(7..6) + end + + def test_slice_should_throw_exceptions_on_invalid_arguments + assert_raise(TypeError) { @chars.slice(2..3, 1) } + assert_raise(TypeError) { @chars.slice(1, 2..3) } + assert_raise(ArgumentError) { @chars.slice(1, 1, 1) } + end + + def test_upcase_should_upcase_ascii_characters + assert_equal '', ''.mb_chars.upcase + assert_equal 'ABC', 'aBc'.mb_chars.upcase + end + + def test_downcase_should_downcase_ascii_characters + assert_equal '', ''.mb_chars.downcase + assert_equal 'abc', 'aBc'.mb_chars.downcase + end + + def test_capitalize_should_work_on_ascii_characters + assert_equal '', ''.mb_chars.capitalize + assert_equal 'Abc', 'abc'.mb_chars.capitalize + end + + def test_respond_to_knows_which_methods_the_proxy_responds_to + assert ''.mb_chars.respond_to?(:slice) # Defined on Chars + assert ''.mb_chars.respond_to?(:capitalize!) # Defined on Chars + assert ''.mb_chars.respond_to?(:gsub) # Defined on String + assert !''.mb_chars.respond_to?(:undefined_method) # Not defined + end + + def test_acts_like_string + assert 'Bambi'.mb_chars.acts_like_string? + end end +# The default Multibyte Chars proxy has more features than the normal string implementation. Tests +# for the implementation of these features should run on all Ruby versions and shouldn't be tested +# through the proxy methods. +class MultibyteCharsExtrasTest < Test::Unit::TestCase + include MultibyteTestHelpers + + if RUBY_VERSION >= '1.9' + def test_tidy_bytes_is_broken_on_1_9_0 + assert_raises(ArgumentError) do + assert_equal_codepoints [0xfffd].pack('U'), chars("\xef\xbf\xbd").tidy_bytes + end + end + end + + def test_upcase_should_be_unicode_aware + assert_equal "АБВГД\0F", chars("аБвгд\0f").upcase + assert_equal 'こにちわ', chars('こにちわ').upcase + end + + def test_downcase_should_be_unicode_aware + assert_equal "абвгд\0f", chars("аБвгд\0f").downcase + assert_equal 'こにちわ', chars('こにちわ').downcase + end + + def test_capitalize_should_be_unicode_aware + { 'аБвг аБвг' => 'Абвг абвг', + 'аБвг АБВГ' => 'Абвг абвг', + 'АБВГ АБВГ' => 'Абвг абвг', + '' => '' }.each do |f,t| + assert_equal t, chars(f).capitalize + end + end + + def test_composition_exclusion_is_set_up_properly + # Normalization of DEVANAGARI LETTER QA breaks when composition exclusion isn't used correctly + qa = [0x915, 0x93c].pack('U*') + assert_equal qa, chars(qa).normalize(:c) + end + + # Test for the Public Review Issue #29, bad explanation of composition might lead to a + # bad implementation: http://www.unicode.org/review/pr-29.html + def test_normalization_C_pri_29 + [ + [0x0B47, 0x0300, 0x0B3E], + [0x1100, 0x0300, 0x1161] + ].map { |c| c.pack('U*') }.each do |c| + assert_equal_codepoints c, chars(c).normalize(:c) + end + end + + def test_normalization_shouldnt_strip_null_bytes + null_byte_str = "Test\0test" + + assert_equal null_byte_str, chars(null_byte_str).normalize(:kc) + assert_equal null_byte_str, chars(null_byte_str).normalize(:c) + assert_equal null_byte_str, chars(null_byte_str).normalize(:d) + assert_equal null_byte_str, chars(null_byte_str).normalize(:kd) + assert_equal null_byte_str, chars(null_byte_str).decompose + assert_equal null_byte_str, chars(null_byte_str).compose + end + + def test_simple_normalization + comp_str = [ + 44, # LATIN CAPITAL LETTER D + 307, # COMBINING DOT ABOVE + 328, # COMBINING OGONEK + 323 # COMBINING DOT BELOW + ].pack("U*") + + assert_equal_codepoints '', chars('').normalize + assert_equal_codepoints [44,105,106,328,323].pack("U*"), chars(comp_str).normalize(:kc).to_s + assert_equal_codepoints [44,307,328,323].pack("U*"), chars(comp_str).normalize(:c).to_s + assert_equal_codepoints [44,307,110,780,78,769].pack("U*"), chars(comp_str).normalize(:d).to_s + assert_equal_codepoints [44,105,106,110,780,78,769].pack("U*"), chars(comp_str).normalize(:kd).to_s + end + + def test_should_compute_grapheme_length + [ + ['', 0], + ['abc', 3], + ['こにちわ', 4], + [[0x0924, 0x094D, 0x0930].pack('U*'), 2], + [%w(cr lf), 1], + [%w(l l), 1], + [%w(l v), 1], + [%w(l lv), 1], + [%w(l lvt), 1], + [%w(lv v), 1], + [%w(lv t), 1], + [%w(v v), 1], + [%w(v t), 1], + [%w(lvt t), 1], + [%w(t t), 1], + [%w(n extend), 1], + [%w(n n), 2], + [%w(n cr lf n), 3], + [%w(n l v t), 2] + ].each do |input, expected_length| + if input.kind_of?(Array) + str = string_from_classes(input) + else + str = input + end + assert_equal expected_length, chars(str).g_length + end + end + + def test_tidy_bytes_should_tidy_bytes + byte_string = "\270\236\010\210\245" + tidy_string = [0xb8, 0x17e, 0x8, 0x2c6, 0xa5].pack('U*') + ascii_padding = 'aa' + utf8_padding = 'éé' + + assert_equal_codepoints tidy_string, chars(byte_string).tidy_bytes + + assert_equal_codepoints ascii_padding.dup.insert(1, tidy_string), + chars(ascii_padding.dup.insert(1, byte_string)).tidy_bytes + assert_equal_codepoints utf8_padding.dup.insert(2, tidy_string), + chars(utf8_padding.dup.insert(2, byte_string)).tidy_bytes + assert_nothing_raised { chars(byte_string).tidy_bytes.to_s.unpack('U*') } + + assert_equal_codepoints "\xC3\xA7", chars("\xE7").tidy_bytes # iso_8859_1: small c cedilla + assert_equal_codepoints "\xE2\x80\x9C", chars("\x93").tidy_bytes # win_1252: left smart quote + assert_equal_codepoints "\xE2\x82\xAC", chars("\x80").tidy_bytes # win_1252: euro + assert_equal_codepoints "\x00", chars("\x00").tidy_bytes # null char + assert_equal_codepoints [0xfffd].pack('U'), chars("\xef\xbf\xbd").tidy_bytes # invalid char + rescue ArgumentError => e + raise e if RUBY_VERSION < '1.9' + end + + private + + def string_from_classes(classes) + # Characters from the character classes as described in UAX #29 + character_from_class = { + :l => 0x1100, :v => 0x1160, :t => 0x11A8, :lv => 0xAC00, :lvt => 0xAC01, :cr => 0x000D, :lf => 0x000A, + :extend => 0x094D, :n => 0x64 + } + classes.collect do |k| + character_from_class[k.intern] + end.pack('U*') + end end diff --git a/activesupport/test/multibyte_conformance.rb b/activesupport/test/multibyte_conformance.rb index 05fb9ef7a7..caae4791b4 100644 --- a/activesupport/test/multibyte_conformance.rb +++ b/activesupport/test/multibyte_conformance.rb @@ -1,13 +1,11 @@ -require 'abstract_unit' -require 'open-uri' - -if RUBY_VERSION < '1.9' +# encoding: utf-8 -$KCODE = 'UTF8' +require 'abstract_unit' +require 'multibyte_test_helpers' -UNIDATA_URL = "http://www.unicode.org/Public/#{ActiveSupport::Multibyte::UNICODE_VERSION}/ucd" -UNIDATA_FILE = '/NormalizationTest.txt' -CACHE_DIR = File.dirname(__FILE__) + '/cache' +require 'fileutils' +require 'open-uri' +require 'tmpdir' class Downloader def self.download(from, to) @@ -27,17 +25,19 @@ class Downloader end end -class String - # Unicode Inspect returns the codepoints of the string in hex - def ui - "#{self} " + ("[%s]" % unpack("U*").map{|cp| cp.to_s(16) }.join(' ')) - end unless ''.respond_to?(:ui) -end - -Dir.mkdir(CACHE_DIR) unless File.exist?(CACHE_DIR) -Downloader.download(UNIDATA_URL + UNIDATA_FILE, CACHE_DIR + UNIDATA_FILE) - -module ConformanceTest +class MultibyteConformanceTest < Test::Unit::TestCase + include MultibyteTestHelpers + + UNIDATA_URL = "http://www.unicode.org/Public/#{ActiveSupport::Multibyte::UNICODE_VERSION}/ucd" + UNIDATA_FILE = '/NormalizationTest.txt' + CACHE_DIR = File.join(Dir.tmpdir, 'cache') + + def setup + FileUtils.mkdir_p(CACHE_DIR) + Downloader.download(UNIDATA_URL + UNIDATA_FILE, CACHE_DIR + UNIDATA_FILE) + @proxy = ActiveSupport::Multibyte::Chars + end + def test_normalizations_C each_line_of_norm_tests do |*cols| col1, col2, col3, col4, col5, comment = *cols @@ -47,13 +47,13 @@ module ConformanceTest # # NFC # c2 == NFC(c1) == NFC(c2) == NFC(c3) - assert_equal col2.ui, @handler.normalize(col1, :c).ui, "Form C - Col 2 has to be NFC(1) - #{comment}" - assert_equal col2.ui, @handler.normalize(col2, :c).ui, "Form C - Col 2 has to be NFC(2) - #{comment}" - assert_equal col2.ui, @handler.normalize(col3, :c).ui, "Form C - Col 2 has to be NFC(3) - #{comment}" + assert_equal_codepoints col2, @proxy.new(col1).normalize(:c), "Form C - Col 2 has to be NFC(1) - #{comment}" + assert_equal_codepoints col2, @proxy.new(col2).normalize(:c), "Form C - Col 2 has to be NFC(2) - #{comment}" + assert_equal_codepoints col2, @proxy.new(col3).normalize(:c), "Form C - Col 2 has to be NFC(3) - #{comment}" # # c4 == NFC(c4) == NFC(c5) - assert_equal col4.ui, @handler.normalize(col4, :c).ui, "Form C - Col 4 has to be C(4) - #{comment}" - assert_equal col4.ui, @handler.normalize(col5, :c).ui, "Form C - Col 4 has to be C(5) - #{comment}" + assert_equal_codepoints col4, @proxy.new(col4).normalize(:c), "Form C - Col 4 has to be C(4) - #{comment}" + assert_equal_codepoints col4, @proxy.new(col5).normalize(:c), "Form C - Col 4 has to be C(5) - #{comment}" end end @@ -63,12 +63,12 @@ module ConformanceTest # # NFD # c3 == NFD(c1) == NFD(c2) == NFD(c3) - assert_equal col3.ui, @handler.normalize(col1, :d).ui, "Form D - Col 3 has to be NFD(1) - #{comment}" - assert_equal col3.ui, @handler.normalize(col2, :d).ui, "Form D - Col 3 has to be NFD(2) - #{comment}" - assert_equal col3.ui, @handler.normalize(col3, :d).ui, "Form D - Col 3 has to be NFD(3) - #{comment}" + assert_equal_codepoints col3, @proxy.new(col1).normalize(:d), "Form D - Col 3 has to be NFD(1) - #{comment}" + assert_equal_codepoints col3, @proxy.new(col2).normalize(:d), "Form D - Col 3 has to be NFD(2) - #{comment}" + assert_equal_codepoints col3, @proxy.new(col3).normalize(:d), "Form D - Col 3 has to be NFD(3) - #{comment}" # c5 == NFD(c4) == NFD(c5) - assert_equal col5.ui, @handler.normalize(col4, :d).ui, "Form D - Col 5 has to be NFD(4) - #{comment}" - assert_equal col5.ui, @handler.normalize(col5, :d).ui, "Form D - Col 5 has to be NFD(5) - #{comment}" + assert_equal_codepoints col5, @proxy.new(col4).normalize(:d), "Form D - Col 5 has to be NFD(4) - #{comment}" + assert_equal_codepoints col5, @proxy.new(col5).normalize(:d), "Form D - Col 5 has to be NFD(5) - #{comment}" end end @@ -78,11 +78,11 @@ module ConformanceTest # # NFKC # c4 == NFKC(c1) == NFKC(c2) == NFKC(c3) == NFKC(c4) == NFKC(c5) - assert_equal col4.ui, @handler.normalize(col1, :kc).ui, "Form D - Col 4 has to be NFKC(1) - #{comment}" - assert_equal col4.ui, @handler.normalize(col2, :kc).ui, "Form D - Col 4 has to be NFKC(2) - #{comment}" - assert_equal col4.ui, @handler.normalize(col3, :kc).ui, "Form D - Col 4 has to be NFKC(3) - #{comment}" - assert_equal col4.ui, @handler.normalize(col4, :kc).ui, "Form D - Col 4 has to be NFKC(4) - #{comment}" - assert_equal col4.ui, @handler.normalize(col5, :kc).ui, "Form D - Col 4 has to be NFKC(5) - #{comment}" + assert_equal_codepoints col4, @proxy.new(col1).normalize(:kc), "Form D - Col 4 has to be NFKC(1) - #{comment}" + assert_equal_codepoints col4, @proxy.new(col2).normalize(:kc), "Form D - Col 4 has to be NFKC(2) - #{comment}" + assert_equal_codepoints col4, @proxy.new(col3).normalize(:kc), "Form D - Col 4 has to be NFKC(3) - #{comment}" + assert_equal_codepoints col4, @proxy.new(col4).normalize(:kc), "Form D - Col 4 has to be NFKC(4) - #{comment}" + assert_equal_codepoints col4, @proxy.new(col5).normalize(:kc), "Form D - Col 4 has to be NFKC(5) - #{comment}" end end @@ -92,11 +92,11 @@ module ConformanceTest # # NFKD # c5 == NFKD(c1) == NFKD(c2) == NFKD(c3) == NFKD(c4) == NFKD(c5) - assert_equal col5.ui, @handler.normalize(col1, :kd).ui, "Form KD - Col 5 has to be NFKD(1) - #{comment}" - assert_equal col5.ui, @handler.normalize(col2, :kd).ui, "Form KD - Col 5 has to be NFKD(2) - #{comment}" - assert_equal col5.ui, @handler.normalize(col3, :kd).ui, "Form KD - Col 5 has to be NFKD(3) - #{comment}" - assert_equal col5.ui, @handler.normalize(col4, :kd).ui, "Form KD - Col 5 has to be NFKD(4) - #{comment}" - assert_equal col5.ui, @handler.normalize(col5, :kd).ui, "Form KD - Col 5 has to be NFKD(5) - #{comment}" + assert_equal_codepoints col5, @proxy.new(col1).normalize(:kd), "Form KD - Col 5 has to be NFKD(1) - #{comment}" + assert_equal_codepoints col5, @proxy.new(col2).normalize(:kd), "Form KD - Col 5 has to be NFKD(2) - #{comment}" + assert_equal_codepoints col5, @proxy.new(col3).normalize(:kd), "Form KD - Col 5 has to be NFKD(3) - #{comment}" + assert_equal_codepoints col5, @proxy.new(col4).normalize(:kd), "Form KD - Col 5 has to be NFKD(4) - #{comment}" + assert_equal_codepoints col5, @proxy.new(col5).normalize(:kd), "Form KD - Col 5 has to be NFKD(5) - #{comment}" end end @@ -104,7 +104,7 @@ module ConformanceTest def each_line_of_norm_tests(&block) lines = 0 max_test_lines = 0 # Don't limit below 38, because that's the header of the testfile - File.open(File.dirname(__FILE__) + '/cache' + UNIDATA_FILE, 'r') do | f | + File.open(File.join(CACHE_DIR, UNIDATA_FILE), 'r') do | f | until f.eof? || (max_test_lines > 38 and lines > max_test_lines) lines += 1 line = f.gets.chomp! @@ -122,25 +122,8 @@ module ConformanceTest end end end -end - -begin - require_library_or_gem('utf8proc_native') - require 'active_record/multibyte/handlers/utf8_handler_proc' - class ConformanceTestProc < Test::Unit::TestCase - include ConformanceTest - def setup - @handler = ::ActiveSupport::Multibyte::Handlers::UTF8HandlerProc + + def inspect_codepoints(str) + str.to_s.unpack("U*").map{|cp| cp.to_s(16) }.join(' ') end - end -rescue LoadError -end - -class ConformanceTestPure < Test::Unit::TestCase - include ConformanceTest - def setup - @handler = ::ActiveSupport::Multibyte::Handlers::UTF8Handler - end -end - -end +end
\ No newline at end of file diff --git a/activesupport/test/multibyte_handler_test.rb b/activesupport/test/multibyte_handler_test.rb deleted file mode 100644 index 5575ecc32d..0000000000 --- a/activesupport/test/multibyte_handler_test.rb +++ /dev/null @@ -1,372 +0,0 @@ -# encoding: utf-8 -require 'abstract_unit' - -if RUBY_VERSION < '1.9' - -$KCODE = 'UTF8' - -class String - # Unicode Inspect returns the codepoints of the string in hex - def ui - "#{self} " + ("[%s]" % unpack("U*").map{|cp| cp.to_s(16) }.join(' ')) - end unless ''.respond_to?(:ui) -end - -module UTF8HandlingTest - - def common_setup - # This is an ASCII string with some russian strings and a ligature. It's nicely calibrated, because - # slicing it at some specific bytes will kill your characters if you use standard Ruby routines. - # It has both capital and standard letters, so that we can test case conversions easily. - # It has 26 characters and 28 when the ligature gets split during normalization. - @string = "Abcd Блå ffi бла бла бла бла" - @string_kd = "Abcd Блå ffi бла бла бла бла" - @string_kc = "Abcd Блå ffi бла бла бла бла" - @string_c = "Abcd Блå ffi бла бла бла бла" - @string_d = "Abcd Блå ffi бла бла бла бла" - @bytestring = "\270\236\010\210\245" # Not UTF-8 - - # Characters from the character classes as described in UAX #29 - @character_from_class = { - :l => 0x1100, :v => 0x1160, :t => 0x11A8, :lv => 0xAC00, :lvt => 0xAC01, :cr => 0x000D, :lf => 0x000A, - :extend => 0x094D, :n => 0x64 - } - end - - def test_utf8_recognition - assert ActiveSupport::Multibyte::Handlers::UTF8Handler.consumes?(@string), - "Should recognize as a valid UTF-8 string" - assert !ActiveSupport::Multibyte::Handlers::UTF8Handler.consumes?(@bytestring), "This is bytestring, not UTF-8" - end - - def test_simple_normalization - # Normalization of DEVANAGARI LETTER QA breaks when composition exclusion isn't used correctly - assert_equal [0x915, 0x93c].pack('U*').ui, [0x915, 0x93c].pack('U*').chars.normalize(:c).to_s.ui - - null_byte_str = "Test\0test" - - assert_equal '', @handler.normalize(''), "Empty string should not break things" - assert_equal null_byte_str.ui, @handler.normalize(null_byte_str, :kc).ui, "Null byte should remain" - assert_equal null_byte_str.ui, @handler.normalize(null_byte_str, :c).ui, "Null byte should remain" - assert_equal null_byte_str.ui, @handler.normalize(null_byte_str, :d).ui, "Null byte should remain" - assert_equal null_byte_str.ui, @handler.normalize(null_byte_str, :kd).ui, "Null byte should remain" - assert_equal null_byte_str.ui, @handler.decompose(null_byte_str).ui, "Null byte should remain" - assert_equal null_byte_str.ui, @handler.compose(null_byte_str).ui, "Null byte should remain" - - comp_str = [ - 44, # LATIN CAPITAL LETTER D - 307, # COMBINING DOT ABOVE - 328, # COMBINING OGONEK - 323 # COMBINING DOT BELOW - ].pack("U*") - norm_str_KC = [44,105,106,328,323].pack("U*") - norm_str_C = [44,307,328,323].pack("U*") - norm_str_D = [44,307,110,780,78,769].pack("U*") - norm_str_KD = [44,105,106,110,780,78,769].pack("U*") - - assert_equal norm_str_KC.ui, @handler.normalize(comp_str, :kc).ui, "Should normalize KC" - assert_equal norm_str_C.ui, @handler.normalize(comp_str, :c).ui, "Should normalize C" - assert_equal norm_str_D.ui, @handler.normalize(comp_str, :d).ui, "Should normalize D" - assert_equal norm_str_KD.ui, @handler.normalize(comp_str, :kd).ui, "Should normalize KD" - - assert_raise(ActiveSupport::Multibyte::Handlers::EncodingError) { @handler.normalize(@bytestring) } - end - - # Test for the Public Review Issue #29, bad explanation of composition might lead to a - # bad implementation: http://www.unicode.org/review/pr-29.html - def test_normalization_C_pri_29 - [ - [0x0B47, 0x0300, 0x0B3E], - [0x1100, 0x0300, 0x1161] - ].map { |c| c.pack('U*') }.each do |c| - assert_equal c.ui, @handler.normalize(c, :c).ui, "Composition is implemented incorrectly" - end - end - - def test_casefolding - simple_str = "abCdef" - simple_str_upcase = "ABCDEF" - simple_str_downcase = "abcdef" - - assert_equal '', @handler.downcase(@handler.upcase('')), "Empty string should not break things" - assert_equal simple_str_upcase, @handler.upcase(simple_str), "should upcase properly" - assert_equal simple_str_downcase, @handler.downcase(simple_str), "should downcase properly" - assert_equal simple_str_downcase, @handler.downcase(@handler.upcase(simple_str_downcase)), "upcase and downcase should be mirrors" - - rus_str = "аБвгд\0f" - rus_str_upcase = "АБВГД\0F" - rus_str_downcase = "абвгд\0f" - assert_equal rus_str_upcase, @handler.upcase(rus_str), "should upcase properly honoring null-byte" - assert_equal rus_str_downcase, @handler.downcase(rus_str), "should downcase properly honoring null-byte" - - jap_str = "の埋め込み化対応はほぼ完成" - assert_equal jap_str, @handler.upcase(jap_str), "Japanse has no upcase, should remain unchanged" - assert_equal jap_str, @handler.downcase(jap_str), "Japanse has no downcase, should remain unchanged" - - assert_raise(ActiveSupport::Multibyte::Handlers::EncodingError) { @handler.upcase(@bytestring) } - end - - def test_capitalize - { 'аБвг аБвг' => 'Абвг абвг', - 'аБвг АБВГ' => 'Абвг абвг', - 'АБВГ АБВГ' => 'Абвг абвг', - '' => '' }.each do |f,t| - assert_equal t, @handler.capitalize(f), "Capitalize should work as expected" - end - assert_raise(ActiveSupport::Multibyte::Handlers::EncodingError) { @handler.capitalize(@bytestring) } - end - - def test_translate_offset - str = "Блaå" # [2, 2, 1, 2] bytes - assert_equal 0, @handler.translate_offset('', 0), "Offset for an empty string makes no sense, return 0" - assert_equal 0, @handler.translate_offset(str, 0), "First character, first byte" - assert_equal 0, @handler.translate_offset(str, 1), "First character, second byte" - assert_equal 1, @handler.translate_offset(str, 2), "Second character, third byte" - assert_equal 1, @handler.translate_offset(str, 3), "Second character, fourth byte" - assert_equal 2, @handler.translate_offset(str, 4), "Third character, fifth byte" - assert_equal 3, @handler.translate_offset(str, 5), "Fourth character, sixth byte" - assert_equal 3, @handler.translate_offset(str, 6), "Fourth character, seventh byte" - assert_raise(ActiveSupport::Multibyte::Handlers::EncodingError) { @handler.translate_offset(@bytestring, 3) } - end - - def test_insert - assert_equal '', @handler.insert('', 0, ''), "Empty string should not break things" - assert_equal "Abcd Блå ffiБУМ бла бла бла бла", @handler.insert(@string, 10, "БУМ"), - "Text should be inserted at right codepoints" - assert_equal "Abcd Блå ffiБУМ бла бла бла бла", @string, "Insert should be destructive" - assert_raise(ActiveSupport::Multibyte::Handlers::EncodingError) do - @handler.insert(@bytestring, 2, "\210") - end - end - - def test_reverse - str = "wБлåa \n" - rev = "\n aåлБw" - assert_equal '', @handler.reverse(''), "Empty string shouldn't change" - assert_equal rev.ui, @handler.reverse(str).ui, "Should reverse properly" - assert_raise(ActiveSupport::Multibyte::Handlers::EncodingError) { @handler.reverse(@bytestring) } - end - - def test_size - assert_equal 0, @handler.size(''), "Empty string has size 0" - assert_equal 26, @handler.size(@string), "String length should be 26" - assert_equal 26, @handler.length(@string), "String length method should be properly aliased" - assert_raise(ActiveSupport::Multibyte::Handlers::EncodingError) { @handler.size(@bytestring) } - end - - def test_slice - assert_equal 0x41, @handler.slice(@string, 0), "Singular characters should return codepoints" - assert_equal 0xE5, @handler.slice(@string, 7), "Singular characters should return codepoints" - assert_equal nil, @handler.slice('', -1..1), "Broken range should return nil" - assert_equal '', @handler.slice('', 0..10), "Empty string should not break things" - assert_equal "d Блå ffi", @handler.slice(@string, 3..9), "Unicode characters have to be returned" - assert_equal "d Блå ffi", @handler.slice(@string, 3, 7), "Unicode characters have to be returned" - assert_equal "A", @handler.slice(@string, 0, 1), "Slicing from an offset should return characters" - assert_equal " Блå ffi ", @handler.slice(@string, 4..10), "Unicode characters have to be returned" - assert_equal "ffi бла", @handler.slice(@string, /ffi бла/u), "Slicing on Regexps should be supported" - assert_equal "ffi бла", @handler.slice(@string, /ffi \w\wа/u), "Slicing on Regexps should be supported" - assert_equal nil, @handler.slice(@string, /unknown/u), "Slicing on Regexps with no match should return nil" - assert_equal "ffi бла", @handler.slice(@string, /(ffi бла)/u,1), "Slicing on Regexps with a match group should be supported" - assert_equal nil, @handler.slice(@string, /(ffi)/u,2), "Slicing with a Regexp and asking for an invalid match group should return nil" - assert_equal "", @handler.slice(@string, 7..6), "Range is empty, should return an empty string" - assert_raise(ActiveSupport::Multibyte::Handlers::EncodingError) { @handler.slice(@bytestring, 2..3) } - assert_raise(TypeError, "With 2 args, should raise TypeError for non-Numeric or Regexp first argument") { @handler.slice(@string, 2..3, 1) } - assert_raise(TypeError, "With 2 args, should raise TypeError for non-Numeric or Regexp second argument") { @handler.slice(@string, 1, 2..3) } - assert_raise(ArgumentError, "Should raise ArgumentError when there are more than 2 args") { @handler.slice(@string, 1, 1, 1) } - end - - def test_grapheme_cluster_length - assert_equal 0, @handler.g_length(''), "String should count 0 grapheme clusters" - assert_equal 2, @handler.g_length([0x0924, 0x094D, 0x0930].pack('U*')), "String should count 2 grapheme clusters" - assert_equal 1, @handler.g_length(string_from_classes(%w(cr lf))), "Don't cut between CR and LF" - assert_equal 1, @handler.g_length(string_from_classes(%w(l l))), "Don't cut between L" - assert_equal 1, @handler.g_length(string_from_classes(%w(l v))), "Don't cut between L and V" - assert_equal 1, @handler.g_length(string_from_classes(%w(l lv))), "Don't cut between L and LV" - assert_equal 1, @handler.g_length(string_from_classes(%w(l lvt))), "Don't cut between L and LVT" - assert_equal 1, @handler.g_length(string_from_classes(%w(lv v))), "Don't cut between LV and V" - assert_equal 1, @handler.g_length(string_from_classes(%w(lv t))), "Don't cut between LV and T" - assert_equal 1, @handler.g_length(string_from_classes(%w(v v))), "Don't cut between V and V" - assert_equal 1, @handler.g_length(string_from_classes(%w(v t))), "Don't cut between V and T" - assert_equal 1, @handler.g_length(string_from_classes(%w(lvt t))), "Don't cut between LVT and T" - assert_equal 1, @handler.g_length(string_from_classes(%w(t t))), "Don't cut between T and T" - assert_equal 1, @handler.g_length(string_from_classes(%w(n extend))), "Don't cut before Extend" - assert_equal 2, @handler.g_length(string_from_classes(%w(n n))), "Cut between normal characters" - assert_equal 3, @handler.g_length(string_from_classes(%w(n cr lf n))), "Don't cut between CR and LF" - assert_equal 2, @handler.g_length(string_from_classes(%w(n l v t))), "Don't cut between L, V and T" - assert_raise(ActiveSupport::Multibyte::Handlers::EncodingError) { @handler.g_length(@bytestring) } - end - - def test_index - s = "Καλημέρα κόσμε!" - assert_equal 0, @handler.index('', ''), "The empty string is always found at the beginning of the string" - assert_equal 0, @handler.index('haystack', ''), "The empty string is always found at the beginning of the string" - assert_equal 0, @handler.index(s, 'Κ'), "Greek K is at 0" - assert_equal 1, @handler.index(s, 'α'), "Greek Alpha is at 1" - - assert_equal nil, @handler.index(@bytestring, 'a') - assert_raise(ActiveSupport::Multibyte::Handlers::EncodingError) { @handler.index(@bytestring, "\010") } - end - - def test_indexed_insert - s = "Καλη!" - @handler[s, 2] = "a" - assert_equal "Καaη!", s - @handler[s, 2] = "ηη" - assert_equal "Καηηη!", s - assert_raises(IndexError) { @handler[s, 10] = 'a' } - assert_equal "Καηηη!", s - @handler[s, 2] = 32 - assert_equal "Κα ηη!", s - @handler[s, 3, 2] = "λλλ" - assert_equal "Κα λλλ!", s - @handler[s, 1, 0] = "λ" - assert_equal "Κλα λλλ!", s - assert_raises(IndexError) { @handler[s, 10, 4] = 'a' } - assert_equal "Κλα λλλ!", s - @handler[s, 4..6] = "ηη" - assert_equal "Κλα ηη!", s - assert_raises(RangeError) { @handler[s, 10..12] = 'a' } - assert_equal "Κλα ηη!", s - @handler[s, /ηη/] = "λλλ" - assert_equal "Κλα λλλ!", s - assert_raises(IndexError) { @handler[s, /ii/] = 'a' } - assert_equal "Κλα λλλ!", s - @handler[s, /(λλ)(.)/, 2] = "α" - assert_equal "Κλα λλα!", s - assert_raises(IndexError) { @handler[s, /()/, 10] = 'a' } - assert_equal "Κλα λλα!", s - @handler[s, "α"] = "η" - assert_equal "Κλη λλα!", s - @handler[s, "λλ"] = "ααα" - assert_equal "Κλη αααα!", s - end - - def test_rjust - s = "Καη" - assert_raises(ArgumentError) { @handler.rjust(s, 10, '') } - assert_raises(ArgumentError) { @handler.rjust(s) } - assert_equal "Καη", @handler.rjust(s, -3) - assert_equal "Καη", @handler.rjust(s, 0) - assert_equal "Καη", @handler.rjust(s, 3) - assert_equal " Καη", @handler.rjust(s, 5) - assert_equal " Καη", @handler.rjust(s, 7) - assert_equal "----Καη", @handler.rjust(s, 7, '-') - assert_equal "ααααΚαη", @handler.rjust(s, 7, 'α') - assert_equal "abaΚαη", @handler.rjust(s, 6, 'ab') - assert_equal "αηαΚαη", @handler.rjust(s, 6, 'αη') - end - - def test_ljust - s = "Καη" - assert_raises(ArgumentError) { @handler.ljust(s, 10, '') } - assert_raises(ArgumentError) { @handler.ljust(s) } - assert_equal "Καη", @handler.ljust(s, -3) - assert_equal "Καη", @handler.ljust(s, 0) - assert_equal "Καη", @handler.ljust(s, 3) - assert_equal "Καη ", @handler.ljust(s, 5) - assert_equal "Καη ", @handler.ljust(s, 7) - assert_equal "Καη----", @handler.ljust(s, 7, '-') - assert_equal "Καηαααα", @handler.ljust(s, 7, 'α') - assert_equal "Καηaba", @handler.ljust(s, 6, 'ab') - assert_equal "Καηαηα", @handler.ljust(s, 6, 'αη') - end - - def test_center - s = "Καη" - assert_raises(ArgumentError) { @handler.center(s, 10, '') } - assert_raises(ArgumentError) { @handler.center(s) } - assert_equal "Καη", @handler.center(s, -3) - assert_equal "Καη", @handler.center(s, 0) - assert_equal "Καη", @handler.center(s, 3) - assert_equal "Καη ", @handler.center(s, 4) - assert_equal " Καη ", @handler.center(s, 5) - assert_equal " Καη ", @handler.center(s, 6) - assert_equal "--Καη--", @handler.center(s, 7, '-') - assert_equal "--Καη---", @handler.center(s, 8, '-') - assert_equal "ααΚαηαα", @handler.center(s, 7, 'α') - assert_equal "ααΚαηααα", @handler.center(s, 8, 'α') - assert_equal "aΚαηab", @handler.center(s, 6, 'ab') - assert_equal "abΚαηab", @handler.center(s, 7, 'ab') - assert_equal "ababΚαηabab", @handler.center(s, 11, 'ab') - assert_equal "αΚαηαη", @handler.center(s, 6, 'αη') - assert_equal "αηΚαηαη", @handler.center(s, 7, 'αη') - end - - def test_strip - # A unicode aware version of strip should strip all 26 types of whitespace. This includes the NO BREAK SPACE - # aka BOM (byte order mark). The byte order mark has no place in UTF-8 because it's used to detect LE and BE. - b = "\n" + [ - 32, # SPACE - 8195, # EM SPACE - 8199, # FIGURE SPACE, - 8201, # THIN SPACE - 8202, # HAIR SPACE - 65279, # NO BREAK SPACE (ZW) - ].pack('U*') - m = "word блин\n\n\n word" - e = [ - 65279, # NO BREAK SPACE (ZW) - 8201, # THIN SPACE - 8199, # FIGURE SPACE, - 32, # SPACE - ].pack('U*') - string = b+m+e - - assert_equal '', @handler.strip(''), "Empty string should stay empty" - assert_equal m+e, @handler.lstrip(string), "Whitespace should be gone on the left" - assert_equal b+m, @handler.rstrip(string), "Whitespace should be gone on the right" - assert_equal m, @handler.strip(string), "Whitespace should be stripped on both sides" - - bs = "\n #{@bytestring} \n\n" - assert_equal @bytestring, @handler.strip(bs), "Invalid unicode strings should still strip" - end - - def test_tidy_bytes - result = [0xb8, 0x17e, 0x8, 0x2c6, 0xa5].pack('U*') - assert_equal result, @handler.tidy_bytes(@bytestring) - assert_equal "a#{result}a", @handler.tidy_bytes('a' + @bytestring + 'a'), - 'tidy_bytes should leave surrounding characters intact' - assert_equal "é#{result}é", @handler.tidy_bytes('é' + @bytestring + 'é'), - 'tidy_bytes should leave surrounding characters intact' - assert_nothing_raised { @handler.tidy_bytes(@bytestring).unpack('U*') } - - assert_equal "\xC3\xA7", @handler.tidy_bytes("\xE7") # iso_8859_1: small c cedilla - assert_equal "\xC2\xA9", @handler.tidy_bytes("\xA9") # iso_8859_1: copyright symbol - assert_equal "\xE2\x80\x9C", @handler.tidy_bytes("\x93") # win_1252: left smart quote - assert_equal "\xE2\x82\xAC", @handler.tidy_bytes("\x80") # win_1252: euro - assert_equal "\x00", @handler.tidy_bytes("\x00") # null char - assert_equal [0xfffd].pack('U'), @handler.tidy_bytes("\xef\xbf\xbd") # invalid char - end - - protected - - def string_from_classes(classes) - classes.collect do |k| - @character_from_class[k.intern] - end.pack('U*') - end -end - - -begin - require_library_or_gem('utf8proc_native') - require 'active_record/multibyte/handlers/utf8_handler_proc' - class UTF8HandlingTestProc < Test::Unit::TestCase - include UTF8HandlingTest - def setup - common_setup - @handler = ::ActiveSupport::Multibyte::Handlers::UTF8HandlerProc - end - end -rescue LoadError -end - -class UTF8HandlingTestPure < Test::Unit::TestCase - include UTF8HandlingTest - def setup - common_setup - @handler = ::ActiveSupport::Multibyte::Handlers::UTF8Handler - end -end - -end diff --git a/activesupport/test/multibyte_test_helpers.rb b/activesupport/test/multibyte_test_helpers.rb new file mode 100644 index 0000000000..597f949059 --- /dev/null +++ b/activesupport/test/multibyte_test_helpers.rb @@ -0,0 +1,19 @@ +# encoding: utf-8 + +module MultibyteTestHelpers + UNICODE_STRING = 'こにちわ' + ASCII_STRING = 'ohayo' + BYTE_STRING = "\270\236\010\210\245" + + def chars(str) + ActiveSupport::Multibyte::Chars.new(str) + end + + def inspect_codepoints(str) + str.to_s.unpack("U*").map{|cp| cp.to_s(16) }.join(' ') + end + + def assert_equal_codepoints(expected, actual, message=nil) + assert_equal(inspect_codepoints(expected), inspect_codepoints(actual), message) + end +end
\ No newline at end of file diff --git a/activesupport/test/multibyte_unicode_database_test.rb b/activesupport/test/multibyte_unicode_database_test.rb new file mode 100644 index 0000000000..fb415e08d3 --- /dev/null +++ b/activesupport/test/multibyte_unicode_database_test.rb @@ -0,0 +1,28 @@ +# encoding: utf-8 + +require 'abstract_unit' + +uses_mocha "MultibyteUnicodeDatabaseTest" do + +class MultibyteUnicodeDatabaseTest < Test::Unit::TestCase + + def setup + @ucd = ActiveSupport::Multibyte::UnicodeDatabase.new + end + + ActiveSupport::Multibyte::UnicodeDatabase::ATTRIBUTES.each do |attribute| + define_method "test_lazy_loading_on_attribute_access_of_#{attribute}" do + @ucd.expects(:load) + @ucd.send(attribute) + end + end + + def test_load + @ucd.load + ActiveSupport::Multibyte::UnicodeDatabase::ATTRIBUTES.each do |attribute| + assert @ucd.send(attribute).length > 1 + end + end +end + +end
\ No newline at end of file diff --git a/railties/doc/guides/debugging/debugging_rails_applications.txt b/railties/doc/guides/debugging/debugging_rails_applications.txt index 37d4dd19d6..f7538cd08b 100644 --- a/railties/doc/guides/debugging/debugging_rails_applications.txt +++ b/railties/doc/guides/debugging/debugging_rails_applications.txt @@ -614,4 +614,4 @@ set listsize 25 http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/5[Lighthouse ticket] -* September 16, 2008: initial version by link:../authors.html#miloops[Emilio Tagua]
\ No newline at end of file +* September 16, 2008: initial version by link:../authors.html#miloops[Emilio Tagua] diff --git a/railties/doc/guides/migrations/migrations.txt b/railties/doc/guides/migrations/migrations.txt index 653fa818dd..be183e8597 100644 --- a/railties/doc/guides/migrations/migrations.txt +++ b/railties/doc/guides/migrations/migrations.txt @@ -19,4 +19,4 @@ include::rakeing_around.txt[] include::using_models_in_migrations.txt[] include::scheming.txt[] include::foreign_keys.txt[] -include::changelog.txt[]
\ No newline at end of file +include::changelog.txt[] diff --git a/railties/doc/guides/routing/routing_outside_in.txt b/railties/doc/guides/routing/routing_outside_in.txt index c04319496e..cef3c3b350 100644 --- a/railties/doc/guides/routing/routing_outside_in.txt +++ b/railties/doc/guides/routing/routing_outside_in.txt @@ -905,4 +905,4 @@ assert_routing { :path => "photos", :method => :post }, { :controller => "photos http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/3[Lighthouse ticket] * September 10, 2008: initial version by link:../authors.html#mgunderloy[Mike Gunderloy] -* September 23, 2008: Added section on namespaced controllers and routing, by link:../authors.html#mgunderloy[Mike Gunderloy]
\ No newline at end of file +* September 23, 2008: Added section on namespaced controllers and routing, by link:../authors.html#mgunderloy[Mike Gunderloy] diff --git a/railties/lib/rails/gem_dependency.rb b/railties/lib/rails/gem_dependency.rb index 471e03fa5f..d58ae450eb 100644 --- a/railties/lib/rails/gem_dependency.rb +++ b/railties/lib/rails/gem_dependency.rb @@ -120,7 +120,9 @@ module Rails def unpack_command cmd = %w(unpack) << @name - cmd << "--version" << %("#{@requirement.to_s}") if @requirement + # We don't quote this requirement as it's run through GemRunner instead + # of shelling out to gem + cmd << "--version" << @requirement.to_s if @requirement cmd end end diff --git a/railties/lib/rails/version.rb b/railties/lib/rails/version.rb index 48d24da52e..a0986a2e05 100644 --- a/railties/lib/rails/version.rb +++ b/railties/lib/rails/version.rb @@ -1,7 +1,7 @@ module Rails module VERSION #:nodoc: MAJOR = 2 - MINOR = 1 + MINOR = 2 TINY = 0 STRING = [MAJOR, MINOR, TINY].join('.') diff --git a/railties/lib/tasks/databases.rake b/railties/lib/tasks/databases.rake index cc079b1d93..1431aa6944 100644 --- a/railties/lib/tasks/databases.rake +++ b/railties/lib/tasks/databases.rake @@ -113,8 +113,16 @@ namespace :db do end namespace :migrate do - desc 'Rollbacks the database one migration and re migrate up. If you want to rollback more than one step, define STEP=x' - task :redo => [ 'db:rollback', 'db:migrate' ] + desc 'Rollbacks the database one migration and re migrate up. If you want to rollback more than one step, define STEP=x. Target specific version with VERSION=x.' + task :redo => :environment do + if ENV["VERSION"] + Rake::Task["db:migrate:down"].invoke + Rake::Task["db:migrate:up"].invoke + else + Rake::Task["db:rollback"].invoke + Rake::Task["db:migrate"].invoke + end + end desc 'Resets your database using your migrations for the current environment' task :reset => ["db:drop", "db:create", "db:migrate"] diff --git a/railties/test/gem_dependency_test.rb b/railties/test/gem_dependency_test.rb index 964ca50992..c94c950455 100644 --- a/railties/test/gem_dependency_test.rb +++ b/railties/test/gem_dependency_test.rb @@ -37,7 +37,7 @@ uses_mocha "Plugin Tests" do end def test_gem_with_version_unpack_install_command - assert_equal ["unpack", "hpricot", "--version", '"= 0.6"'], @gem_with_version.unpack_command + assert_equal ["unpack", "hpricot", "--version", '= 0.6'], @gem_with_version.unpack_command end def test_gem_adds_load_paths |