Remove `#among?` from Active Support

After a long list of discussion about the performance problem from using varargs and the reason that we can't find a great pair for it, it would be best to remove support for it for now.

It will come back if we can find a good pair for it. For now, Bon Voyage, `#among?`.
This commit is contained in:
Prem Sichanugrist 2011-04-13 00:04:40 +08:00 committed by David Heinemeier Hansson
parent 1f869114f5
commit 733bfa63f5
37 changed files with 38 additions and 53 deletions

View File

@ -1346,11 +1346,11 @@ module ActionDispatch
end
def resource_scope? #:nodoc:
@scope[:scope_level].among?(:resource, :resources)
@scope[:scope_level].in?([:resource, :resources])
end
def resource_method_scope? #:nodoc:
@scope[:scope_level].among?(:collection, :member, :new)
@scope[:scope_level].in?([:collection, :member, :new])
end
def with_exclusive_scope

View File

@ -35,7 +35,7 @@ module ActionDispatch
def assert_response(type, message = nil)
validate_request!
if type.among?(:success, :missing, :redirect, :error) && @response.send("#{type}?")
if type.in?([:success, :missing, :redirect, :error]) && @response.send("#{type}?")
assert_block("") { true } # to count the assertion
elsif type.is_a?(Fixnum) && @response.response_code == type
assert_block("") { true } # to count the assertion

View File

@ -321,7 +321,7 @@ module ActionDispatch
define_method(method) do |*args|
reset! unless integration_session
# reset the html_document variable, but only for new get/post calls
@html_document = nil unless method.among?("cookies", "assigns")
@html_document = nil unless method.in?(["cookies", "assigns"])
integration_session.__send__(method, *args).tap do
copy_session_variables!
end

View File

@ -157,7 +157,7 @@ class RespondToController < ActionController::Base
protected
def set_layout
if action_name.among?("all_types_with_layout", "iphone_with_html_response_type")
if action_name.in?(["all_types_with_layout", "iphone_with_html_response_type"])
"respond_to/layouts/standard"
elsif action_name == "iphone_with_html_response_type_without_layout"
"respond_to/layouts/missing"

View File

@ -496,7 +496,7 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
resources :todos, :id => /\d+/
end
scope '/countries/:country', :constraints => lambda { |params, req| params[:country].among?("all", "France") } do
scope '/countries/:country', :constraints => lambda { |params, req| params[:country].in?(["all", "France"]) } do
match '/', :to => 'countries#index'
match '/cities', :to => 'countries#cities'
end

View File

@ -1744,7 +1744,7 @@ class FormHelperTest < ActionView::TestCase
def snowman(method = nil)
txt = %{<div style="margin:0;padding:0;display:inline">}
txt << %{<input name="utf8" type="hidden" value="&#x2713;" />}
if method && !method.to_s.among?('get', 'post')
if method && !method.to_s.in?(['get', 'post'])
txt << %{<input name="_method" type="hidden" value="#{method}" />}
end
txt << %{</div>}

View File

@ -83,7 +83,7 @@ class FormOptionsHelperTest < ActionView::TestCase
def test_collection_options_with_proc_for_disabled
assert_dom_equal(
"<option value=\"&lt;Abe&gt;\">&lt;Abe&gt; went home</option>\n<option value=\"Babe\" disabled=\"disabled\">Babe went home</option>\n<option value=\"Cabe\" disabled=\"disabled\">Cabe went home</option>",
options_from_collection_for_select(dummy_posts, "author_name", "title", :disabled => lambda{|p| p.author_name.among?("Babe", "Cabe") })
options_from_collection_for_select(dummy_posts, "author_name", "title", :disabled => lambda{|p| p.author_name.in?(["Babe", "Cabe"]) })
)
end

View File

@ -14,7 +14,7 @@ class FormTagHelperTest < ActionView::TestCase
txt = %{<div style="margin:0;padding:0;display:inline">}
txt << %{<input name="utf8" type="hidden" value="&#x2713;" />}
if method && !method.to_s.among?('get','post')
if method && !method.to_s.in?(['get','post'])
txt << %{<input name="_method" type="hidden" value="#{method}" />}
end
txt << %{</div>}

