aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--actionmailer/lib/action_mailer/version.rb2
-rw-r--r--actionpack/CHANGELOG2
-rw-r--r--actionpack/lib/action_controller/base.rb2
-rw-r--r--actionpack/lib/action_controller/cgi_ext/session.rb24
-rw-r--r--actionpack/lib/action_controller/cgi_process.rb3
-rw-r--r--actionpack/lib/action_controller/rack_process.rb3
-rw-r--r--actionpack/lib/action_controller/session/cookie_store.rb3
-rw-r--r--actionpack/lib/action_controller/session_management.rb4
-rw-r--r--actionpack/lib/action_pack/version.rb2
-rw-r--r--actionpack/lib/action_view.rb2
-rw-r--r--actionpack/lib/action_view/helpers.rb1
-rw-r--r--actionpack/lib/action_view/helpers/asset_tag_helper.rb464
-rw-r--r--actionpack/lib/action_view/helpers/form_country_helper.rb92
-rw-r--r--actionpack/lib/action_view/helpers/form_helper.rb8
-rw-r--r--actionpack/lib/action_view/helpers/form_options_helper.rb3
-rw-r--r--actionpack/lib/action_view/helpers/text_helper.rb206
-rw-r--r--actionpack/lib/action_view/template.rb13
-rw-r--r--actionpack/lib/action_view/template_error.rb30
-rw-r--r--actionpack/test/controller/session/cookie_store_test.rb53
-rw-r--r--actionpack/test/fixtures/test/sub_template_raise.html.erb1
-rw-r--r--actionpack/test/template/asset_tag_helper_test.rb64
-rw-r--r--actionpack/test/template/form_country_helper_test.rb1549
-rw-r--r--actionpack/test/template/render_test.rb18
-rw-r--r--activerecord/CHANGELOG8
-rw-r--r--activerecord/lib/active_record.rb4
-rwxr-xr-xactiverecord/lib/active_record/associations.rb55
-rw-r--r--activerecord/lib/active_record/associations/association_collection.rb32
-rw-r--r--activerecord/lib/active_record/associations/has_many_association.rb5
-rw-r--r--activerecord/lib/active_record/associations/has_many_through_association.rb4
-rw-r--r--activerecord/lib/active_record/attribute_methods.rb10
-rwxr-xr-xactiverecord/lib/active_record/base.rb46
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb4
-rw-r--r--activerecord/lib/active_record/connection_adapters/mysql_adapter.rb7
-rw-r--r--activerecord/lib/active_record/i18n_interpolation_deprecation.rb26
-rw-r--r--activerecord/lib/active_record/schema_dumper.rb2
-rw-r--r--activerecord/lib/active_record/validations.rb4
-rw-r--r--activerecord/lib/active_record/version.rb2
-rw-r--r--activerecord/test/cases/associations/extension_test.rb15
-rw-r--r--activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb11
-rw-r--r--activerecord/test/cases/associations/has_many_associations_test.rb24
-rw-r--r--activerecord/test/cases/associations/has_many_through_associations_test.rb9
-rw-r--r--activerecord/test/cases/associations_test.rb8
-rw-r--r--activerecord/test/cases/attribute_methods_test.rb60
-rwxr-xr-x[-rw-r--r--]activerecord/test/cases/base_test.rb74
-rw-r--r--activerecord/test/cases/defaults_test.rb31
-rw-r--r--activerecord/test/cases/finder_test.rb15
-rw-r--r--activerecord/test/cases/helper.rb14
-rw-r--r--activerecord/test/cases/method_scoping_test.rb30
-rw-r--r--activerecord/test/cases/migration_test.rb6
-rw-r--r--activerecord/test/cases/named_scope_test.rb6
-rw-r--r--activerecord/test/cases/sanitize_test.rb8
-rw-r--r--activerecord/test/cases/validations_i18n_test.rb6
-rw-r--r--activeresource/lib/active_resource/connection.rb2
-rw-r--r--activeresource/test/connection_test.rb12
-rw-r--r--activesupport/CHANGELOG8
-rwxr-xr-xactivesupport/bin/generate_tables147
-rw-r--r--activesupport/lib/active_support.rb2
-rw-r--r--activesupport/lib/active_support/buffered_logger.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/date/calculations.rb33
-rw-r--r--activesupport/lib/active_support/core_ext/date_time/calculations.rb24
-rw-r--r--activesupport/lib/active_support/core_ext/file/atomic.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/hash/slice.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/string.rb6
-rw-r--r--activesupport/lib/active_support/core_ext/string/access.rb10
-rw-r--r--activesupport/lib/active_support/core_ext/string/multibyte.rb81
-rw-r--r--activesupport/lib/active_support/core_ext/string/unicode.rb66
-rw-r--r--activesupport/lib/active_support/core_ext/time/calculations.rb37
-rw-r--r--activesupport/lib/active_support/inflector.rb16
-rw-r--r--activesupport/lib/active_support/multibyte.rb36
-rw-r--r--activesupport/lib/active_support/multibyte/chars.rb791
-rw-r--r--activesupport/lib/active_support/multibyte/exceptions.rb8
-rwxr-xr-xactivesupport/lib/active_support/multibyte/generators/generate_tables.rb149
-rw-r--r--activesupport/lib/active_support/multibyte/handlers/passthru_handler.rb9
-rw-r--r--activesupport/lib/active_support/multibyte/handlers/utf8_handler.rb564
-rw-r--r--activesupport/lib/active_support/multibyte/handlers/utf8_handler_proc.rb43
-rw-r--r--activesupport/lib/active_support/multibyte/unicode_database.rb71
-rw-r--r--activesupport/lib/active_support/test_case.rb8
-rw-r--r--activesupport/lib/active_support/time_with_zone.rb94
-rw-r--r--activesupport/lib/active_support/values/unicode_tables.datbin656156 -> 710734 bytes
-rwxr-xr-xactivesupport/lib/active_support/vendor/i18n-0.0.1/i18n.rb27
-rw-r--r--activesupport/lib/active_support/vendor/i18n-0.0.1/i18n/backend/simple.rb21
-rw-r--r--activesupport/lib/active_support/version.rb2
-rw-r--r--activesupport/test/abstract_unit.rb19
-rw-r--r--activesupport/test/core_ext/date_ext_test.rb23
-rw-r--r--activesupport/test/core_ext/date_time_ext_test.rb75
-rw-r--r--activesupport/test/core_ext/hash_ext_test.rb10
-rw-r--r--activesupport/test/core_ext/string_ext_test.rb59
-rw-r--r--activesupport/test/core_ext/time_ext_test.rb81
-rw-r--r--activesupport/test/core_ext/time_with_zone_test.rb74
-rw-r--r--activesupport/test/inflector_test.rb6
-rw-r--r--activesupport/test/inflector_test_cases.rb5
-rw-r--r--activesupport/test/json/encoding_test.rb12
-rw-r--r--activesupport/test/multibyte_chars_test.rb705
-rw-r--r--activesupport/test/multibyte_conformance.rb105
-rw-r--r--activesupport/test/multibyte_handler_test.rb372
-rw-r--r--activesupport/test/multibyte_test_helpers.rb19
-rw-r--r--activesupport/test/multibyte_unicode_database_test.rb28
-rw-r--r--railties/Rakefile7
-rw-r--r--railties/doc/guides/.DS_Storebin6148 -> 0 bytes
-rw-r--r--railties/doc/guides/actioncontroller/actioncontroller.txt28
-rw-r--r--railties/doc/guides/actioncontroller/cookies.txt26
-rw-r--r--railties/doc/guides/actioncontroller/filters.txt118
-rw-r--r--railties/doc/guides/actioncontroller/http_auth.txt24
-rw-r--r--railties/doc/guides/actioncontroller/introduction.txt7
-rw-r--r--railties/doc/guides/actioncontroller/methods.txt37
-rw-r--r--railties/doc/guides/actioncontroller/parameter_filtering.txt14
-rw-r--r--railties/doc/guides/actioncontroller/params.txt62
-rw-r--r--railties/doc/guides/actioncontroller/request_response_objects.txt35
-rw-r--r--railties/doc/guides/actioncontroller/rescue.txt3
-rw-r--r--railties/doc/guides/actioncontroller/session.txt130
-rw-r--r--railties/doc/guides/actioncontroller/streaming.txt91
-rw-r--r--railties/doc/guides/actioncontroller/verification.txt3
-rw-r--r--railties/doc/guides/actionview/layouts_and_rendering.txt597
-rw-r--r--railties/doc/guides/activerecord/association_basics.txt393
-rw-r--r--railties/doc/guides/activerecord/images/has_many_through.pngbin112630 -> 100220 bytes
-rw-r--r--railties/doc/guides/activerecord/images/polymorphic.pngbin0 -> 85248 bytes
-rw-r--r--railties/doc/guides/benchmarking_and_profiling/examples/.DS_Storebin6148 -> 0 bytes
-rw-r--r--railties/doc/guides/benchmarking_and_profiling/rubyprof.txt2
-rw-r--r--railties/doc/guides/debugging/debugging_rails_applications.txt2
-rw-r--r--railties/doc/guides/index.txt98
-rw-r--r--railties/doc/guides/migrations/migrations.txt2
-rw-r--r--railties/doc/guides/routing/routing_outside_in.txt16
-rw-r--r--railties/doc/guides/testing_rails_applications/testing_rails_applications.txt137
-rw-r--r--railties/lib/rails/gem_dependency.rb4
-rw-r--r--railties/lib/rails/version.rb2
-rw-r--r--railties/lib/tasks/databases.rake12
-rw-r--r--railties/test/gem_dependency_test.rb2
127 files changed, 4804 insertions, 3989 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/base.rb b/actionpack/lib/action_controller/base.rb
index fe168788e2..91f531f12c 100644
--- a/actionpack/lib/action_controller/base.rb
+++ b/actionpack/lib/action_controller/base.rb
@@ -252,7 +252,7 @@ module ActionController #:nodoc:
#
# def do_something
# redirect_to(:action => "elsewhere") and return if monkeys.nil?
- # render :action => "overthere" # won't be called unless monkeys is nil
+ # render :action => "overthere" # won't be called if monkeys is nil
# end
#
class Base
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_helper.rb b/actionpack/lib/action_view/helpers/form_helper.rb
index 7bb82ba5bb..621e2946b5 100644
--- a/actionpack/lib/action_view/helpers/form_helper.rb
+++ b/actionpack/lib/action_view/helpers/form_helper.rb
@@ -442,10 +442,10 @@ module ActionView
end
# Returns a checkbox tag tailored for accessing a specified attribute (identified by +method+) on an object
- # assigned to the template (identified by +object+). It's intended that +method+ returns an integer and if that
- # integer is above zero, then the checkbox is checked. Additional options on the input tag can be passed as a
- # hash with +options+. The +checked_value+ defaults to 1 while the default +unchecked_value+
- # is set to 0 which is convenient for boolean values.
+ # assigned to the template (identified by +object+). This object must be an instance object (@object) and not a local object.
+ # It's intended that +method+ returns an integer and if that integer is above zero, then the checkbox is checked.
+ # Additional options on the input tag can be passed as a hash with +options+. The +checked_value+ defaults to 1
+ # while the default +unchecked_value+ is set to 0 which is convenient for boolean values.
#
# ==== Gotcha
#
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
index 35edb148c3..74b333d416 100644
--- a/activesupport/lib/active_support/values/unicode_tables.dat
+++ b/activesupport/lib/active_support/values/unicode_tables.dat
Binary files differ
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/Rakefile b/railties/Rakefile
index e279bf922e..8de7e24738 100644
--- a/railties/Rakefile
+++ b/railties/Rakefile
@@ -277,16 +277,19 @@ Rake::RDocTask.new { |rdoc|
# doesn't equal its folder name, then specify a hash: { 'folder_name' => 'basename' }
guides = [
'getting_started_with_rails',
- 'testing_rails_applications',
+ # 'testing_rails_applications',
'creating_plugins',
+ 'actioncontroller',
'migrations',
{ 'securing_rails_applications' => 'security' },
{ 'routing' => 'routing_outside_in' },
{ 'forms' =>'form_helpers' },
{ 'activerecord' => 'association_basics' },
+ { 'activerecord' => 'finders' },
{ 'debugging' => 'debugging_rails_applications' },
{ 'caching' => 'caching_with_rails' },
- { 'benchmarking_and_profiling' => 'preamble' }
+ { 'benchmarking_and_profiling' => 'preamble' },
+ { 'actionview' => 'layouts_and_rendering' }
]
guides_html_files = [] # autogenerated from the 'guides' variable.
diff --git a/railties/doc/guides/.DS_Store b/railties/doc/guides/.DS_Store
deleted file mode 100644
index aa78fbf68c..0000000000
--- a/railties/doc/guides/.DS_Store
+++ /dev/null
Binary files differ
diff --git a/railties/doc/guides/actioncontroller/actioncontroller.txt b/railties/doc/guides/actioncontroller/actioncontroller.txt
new file mode 100644
index 0000000000..c5a594d713
--- /dev/null
+++ b/railties/doc/guides/actioncontroller/actioncontroller.txt
@@ -0,0 +1,28 @@
+Action Controller basics
+=======================
+
+In this guide you will learn how controllers work and how they fit into the request cycle in your application. You will learn how to make use of the many tools provided by Action Controller to work with the session, cookies and filters and how to use the built-in HTTP authentication and data streaming facilities. In the end, we will take a look at some tools that will be useful once your controllers are ready and working, like how to filter sensitive parameters from the log and how to rescue and deal with exceptions that may be raised during the request.
+
+include::introduction.txt[]
+
+include::methods.txt[]
+
+include::params.txt[]
+
+include::session.txt[]
+
+include::cookies.txt[]
+
+include::filters.txt[]
+
+include::request_response_objects.txt[]
+
+include::http_auth.txt[]
+
+include::streaming.txt[]
+
+include::parameter_filtering.txt[]
+
+include::verification.txt[]
+
+include::rescue.txt[]
diff --git a/railties/doc/guides/actioncontroller/cookies.txt b/railties/doc/guides/actioncontroller/cookies.txt
new file mode 100644
index 0000000000..a845e452b2
--- /dev/null
+++ b/railties/doc/guides/actioncontroller/cookies.txt
@@ -0,0 +1,26 @@
+== Cookies ==
+
+Your application can store small amounts of data on the client - called cookies - that will be persisted across requests and even sessions. Rails provides easy access to cookies via the `cookies` method, which - much like the `session` - works like a hash:
+
+TODO: Find a real-world example where cookies are used
+
+[source, ruby]
+-----------------------------------------
+class FooController < ApplicationController
+
+ def foo
+ cookies[:foo] = "bar"
+ end
+
+ def display_foo
+ @foo = cookies[:foo]
+ end
+
+ def remove_foo
+ cookies.delete(:foo)
+ end
+
+end
+-----------------------------------------
+
+Note that while for session values, you set the key to `nil`, to delete a cookie value, you use `cookies.delete(:key)`.
diff --git a/railties/doc/guides/actioncontroller/filters.txt b/railties/doc/guides/actioncontroller/filters.txt
new file mode 100644
index 0000000000..2baf92d6ef
--- /dev/null
+++ b/railties/doc/guides/actioncontroller/filters.txt
@@ -0,0 +1,118 @@
+== Filters ==
+
+Filters are methods that are run before, after or "around" a controller action. For example, one filter might check to see if the logged in user has the right credentials to access that particular controller or action. Filters are inherited, so if you set a filter on ApplicationController, it will be run on every controller in your application. A common, simple filter is one which requires that a user is logged in for an action to be run. Let's define the filter method first:
+
+[source, ruby]
+---------------------------------
+class ApplicationController < ActionController::Base
+
+private
+
+ def require_login
+ unless logged_in?
+ flash[:error] = "You must be logged in to access this section"
+ redirect_to new_login_url # Prevents the current action from running
+ end
+ end
+
+ # The logged_in? method simply returns true if the user is logged in and
+ # false otherwise. It does this by "booleanizing" the current_user method
+ # we created previously using a double ! operator. Note that this is not
+ # common in Ruby and is discouraged unless you really mean to convert something
+ # into true or false.
+ def logged_in?
+ !!current_user
+ end
+
+end
+---------------------------------
+
+The method simply stores an error message in the flash and redirects to the login form if the user is not logged in. If a before filter (a filter which is run before the action) renders or redirects, the action will not run. If there are additional filters scheduled to run after the rendering/redirecting filter, they are also cancelled. To use this filter in a controller, use the "before_filter":http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html#M000704 method:
+
+[source, ruby]
+---------------------------------
+class ApplicationController < ActionController::Base
+
+ before_filter :require_login
+
+end
+---------------------------------
+
+In this example, the filter is added to ApplicationController and thus all controllers in the application. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn't be able to log in in the first place!), not all controllers or actions should require this, so to prevent this filter from running you can use "skip_before_filter":http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html#M000711 :
+
+[source, ruby]
+---------------------------------
+class LoginsController < Application
+
+ skip_before_filter :require_login, :only => [:new, :create]
+
+end
+---------------------------------
+
+Now, the LoginsController's "new" and "create" actions will work as before without requiring the user to be logged in. The `:only` option is used to only skip this filter for these actions, and there is also an `:except` option which works the other way. These options can be used when adding filters too, so you can add a filter which only runs for selected actions in the first place.
+
+=== After filters and around filters ===
+
+In addition to the before filters, you can run filters after an action has run or both before and after. The after filter is similar to the before filter, but because the action has already been run it has access to the response data that's about to be sent to the client. Obviously, after filters can not stop the action from running. Around filters are responsible for running the action, but they can choose not to, which is the around filter's way of stopping it.
+
+TODO: Find a real example for an around filter
+
+[source, ruby]
+---------------------------------
+class ApplicationController < Application
+
+ around_filter :foo
+
+private
+
+ def foo
+ logger.debug("Action has not been run yet")
+ yield #Run the action
+ logger.debug("Action has been run")
+ end
+
+end
+---------------------------------
+
+=== Other types of filters ===
+
+While the most common way to use filters is by creating private methods and using *_filter to add them, there are two other ways.
+
+The first is to use a block directly with the *_filter methods. The block receives the controller as an argument, and the `require_login` filter from above could be rewritte to use a block:
+
+[source, ruby]
+---------------------------------
+class ApplicationController < ActionController::Base
+
+ before_filter { |controller| redirect_to new_login_url unless controller.send(:logged_in?) }
+
+end
+---------------------------------
+
+Note that the filter in this case uses `send` because the `logged_in?` method is private and the filter is not run in the scope of the controller. This is not the recommended way to implement this particular filter, but in more simple cases it might be useful.
+
+The second way is to use a class (actually, any object that responds to the right methods will do) to handle the filtering. This is useful in cases that are more complex than can not be implemented in a readable and reusable way using the two other methods. As an example, we will rewrite the login filter again to use a class:
+
+[source, ruby]
+---------------------------------
+class ApplicationController < ActionController::Base
+
+ before_filter LoginFilter
+
+end
+
+class LoginFilter
+
+ def self.filter(controller)
+ unless logged_in?
+ controller.flash[:error] = "You must be logged in to access this section"
+ controller.redirect_to controller.new_login_url
+ end
+ end
+
+end
+---------------------------------
+
+Again, this is not an ideal example for this filter, because it's not run in the scope of the controller but gets it passed as an argument. The filter class has a class method `filter` which gets run before or after the action, depending on if it's a before or after filter. Classes used as around filters can also use the same `filter` method, which will get run in the same way. The method must `yield` to execute the action. Alternatively, it can have both a `before` and an `after` method that are run before and after the action.
+
+The Rails API documentation has "more information and detail on using filters":http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html
diff --git a/railties/doc/guides/actioncontroller/http_auth.txt b/railties/doc/guides/actioncontroller/http_auth.txt
new file mode 100644
index 0000000000..5a95de0bb3
--- /dev/null
+++ b/railties/doc/guides/actioncontroller/http_auth.txt
@@ -0,0 +1,24 @@
+== HTTP Basic Authentication ==
+
+Rails comes with built-in HTTP Basic authentication. This is an authentication scheme that is supported by the majority of browsers and other HTTP clients. As an example, we will create an administration section which will only be available by entering a username and a password into the browser's HTTP Basic dialog window. Using the built-in authentication is quite easy and only requires you to use one method, "authenticate_or_request_with_http_basic":http://api.rubyonrails.org/classes/ActionController/HttpAuthentication/Basic/ControllerMethods.html#M000610
+
+[source, ruby]
+-------------------------------------
+class AdminController < ApplicationController
+
+ USERNAME, PASSWORD = "humbaba", "f59a4805511bf4bb61978445a5380c6c"
+
+ before_filter :authenticate
+
+private
+
+ def authenticate
+ authenticate_or_request_with_http_basic do |username, password|
+ username == USERNAME && Digest::MD5.hexdigest(password) == PASSWORD
+ end
+ end
+
+end
+-------------------------------------
+
+With this in place, you can create namespaced controllers that inherit from AdminController. The before filter will thus be run for all actions in those controllers, protecting them with HTTP Basic authentication.
diff --git a/railties/doc/guides/actioncontroller/introduction.txt b/railties/doc/guides/actioncontroller/introduction.txt
new file mode 100644
index 0000000000..35540bbc09
--- /dev/null
+++ b/railties/doc/guides/actioncontroller/introduction.txt
@@ -0,0 +1,7 @@
+== What does a controller do? ==
+
+Action Controller is the C in MVC. After routing has determined which controller to use for a request, your controller is responsible for making sense of the request and producing the appropriate output. Luckily, Action Controller does most of the groundwork for you and uses smart conventions to make this as straight-forward as possible.
+
+For most conventional RESTful applications, the controller will receive the request (this is invisible to the developer), fetch or save data from a model and use a view to create HTML output. If your controller needs to do things a little differently, that's not a problem, this is just the most common way for a controller to work.
+
+A controller can thus be thought of as a middle man between models and views. It makes the model data available to the view so it can display it to the user, and it saves or updates data from the user to the model.
diff --git a/railties/doc/guides/actioncontroller/methods.txt b/railties/doc/guides/actioncontroller/methods.txt
new file mode 100644
index 0000000000..0818dbb849
--- /dev/null
+++ b/railties/doc/guides/actioncontroller/methods.txt
@@ -0,0 +1,37 @@
+== Methods and actions ==
+
+A controller is a Ruby class which inherits from ActionController::Base and has methods just like any other class. Usually these methods correspond to actions in MVC, but they can just as well be helpful methods which can be called by actions. When your application receives a request, the routing will determine which controller and action to run. Then an instance of that controller will be created and the method corresponding to the action (the method with the same name as the action) is run.
+
+[source, ruby]
+----------------------------------------------
+class ClientsController < ActionController::Base
+
+ # Actions are public methods
+ def new
+ end
+
+ # These methods are responsible for producing output
+ def edit
+ end
+
+# Helper methods are private and can not be used as actions
+private
+
+ def foo
+ end
+
+end
+----------------------------------------------
+
+Private methods in a controller are also used as filters, which will be covered later in this guide.
+
+As an example, if the user goes to `/clients/new` in your application to add a new client, a ClientsController instance will be created and the `new` method will be run. Note that the empty method from the example above could work just fine because Rails will by default render the `new.html.erb` view unless the action says otherwise. The `new` method could make available to the view a `@client` instance variable by creating a new Client:
+
+[source, ruby]
+----------------------------------------------
+def new
+ @client = Client.new
+end
+----------------------------------------------
+
+The Layouts & rendering guide explains this in more detail.
diff --git a/railties/doc/guides/actioncontroller/parameter_filtering.txt b/railties/doc/guides/actioncontroller/parameter_filtering.txt
new file mode 100644
index 0000000000..dce4b252c3
--- /dev/null
+++ b/railties/doc/guides/actioncontroller/parameter_filtering.txt
@@ -0,0 +1,14 @@
+== Parameter filtering ==
+
+Rails keeps a log file for each environment (development, test and production) in the "log" folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. The "filter_parameter_logging":http://api.rubyonrails.org/classes/ActionController/Base.html#M000837 can be used to filter out sensitive information from the log. It works by replacing certain keys in the `params` hash with "[FILTERED]" before they are written to the log. As an example, let's see how to filter all parameters with keys that include "password":
+
+[source, ruby]
+-------------------------
+class ApplicationController < ActionController::Base
+
+ filter_parameter_logging :password
+
+end
+-------------------------
+
+The method works recursively through all levels of the params hash and takes an optional second parameter which is used as the replacement string if present. It can also take a block which receives each key in return and replaces those for which the block returns true.
diff --git a/railties/doc/guides/actioncontroller/params.txt b/railties/doc/guides/actioncontroller/params.txt
new file mode 100644
index 0000000000..67f97b6135
--- /dev/null
+++ b/railties/doc/guides/actioncontroller/params.txt
@@ -0,0 +1,62 @@
+== Parameters ==
+
+You will probably want to access data sent in by the user or other parameters in your controller actions. There are two kinds of parameters possible in a web application. The first are parameters that are sent as part of the URL, query string parameters. The query string is everything after "?" in the URL. The second type of parameter is usually referred to as POST data. This information usually comes from a HTML form which has been filled in by the user. It's called POST data because it can only be sent as part of an HTTP POST request. Rails does not make any distinction between query string parameters and POST parameters, and both are available in the `params` hash in your controller:
+
+[source, ruby]
+-------------------------------------
+class ClientsController < ActionController::Base
+
+ # This action uses query string parameters because it gets run by a HTTP GET request,
+ # but this does not make any difference to the way in which the parameters are accessed.
+ # The URL for this action would look like this in order to list activated clients: /clients/?status=activated
+ def index
+ if params[:status] = "activated"
+ @clients = Client.activated
+ else
+ @clients = Client.unativated
+ end
+ end
+
+ # This action uses POST parameters. They are most likely coming from an HTML
+ # form which the user has submitted. The URL for this RESTful request will
+ # be "/clients", and the data will be sent as part of the request body.
+ def create
+ @client = Client.new(params[:client])
+ if @client.save
+ redirect_to @client
+ else
+ # This line overrides the default rendering behavior, which would have been
+ # to render the "create" view.
+ render :action => "new"
+ end
+ end
+
+end
+-------------------------------------
+
+=== Hash and array parameters ===
+
+The params hash is not limited to one-dimensional keys and values. It can contain arrays and (nested) hashes. To send an array of values, append "[]" to the key name:
+
+-------------------------------------
+GET /clients?ids[]=1&ids[2]&ids[]=3
+-------------------------------------
+
+The value of `params[:ids]` will now be `["1", "2", "3"]`. Note that parameter values are always strings; Rails makes no attempt to guess or cast the type.
+
+To send a hash you include the key name inside the brackets:
+
+-------------------------------------
+<form action="/clients">
+ <input type="text" name="client[name]" value="Acme" />
+ <input type="text" name="client[phone]" value="12345" />
+ <input type="text" name="client[address][postcode]" value="12345" />
+ <input type="text" name="client[address][city]" value="Carrot City" />
+</form>
+-------------------------------------
+
+The value of `params[:client]` when this form is submitted will be `{:name => "Acme", :phone => "12345", :address => {:postcode => "12345", :city => "Carrot City"}}`. Note the nested hash in `params[:client][:address]`.
+
+=== Routing parameters ===
+
+The `params` hash will always contain the `:controller` and `:action` keys, but you should use the methods `controller_name` and `action_name` instead to access these values. Any other parameters defined by the routing, such as `:id` will also be available.
diff --git a/railties/doc/guides/actioncontroller/request_response_objects.txt b/railties/doc/guides/actioncontroller/request_response_objects.txt
new file mode 100644
index 0000000000..d335523a25
--- /dev/null
+++ b/railties/doc/guides/actioncontroller/request_response_objects.txt
@@ -0,0 +1,35 @@
+== The request and response objects ==
+
+In every controller there are two accessor methods pointing to the request and the response objects associated with the request cycle that is currently in execution. The `request` method contains an instance of "AbstractRequest":http://api.rubyonrails.org/classes/ActionController/AbstractRequest.html and the `response` method contains the "response object":http://github.com/rails/rails/tree/master/actionpack/lib/action_controller/response.rb representing what is going to be sent back to the client.
+
+=== The request ===
+
+The request object contains a lot of useful information about the request coming in from the client. To get a full list of the available methods, refer to the "Rails API documentation":http://api.rubyonrails.org/classes/ActionController/AbstractRequest.html
+
+ * host - The hostname used for this request.
+ * domain - The hostname without the first part (usually "www").
+ * format - The content type requested by the client.
+ * method - The HTTP method used for the request.
+ * get?, post?, put?, delete?, head? - Returns true if the HTTP method is get/post/put/delete/head.
+ * headers - Returns a hash containing the headers associated with the request.
+ * port - The port number (integer) used for the request.
+ * protocol - The protocol used for the request.
+ * query_string - The query string part of the URL - everything after "?".
+ * remote_ip - The IP address of the client.
+ * url - The entire URL used for the request.
+
+==== path_parameters, query_parameters and request_parameters ====
+
+TODO: Does this belong here?
+
+Rails collects all of the parameters sent along with the request in the `params` hash, whether they are sent as part of the query string or the post body. The request object has three accessors that give you access to these parameters depending on where they came from. The `query_parameters` hash contains parameters that were sent as part of the query string while the `request_parameters` hash contains parameters sent as part of the post body. The `path_parameters` hash contains parameters that were recognised by the routing as being part of the path leading to this particular controller and action.
+
+=== The response ===
+
+The response objects is not usually used directly, but is built up during the execution of the action and rendering of the data that is being sent back to the user, but sometimes - like in an after filter - it can be useful to access the response directly. Some of these accessor methods also have setters, allowing you to change their values.
+
+ * body - This is the string of data being sent back to the client. This is most often HTML.
+ * status - The HTTP status code for the response, like 200 for a successful request or 404 for file not found.
+ * location - The URL the client is being redirected to, if any.
+ * content_type - The content type of the response.
+ * charset - The character set being used for the response. Default is "utf8".
diff --git a/railties/doc/guides/actioncontroller/rescue.txt b/railties/doc/guides/actioncontroller/rescue.txt
new file mode 100644
index 0000000000..6ff7ea67d8
--- /dev/null
+++ b/railties/doc/guides/actioncontroller/rescue.txt
@@ -0,0 +1,3 @@
+== Rescue ==
+
+Describe how to use rescue_from et al to rescue exceptions in controllers.
diff --git a/railties/doc/guides/actioncontroller/session.txt b/railties/doc/guides/actioncontroller/session.txt
new file mode 100644
index 0000000000..50ed76e3ae
--- /dev/null
+++ b/railties/doc/guides/actioncontroller/session.txt
@@ -0,0 +1,130 @@
+== Session ==
+
+Your application sets up a session for each user which can persist small amounts of data between requests. The session is only available in the controller. It can be stored in a number of different session stores:
+
+TODO: Not sure if all of these are available by default.
+
+ * CookieStore - Stores everything on the client.
+ * SQLSessionStore - Stores the data in a database using SQL.
+ * DRBStore - Stores the data on a DRb client.
+ * MemCacheStore - Stores the data in MemCache.
+ * ActiveRecordStore - Stores the data in a database using Active Record.
+
+All session stores store the session id in a cookie - there is no other way of passing it to the server. Most stores also use this key to locate the session data on the server.
+
+The default and recommended store, the Cookie Store, does not store session data on the server, but in the cookie itself. The data is cryptographically signed to make it tamper-proof, but it is not encrypted, so anyone with access to it can read its contents. It can only store 4Kb of data - much less than the others - but this is usually enough. Storing large amounts of data is discouraged no matter which session store your application uses. Expecially discouraged is storing complex objects (anything other than basic Ruby objects) in the session, as the server might not be able to reassemble them between requests, which will result in an error. The Cookie Store has the added advantage that it does not require any setting up beforehand - Rails will generate a "secret key" which will be used to sign the cookie when you create the application.
+
+If you need a different session storage mechanism, you can change it in the `config/environment.rb` file:
+
+[source, ruby]
+------------------------------------------
+# Set to one of [:active_record_store, :sql_session_store, :drb_store, :mem_cache_store, :cookie_store]
+config.action_controller.session_store = :active_record_store
+------------------------------------------
+
+=== Accessing the session ===
+
+In your controller you can access the session through the `session` method. Session values are stored using key/value pairs like a hash:
+
+[source, ruby]
+------------------------------------------
+class ApplicationController < ActionController::Base
+
+private
+
+ # Finds the User with the ID stored in the session with the key :current_user_id
+ def current_user
+ @_current_user ||= session[:current_user_id] && User.find(session[:current_user_id])
+ end
+
+end
+------------------------------------------
+
+To store something in the session, just assign it to the key like a hash:
+
+[source, ruby]
+------------------------------------------
+class LoginsController < ApplicationController
+
+ # "Create" a login, aka "log the user in"
+ def create
+ if user = User.authenticate(params[:username, params[:password])
+ # Save the user ID in the session so it can be used in subsequent requests
+ session[:current_user_id] = user.id
+ redirect_to root_url
+ end
+ end
+
+end
+------------------------------------------
+
+To remove something from the session, assign that key to be `nil`:
+
+[source, ruby]
+------------------------------------------
+class LoginsController < ApplicationController
+
+ # "Delete" a login, aka "log the user out"
+ def destroy
+ # Remove the user id from the session
+ session[:current_user_id] = nil
+ redirect_to root_url
+ end
+
+end
+------------------------------------------
+
+To reset the entire session, use `reset_session`.
+
+=== The flash ===
+
+The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for storing error messages etc. It is accessed in much the same way as the session, like a hash. Let's use the act of logging out as an example. The controller can set a message which will be displayed to the user on the next request:
+
+[source, ruby]
+------------------------------------------
+class LoginsController < ApplicationController
+
+ def destroy
+ session[:current_user_id] = nil
+ flash[:notice] = "You have successfully logged out"
+ redirect_to root_url
+ end
+
+end
+------------------------------------------
+
+The `destroy` action redirects to the application's `root_url`, where the message will be displayed. Note that it's entirely up to the next action to decide what, if anything, it will do with what the previous action put in the flash. It's conventional to a display eventual errors or notices from the flash in the application's layout:
+
+[source, ruby]
+------------------------------------------
+<!-- head, etc -->
+<body>
+ <% if flash[:notice] -%>
+ <p class="notice"><%= flash[:notice] %></p>
+ <% end -%>
+ <% if flash[:error] -%>
+ <p class="error"><%= flash[:error] %></p>
+ <% end -%>
+ <!-- more content -->
+</body>
+</html>
+------------------------------------------
+
+This way, if an action sets an error or a notice message, the layout will display it automatically.
+
+If you want a flash value to be carried over to another request, use the `keep` method:
+
+[source, ruby]
+------------------------------------------
+class MainController < ApplicationController
+
+ # Let's say this action corresponds to root_url, but you want all requests here to be redirected to
+ # UsersController#index. If an action sets the flash and redirects here, the values would normally be
+ # lost when another redirect happens, but you can use keep to make it persist for another request.
+ def index
+ flash.keep # Will persist all flash values. You can also use a key to keep only that value: flash.keep(:notice)
+ redirect_to users_url
+ end
+
+end
+------------------------------------------
diff --git a/railties/doc/guides/actioncontroller/streaming.txt b/railties/doc/guides/actioncontroller/streaming.txt
new file mode 100644
index 0000000000..6026a8c51b
--- /dev/null
+++ b/railties/doc/guides/actioncontroller/streaming.txt
@@ -0,0 +1,91 @@
+== Streaming and file downloads ==
+
+Sometimes you may want to send a file to the user instead of rendering an HTML page. All controllers in Rails have the "send_data":http://api.rubyonrails.org/classes/ActionController/Streaming.html#M000624 and the "send_file":http://api.rubyonrails.org/classes/ActionController/Streaming.html#M000623 methods, that will both stream data to the client. `send_file` is a convenience method which lets you provide the name of a file on the disk and it will stream the contents of that file for you.
+
+To stream data to the client, use `send_data`:
+
+[source, ruby]
+----------------------------
+require "prawn"
+class ClientsController < ApplicationController
+
+ # Generate a PDF document with information on the client and return it.
+ # The user will get the PDF as a file download.
+ def download_pdf
+ client = Client.find(params[:id])
+ send_data(generate_pdf, :filename => "#{client.name}.pdf", :type => "application/pdf")
+ end
+
+private
+
+ def generate_pdf(client)
+ Prawn::Document.new do
+ text client.name, :align => :center
+ text "Address: #{client.address}"
+ text "Email: #{client.email}"
+ end.render
+ end
+
+end
+----------------------------
+
+The `download_pdf` action in the example above will call a private method which actually generates the file (a PDF document) and returns it as a string. This string will then be streamed to the client as a file download and a filename will be suggested to the user. Sometimes when streaming files to the user, you may not want them to download the file. Take images, for example, which can be embedded into HTML pages. To tell the browser a file is not meant to be downloaded, you can set the `:disposition` option to "inline". The opposite and default value for this option is "attachment".
+
+=== Sending files ===
+
+If you want to send a file that already exists on disk, use the `send_file` method. This is usually not recommended, but can be useful if you want to perform some authentication before letting the user download the file.
+
+[source, ruby]
+----------------------------
+class ClientsController < ApplicationController
+
+ # Stream a file that has already been generated and stored on disk
+ def download_pdf
+ client = Client.find(params[:id])
+ send_data("#{RAILS_ROOT}/files/clients/#{client.id}.pdf", :filename => "#{client.name}.pdf", :type => "application/pdf")
+ end
+
+end
+----------------------------
+
+NOTE: Be careful when using (or just don't use) "outside" data (params, cookies, etc) to locate the file on disk, as this is a security risk as someone could gain access to files they are not meant to have access to.
+
+NOTE: It is not recommended that you stream static files through Rails if you can instead keep them in a public folder on your web server. It is much more efficient to let the user download the file directly using Apache or another web server, keeping the request from unnecessarily going through the whole Rails stack.
+
+This will read and stream the file 4Kb at the time, avoiding loading the entire file into memory at once. You can turn off streaming with the `stream` option or adjust the block size with the `buffer_size` option.
+
+=== RESTful downloads ===
+
+While `send_data` works just fine, if you are creating a RESTful application having separate actions for file downloads is a bit ugly. In REST terminology, the PDF file from the example above can be considered just another representation of the client resource. Rails provides an easy and quite sleek way of doing "RESTful downloads". Let's try to rewrite the example so that the PDF download is a part of the `show` action:
+
+[source, ruby]
+----------------------------
+class ClientsController < ApplicationController
+
+ # The user can request to receive this resource as HTML or PDF.
+ def show
+ @client = Client.find(params[:id])
+
+ respond_to do |format|
+ format.html
+ format.pdf{ render :pdf => generate_pdf(@client) }
+ end
+ end
+
+end
+----------------------------
+
+In order for this example to work, we have to add the PDF MIME type to Rails. This can be done by adding the following line to the file `config/initializers/mime_types.rb`:
+
+[source, ruby]
+----------------------------
+Mime::Type.register "application/pdf", :pdf
+----------------------------
+
+NOTE: Configuration files are not reloaded on each request, so you have to restart the server in order for their changes to take effect.
+
+Now the user can request to get a PDF version of a client just by adding ".pdf" to the URL:
+
+----------------------------
+GET /clients/1.pdf
+----------------------------
diff --git a/railties/doc/guides/actioncontroller/verification.txt b/railties/doc/guides/actioncontroller/verification.txt
new file mode 100644
index 0000000000..129ff7e7b0
--- /dev/null
+++ b/railties/doc/guides/actioncontroller/verification.txt
@@ -0,0 +1,3 @@
+== Verification ==
+
+Describe how to use the verify methods to make sure some prerequisites are met before an action gets run
diff --git a/railties/doc/guides/actionview/layouts_and_rendering.txt b/railties/doc/guides/actionview/layouts_and_rendering.txt
index c21ab72ee9..5a370500e5 100644
--- a/railties/doc/guides/actionview/layouts_and_rendering.txt
+++ b/railties/doc/guides/actionview/layouts_and_rendering.txt
@@ -1,5 +1,5 @@
Layouts and Rendering in Rails
-=====================================
+==============================
This guide covers the basic layout features of Action Controller and Action View. By referring to this guide, you will be able to:
@@ -80,50 +80,637 @@ WARNING: Using +render+ with +:action+ is a frequent source of confusion for Rai
==== Using +render+ with +:template+
+What if you want to render a template from an entirely different controller from the one that contains the action code? You can do that with the +:template+ option to +render+, which accepts the full path (relative to +app/views+) of the template to render. For example, if you're running code in an +AdminProductsController+ that lives in +app/controllers/admin+, you can render the results of an action to a template in +app/views/products+ this way:
+
+[source, ruby]
+-------------------------------------------------------
+render :template => 'products/show'
+-------------------------------------------------------
+
==== Using +render+ with +:file+
+If you want to use a view that's entirely outside of your application (perhaps you're sharing views between two Rails applications), you can use the +:file+ option to +render+:
+
+[source, ruby]
+-------------------------------------------------------
+render :file => "/u/apps/warehouse_app/current/app/views/products/show"
+-------------------------------------------------------
+
+The +:file+ option takes an absolute file-system path. Of course, you need to have rights to the view that you're using to render the content.
+
+NOTE: By default, if you use the +:file+ option, the file is rendered without using the current layout. If you want Rails to put the file into the current layout, you need to add the +:layout => true+ option
+
==== Using +render+ with +:inline+
+The +render+ method can do without a view completely, if you're willing to use the +:inline+ option to supply ERB as part of the method call. This is perfectly valid:
+
+[source, ruby]
+-------------------------------------------------------
+render :inline => "<% products.each do |p| %><p><%= p.name %><p><% end %>"
+-------------------------------------------------------
+
+WARNING: There is seldom any good reason to use this option. Mixing ERB into your controllers defeats the MVC orientation of Rails and will make it harder for other developers to follow the logic of your project. Use a separate erb view instead.
+
+By default, inline rendering uses ERb. You can force it to use Builder instead with the +:type+ option:
+
+[source, ruby]
+-------------------------------------------------------
+render :inline => "xml.p {'Horrid coding practice!'}", :type => :builder
+-------------------------------------------------------
+
==== Using +render+ with +:update+
+You can also render javascript-based page updates inline using the +:update+ option to +render+:
+
+[source, ruby]
+-------------------------------------------------------
+render :update do |page|
+ page.replace_html 'warning', "Invalid options supplied"
+end
+-------------------------------------------------------
+
+WARNING: Placing javascript updates in your controller may seem to streamline small updates, but it defeats the MVC orientation of Rails and will make it harder for other developers to follow the logic of your project. I recommend using a separate rjs template instead, no matter how small the update.
+
==== Rendering Text
+You can send plain text - with no markup at all - back to the browser by using the +:text+ option to +render+:
+
+[source, ruby]
+-------------------------------------------------------
+render :text => "OK"
+-------------------------------------------------------
+
+TIP: Rendering pure text is most useful when you're responding to AJAX or web service requests that are expecting something other than proper HTML.
+
+NOTE: By default, if you use the +:text+ option, the file is rendered without using the current layout. If you want Rails to put the text into the current layout, you need to add the +:layout => true+ option
+
==== Rendering JSON
+JSON is a javascript data format used by many AJAX libraries. Rails has built-in support for converting objects to JSON and rendering that JSON back to the browser:
+
+[source, ruby]
+-------------------------------------------------------
+render :json => @product
+-------------------------------------------------------
+
+TIP: You don't need to call +to_json+ on the object that you want to render. If you use the +:json+ option, +render+ will automatically call +to_json+ for you.
+
==== Rendering XML
+Rails also has built-in support for converting objects to XML and rendering that XML back to the caller:
+
+[source, ruby]
+-------------------------------------------------------
+render :xml => @product
+-------------------------------------------------------
+
+TIP: You don't need to call +to_xml+ on the object that you want to render. If you use the +:xml+ option, +render+ will automatically call +to_xml+ for you.
+
==== Options for +render+
+Calls to the +render+ method generally accept four options:
+
+* +:content_type+
+* +:layout+
+* +:status+
+* +:location+
+
===== The +:content_type+ Option
+By default, Rails will serve the results of a rendering operation with the MIME content-type of +text/html+ (or +application/json+ if you use the +:json+ option, or +application/xml+ for the +:xml+ option.). There are times when you might like to change this, and you can do so by setting the +:content_type+ option:
+
+[source, ruby]
+-------------------------------------------------------
+render :file => filename, :content_type => 'application/rss'
+-------------------------------------------------------
+
===== The +:layout+ Option
-include :layout => false
+With most of the options to +render+, the rendered content is displayed as part of the current layout. You'll learn more about layouts and how to use them later in this guide. To find the current layout, Rails first looks for a file in +app/views/layouts+ with the same base name as the controller. For example, rendering actions from the +PhotosController+ class will use +/app/views/layouts/photos.html.erb+. If there is no such controller-specific layout, Rails will use +/app/views/layouts/application.html.erb+.
+
+You can use the +:layout+ option to tell Rails to use a specific file as the layout for the current action:
+
+[source, ruby]
+-------------------------------------------------------
+render :layout => 'special_layout'
+-------------------------------------------------------
+
+You can also tell Rails to render with no layout at all:
+
+[source, ruby]
+-------------------------------------------------------
+render :layout => false
+-------------------------------------------------------
===== The +:status+ Option
+Rails will automatically generate a response with the correct HTML status code (in most cases, this is +200 OK+). You can use the +:status+ option to change this:
+
+[source, ruby]
+-------------------------------------------------------
+render :status => 500
+render :status => :forbidden
+-------------------------------------------------------
+
+Rails understands either numeric status codes or symbols for status codes. You can find its list of status codes in +actionpack/lib/action_controller/status_codes.rb+. You can also see there how it maps symbols to status codes in that file.
+
===== The +:location+ Option
+You can use the +:location+ option to set the HTTP +Location+ header:
+
+[source, ruby]
+-------------------------------------------------------
+render :xml => photo, :location => photo_url(photo)
+-------------------------------------------------------
+
+==== Avoiding Double Render Errors
+
+Sooner or later, most Rails developers will see the error message "Can only render or redirect once per action". While this is annoying, it's relatively easy to fix. Usually it happens because of a fundamental misunderstanding of the way that +render+ works.
+
+For example, here's some code that will trigger this error:
+
+[source, ruby]
+-------------------------------------------------------
+def show
+ @book = Book.find(params[:id])
+ if @book.special?
+ render :action => "special_show"
+ end
+end
+-------------------------------------------------------
+
+If +@book.special?+ evaluates to +true+, Rails will start the rendering process to dump the +@book+ variable into the +special_show+ view. But this will _not_ stop the rest of the code in the +show+ action from running, and when Rails hits the end of the action, it will start to render the +show+ view - and throw an error. The solution is simple: make sure that you only have one call to +render+ or +redirect+ in a single code path. One thing that can help is +and return+. Here's a patched version of the method:
+
+[source, ruby]
+-------------------------------------------------------
+def show
+ @book = Book.find(params[:id])
+ if @book.special?
+ render :action => "special_show" and return
+ end
+end
+-------------------------------------------------------
+
=== Using +redirect_to+
+Another way to handle returning responses to a HTTP request is with +redirect_to+. As you've seen, +render+ tells Rails which view (or other asset) to use in constructing a response. The +redirect_to+ method does something completely different: it tells the browser to send a new request for a different URL. For example, you could redirect from wherever you are in your code to the index of photos in your application with this call:
+
+[source, ruby]
+-------------------------------------------------------
+redirect_to photos_path
+-------------------------------------------------------
+
+You can use +redirect_to+ with any arguments that you could use with +link_to+ or +url_for+. In addition, there's a special redirect that sends the user back to the page they just came from:
+
+-------------------------------------------------------
+redirect_to :back
+-------------------------------------------------------
+
==== Getting a Different Redirect Status Code
+Rails uses HTTP status code 302 (permanent redirect) when you call +redirect_to+. If you'd like to use a different status code (perhaps 301, temporary redirect), you can do so by using the +:status+ option:
+
+-------------------------------------------------------
+redirect_to photos_path, :status => 301
+-------------------------------------------------------
+
+Just like the +:status+ option for +render+, +:status+ for +redirect_to+ accepts both numeric and symbolic header designations.
+
+==== The Difference Between +render+ and +redirect+
+
+Sometimes inexperienced developers conceive of +redirect_to+ as a sort of +goto+ command, moving execution from one place to another in your Rails code. This is _not_ correct. Your code stops running and waits for a new request for the browser. It just happens that you've told the browser what request it should make next, by sending back a HTTP 302 status code.
+
+Consider these actions to see the difference:
+
+[source, ruby]
+-------------------------------------------------------
+def index
+ @books = Book.find(:all)
+end
+
+def show
+ @book = Book.find(params[:id])
+ if @book.nil?
+ render :action => "index" and return
+ end
+end
+-------------------------------------------------------
+
+With the code in this form, there will be likely be a problem if the +@book+ variable is +nil+. Remember, a +render :action+ doesn't run any code in the target action, so nothing will set up the +@books+ variable that the +index+ view is presumably depending on. One way to fix this is to redirect instead of rendering:
+
+[source, ruby]
+-------------------------------------------------------
+def index
+ @books = Book.find(:all)
+end
+
+def show
+ @book = Book.find(params[:id])
+ if @book.nil?
+ redirect_to :action => "index" and return
+ end
+end
+-------------------------------------------------------
+
+With this code, the browser will make a fresh request for the index page, the code in the +index+ method will run, and all will be well.
+
=== Using +head+ To Build Header-Only Responses
+The +head+ method exists to let you send back responses to the browser that have only headers. It provides a more obvious alternative to calling +render :nothing+. The +head+ method takes one response, which is interpreted as a hash of header names and values. For example, you can return only an error header:
+
+[source, ruby]
+-------------------------------------------------------
+head :bad_request
+-------------------------------------------------------
+
+Or you can use other HTTP headers to convey additional information:
+
+[source, ruby]
+-------------------------------------------------------
+head :created, :location => photo_path(@photo)
+-------------------------------------------------------
+
== Structuring Layouts
-=== Include Statements
+When Rails renders a view as a response, it does so by combining the view with the current layout. To find the current layout, Rails first looks for a file in +app/views/layouts+ with the same base name as the controller. For example, rendering actions from the +PhotosController+ class will use +/app/views/layouts/photos.html.erb+. If there is no such controller-specific layout, Rails will use +/app/views/layouts/application.html.erb+. You can also specify a particular layout by using the +:layout+ option to +render+.
+
+Within a layout, you have access to three tools for combining different bits of output to form the overall response:
+
+* Asset tags
+* +yield+ and +content_for+
+* Partials
+
+I'll discuss each of these in turn.
+
+=== Asset Tags
+
+Asset tags provide methods for generating HTML that links views to assets like images, javascript, stylesheets, and feeds. There are four types of include tag:
+
+* auto_discovery_link_tag
+* javascript_include_tag
+* stylesheet_link_tag
+* image_tag
+
+You can use these tags in layouts or other views, although the tags other than +image_tag+ are most commonly used in the +<head>+ section of a layout.
+
+WARNING: The asset tags do _not_ verify the existence of the assets at the specified locations; they simply assume that you know what you're doing and generate the link.
+
+==== Linking to Feeds with +auto_discovery_link_tag+
+
+The +auto_discovery_link_tag helper builds HTML that most browsers and newsreaders can use to detect the presences of RSS or ATOM feeds. It takes the type of the link (+:rss+ or +:atom+), a hash of options that are passed through to url_for, and a hash of options for the tag:
+
+[source, ruby]
+-------------------------------------------------------
+<%= auto_discovery_link_tag(:rss, {:action => "feed"}, {:title => "RSS Feed"}) %>
+-------------------------------------------------------
+
+There are three tag options available for +auto_discovery_link_tag+:
+
+* +:rel+ specifies the +rel+ value in the link (defaults to "alternate")
+* +:type+ specifies an explicit MIME type. Rails will generate an appropriate MIME type automatically
+* +:title+ specifies the title of the link
+
+==== Linking to Javascript Files with +javascript_include_tag+
+
+The +javascript_include_tag+ helper returns an HTML +<script>+ tag for each source provided. Rails looks in +public/javascripts+ for these files by default, but you can specify a full path relative to the document root, or a URL, if you prefer. For example, to include +public/javascripts/main.js+:
+
+[source, ruby]
+-------------------------------------------------------
+<%= javascript_include_tag "main" %>
+-------------------------------------------------------
+
+To include +public/javascripts/main.js+ and +public/javascripts/columns.js+:
+
+[source, ruby]
+-------------------------------------------------------
+<%= javascript_include_tag "main", "columns" %>
+-------------------------------------------------------
+
+To include +public/javascripts/main.js+ and +public/photos/columns.js+:
+
+[source, ruby]
+-------------------------------------------------------
+<%= javascript_include_tag "main", "/photos/columns" %>
+-------------------------------------------------------
+
+To include +http://example.com/main.js+:
+
+[source, ruby]
+-------------------------------------------------------
+<%= javascript_include_tag "http://example.com/main.js" %>
+-------------------------------------------------------
+
+The +defaults+ option loads the Prototype and Scriptaculous libraries:
+
+[source, ruby]
+-------------------------------------------------------
+<%= javascript_include_tag :defaults %>
+-------------------------------------------------------
+
+The +all+ option loads every javascript file in +public/javascripts+, starting with the Prototype and Scriptaculous libraries:
+
+[source, ruby]
+-------------------------------------------------------
+<%= javascript_include_tag :all %>
+-------------------------------------------------------
+
+You can supply the +:recursive+ option to load files in subfolders of +public/javascripts+ as well:
+
+[source, ruby]
+-------------------------------------------------------
+<%= javascript_include_tag :all, :recursive %>
+-------------------------------------------------------
+
+If you're loading multiple javascript files, you can create a better user experience by combining multiple files into a single download. To make this happen in production, specify +:cache => true+ in your +javascript_include_tag+:
+
+[source, ruby]
+-------------------------------------------------------
+<%= javascript_include_tag "main", "columns", :cache => true %>
+-------------------------------------------------------
+
+==== Linking to CSS Files with +stylesheet_link_tag+
+
+The +stylesheet_link_tag+ helper returns an HTML +<link>+ tag for each source provided. Rails looks in +public/stylesheets+ for these files by default, but you can specify a full path relative to the document root, or a URL, if you prefer. For example, to include +public/stylesheets/main.cs+:
+
+[source, ruby]
+-------------------------------------------------------
+<%= stylesheet_link_tag "main" %>
+-------------------------------------------------------
+
+To include +public/stylesheets/main.css+ and +public/stylesheets/columns.css+:
+
+[source, ruby]
+-------------------------------------------------------
+<%= stylesheet_link_tag "main", "columns" %>
+-------------------------------------------------------
+
+To include +public/stylesheets/main.css+ and +public/photos/columns.css+:
+
+[source, ruby]
+-------------------------------------------------------
+<%= stylesheet_link_tag "main", "/photos/columns" %>
+-------------------------------------------------------
+
+To include +http://example.com/main.cs+:
+
+[source, ruby]
+-------------------------------------------------------
+<%= stylesheet_link_tag "http://example.com/main.cs" %>
+-------------------------------------------------------
+
+By default, +stylesheet_link_tag+ creates links with +media="screen" rel="stylesheet" type="text/css"+. You can override any of these defaults by specifying an appropriate option (:media, :rel, or :type):
+
+[source, ruby]
+-------------------------------------------------------
+<%= stylesheet_link_tag "main_print", media => "print" %>
+-------------------------------------------------------
+
+The +all+ option links every CSS file in +public/stylesheets+:
+
+[source, ruby]
+-------------------------------------------------------
+<%= stylesheet_link_tag :all %>
+-------------------------------------------------------
+
+You can supply the +:recursive+ option to link files in subfolders of +public/stylesheets+ as well:
+
+[source, ruby]
+-------------------------------------------------------
+<%= stylesheet_link_tag :all, :recursive %>
+-------------------------------------------------------
+
+If you're loading multiple CSS files, you can create a better user experience by combining multiple files into a single download. To make this happen in production, specify +:cache => true+ in your +stylesheet_link_tag+:
+
+[source, ruby]
+-------------------------------------------------------
+<%= stylesheet_link_tag "main", "columns", :cache => true %>
+-------------------------------------------------------
+
+==== Linking to Images with +image_tag+
+
+The +image_tag+ helper builds an HTML +<image>+ tag to the specified file. By default, files are loaded from +public/images+. If you don't specify an extension, .png is assumed by default:
+
+[source, ruby]
+-------------------------------------------------------
+<%= image_tag "header" %>
+-------------------------------------------------------
+
+You can supply a path to the image if you like:
+
+[source, ruby]
+-------------------------------------------------------
+<%= image_tag "icons/delete.gif" %>
+-------------------------------------------------------
+
+You can supply a hash of additional HTML options:
+
+[source, ruby]
+-------------------------------------------------------
+<%= image_tag "icons/delete.gif", :height => 45 %>
+-------------------------------------------------------
+
+There are also three special options you can use with +image_tag+:
+
+* +:alt+ specifies the alt text for the image (which defaults to the file name of the file, capitalized and with no extension)
+* +:size+ specifies both width and height, in the format "{width}x{height}" (for example, "150x125")
+* +:mouseover+ sets an alternate image to be used when the onmouseover event is fired.
=== Understanding +yield+
+Within the context of a layout, +yield+ identifies a section where content from the view should be inserted. The simplest way to use this is to have a single +yield+, into which the entire contents of the view currently being rendered is inserted:
+
+[source, html]
+-------------------------------------------------------
+<html>
+ <head>
+ </head>
+ <body>
+ <%= yield %>
+ <hbody>
+</html>
+-------------------------------------------------------
+
+You can also create a layout with multiple yielding regions:
+
+[source, html]
+-------------------------------------------------------
+<html>
+ <head>
+ <%= yield :head %>
+ </head>
+ <body>
+ <%= yield %>
+ <hbody>
+</html>
+-------------------------------------------------------
+
+The main body of the view will always render into the unnamed +yield+. To render content into a named +yield+, you use the +content_for+ method.
+
=== Using +content_for+
+The +content_for+ method allows you to insert content into a +yield+ block in your layout. You only use +content_for+ to insert content in named yields. For example, this view would work with the layout that you just saw:
+
+[source, html]
+-------------------------------------------------------
+<% content_for :head do %>
+ <title>A simple page</title>
+<% end %>
+
+<p>Hello, Rails!</p>
+-------------------------------------------------------
+
+The result of rendering this page into the supplied layout would be this HTML:
+
+[source, html]
+-------------------------------------------------------
+<html>
+ <head>
+ <title>A simple page</title>
+ </head>
+ <body>
+ <p>Hello, Rails!</p>
+ <hbody>
+</html>
+-------------------------------------------------------
+
+The +content_for+ method is very helpful when your layout contains distinct regions such as sidebars and footers that should get their own blocks of content inserted. It's also useful for inserting tags that load page-specific javascript or css files into the header of an otherwise-generic layout.
+
=== Using Partials
-< toc tbd >
+Partial templates - usually just called "partials" - are another device for breaking apart the rendering process into more manageable chunks. With a partial, you can move the code for rendering a particular piece of a response to its own file.
+
+==== Naming Partials
+
+To render a partial as part of a view, you use the +render+ method within the view, and include the +:partial+ option:
+
+[source, ruby]
+-------------------------------------------------------
+<%= render :partial => "menu" %>
+-------------------------------------------------------
+
+This will render a file named +_menu.html.erb+ at that point within the view being rendered. Note the leading underscore character: partials are named with a leading underscore to distinguish them from regular views, even though they are referred to without the underscore. This holds true even when you're pulling in a partial from another folder:
+
+[source, ruby]
+-------------------------------------------------------
+<%= render :partial => "shared/menu" %>
+-------------------------------------------------------
+
+That code will pull in the partial from +app/views/shared/_menu.html.erb+.
+
+==== Using Partials to Simplify Views
+
+One way to use partials is to treat them as the equivalent of subroutines: as a way to move details out of a view so that you can grasp what's going on more easily. For example, you might have a view that looked like this:
+
+[source, html]
+-------------------------------------------------------
+<%= render :partial => "shared/ad_banner" %>
+
+<h1>Products</h1>
+
+<p>Here are a few of our fine products:</p>
+...
+
+<%= render :partial => "shared/footer" %>
+-------------------------------------------------------
+
+Here, the +_ad_banner.html.erb+ and +_footer.html.erb+ partials could contain content that is shared among many pages in your application. You don't need to see the details of these sections when you're concentrating on a particular page.
+
+TIP: For content that is shared among all pages in your application, you can use partials directly from layouts.
+
+==== Passing Local Variables
+
+You can also pass local variables into partials, making them even more powerful and flexible. For example, you can use this technique to reduce duplication between new and edit pages, while still keeping a bit of distinct content:
+
+[source, html]
+-------------------------------------------------------
+new.rhtml.erb:
+
+<h1>New zone</h1>
+<%= error_messages_for :zone %>
+<%= render :partial => "form", :locals => { :button_label => "Create zone", :zone => @zone } %>
+
+edit.html.erb:
+
+<h1>Editing zone</h1>
+<%= error_messages_for :zone %>
+<%= render :partial => "form", :locals => { :button_label => "Update zone", :zone => @zone } %>
+
+_form.html.erb:
+
+<% form_for(@zone) do |f| %>
+ <p>
+ <b>Zone name</b><br />
+ <%= f.text_field :name %>
+ </p>
+ <p>
+ <%= f.submit button_label %>
+ </p>
+<% end %>
+-------------------------------------------------------
+
+Although the same partial will be rendered into both views, the label on the submit button is controlled by a local variable passed into the partial.
+
+==== Rendering Collections
+
+Partials are very useful in rendering collections. When you pass a collection to a partial via the +:collection+ option, the partial will be inserted once for each member in the collection:
+
+[source, html]
+-------------------------------------------------------
+index.rhtml.erb:
+
+<h1>Products</h1>
+<%= render :partial => "product", :collection => @products %>
+
+_product.html.erb:
+
+<p>Product Name: <%= product.name %></p>
+-------------------------------------------------------
+
+When a partial is called with a pluralized collection, then the individual instances of the partial have access to the member of the collection being rendered via a singularized variable. In this case, the collection is +@products+, and within the +_product+ partial, you can refer to +product+ to get the instance that is being rendered.
== Changelog ==
http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/15[Lighthouse ticket]
-* September 20, 2008: First draft by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication)
+* September 28, 2008: First draft by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication)
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/railties/doc/guides/activerecord/association_basics.txt b/railties/doc/guides/activerecord/association_basics.txt
index d33c0ac3cf..b91052f91f 100644
--- a/railties/doc/guides/activerecord/association_basics.txt
+++ b/railties/doc/guides/activerecord/association_basics.txt
@@ -345,6 +345,8 @@ class CreatePictures < ActiveRecord::Migration
end
-------------------------------------------------------
+image:images/polymorphic.png[Polymorphic Association Diagram]
+
=== Self Joins
In designing a data model, you will sometimes find a model that should have a relation to itself. For example, you may want to store all employees in a single database model, but be able to trace relationships such as manager and subordinates. This situation can be modeled with self-joining associations:
@@ -614,6 +616,24 @@ class Order < ActiveRecord::Base
end
-------------------------------------------------------
+The +belongs_to+ association supports these options:
+
+// * +:accessible+
+* +:class_name+
+* +:conditions+
+* +:counter_cache+
+* +:dependent+
+* +:foreign_key+
+* +:include+
+* +:polymorphic+
+* +:readonly+
+* +:select+
+* +:validate+
+
+// ===== +:accessible+
+//
+// The +:accessible+ option is the association version of +ActiveRecord::Base#attr_accessible+. If you set the +:accessible+ option to true, then mass // assignment is allowed for this association.
+//
===== +:class_name+
If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if an order belongs to a customer, but the actual name of the model containing customers is patron, you'd set things up this way:
@@ -636,29 +656,6 @@ class Order < ActiveRecord::Base
end
-------------------------------------------------------
-===== +:select+
-
-The +:select+ option lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.
-
-===== +:foreign_key+
-
-By convention, Rails guesses that the column used to hold the foreign key on this model is the name of the association with the suffix +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly:
-
-[source, ruby]
--------------------------------------------------------
-class Order < ActiveRecord::Base
- belongs_to :customer, :class_name => :patron, :foreign_key => "patron_id"
-end
--------------------------------------------------------
-
-TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
-
-===== +:dependent+
-
-If you set the +:dependent+ option to +:destroy+, then deleting this object will call the destroy method on the associated object to delete that object. If you set the +:dependent+ option to +:delete+, then deleting this object will delete the associated object _without_ calling its +destroy+ method.
-
-WARNING: You should not specify this option on a +belongs_to+ association that is connected with a +has_many+ association on the other class. Doing so can lead to orphaned records in your database.
-
===== +:counter_cache+
The +:counter_cache+ option can be used to make finding the number of belonging objects more efficient. Consider these models:
@@ -703,6 +700,25 @@ Counter cache columns are added to the containing model's list of read-only attr
WARNING: When you create a counter cache column in the database, be sure to specify a default value of zero. Otherwise, Rails will not properly maintain the counter.
+===== +:dependent+
+
+If you set the +:dependent+ option to +:destroy+, then deleting this object will call the destroy method on the associated object to delete that object. If you set the +:dependent+ option to +:delete+, then deleting this object will delete the associated object _without_ calling its +destroy+ method.
+
+WARNING: You should not specify this option on a +belongs_to+ association that is connected with a +has_many+ association on the other class. Doing so can lead to orphaned records in your database.
+
+===== +:foreign_key+
+
+By convention, Rails guesses that the column used to hold the foreign key on this model is the name of the association with the suffix +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly:
+
+[source, ruby]
+-------------------------------------------------------
+class Order < ActiveRecord::Base
+ belongs_to :customer, :class_name => :patron, :foreign_key => "patron_id"
+end
+-------------------------------------------------------
+
+TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
+
===== +:include+
You can use the :include option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:
@@ -747,15 +763,16 @@ Passing +true+ to the +:polymorphic+ option indicates that this is a polymorphic
If you set the +:readonly+ option to +true+, then the associated object will be read-only when retrieved via the association.
-===== +:validate+
+===== +:select+
-If you set the +:validate+ option to +true+, then associated objects will be validated whenever you save this object. By default, this is +false+: associated objects will not be validated when this object is saved.
+The +:select+ option lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.
-===== +:accessible+
+===== +:validate+
-The +:accessible+ option is the association version of +ActiveRecord::Base#attr_accessible+. If you set the +:accessible+ option to true, then mass assignment is allowed for this association.
+If you set the +:validate+ option to +true+, then associated objects will be validated whenever you save this object. By default, this is +false+: associated objects will not be validated when this object is saved.
==== When are Objects Saved?
+
Assigning an object to a +belongs_to+ association does _not_ automatically save the object. It does not save the associated object either.
=== The has_one Association
@@ -843,7 +860,6 @@ The +create__\_association__+ method returns a new object of the associated type
==== Options for +has_one+
-
In many situations, you can use the default behavior of +has_one+ without any customization. But despite Rails' emphasis of convention over customization, you can alter that behavior in a number of ways. This section covers the options that you can pass when you create a +has_one+ association. For example, an association with several options might look like this:
[source, ruby]
@@ -853,6 +869,32 @@ class Supplier < ActiveRecord::Base
end
-------------------------------------------------------
+The +has_one+ association supports these options:
+
+// * +:accessible+
+* +:as+
+* +:class_name+
+* +:conditions+
+* +:dependent+
+* +:foreign_key+
+* +:include+
+* +:order+
+* +:primary_key+
+* +:readonly+
+* +:select+
+* +:source+
+* +:source_type+
+* +:through+
+* +:validate+
+
+// ===== +:accessible+
+//
+// The +:accessible+ option is the association version of +ActiveRecord::Base#attr_accessible+. If you set the +:accessible+ option to true, then mass // assignment is allowed for this association.
+//
+===== +:as+
+
+Setting the +:as+ option indicates that this is a polymorphic association. Polymorphic associations are discussed in detail later in this guide.
+
===== +:class_name+
If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if a supplier has an account, but the actual name of the model containing accounts is billing, you'd set things up this way:
@@ -875,10 +917,6 @@ class Supplier < ActiveRecord::Base
end
-------------------------------------------------------
-===== +:order+
-
-The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +ORDER BY+ clause). Because a +has_one+ association will only retrieve a single associated object, this option should not be needed.
-
===== +:dependent+
If you set the +:dependent+ option to +:destroy+, then deleting this object will call the destroy method on the associated object to delete that object. If you set the +:dependent+ option to +:delete+, then deleting this object will delete the associated object _without_ calling its +destroy+ method. If you set the +:dependent+ option to +:nullify+, then deleting this object will set the foreign key in the association object to +NULL+.
@@ -896,10 +934,6 @@ end
TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
-===== +:primary_key+
-
-By convention, Rails guesses that the column used to hold the primary key of this model is +id+. You can override this and explicitly specify the primary key with the +:primary_key+ option.
-
===== +:include+
You can use the :include option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:
@@ -934,17 +968,21 @@ class Representative < ActiveRecord::Base
end
-------------------------------------------------------
-===== +:as+
+===== +:order+
-Setting the +:as+ option indicates that this is a polymorphic association. Polymorphic associations are discussed in detail later in this guide.
+The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +ORDER BY+ clause). Because a +has_one+ association will only retrieve a single associated object, this option should not be needed.
-===== +:select+
+===== +:primary_key+
-The +:select+ option lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.
+By convention, Rails guesses that the column used to hold the primary key of this model is +id+. You can override this and explicitly specify the primary key with the +:primary_key+ option.
-===== +:through+
+===== +:readonly+
-The +:through+ option specifies a join model through which to perform the query. +has_one :through+ associations are discussed in detail later in this guide.
+If you set the +:readonly+ option to +true+, then the associated object will be read-only when retrieved via the association.
+
+===== +:select+
+
+The +:select+ option lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.
===== +:source+
@@ -954,18 +992,14 @@ The +:source+ option specifies the source association name for a +has_one :throu
The +:source_type+ option specifies the source association type for a +has_one :through+ association that proceeds through a polymorphic association.
-===== +:readonly+
+===== +:through+
-If you set the +:readonly+ option to +true+, then the associated object will be read-only when retrieved via the association.
+The +:through+ option specifies a join model through which to perform the query. +has_one :through+ associations are discussed in detail later in this guide.
===== +:validate+
If you set the +:validate+ option to +true+, then associated objects will be validated whenever you save this object. By default, this is +false+: associated objects will not be validated when this object is saved.
-===== +:accessible+
-
-The +:accessible+ option is the association version of +ActiveRecord::Base#attr_accessible+. If you set the +:accessible+ option to true, then mass assignment is allowed for this association.
-
==== When are Objects Saved?
When you assign an object to a +has_one+ association, that object is automatically saved (in order to update its foreign key). In addition, any object being replaced is also automatically saved, because its foreign key will change too.
@@ -1138,6 +1172,39 @@ class Customer < ActiveRecord::Base
end
-------------------------------------------------------
+The +has_many+ association supports these options:
+
+// * +:accessible+
+* +:as+
+* +:class_name+
+* +:conditions+
+* +:counter_sql+
+* +:dependent+
+* +:extend+
+* +:finder_sql+
+* +:foreign_key+
+* +:group+
+* +:include+
+* +:limit+
+* +:offset+
+* +:order+
+* +:primary_key+
+* +:readonly+
+* +:select+
+* +:source+
+* +:source_type+
+* +:through+
+* +:uniq+
+* +:validate+
+
+// ===== +:accessible+
+//
+// The +:accessible+ option is the association version of +ActiveRecord::Base#attr_accessible+. If you set the +:accessible+ option to true, then mass // assignment is allowed for this association.
+//
+===== +:as+
+
+Setting the +:as+ option indicates that this is a polymorphic association, as discussed earlier in this guide.
+
===== +:class_name+
If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if a customer has many orders, but the actual name of the model containing orders is transactions, you'd set things up this way:
@@ -1171,16 +1238,25 @@ end
If you use a hash-style +:conditions+ option, then record creation via this association will be automatically scoped using the hash. In this case, using +@customer.confirmed_orders.create+ or +@customer.confirmed_orders.build+ will create orders where the confirmed column has the value +true+.
-===== +:order+
+===== +:counter_sql+
-The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +ORDER BY+ clause).
+Normally Rails automatically generates the proper SQL to count the association members. With the +:counter_sql+ option, you can specify a complete SQL statement to count them yourself.
-[source, ruby]
--------------------------------------------------------
-class Customer < ActiveRecord::Base
- has_many :orders, :order => "date_confirmed DESC"
-end
--------------------------------------------------------
+NOTE: If you specify +:finder_sql+ but not +:counter_sql+, then the counter SQL will be generated by substituting +SELECT COUNT(*) FROM+ for the +SELECT ... FROM+ clause of your +:finder_sql+ statement.
+
+===== +:dependent+
+
+If you set the +:dependent+ option to +:destroy+, then deleting this object will call the destroy method on the associated objects to delete those objects. If you set the +:dependent+ option to +:delete_all+, then deleting this object will delete the associated objects _without_ calling their +destroy+ method. If you set the +:dependent+ option to +:nullify+, then deleting this object will set the foreign key in the associated objects to +NULL+.
+
+NOTE: This option is ignored when you use the +:through+ option on the association.
+
+===== +:extend+
+
+The +:extend+ option specifies a named module to extend the association proxy. Association extensions are discussed in detail later in this guide.
+
+===== +:finder_sql+
+
+Normally Rails automatically generates the proper SQL to fetch the association members. With the +:finder_sql+ option, you can specify a complete SQL statement to fetch them yourself. If fetching objects requires complex multi-table SQL, this may be necessary.
===== +:foreign_key+
@@ -1195,29 +1271,16 @@ end
TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
-===== +:primary_key+
-
-By convention, Rails guesses that the column used to hold the primary key of this model is +id+. You can override this and explicitly specify the primary key with the +:primary_key+ option.
-
-===== +:dependent+
-
-If you set the +:dependent+ option to +:destroy+, then deleting this object will call the destroy method on the associated objects to delete those objects. If you set the +:dependent+ option to +:delete_all+, then deleting this object will delete the associated objects _without_ calling their +destroy+ method. If you set the +:dependent+ option to +:nullify+, then deleting this object will set the foreign key in the associated objects to +NULL+.
-
-NOTE: This option is ignored when you use the +:through+ option on the association.
-
-===== +:finder_sql+
-
-Normally Rails automatically generates the proper SQL to fetch the association members. With the +:finder_sql+ option, you can specify a complete SQL statement to fetch them yourself. If fetching objects requires complex multi-table SQL, this may be necessary.
-
-===== +:counter_sql+
-
-Normally Rails automatically generates the proper SQL to count the association members. With the +:counter_sql+ option, you can specify a complete SQL statement to count them yourself.
-
-NOTE: If you specify +:finder_sql+ but not +:counter_sql+, then the counter SQL will be generated by substituting +SELECT COUNT(*) FROM+ for the +SELECT ... FROM+ clause of your +:finder_sql+ statement.
+===== +:group+
-===== +:extend+
+The +:group+ option supplies an attribute name to group the result set by, using a +GROUP BY+ clause in the finder SQL.
-The +:extend+ option specifies a named module to extend the association proxy. Association extensions are discussed in detail later in this guide.
+[source, ruby]
+-------------------------------------------------------
+class Customer < ActiveRecord::Base
+ has_many :line_items, :through => :orders, :group => "orders.id"
+end
+-------------------------------------------------------
===== +:include+
@@ -1253,31 +1316,39 @@ class LineItem < ActiveRecord::Base
end
-------------------------------------------------------
-===== +:group+
+===== +:limit+
-The +:group+ option supplies an attribute name to group the result set by, using a +GROUP BY+ clause in the finder SQL.
+The +:limit+ option lets you restrict the total number of objects that will be fetched through an association.
[source, ruby]
-------------------------------------------------------
class Customer < ActiveRecord::Base
- has_many :line_items, :through => :orders, :group => "orders.id"
+ has_many :recent_orders, :class_name => :orders, :order => "order_date DESC", :limit => 100
end
-------------------------------------------------------
-===== +:limit+
+===== +:offset+
-The +:limit+ option lets you restrict the total number of objects that will be fetched through an association.
+The +:offset+ option lets you specify the starting offset for fetching objects via an association. For example, if you set +:offset => 11+, it will skip the first 10 records.
+
+===== +:order+
+
+The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +ORDER BY+ clause).
[source, ruby]
-------------------------------------------------------
class Customer < ActiveRecord::Base
- has_many :recent_orders, :class_name => :orders, :order => "order_date DESC", :limit => 100
+ has_many :orders, :order => "date_confirmed DESC"
end
-------------------------------------------------------
-===== +:offset+
+===== +:primary_key+
-The +:offset+ option lets you specify the starting offset for fetching objects via an association. For example, if you set +:offset => 11+, it will skip the first 10 records.
+By convention, Rails guesses that the column used to hold the primary key of this model is +id+. You can override this and explicitly specify the primary key with the +:primary_key+ option.
+
+===== +:readonly+
+
+If you set the +:readonly+ option to +true+, then the associated objects will be read-only when retrieved via the association.
===== +:select+
@@ -1285,14 +1356,6 @@ The +:select+ option lets you override the SQL +SELECT+ clause that is used to r
WARNING: If you specify your own +:select+, be sure to include the primary key and foreign key columns of the associated model. If you do not, Rails will throw an error.
-===== +:as+
-
-Setting the +:as+ option indicates that this is a polymorphic association, as discussed earlier in this guide.
-
-===== +:through+
-
-The +:through+ option specifies a join model through which to perform the query. +has_many :through+ associations provide a way to implement many-to-many relationships, as discussed earlier in this guide.
-
===== +:source+
The +:source+ option specifies the source association name for a +has_many :through+ association. You only need to use this option if the name of the source association cannot be automatically inferred from the association name.
@@ -1301,22 +1364,18 @@ The +:source+ option specifies the source association name for a +has_many :thro
The +:source_type+ option specifies the source association type for a +has_many :through+ association that proceeds through a polymorphic association.
-===== +:uniq+
+===== +:through+
-Specify the +:uniq => true+ option to remove duplicates from the collection. This is most useful in conjunction with the +:through+ option.
+The +:through+ option specifies a join model through which to perform the query. +has_many :through+ associations provide a way to implement many-to-many relationships, as discussed earlier in this guide.
-===== +:readonly+
+===== +:uniq+
-If you set the +:readonly+ option to +true+, then the associated objects will be read-only when retrieved via the association.
+Specify the +:uniq => true+ option to remove duplicates from the collection. This is most useful in conjunction with the +:through+ option.
===== +:validate+
If you set the +:validate+ option to +false+, then associated objects will not be validated whenever you save this object. By default, this is +true+: associated objects will be validated when this object is saved.
-===== +:accessible+
-
-The +:accessible+ option is the association version of +ActiveRecord::Base#attr_accessible+. If you set the +:accessible+ option to true, then mass assignment is allowed for this association.
-
==== When are Objects Saved?
When you assign an object to a +has_many+ association, that object is automatically saved (in order to update its foreign key). If you assign multiple objects in one statement, then they are all saved.
@@ -1498,25 +1557,33 @@ class Parts < ActiveRecord::Base
end
-------------------------------------------------------
-===== +:class_name+
-
-If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if a part has many assemblies, but the actual name of the model containing assemblies is gadgets, you'd set things up this way:
-
-[source, ruby]
--------------------------------------------------------
-class Parts < ActiveRecord::Base
- has_and_belongs_to_many :assemblies, :class_name => :gadgets
-end
--------------------------------------------------------
-
-===== +:join_table+
-
-If the default name of the join table, based on lexical ordering, is not what you want, you can use the +:join_table+ option to override the default.
-
-===== +:foreign_key+
-
-By convention, Rails guesses that the column in the join table used to hold the foreign key pointing to this model is the name of this model with the suffix +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly:
-
+The +has_and_belongs_to_many+ association supports these options:
+
+// * +:accessible+
+* +:association_foreign_key+
+* +:class_name+
+* +:conditions+
+* +:counter_sql+
+* +:delete_sql+
+* +:extend+
+* +:finder_sql+
+* +:foreign_key+
+* +:group+
+* +:include+
+* +:insert_sql+
+* +:join_table+
+* +:limit+
+* +:offset+
+* +:order+
+* +:readonly+
+* +:select+
+* +:uniq+
+* +:validate+
+
+// ===== +:accessible+
+//
+// The +:accessible+ option is the association version of +ActiveRecord::Base#attr_accessible+. If you set the +:accessible+ option to true, then mass // assignment is allowed for this association.
+//
===== +:association_foreign_key+
By convention, Rails guesses that the column in the join table used to hold the foreign key pointing to the other model is the name of that model with the suffix +_id+ added. The +:association_foreign_key+ option lets you set the name of the foreign key directly:
@@ -1531,47 +1598,38 @@ class User < ActiveRecord::Base
end
-------------------------------------------------------
-===== +:conditions+
+===== +:class_name+
-The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL +WHERE+ clause).
+If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if a part has many assemblies, but the actual name of the model containing assemblies is gadgets, you'd set things up this way:
[source, ruby]
-------------------------------------------------------
class Parts < ActiveRecord::Base
- has_and_belongs_to_many :assemblies, :conditions => "factory = 'Seattle'"
+ has_and_belongs_to_many :assemblies, :class_name => :gadgets
end
-------------------------------------------------------
-You can also set conditions via a hash:
+===== +:conditions+
+
+The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL +WHERE+ clause).
[source, ruby]
-------------------------------------------------------
class Parts < ActiveRecord::Base
- has_and_belongs_to_many :assemblies, :conditions => { :factory => 'Seattle' }
+ has_and_belongs_to_many :assemblies, :conditions => "factory = 'Seattle'"
end
-------------------------------------------------------
-If you use a hash-style +:conditions+ option, then record creation via this association will be automatically scoped using the hash. In this case, using +@parts.assemblies.create+ or +@parts.assemblies.build+ will create orders where the factory column has the value "Seattle".
-
-===== +:order+
-
-The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +ORDER BY+ clause).
-
+You can also set conditions via a hash:
[source, ruby]
-------------------------------------------------------
class Parts < ActiveRecord::Base
- has_and_belongs_to_many :assemblies, :order => "assembly_name ASC"
+ has_and_belongs_to_many :assemblies, :conditions => { :factory => 'Seattle' }
end
-------------------------------------------------------
-===== +:uniq+
-
-Specify the +:uniq => true+ option to remove duplicates from the collection.
-
-===== +:finder_sql+
-
-Normally Rails automatically generates the proper SQL to fetch the association members. With the +:finder_sql+ option, you can specify a complete SQL statement to fetch them yourself. If fetching objects requires complex multi-table SQL, this may be necessary.
+If you use a hash-style +:conditions+ option, then record creation via this association will be automatically scoped using the hash. In this case, using +@parts.assemblies.create+ or +@parts.assemblies.build+ will create orders where the factory column has the value "Seattle".
===== +:counter_sql+
@@ -1583,17 +1641,25 @@ NOTE: If you specify +:finder_sql+ but not +:counter_sql+, then the counter SQL
Normally Rails automatically generates the proper SQL to remove links between the associated classes. With the +:delete_sql+ option, you can specify a complete SQL statement to delete them yourself.
-===== +:insert_sql+
-
-Normally Rails automatically generates the proper SQL to create links between the associated classes. With the +:insert_sql+ option, you can specify a complete SQL statement to insert them yourself.
-
===== +:extend+
The +:extend+ option specifies a named module to extend the association proxy. Association extensions are discussed in detail later in this guide.
-===== +:include+
+===== +:finder_sql+
-You can use the :include option to specify second-order associations that should be eager-loaded when this association is used.
+Normally Rails automatically generates the proper SQL to fetch the association members. With the +:finder_sql+ option, you can specify a complete SQL statement to fetch them yourself. If fetching objects requires complex multi-table SQL, this may be necessary.
+
+===== +:foreign_key+
+
+By convention, Rails guesses that the column in the join table used to hold the foreign key pointing to this model is the name of this model with the suffix +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly:
+
+[source, ruby]
+-------------------------------------------------------
+class User < ActiveRecord::Base
+ has_and_belongs_to_many :friends, :class_name => :users,
+ :foreign_key => "this_user_id", :association_foreign_key => "other_user_id"
+end
+-------------------------------------------------------
===== +:group+
@@ -1606,6 +1672,18 @@ class Parts < ActiveRecord::Base
end
-------------------------------------------------------
+===== +:include+
+
+You can use the :include option to specify second-order associations that should be eager-loaded when this association is used.
+
+===== +:insert_sql+
+
+Normally Rails automatically generates the proper SQL to create links between the associated classes. With the +:insert_sql+ option, you can specify a complete SQL statement to insert them yourself.
+
+===== +:join_table+
+
+If the default name of the join table, based on lexical ordering, is not what you want, you can use the +:join_table+ option to override the default.
+
===== +:limit+
The +:limit+ option lets you restrict the total number of objects that will be fetched through an association.
@@ -1621,22 +1699,32 @@ end
The +:offset+ option lets you specify the starting offset for fetching objects via an association. For example, if you set +:offset => 11+, it will skip the first 10 records.
-===== +:select+
+===== +:order+
-The +:select+ option lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated objects. By default, Rails retrieves all columns.
+The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +ORDER BY+ clause).
+
+[source, ruby]
+-------------------------------------------------------
+class Parts < ActiveRecord::Base
+ has_and_belongs_to_many :assemblies, :order => "assembly_name ASC"
+end
+-------------------------------------------------------
===== +:readonly+
If you set the +:readonly+ option to +true+, then the associated objects will be read-only when retrieved via the association.
-===== +:validate+
+===== +:select+
-If you set the +:validate+ option to +false+, then associated objects will not be validated whenever you save this object. By default, this is +true+: associated objects will be validated when this object is saved.
+The +:select+ option lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated objects. By default, Rails retrieves all columns.
-===== +:accessible+
+===== +:uniq+
-The +:accessible+ option is the association version of +ActiveRecord::Base#attr_accessible+. If you set the +:accessible+ option to true, then mass assignment is allowed for this association.
+Specify the +:uniq => true+ option to remove duplicates from the collection.
+===== +:validate+
+
+If you set the +:validate+ option to +false+, then associated objects will not be validated whenever you save this object. By default, this is +true+: associated objects will be validated when this object is saved.
==== When are Objects Saved?
@@ -1746,5 +1834,6 @@ Extensions can refer to the internals of the association proxy using these three
http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/11[Lighthouse ticket]
-* September 14, 2008: initial version by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication)
+* September 28, 2008: Corrected +has_many :through+ diagram, added polymorphic diagram, some reorganization by link:../authors.html#mgunderloy[Mike Gunderloy] . First release version.
* September 22, 2008: Added diagrams, misc. cleanup by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication)
+* September 14, 2008: initial version by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication)
diff --git a/railties/doc/guides/activerecord/images/has_many_through.png b/railties/doc/guides/activerecord/images/has_many_through.png
index 9872201416..85d7599925 100644
--- a/railties/doc/guides/activerecord/images/has_many_through.png
+++ b/railties/doc/guides/activerecord/images/has_many_through.png
Binary files differ
diff --git a/railties/doc/guides/activerecord/images/polymorphic.png b/railties/doc/guides/activerecord/images/polymorphic.png
new file mode 100644
index 0000000000..ff2fd9f76d
--- /dev/null
+++ b/railties/doc/guides/activerecord/images/polymorphic.png
Binary files differ
diff --git a/railties/doc/guides/benchmarking_and_profiling/examples/.DS_Store b/railties/doc/guides/benchmarking_and_profiling/examples/.DS_Store
deleted file mode 100644
index 5008ddfcf5..0000000000
--- a/railties/doc/guides/benchmarking_and_profiling/examples/.DS_Store
+++ /dev/null
Binary files differ
diff --git a/railties/doc/guides/benchmarking_and_profiling/rubyprof.txt b/railties/doc/guides/benchmarking_and_profiling/rubyprof.txt
index 2dd5f2a99a..fa01d413a1 100644
--- a/railties/doc/guides/benchmarking_and_profiling/rubyprof.txt
+++ b/railties/doc/guides/benchmarking_and_profiling/rubyprof.txt
@@ -8,7 +8,7 @@ One of the things that is important to us is how long it takes to render the hom
In the terminal run
-[source, bash]
+[source, ruby]
----------------------------------------------------------------------------
[User profiling_tester]$ gcruby tests/performance/homepage.rb
----------------------------------------------------------------------------
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/index.txt b/railties/doc/guides/index.txt
index 78228ea4a0..ad82aea3ec 100644
--- a/railties/doc/guides/index.txt
+++ b/railties/doc/guides/index.txt
@@ -3,66 +3,91 @@ Ruby on Rails guides
WARNING: This page is the result of ongoing http://hackfest.rubyonrails.org/guide[Rails Guides hackfest] and a work in progress.
+CAUTION: Guides marked with this icon are currently being worked on. While they might still be useful to you, they may contain incomplete information and even errors. You can help by reviewing them and posting your comments and corrections at the respective Lighthouse ticket.
+
++++++++++++++++++++++++++++++++++++++
-<h2>Finished Guides</h2>
+<h2>Start Here</h2>
++++++++++++++++++++++++++++++++++++++
-These guides are complete and the authors are listed link:authors.html[here].
+.link:getting_started_with_rails/getting_started_with_rails.html[Getting Started with Rails]
+***********************************************************
+CAUTION: link:http://rails.lighthouseapp.com/projects/16213/tickets/2[Lighthouse Ticket]
+
+Everything you need to know to install Rails and create your first application.
+***********************************************************
+
+++++++++++++++++++++++++++++++++++++++
+<h2>Models</h2>
+++++++++++++++++++++++++++++++++++++++
.link:migrations/migrations.html[Rails Database Migrations]
***********************************************************
-TODO: Insert some description here.
+This guide covers how you can use Active Record migrations to alter your database in a structured and organized manner.
***********************************************************
-.link:routing/routing_outside_in.html[Rails Routing from the Outside In]
+.link:activerecord/association_basics.html[Active Record Associations]
***********************************************************
-This guide covers the user-facing features of Rails routing. If you want to
-understand how to use routing in your own Rails applications, start here.
+This guide covers all the associations provided by Active Record.
+***********************************************************
+
+.link:activerecord/finders.html[Active Record Finders]
+***********************************************************
+CAUTION: link:http://rails.lighthouseapp.com/projects/16213/tickets/16[Lighthouse Ticket]
+
+This guide covers the find method defined in ActiveRecord::Base, as well as named scopes.
***********************************************************
++++++++++++++++++++++++++++++++++++++
-<h2>Guides in progress</h2>
+<h2>Views</h2>
++++++++++++++++++++++++++++++++++++++
-These guides are currently being worked on. While they still might be useful to you, you could always help by reviewing them and posting your
-findings at the respective Lighthouse ticket.
-
-.link:debugging/debugging_rails_applications.html[Debugging Rails Applications]
+.link:actionview/layouts_and_rendering.html[Layouts and Rendering in Rails]
***********************************************************
-link:http://rails.lighthouseapp.com/projects/16213/tickets/5[Lighthouse Ticket]
+CAUTION: link:http://rails.lighthouseapp.com/projects/16213/tickets/15[Lighthouse Ticket]
-This guide describes how to debug Rails applications. It covers the different
-ways of achieving this and how to understand what is happening "behind the scenes"
-of your code.
+This guide covers the basic layout features of Action Controller and Action View,
+including rendering and redirecting, using +content_for_ blocks, and working
+with partials.
***********************************************************
-.link:getting_started_with_rails/getting_started_with_rails.html[Getting Started with Rails]
+.link:forms/form_helpers.html[Action View Form Helpers]
***********************************************************
-link:http://rails.lighthouseapp.com/projects/16213/tickets/2[Lighthouse Ticket]
+CAUTION: link:http://rails.lighthouseapp.com/projects/16213/tickets/1[Lighthouse Ticket]
+
+Guide to using built in Form helpers.
***********************************************************
-.link:activerecord/association_basics.html[Active Record Associations]
+++++++++++++++++++++++++++++++++++++++
+<h2>Controllers</h2>
+++++++++++++++++++++++++++++++++++++++
+
+.link:routing/routing_outside_in.html[Rails Routing from the Outside In]
***********************************************************
-link:http://rails.lighthouseapp.com/projects/16213/tickets/11[Lighthouse Ticket]
+This guide covers the user-facing features of Rails routing. If you want to
+understand how to use routing in your own Rails applications, start here.
***********************************************************
-.link:forms/form_helpers.html[Action View Form Helpers]
+.link:actioncontroller/actioncontroller.html[Basics of Action Controller]
***********************************************************
-link:http://rails.lighthouseapp.com/projects/16213/tickets/1[Lighthouse Ticket]
+CAUTION: link:http://rails.lighthouseapp.com/projects/16213/tickets/17[Lighthouse Ticket]
-Guide to using built in Form helpers.
+This guide covers how controllers work and how they fit into the request cycle in your application. It includes sessions, filters, and cookies, data streaming, and dealing with exceptions raised by a request, among other topics.
***********************************************************
-.link:benchmarking_and_profiling/preamble.html[Benchmarking and Profiling Rails Applications]
+.link:caching/caching_with_rails.html[Rails Caching]
***********************************************************
-link:http://rails.lighthouseapp.com/projects/16213/tickets/4[Lighthouse Ticket]
+CAUTION: link:http://rails.lighthouseapp.com/projects/16213/tickets/10[Lighthouse Ticket]
-TODO: Insert some description here.
+This guide covers the three types of caching that Rails provides by default.
***********************************************************
+++++++++++++++++++++++++++++++++++++++
+<h2>Digging Deeper</h2>
+++++++++++++++++++++++++++++++++++++++
+
.link:testing_rails_applications/testing_rails_applications.html[Testing Rails Applications]
***********************************************************
-link:http://rails.lighthouseapp.com/projects/16213/tickets/8[Lighthouse Ticket]
+CAUTION: link:http://rails.lighthouseapp.com/projects/16213/tickets/8[Lighthouse Ticket]
This is a rather comprehensive guide to doing both unit and functional tests
in Rails. It covers everything from ``What is a test?'' to the testing APIs.
@@ -71,20 +96,31 @@ Enjoy.
.link:securing_rails_applications/security.html[Securing Rails Applications]
***********************************************************
-link:http://rails.lighthouseapp.com/projects/16213/tickets/7[Lighthouse Ticket]
+CAUTION: link:http://rails.lighthouseapp.com/projects/16213/tickets/7[Lighthouse Ticket]
This manual describes common security problems in web applications and how to
avoid them with Rails.
***********************************************************
-.link:caching/caching_with_rails.html[Rails Caching]
+.link:debugging/debugging_rails_applications.html[Debugging Rails Applications]
+***********************************************************
+CAUTION: link:http://rails.lighthouseapp.com/projects/16213/tickets/5[Lighthouse Ticket]
+
+This guide describes how to debug Rails applications. It covers the different
+ways of achieving this and how to understand what is happening "behind the scenes"
+of your code.
+***********************************************************
+
+.link:benchmarking_and_profiling/preamble.html[Benchmarking and Profiling Rails Applications]
***********************************************************
-link:http://rails.lighthouseapp.com/projects/16213/tickets/10[Lighthouse Ticket]
+CAUTION: link:http://rails.lighthouseapp.com/projects/16213/tickets/4[Lighthouse Ticket]
-TODO: Insert some description here.
+This guide covers ways to analyze and optimize your running Rails code.
***********************************************************
.link:creating_plugins/creating_plugins.html[The Basics of Creating Rails Plugins]
***********************************************************
-TODO: Insert some description here. No Lighthouse ticket.
+This guide covers how to build a plugin to extend the functionality of Rails.
***********************************************************
+
+Authors who have contributed to complete guides are listed link:authors.html[here].
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 fcd435ce66..2c1870d9d4 100644
--- a/railties/doc/guides/routing/routing_outside_in.txt
+++ b/railties/doc/guides/routing/routing_outside_in.txt
@@ -195,7 +195,7 @@ You can also apply RESTful routing to singleton resources within your applicatio
map.resource :geocoder
-------------------------------------------------------
-creates seven different routes in your application:
+creates six different routes in your application:
[grid="all"]
`----------`---------------`-----------`--------`-------------------------------------------
@@ -256,7 +256,7 @@ PUT /photos/1 Images update update a specific image
DELETE /photos/1 Images destroy delete a specific image
--------------------------------------------------------------------------------------------
-NOTE: The helpers will be generated with the name of the resource, not the name of the controller. So in this case, you'd still get +photos_path+, +photos_new_path+, and so on.
+NOTE: The helpers will be generated with the name of the resource, not the name of the controller. So in this case, you'd still get +photos_path+, +new_photo_path+, and so on.
=== Controller Namespaces and Routing ===
@@ -321,7 +321,7 @@ PUT /images/1 Photos update update a specific photo
DELETE /images/1 Photos destroy delete a specific photo
--------------------------------------------------------------------------------------------
-NOTE: The helpers will be generated with the name of the resource, not the path name. So in this case, you'd still get +photos_path+, +photos_new_path+, and so on.
+NOTE: The helpers will be generated with the name of the resource, not the path name. So in this case, you'd still get +photos_path+, +new_photo_path+, and so on.
==== Using :path_names
@@ -376,7 +376,7 @@ map.resources :photos, :path_prefix => '/photographers/:photographer_id', :name_
map.resources :photos, :path_prefix => '/agencies/:agency_id', :name_prefix => 'agency_'
-------------------------------------------------------
-This combination will give you route helpers such as +photographer_photos_path+ and +agency_photo_edit_path+ to use in your code.
+This combination will give you route helpers such as +photographer_photos_path+ and +agency_edit_photo_path+ to use in your code.
=== Nested Resources
@@ -537,8 +537,8 @@ It's possible to do some quite complex things by combining +:path_prefix+ and +:
[source, ruby]
-------------------------------------------------------
map.resources :photos, :path_prefix => 'admin', :controller => 'admin/photos'
-map.resources :tags, :path_prefix => 'admin_photo_', :path_prefix => 'admin/photos/:photo_id', :controller => 'admin/photo_tags'
-map.resources :ratings, :path_prefix => 'admin_photo_', :path_prefix => 'admin/photos/:photo_id', :controller => 'admin/photo_ratings'
+map.resources :tags, :name_prefix => 'admin_photo_', :path_prefix => 'admin/photos/:photo_id', :controller => 'admin/photo_tags'
+map.resources :ratings, :name_prefix => 'admin_photo_', :path_prefix => 'admin/photos/:photo_id', :controller => 'admin/photo_ratings'
-------------------------------------------------------
The good news is that if you find yourself using this level of complexity, you can stop. Rails supports _namespaced resources_ to make placing resources in their own folder a snap. Here's the namespaced version of those same three routes:
@@ -551,7 +551,7 @@ map.namespace(:admin) do |admin|
end
-------------------------------------------------------
-As you can see, the namespaced version is much more succinct than the one that spells everything out - but it still creates the same routes. For example, you'll get +admin_photos_url+ that expects to find an +Admin::PhotosController+ and that matches +admin/photos+, and +admin_photos_ratings+path+ that matches +/admin/photos/_photo_id_/ratings+, expecting to use +Admin::RatingsController+.
+As you can see, the namespaced version is much more succinct than the one that spells everything out - but it still creates the same routes. For example, you'll get +admin_photos_url+ that expects to find an +Admin::PhotosController+ and that matches +admin/photos+, and +admin_photos_ratings+path+ that matches +/admin/photos/_photo_id_/ratings+, expecting to use +Admin::RatingsController+. Even though you're not specifying +path_prefix+ explicitly, the routing code will calculate the appropriate +path_prefix+ from the route nesting.
=== Adding More RESTful Actions
@@ -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/doc/guides/testing_rails_applications/testing_rails_applications.txt b/railties/doc/guides/testing_rails_applications/testing_rails_applications.txt
index 254fd99357..11ff2e6a41 100644
--- a/railties/doc/guides/testing_rails_applications/testing_rails_applications.txt
+++ b/railties/doc/guides/testing_rails_applications/testing_rails_applications.txt
@@ -2,15 +2,18 @@ A Guide to Testing Rails Applications
=====================================
This guide covers built-in mechanisms offered by Rails to test your application. By referring to this guide, you will be able to:
+
* Understand Rails testing terminologies
* Write unit, functional and integration tests for your application
* Read about other popular testing approaches and plugins
Assumptions:
+
* You have spent more than 15 minutes in building your first application
* The guide has been written for Rails 2.1 and above
-== Why write tests for your Rails applications?
+== Why write tests for your Rails applications? ==
+
* Since Ruby code that you write in your Rails application is interpreted, you may only find that its broken when you actually run your application server and use it through the browser. Writing tests is a clean way of running through your code and catching syntactical and logic errors.
* Rails tests can also simulate browser requests and thus you can test your applications response without having to test it through your browser.
* By simply running your Rails tests you can ensure your code adheres to the desired functionality even after some major code refactoring.
@@ -63,7 +66,7 @@ The 'unit' folder is meant to hold tests for your models, 'functional' folder is
==== What They Are ====
-Fixtures is a fancy word for 'sample data'. Fixtures allow you to populate your testing database with predefined data before your tests run. Fixtures are database independent and assume one of two formats: *YAML* or *CSV*.
+Fixtures is a fancy word for sample data. Fixtures allow you to populate your testing database with predefined data before your tests run. Fixtures are database independent and assume one of two formats: *YAML* or *CSV*.
You'll find fixtures under your 'test/fixtures' directory. When you run `script/generate model` to create a new model, fixture stubs will be automatically created and placed in this directory.
@@ -92,7 +95,7 @@ Each fixture is given a 'name' followed by an indented list of colon-separated k
==== Comma Seperated ====
-Fixtures can also be described using the all-too-familiar comma-separated value file format. These files, just like YAML fixtures are placed in the 'test/fixtures directory', but these end with the *.csv* file extension (as in 'celebrity_holiday_figures.csv').
+Fixtures can also be described using the all-too-familiar comma-separated value file format. These files, just like YAML fixtures are placed in the 'test/fixtures' directory, but these end with the *.csv* file extension (as in 'celebrity_holiday_figures.csv').
A CSV fixture looks like this:
@@ -111,7 +114,7 @@ The first line is the header. It is a comma-separated list of fields. The rest o
* don't use blank lines
* nulls can be achived by just placing a comma, for example, (1,sclaus,,false,) minus the parenthesis of course.
-Unlike the YAML format where you give each fixture a name, CSV fixture names are automatically generated. They follow a pattern of ``model-name''-''counter''. In the above example, you would have:
+Unlike the YAML format where you give each fixture a name, CSV fixture names are automatically generated. They follow a pattern of ``model-name-counter''. In the above example, you would have:
--------------------------------------------------------------
celebrity-holiday-figures-1
@@ -497,7 +500,11 @@ You would get to see the usage of some of these assertions in the next chapter.
== Functional tests for your Controllers ==
-In Rails, testing various actions of a single controller is termed as writing functional tests for that controller. Controllers handle the incoming web requests to your application and eventually respond with a rendered view. Thus, you should test for things such as:
+In Rails, testing various actions of a single controller is termed as writing functional tests for that controller. Controllers handle the incoming web requests to your application and eventually respond with a rendered view.
+
+=== What to include in your Functional Tests ===
+
+You should test for things such as:
* was the web request successful?
* were we redirected to the right page?
@@ -569,7 +576,7 @@ For those of you familiar with HTTP protocol, you'll know that get is a type of
* head
* delete
-All of request types are methods that you can use, however, you'll probably end up using the first two more ofter than the others.
+All of request types are methods that you can use, however, you'll probably end up using the first two more often than the others.
=== The 4 Hashes of the Apocolypse ===
@@ -577,27 +584,26 @@ After the request has been made by using one of the 5 methods (get, post, etc…
They are (starring in alphabetical order):
-assigns
+`assigns`::
Any objects that are stored as instance variables in actions for use in views.
-cookies
+`cookies`::
Any objects cookies that are set.
-flash
+`flash`::
Any objects living in the flash.
-session
+`session`::
Any object living in session variables.
-
As is the case with normal Hash objects, you can access the values by referencing the keys by string. You can also reference them by symbol name… except assigns. Check it out:
-flash["gordon"] flash[:gordon]
-session["shmession"] session[:shmession]
-cookies["are_good_for_u"] cookies[:are_good_for_u]
+ flash["gordon"] flash[:gordon]
+ session["shmession"] session[:shmession]
+ cookies["are_good_for_u"] cookies[:are_good_for_u]
# Because you can't use assigns[:something] for historical reasons:
-assigns["something"] assigns(:something)
+ assigns["something"] assigns(:something)
=== Instance variables available ===
@@ -618,14 +624,58 @@ Another example that uses flash, assert_redirected_to, assert_difference
end
--------------------------------------------------
-=== Testing Views using assert_select ===
-http://api.rubyonrails.org/classes/ActionController/Assertions/SelectorAssertions.html#M000749
+=== Testing Views ===
+
+Testing the response to your request by asserting the presence of key html elements and their content is a good practice. `assert_select` allows you to do all this by using a simple yet powerful syntax.
+
+[NOTE]
+`assert_tag` is now deprecated in favor of `assert_select`
+
+`assert_select(selector, [equality], [message])`::
+Ensures that the equality condition is met on the selected elements through the selector. The selector may be a CSS selector expression (String), an expression with substitution values, or an HTML::Selector object.
+
+`assert_select(element, selector, [equality], [message])`::
+Ensures that the equality condition is met on all the selected elements through the selector starting from the _element_ (instance of HTML::Node) and its descendants.
+
+For example, you could verify the contents on the title element in your response with:
+
+[source,ruby]
+--------------------------------------------------
+assert_select 'title', "Welcome to Rails Testing Guide"
+--------------------------------------------------
+
+You can also use nested `assert_select` blocks. In this case the inner `assert_select` will run the assertion on each element selected by the outer `assert_select` block.
+
+[source,ruby]
+--------------------------------------------------
+assert_select 'ul.navigation' do
+ assert_select 'li.menu_item'
+end
+--------------------------------------------------
+
+`assert_select` is really powerful and I would recommend you to go through its http://api.rubyonrails.com/classes/ActionController/Assertions/SelectorAssertions.html#M000749[documentation] for its advanced usage.
==== Additional view based assertions ====
- * assert_select_rjs
- * assert_select_email
- * assert_select_encoded
+`assert_select_email`::
+Allows you to make assertions on the body of an e-mail.
+
+[source,ruby]
+--------------------------------------------------
+assert_select_email do
+ assert_select 'small', 'Please click the "Unsubscribe" link if you want to opt-out.'
+end
+--------------------------------------------------
+
+`assert_select_rjs`::
+Allows you to make assertions on RJS response. `assert_select_rjs` has variants which allow you to narrow down upon the updated element or event a particular operation on an element.
+
+`assert_select_encoded`::
+Allows you to make assertions on encoded HTML. It does this by un-encoding the contents of each element and then calling the block with all the un-encoded elements.
+
+`css_select(selector)`::
+`css_select(element, selector)`::
+Returns an array of all the elements selected by the _selector_. In the second variant it first matches the base _element_ and tries to match the _selector_ expression on any of its children. If there are no matches both variants return an empty array.
== Integration Testing ==
@@ -660,25 +710,30 @@ end
* You will have to include fixtures explicitly unlike unit and functional tests in which all the fixtures are loaded by default (through test_helper)
* Additional helpers: https?, https!, host!, follow_redirect!, post/get_via_redirect, open_session, reset
-
-== Guide TODO ==
- * What to test in unit tests
- * Testing views (assert_select)
- * Examples for integration test
- * Updating Rake tasks
- * Update sectino on testing file uploads
- * Updating the section on testing mailers
-
-== Rake tasks related to testing
-
-rake db:test:*
-
-rake test
-rake test:units
-rake test:functionals
-rake test:integration
-rake test:plugin
-
+== Rake Tasks for Testing
+
+The table below lists all rake tasks that come along in the default Rakefile when you initiate a Rail project.
+
+.Default Rake tasks
+[grid="all"]
+-------------------------
+Tasks Description
+-------------------------
+`rake test` Runs all unit, functional and integration tests. You can also simply run `rake` as _test_ target is default.
+`rake test:units` Runs all the unit tests from 'test/unit'
+`rake test:functionals` Runs all the functional tests from 'test/functional'
+`rake test:integration` Runs all the integration tests from 'test/integration'
+`rake test:recent` Tests recent changes
+`rake test:uncommitted` Runs all the tests which are uncommitted. Only supports Subversion
+`rake test:plugins` Run all the plugin tests from vendor/plugins/*/**/test (or specify with `PLUGIN=_name_`)
+`rake db:test:clone` Recreate the test database from the current environment's database schema
+`rake db:test:clone_structure` Recreate the test databases from the development structure
+`rake db:test:load` Recreate the test database from the current schema.rb
+`rake db:test:prepare` Check for pending migrations and load the test schema
+`rake db:test:purge` Empty the test database.
+-------------------------
+
+TIP: You can see all these rake task and their descriptions by running `rake --tasks --describe`
== Testing Your Mailers ==
@@ -877,3 +932,7 @@ class ActionMailer::Base
end
----------------------------------------------------------------
+== Guide TODO ==
+ * Describe _setup_ and _teardown_
+ * Examples for integration test
+ * Updating the section on testing mailers
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