1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

removes usage of Object#in? from the code base (the method remains defined by Active Support)

Selecting which key extensions to include in active_support/rails
made apparent the systematic usage of Object#in? in the code base.
After some discussion in

    5ea6b0df9a

we decided to remove it and use plain Ruby, which seems enough
for this particular idiom.

In this commit the refactor has been made case by case. Sometimes
include? is the natural alternative, others a simple || is the
way you actually spell the condition in your head, others a case
statement seems more appropriate. I have chosen the one I liked
the most in each case.
This commit is contained in:
Xavier Noria 2012-08-06 00:27:56 +02:00
parent 6126f02cf9
commit 447b6a4e67
32 changed files with 53 additions and 66 deletions

View file

@ -341,9 +341,9 @@ module ActionController #:nodoc:
config = self.class.mimes_for_respond_to[mime] config = self.class.mimes_for_respond_to[mime]
if config[:except] if config[:except]
!action.in?(config[:except]) !config[:except].include?(action)
elsif config[:only] elsif config[:only]
action.in?(config[:only]) config[:only].include?(action)
else else
true true
end end

View file

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

View file

@ -151,10 +151,11 @@ class RespondToController < ActionController::Base
protected protected
def set_layout def set_layout
if action_name.in?(["all_types_with_layout", "iphone_with_html_response_type"]) case action_name
"respond_to/layouts/standard" when "all_types_with_layout", "iphone_with_html_response_type"
elsif action_name == "iphone_with_html_response_type_without_layout" "respond_to/layouts/standard"
"respond_to/layouts/missing" when "iphone_with_html_response_type_without_layout"
"respond_to/layouts/missing"
end end
end end
end end

View file

@ -1307,7 +1307,7 @@ class ResourcesTest < ActionController::TestCase
def assert_resource_methods(expected, resource, action_method, method) def assert_resource_methods(expected, resource, action_method, method)
assert_equal expected.length, resource.send("#{action_method}_methods")[method].size, "#{resource.send("#{action_method}_methods")[method].inspect}" assert_equal expected.length, resource.send("#{action_method}_methods")[method].size, "#{resource.send("#{action_method}_methods")[method].inspect}"
expected.each do |action| expected.each do |action|
assert action.in?(resource.send("#{action_method}_methods")[method]) assert resource.send("#{action_method}_methods")[method].include?(action)
"#{method} not in #{action_method} methods: #{resource.send("#{action_method}_methods")[method].inspect}" "#{method} not in #{action_method} methods: #{resource.send("#{action_method}_methods")[method].inspect}"
end end
end end
@ -1344,9 +1344,9 @@ class ResourcesTest < ActionController::TestCase
options = options.merge(:action => action.to_s) options = options.merge(:action => action.to_s)
path_options = { :path => path, :method => method } path_options = { :path => path, :method => method }
if action.in?(Array(allowed)) if Array(allowed).include?(action)
assert_recognizes options, path_options assert_recognizes options, path_options
elsif action.in?(Array(not_allowed)) elsif Array(not_allowed).include?(action)
assert_not_recognizes options, path_options assert_not_recognizes options, path_options
end end
end end

View file

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

View file

@ -39,7 +39,7 @@ class ErbUtilTest < ActiveSupport::TestCase
def test_rest_in_ascii def test_rest_in_ascii
(0..127).to_a.map {|int| int.chr }.each do |chr| (0..127).to_a.map {|int| int.chr }.each do |chr|
next if chr.in?('&"<>\'') next if %('"&<>).include?(chr)
assert_equal chr, html_escape(chr) assert_equal chr, html_escape(chr)
end end
end end

View file

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

View file

@ -82,7 +82,7 @@ class FormOptionsHelperTest < ActionView::TestCase
def test_collection_options_with_proc_for_disabled def test_collection_options_with_proc_for_disabled
assert_dom_equal( 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>", "<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.in?(["Babe", "Cabe"]) }) options_from_collection_for_select(dummy_posts, "author_name", "title", :disabled => lambda {|p| %w(Babe Cabe).include?(p.author_name)})
) )
end end

View file

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

View file

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

View file

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

View file