View File

@ -68,7 +68,7 @@ module ActiveModel #:nodoc:
#
# class TitleValidator < ActiveModel::EachValidator
# def validate_each(record, attribute, value)
# record.errors[attribute] << 'must be Mr. Mrs. or Dr.' unless value.among?('Mr.', 'Mrs.', 'Dr.')
# record.errors[attribute] << 'must be Mr. Mrs. or Dr.' unless value.in?(['Mr.', 'Mrs.', 'Dr.'])
# end
# end
#

View File

@ -164,7 +164,7 @@ module ActiveRecord
def creation_attributes
attributes = {}
if reflection.macro.among?(:has_one, :has_many) && !options[:through]
if reflection.macro.in?([:has_one, :has_many]) && !options[:through]
attributes[reflection.foreign_key] = owner[reflection.active_record_primary_key]
if reflection.options[:as]

View File

@ -67,7 +67,7 @@ module ActiveRecord::Associations::Builder
def configure_dependency
if options[:dependent]
unless options[:dependent].among?(:destroy, :delete)
unless options[:dependent].in?([:destroy, :delete])
raise ArgumentError, "The :dependent option expects either :destroy or :delete (#{options[:dependent].inspect})"
end

View File

@ -16,7 +16,7 @@ module ActiveRecord::Associations::Builder
def configure_dependency
if options[:dependent]
unless options[:dependent].among?(:destroy, :delete_all, :nullify, :restrict)
unless options[:dependent].in?([:destroy, :delete_all, :nullify, :restrict])
raise ArgumentError, "The :dependent option expects either :destroy, :delete_all, " \
":nullify or :restrict (#{options[:dependent].inspect})"
end

View File

@ -29,7 +29,7 @@ module ActiveRecord::Associations::Builder
def configure_dependency
if options[:dependent]
unless options[:dependent].among?(:destroy, :delete, :nullify, :restrict)
unless options[:dependent].in?([:destroy, :delete, :nullify, :restrict])
raise ArgumentError, "The :dependent option expects either :destroy, :delete, " \
":nullify or :restrict (#{options[:dependent].inspect})"
end

View File

@ -52,7 +52,7 @@ module ActiveRecord
end
def remove_target!(method)
if method.among?(:delete, :destroy)
if method.in?([:delete, :destroy])
target.send(method)
else
nullify_owner_attributes(target)

View File

@ -59,7 +59,7 @@ module ActiveRecord
private
def create_time_zone_conversion_attribute?(name, column)
time_zone_aware_attributes && !self.skip_time_zone_conversion_for_attributes.include?(name.to_sym) && column.type.among?(:datetime, :timestamp)
time_zone_aware_attributes && !self.skip_time_zone_conversion_for_attributes.include?(name.to_sym) && column.type.in?([:datetime, :timestamp])
end
end
end

View File

@ -137,7 +137,7 @@ db_namespace = namespace :db do
end
def local_database?(config, &block)
if config['host'].among?("127.0.0.1", "localhost") || config['host'].blank?
if config['host'].in?(["127.0.0.1", "localhost"]) || config['host'].blank?
yield
else
$stderr.puts "This task only modifies local databases. #{config['database']} is on a remote host."

View File

@ -164,7 +164,7 @@ module ActiveRecord
def initialize(macro, name, options, active_record)
super
@collection = macro.among?(:has_many, :has_and_belongs_to_many)
@collection = macro.in?([:has_many, :has_and_belongs_to_many])
end
# Returns a new, unsaved instance of the associated class. +options+ will

View File

@ -14,7 +14,7 @@ module ActiveRecord
def session_table_name
current_table_name = ActiveRecord::SessionStore::Session.table_name
if current_table_name.among?("sessions", "session")
if current_table_name.in?(["sessions", "session"])
current_table_name = (ActiveRecord::Base.pluralize_table_names ? 'session'.pluralize : 'session')
end
current_table_name

