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]
if config[:except]
!action.in?(config[:except])
!config[:except].include?(action)
elsif config[:only]
action.in?(config[:only])
config[:only].include?(action)
else
true
end

View File

@ -345,7 +345,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.in?(["cookies", "assigns"])
@html_document = nil unless method == 'cookies' || method == 'assigns'
integration_session.__send__(method, *args).tap do
copy_session_variables!
end

View File

@ -151,10 +151,11 @@ class RespondToController < ActionController::Base
protected
def set_layout
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"
case action_name
when "all_types_with_layout", "iphone_with_html_response_type"
"respond_to/layouts/standard"
when "iphone_with_html_response_type_without_layout"
"respond_to/layouts/missing"
end
end
end

View File

@ -1307,7 +1307,7 @@ class ResourcesTest < ActionController::TestCase
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}"
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}"
end
end
@ -1344,9 +1344,9 @@ class ResourcesTest < ActionController::TestCase
options = options.merge(:action => action.to_s)
path_options = { :path => path, :method => method }
if action.in?(Array(allowed))
if Array(allowed).include?(action)
assert_recognizes options, path_options
elsif action.in?(Array(not_allowed))
elsif Array(not_allowed).include?(action)
assert_not_recognizes options, path_options
end
end

View File

@ -511,7 +511,7 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
resources :todos, :id => /\d+/
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 '/cities', :to => 'countries#cities'
end

View File

@ -39,7 +39,7 @@ class ErbUtilTest < ActiveSupport::TestCase
def test_rest_in_ascii
(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)
end
end

View File

@ -2659,7 +2659,7 @@ class FormHelperTest < ActionView::TestCase
def hidden_fields(method = nil)
txt = %{<div style="margin:0;padding:0;display:inline">}
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}" />}
end
txt << %{</div>}

View File

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

View File

@ -15,7 +15,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.in?(['get','post'])
if method && !%w(get post).include?(method.to_s)
txt << %{<input name="_method" type="hidden" value="#{method}" />}
end
txt << %{</div>}

View File

@ -65,7 +65,7 @@ module ActiveModel
#
# class TitleValidator < ActiveModel::EachValidator
# 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
#

View File

@ -176,7 +176,7 @@ module ActiveRecord
def creation_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]
if reflection.options[:as]

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -453,7 +453,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
assert saved_post.tags.include?(new_tag)
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.")
@ -466,7 +466,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
new_post.save!
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.new.persisted?

View File

@ -47,13 +47,13 @@ module ActiveRecord
instance = @klass.new
@klass.column_names.each do |name|
assert !name.in?(instance.methods.map(&:to_s))
assert !instance.methods.map(&:to_s).include?(name)
end
@klass.define_attribute_methods
@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

View File

@ -94,7 +94,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.in?([0, nil])
assert [0, nil].include?(klass.columns_hash['omit'].default)
assert !klass.columns_hash['omit'].null
assert_raise(ActiveRecord::StatementInvalid) { klass.create! }

View File

@ -1,6 +1,5 @@
require 'active_support/core_ext/file/atomic'
require 'active_support/core_ext/string/conversions'
require 'active_support/core_ext/object/inclusion'
require 'uri/common'
module ActiveSupport
@ -23,7 +22,7 @@ module ActiveSupport
end
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)})
end
@ -151,7 +150,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.in?(EXCLUDED_DIRS)}.empty?
if Dir.entries(dir).reject {|f| EXCLUDED_DIRS.include?(f)}.empty?
File.delete(dir) rescue nil
delete_empty_directories(File.dirname(dir))
end
@ -165,7 +164,7 @@ module ActiveSupport
def search_dir(dir, &callback)
return if !File.exist?(dir)
Dir.foreach(dir) do |d|
next if d.in?(EXCLUDED_DIRS)
next if EXCLUDED_DIRS.include?(d)
name = File.join(dir, d)
if File.directory?(name)
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/kernel/reporting'
require 'active_support/core_ext/kernel/singleton_class'
require 'active_support/core_ext/object/inclusion'
module ActiveSupport
# \Callbacks are code hooks that are run at key points in an object's lifecycle.
@ -353,7 +352,7 @@ module ActiveSupport
# CallbackChain.
#
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 : {}
filters.unshift(block) if block

View File

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

View File

@ -1,6 +1,5 @@
require 'active_support/values/time_zone'
require 'active_support/core_ext/object/acts_like'
require 'active_support/core_ext/object/inclusion'
module ActiveSupport
# 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
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
def wrap_with_time_zone(time)

View File

@ -1,7 +1,6 @@
# encoding: utf-8
require 'abstract_unit'
require 'active_support/inflector/transliterate'
require 'active_support/core_ext/object/inclusion'
class TransliterateTest < ActiveSupport::TestCase
@ -16,7 +15,7 @@ class TransliterateTest < ActiveSupport::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.in?([0xD7, 0xF7])}.pack("U*")
string = (0xC0..0x17E).to_a.reject {|c| [0xD7, 0xF7].include?(c)}.pack("U*")
string.each_char do |char|
assert_match %r{^[a-zA-Z']*$}, ActiveSupport::Inflector.transliterate(string)
end

View File

@ -1,5 +1,3 @@
require 'active_support/core_ext/object/inclusion'
module RedCloth::Formatters::HTML
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):
<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>
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.enabled = false
@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)$/ ]
@assets.prefix = "/assets"
@assets.version = ''

View File

@ -1,5 +1,3 @@
require 'active_support/core_ext/object/inclusion'
ARGV << '--help' if ARGV.empty?
aliases = {
@ -71,7 +69,7 @@ when 'application', 'runner'
require "rails/commands/#{command}"
when 'new'
if ARGV.first.in?(['-h', '--help'])
if %w(-h --help).include?(ARGV.first)
require 'rails/commands/application'
else
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'
else
puts "Error: Command not recognized" unless command.in?(['-h', '--help'])
puts "Error: Command not recognized" unless %w(-h --help).include?(command)
puts <<-EOT
Usage: rails COMMAND [ARGS]

View File

@ -1,7 +1,6 @@
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'
exit
end

View File

@ -1,7 +1,6 @@
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'
exit
end

View File

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

View File

@ -8,7 +8,6 @@ rescue LoadError
end
require 'rails/generators/actions'
require 'active_support/core_ext/object/inclusion'
module Rails
module Generators
@ -171,7 +170,7 @@ module Rails
names.each do |name|
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 => "" }
else
{ :desc => "#{name.to_s.humanize} to be invoked", :banner => "NAME" }