@ -51,16 +51,19 @@ module ActiveRecord
end end
def remove_target!(method) def remove_target!(method)
if method.in?([:delete, :destroy]) case method
target.send(method) when :delete
else target.delete
nullify_owner_attributes(target) when :destroy
target.destroy
else
nullify_owner_attributes(target)
if target.persisted? && owner.persisted? && !target.save if target.persisted? && owner.persisted? && !target.save
set_owner_attributes(target) set_owner_attributes(target)
raise RecordNotSaved, "Failed to remove the existing associated #{reflection.name}. " + raise RecordNotSaved, "Failed to remove the existing associated #{reflection.name}. " +
"The record failed to save when after its foreign key was set to nil." "The record failed to save when after its foreign key was set to nil."
end end
end end
end end

View file

@ -55,7 +55,7 @@ module ActiveRecord
end end
sup = active_record_super sup = active_record_super
if sup.in?([Base, Model]) || sup.abstract_class? if sup == Base || sup == Model || sup.abstract_class?
self self
else else
sup.base_class sup.base_class

View file

@ -1,4 +1,3 @@
require 'active_support/core_ext/object/inclusion'
require 'active_record' require 'active_record'
db_namespace = namespace :db do db_namespace = namespace :db do

View file

@ -115,7 +115,7 @@ module ActiveRecord
end end
def local_database?(configuration) def local_database?(configuration)
configuration['host'].in?(LOCAL_HOSTS) || configuration['host'].blank? configuration['host'].blank? || LOCAL_HOSTS.include?(configuration['host'])
end end
end end
end end

View file

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

View file

@ -453,7 +453,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
assert saved_post.tags.include?(new_tag) assert saved_post.tags.include?(new_tag)
assert new_tag.persisted? assert new_tag.persisted?
assert new_tag.in?(saved_post.reload.tags(true)) assert saved_post.reload.tags(true).include?(new_tag)
new_post = Post.new(:title => "Association replacmenet works!", :body => "You best believe it.") new_post = Post.new(:title => "Association replacmenet works!", :body => "You best believe it.")
@ -466,7 +466,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
new_post.save! new_post.save!
assert new_post.persisted? assert new_post.persisted?
assert saved_tag.in?(new_post.reload.tags(true)) assert new_post.reload.tags(true).include?(saved_tag)
assert !posts(:thinking).tags.build.persisted? assert !posts(:thinking).tags.build.persisted?
assert !posts(:thinking).tags.new.persisted? assert !posts(:thinking).tags.new.persisted?

View file

@ -47,13 +47,13 @@ module ActiveRecord
instance = @klass.new instance = @klass.new
@klass.column_names.each do |name| @klass.column_names.each do |name|
assert !name.in?(instance.methods.map(&:to_s)) assert !instance.methods.map(&:to_s).include?(name)
end end
@klass.define_attribute_methods @klass.define_attribute_methods
@klass.column_names.each do |name| @klass.column_names.each do |name|
assert name.in?(instance.methods.map(&:to_s)), "#{name} is not defined" assert instance.methods.map(&:to_s).include?(name), "#{name} is not defined"
end end
end end

View file

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

View file

@ -1,6 +1,5 @@
require 'active_support/core_ext/file/atomic' require 'active_support/core_ext/file/atomic'
require 'active_support/core_ext/string/conversions' require 'active_support/core_ext/string/conversions'
require 'active_support/core_ext/object/inclusion'
require 'uri/common' require 'uri/common'
module ActiveSupport module ActiveSupport
@ -23,7 +22,7 @@ module ActiveSupport
end end
def clear(options = nil) def clear(options = nil)
root_dirs = Dir.entries(cache_path).reject{|f| f.in?(EXCLUDED_DIRS + [".gitkeep"])} root_dirs = Dir.entries(cache_path).reject {|f| (EXCLUDED_DIRS + [".gitkeep"]).include?(f)}
FileUtils.rm_r(root_dirs.collect{|f| File.join(cache_path, f)}) FileUtils.rm_r(root_dirs.collect{|f| File.join(cache_path, f)})
end end
@ -151,7 +150,7 @@ module ActiveSupport
# Delete empty directories in the cache. # Delete empty directories in the cache.
def delete_empty_directories(dir) def delete_empty_directories(dir)
return if dir == cache_path return if dir == cache_path
if Dir.entries(dir).reject{|f| f.in?(EXCLUDED_DIRS)}.empty? if Dir.entries(dir).reject {|f| EXCLUDED_DIRS.include?(f)}.empty?
File.delete(dir) rescue nil File.delete(dir) rescue nil
delete_empty_directories(File.dirname(dir)) delete_empty_directories(File.dirname(dir))
end end
@ -165,7 +164,7 @@ module ActiveSupport
def search_dir(dir, &callback) def search_dir(dir, &callback)
return if !File.exist?(dir) return if !File.exist?(dir)
Dir.foreach(dir) do |d| Dir.foreach(dir) do |d|
next if d.in?(EXCLUDED_DIRS) next if EXCLUDED_DIRS.include?(d)
name = File.join(dir, d) name = File.join(dir, d)
if File.directory?(name) if File.directory?(name)
search_dir(name, &callback) search_dir(name, &callback)