View File

@ -639,7 +639,7 @@ class AttributeMethodsTest < ActiveRecord::TestCase
end
def time_related_columns_on_topic
Topic.columns.select { |c| c.type.among?(:time, :date, :datetime, :timestamp) }
Topic.columns.select { |c| c.type.in?([:time, :date, :datetime, :timestamp]) }
end
def serialized_columns_on_topic

View File

@ -95,7 +95,7 @@ if current_adapter?(:MysqlAdapter) or current_adapter?(:Mysql2Adapter)
assert_equal 0, klass.columns_hash['zero'].default
assert !klass.columns_hash['zero'].null
# 0 in MySQL 4, nil in 5.
assert klass.columns_hash['omit'].default.among?(0, nil)
assert klass.columns_hash['omit'].default.in?([0, nil])
assert !klass.columns_hash['omit'].null
assert_raise(ActiveRecord::StatementInvalid) { klass.create! }

View File

@ -278,7 +278,7 @@ module ActiveResource
def legitimize_auth_type(auth_type)
return :basic if auth_type.nil?
auth_type = auth_type.to_sym
auth_type.among?(:basic, :digest) ? auth_type : :basic
auth_type.in?([:basic, :digest]) ? auth_type : :basic
end
end
end

View File

@ -193,7 +193,7 @@ class HttpMockTest < ActiveSupport::TestCase
end
def request(method, path, headers = {}, body = nil)
if method.among?(:put, :post)
if method.in?([:put, :post])
@http.send(method, path, body, headers)
else
@http.send(method, path, headers)

View File

@ -1,6 +1,6 @@
*Rails 3.1.0 (unreleased)*
* Add Object#in? to test if an object is included in another object, and Object#among? to test if an object is included in a list of objects which will be passed as arguments. [Prem Sichanugrist, Brian Morearty, John Reitano]
* Add Object#in? to test if an object is included in another object [Prem Sichanugrist, Brian Morearty, John Reitano]
* LocalCache strategy is now a real middleware class, not an anonymous class
posing for pictures.

View File

@ -21,7 +21,7 @@ module ActiveSupport
end
def clear(options = nil)
root_dirs = Dir.entries(cache_path).reject{|f| f.among?('.', '..')}
root_dirs = Dir.entries(cache_path).reject{|f| f.in?(['.', '..'])}
FileUtils.rm_r(root_dirs.collect{|f| File.join(cache_path, f)})
end
@ -162,7 +162,7 @@ module ActiveSupport
# Delete empty directories in the cache.
def delete_empty_directories(dir)
return if dir == cache_path
if Dir.entries(dir).reject{|f| f.among?('.', '..')}.empty?
if Dir.entries(dir).reject{|f| f.in?(['.', '..'])}.empty?
File.delete(dir) rescue nil
delete_empty_directories(File.dirname(dir))
end

View File

@ -413,7 +413,7 @@ module ActiveSupport
# CallbackChain.
#
def __update_callbacks(name, filters = [], block = nil) #:nodoc:
type = filters.first.among?(:before, :after, :around) ? filters.shift : :before
type = filters.first.in?([:before, :after, :around]) ? filters.shift : :before
options = filters.last.is_a?(Hash) ? filters.pop : {}
filters.unshift(block) if block

View File

@ -8,13 +8,4 @@ class Object
def in?(another_object)
another_object.include?(self)
end
# Returns true if this object is included in the argument list. Usage:
#
# username = "sikachu"
# username.among?("josevalim", "dhh", "wycats") # => false
#
def among?(*objects)
objects.include?(self)
end
end

View File

@ -345,7 +345,7 @@ module ActiveSupport
end
def duration_of_variable_length?(obj)
ActiveSupport::Duration === obj && obj.parts.any? {|p| p[0].among?(:years, :months, :days) }
ActiveSupport::Duration === obj && obj.parts.any? {|p| p[0].in?([:years, :months, :days]) }
end
end
end

View File