View file

@ -3,7 +3,6 @@ require 'active_support/descendants_tracker'
require 'active_support/core_ext/class/attribute' require 'active_support/core_ext/class/attribute'
require 'active_support/core_ext/kernel/reporting' require 'active_support/core_ext/kernel/reporting'
require 'active_support/core_ext/kernel/singleton_class' require 'active_support/core_ext/kernel/singleton_class'
require 'active_support/core_ext/object/inclusion'
module ActiveSupport module ActiveSupport
# \Callbacks are code hooks that are run at key points in an object's lifecycle. # \Callbacks are code hooks that are run at key points in an object's lifecycle.
@ -353,7 +352,7 @@ module ActiveSupport
# CallbackChain. # CallbackChain.
# #
def __update_callbacks(name, filters = [], block = nil) #:nodoc: def __update_callbacks(name, filters = [], block = nil) #:nodoc:
type = filters.first.in?([:before, :after, :around]) ? filters.shift : :before type = [:before, :after, :around].include?(filters.first) ? filters.shift : :before
options = filters.last.is_a?(Hash) ? filters.pop : {} options = filters.last.is_a?(Hash) ? filters.pop : {}
filters.unshift(block) if block filters.unshift(block) if block

View file

@ -11,9 +11,6 @@
# Defines Object#blank? and Object#present?. # Defines Object#blank? and Object#present?.
require 'active_support/core_ext/object/blank' require 'active_support/core_ext/object/blank'
# Defines Object#in?.
require 'active_support/core_ext/object/inclusion'
# Rails own autoload, eager_load, etc. # Rails own autoload, eager_load, etc.
require 'active_support/dependencies/autoload' require 'active_support/dependencies/autoload'

View file

@ -1,6 +1,5 @@
require 'active_support/values/time_zone' require 'active_support/values/time_zone'
require 'active_support/core_ext/object/acts_like' require 'active_support/core_ext/object/acts_like'
require 'active_support/core_ext/object/inclusion'
module ActiveSupport 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
@ -339,7 +338,7 @@ module ActiveSupport
end end
def duration_of_variable_length?(obj) def duration_of_variable_length?(obj)
ActiveSupport::Duration === obj && obj.parts.any? {|p| p[0].in?([:years, :months, :days]) } ActiveSupport::Duration === obj && obj.parts.any? {|p| [:years, :months, :days].include?(p[0]) }
end end
def wrap_with_time_zone(time) def wrap_with_time_zone(time)

View file

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

View file

@ -1,5 +1,3 @@
require 'active_support/core_ext/object/inclusion'
module RedCloth::Formatters::HTML module RedCloth::Formatters::HTML
def emdash(opts) def emdash(opts)
"--" "--"

View file

@ -432,7 +432,7 @@ NOTE. If you are precompiling your assets locally, you can use +bundle install -
The default matcher for compiling files includes +application.js+, +application.css+ and all non-JS/CSS files (this will include all image assets automatically): The default matcher for compiling files includes +application.js+, +application.css+ and all non-JS/CSS files (this will include all image assets automatically):
<ruby> <ruby>
[ Proc.new{ |path| !File.extname(path).in?(['.js', '.css']) }, /application.(css|js)$/ ] [ Proc.new{ |path| !%w(.js .css).include?(File.extname(path)) }, /application.(css|js)$/ ]
</ruby> </ruby>
NOTE. The matcher (and other members of the precompile array; see below) is applied to final compiled file names. This means that anything that compiles to JS/CSS is excluded, as well as raw JS/CSS files; for example, +.coffee+ and +.scss+ files are *not* automatically included as they compile to JS/CSS. NOTE. The matcher (and other members of the precompile array; see below) is applied to final compiled file names. This means that anything that compiles to JS/CSS is excluded, as well as raw JS/CSS files; for example, +.coffee+ and +.scss+ files are *not* automatically included as they compile to JS/CSS.

View file

@ -49,7 +49,7 @@ module Rails
@assets = ActiveSupport::OrderedOptions.new @assets = ActiveSupport::OrderedOptions.new
@assets.enabled = false @assets.enabled = false
@assets.paths = [] @assets.paths = []
@assets.precompile = [ Proc.new{ |path| !File.extname(path).in?(['.js', '.css']) }, @assets.precompile = [ Proc.new { |path| !%w(.js .css).include?(File.extname(path)) },
/(?:\/|\\|\A)application\.(css|js)$/ ] /(?:\/|\\|\A)application\.(css|js)$/ ]
@assets.prefix = "/assets" @assets.prefix = "/assets"
@assets.version = '' @assets.version = ''

View file

@ -1,5 +1,3 @@
require 'active_support/core_ext/object/inclusion'
ARGV << '--help' if ARGV.empty? ARGV << '--help' if ARGV.empty?
aliases = { aliases = {
@ -71,7 +69,7 @@ when 'application', 'runner'
require "rails/commands/#{command}" require "rails/commands/#{command}"
when 'new' when 'new'
if ARGV.first.in?(['-h', '--help']) if %w(-h --help).include?(ARGV.first)
require 'rails/commands/application' require 'rails/commands/application'
else else
puts "Can't initialize a new Rails application within the directory of another, please change to a non-Rails directory first.\n" puts "Can't initialize a new Rails application within the directory of another, please change to a non-Rails directory first.\n"
@ -84,7 +82,7 @@ when '--version', '-v'
require 'rails/commands/application' require 'rails/commands/application'
else else
puts "Error: Command not recognized" unless command.in?(['-h', '--help']) puts "Error: Command not recognized" unless %w(-h --help).include?(command)
puts <<-EOT puts <<-EOT
Usage: rails COMMAND [ARGS] Usage: rails COMMAND [ARGS]

View file

@ -1,7 +1,6 @@
require 'rails/generators' require 'rails/generators'
require 'active_support/core_ext/object/inclusion'
if ARGV.first.in?([nil, "-h", "--help"]) if [nil, "-h", "--help"].include?(ARGV.first)
Rails::Generators.help 'destroy' Rails::Generators.help 'destroy'
exit exit
end end

View file

@ -1,7 +1,6 @@
require 'rails/generators' require 'rails/generators'
require 'active_support/core_ext/object/inclusion'
if ARGV.first.in?([nil, "-h", "--help"]) if [nil, "-h", "--help"].include?(ARGV.first)
Rails::Generators.help 'generate' Rails::Generators.help 'generate'
exit exit
end end

View file

@ -1,5 +1,3 @@
require 'active_support/core_ext/object/inclusion'
ARGV << '--help' if ARGV.empty? ARGV << '--help' if ARGV.empty?
aliases = { aliases = {
@ -25,7 +23,7 @@ when '--version', '-v'
require 'rails/commands/application' require 'rails/commands/application'
else else
puts "Error: Command not recognized" unless command.in?(['-h', '--help']) puts "Error: Command not recognized" unless %w(-h --help).include?(command)
puts <<-EOT puts <<-EOT
Usage: rails COMMAND [ARGS] Usage: rails COMMAND [ARGS]

View file

@ -8,7 +8,6 @@ rescue LoadError
end end
require 'rails/generators/actions' require 'rails/generators/actions'
require 'active_support/core_ext/object/inclusion'
module Rails module Rails
module Generators module Generators
@ -171,7 +170,7 @@ module Rails
names.each do |name| names.each do |name|
defaults = if options[:type] == :boolean defaults = if options[:type] == :boolean
{ } { }
elsif default_value_for_option(name, options).in?([true, false]) elsif [true, false].include?(default_value_for_option(name, options))
{ :banner => "" } { :banner => "" }
else else
{ :desc => "#{name.to_s.humanize} to be invoked", :banner => "NAME" } { :desc => "#{name.to_s.humanize} to be invoked", :banner => "NAME" }