@ -30,12 +30,6 @@ class InTest < Test::Unit::TestCase
assert !3.in?(s)
end
def test_among
assert 1.among?(1,2,3)
assert !5.among?(1,2,3)
assert [1,2,3].among?([1,2,3], 2, [3,4,5])
end
module A
end
class B

View File

@ -16,7 +16,7 @@ class TransliterateTest < Test::Unit::TestCase
# create string with range of Unicode"s western characters with
# diacritics, excluding the division and multiplication signs which for
# some reason or other are floating in the middle of all the letters.
string = (0xC0..0x17E).to_a.reject {|c| c.among?(0xD7, 0xF7)}.pack("U*")
string = (0xC0..0x17E).to_a.reject {|c| c.in?([0xD7, 0xF7])}.pack("U*")
string.each_char do |char|
assert_match %r{^[a-zA-Z']*$}, ActiveSupport::Inflector.transliterate(string)
end

View File

@ -5,7 +5,7 @@ module RailsGuides
def notestuff(body)
body.gsub!(/^(IMPORTANT|CAUTION|WARNING|NOTE|INFO)[.:](.*)$/) do |m|
css_class = $1.downcase
css_class = 'warning' if css_class.among?('caution', 'important')
css_class = 'warning' if css_class.in?(['caution', 'important'])
result = "<div class='#{css_class}'><p>"
result << $2.strip
@ -35,7 +35,7 @@ module RailsGuides
def code(body)
body.gsub!(%r{<(yaml|shell|ruby|erb|html|sql|plain)>(.*?)</\1>}m) do |m|
es = ERB::Util.h($2)
css_class = $1.among?('erb', 'shell') ? 'html' : $1
css_class = $1.in?(['erb', 'shell']) ? 'html' : $1
%{<notextile><div class="code_container"><code class="#{css_class}">#{es}</code></div></notextile>}
end
end

View File

@ -71,7 +71,7 @@ when '--version', '-v'
require 'rails/commands/application'
else
puts "Error: Command not recognized" unless command.among?('-h', '--help')
puts "Error: Command not recognized" unless command.in?(['-h', '--help'])
puts <<-EOT
Usage: rails COMMAND [ARGS]

View File

@ -1,6 +1,6 @@
require 'active_support/core_ext/object/inclusion'
if ARGV.first.among?(nil, "-h", "--help")
if ARGV.first.in?([nil, "-h", "--help"])
puts "Usage: rails benchmarker [times] 'Person.expensive_way' 'Person.another_expensive_way' ..."
exit 1
end

View File

@ -3,7 +3,7 @@ require 'active_support/core_ext/object/inclusion'
Rails::Generators.configure!
if ARGV.first.among?(nil, "-h", "--help")
if ARGV.first.in?([nil, "-h", "--help"])
Rails::Generators.help 'destroy'
exit
end

View File

@ -3,7 +3,7 @@ require 'active_support/core_ext/object/inclusion'
Rails::Generators.configure!
if ARGV.first.among?(nil, "-h", "--help")
if ARGV.first.in?([nil, "-h", "--help"])
Rails::Generators.help 'generate'
exit
end

View File

@ -1,6 +1,6 @@
require 'active_support/core_ext/object/inclusion'
if ARGV.first.among?(nil, "-h", "--help")
if ARGV.first.in?([nil, "-h", "--help"])
$stderr.puts "Usage: rails profiler 'Person.expensive_method(10)' [times] [flat|graph|graph_html]"
exit(1)
end

View File

@ -165,7 +165,7 @@ module Rails
names.each do |name|
defaults = if options[:type] == :boolean
{ }
elsif default_value_for_option(name, options).among?(true, false)
elsif default_value_for_option(name, options).in?([true, false])
{ :banner => "" }
else
{ :desc => "#{name.to_s.humanize} to be invoked", :banner => "NAME" }

View File

@ -45,7 +45,7 @@ module Rails
end
def reference?
self.type.among?(:references, :belongs_to)
self.type.in?([:references, :belongs_to])
end
end
end