From c91c26687265d3e7c62026a9f7986187f6da5033 Mon Sep 17 00:00:00 2001 From: Jean Boussier Date: Sun, 5 Sep 2021 16:29:32 +0200 Subject: [PATCH] Enable `Style/ExplicitBlockArgument` cop This reduce the stack size which is beneficial for exceptions performance. See: https://gist.github.com/byroot/cb3bcadcc3701c2518d002fb8d3a4e7a However the cop is unsafe because it might change the block arity, so it can run into some false positives. --- .rubocop.yml | 3 ++ .../connection/tagged_logger_proxy.rb | 4 +-- actioncable/lib/action_cable/server/worker.rb | 6 ++-- .../active_record_connection_management.rb | 4 +-- .../abstract_controller/caching/fragments.rb | 4 +-- .../metal/strong_parameters.rb | 2 +- .../lib/action_dispatch/http/mime_type.rb | 8 ++--- .../lib/action_dispatch/middleware/stack.rb | 4 +-- .../lib/action_dispatch/routing/mapper.rb | 36 +++++++++---------- .../lib/action_dispatch/routing/route_set.rb | 4 +-- .../test/controller/live_stream_test.rb | 4 +-- actionpack/test/controller/render_test.rb | 4 +-- .../request_forgery_protection_test.rb | 22 +++++------- .../lib/action_view/helpers/text_helper.rb | 4 +-- actionview/test/lib/controller/fake_models.rb | 4 +-- activejob/lib/active_job/logging.rb | 4 +-- activejob/test/cases/logging_test.rb | 6 ++-- .../associations/has_one_association.rb | 4 +-- .../abstract/database_statements.rb | 4 +-- .../connection_adapters/abstract_adapter.rb | 6 ++-- .../connection_adapters/mysql2_adapter.rb | 6 ++-- activerecord/lib/active_record/fixtures.rb | 4 +-- .../middleware/database_selector/resolver.rb | 10 ++---- activerecord/lib/active_record/migration.rb | 26 +++++++------- .../migration/command_recorder.rb | 4 +-- activerecord/lib/active_record/relation.rb | 10 +++--- .../lib/active_record/relation/batches.rb | 4 +-- .../relation/batches/batch_enumerator.rb | 8 ++--- .../active_record/relation/query_methods.rb | 6 ++-- activerecord/lib/active_record/result.rb | 4 +-- .../lib/active_record/scoping/default.rb | 4 +-- activerecord/test/cases/explain_test.rb | 6 ++-- activerecord/test/cases/locking_test.rb | 4 +-- activerecord/test/cases/migration_test.rb | 6 ++-- activerecord/test/cases/query_cache_test.rb | 6 ++-- .../test/cases/tasks/database_tasks_test.rb | 30 ++++++---------- .../test/cases/tasks/mysql_rake_test.rb | 18 ++++------ .../test/cases/tasks/postgresql_rake_test.rb | 18 ++++------ activerecord/test/cases/test_case.rb | 4 +-- activestorage/test/models/attachment_test.rb | 6 ++-- .../lib/active_support/benchmarkable.rb | 4 +-- .../cache/strategy/local_cache.rb | 8 ++--- .../load_interlock_aware_monitor.rb | 6 ++-- .../active_support/concurrency/share_lock.rb | 4 +-- .../active_support/core_ext/array/grouping.rb | 12 +++---- .../core_ext/kernel/reporting.rb | 8 ++--- .../lib/active_support/dependencies.rb | 12 +++---- .../active_support/dependencies/interlock.rb | 24 +++++-------- activesupport/lib/active_support/test_case.rb | 8 ++--- .../testing/method_call_assertions.rb | 8 ++--- .../lib/active_support/testing/stream.rb | 6 ++-- .../test/core_ext/enumerable_test.rb | 4 +-- railties/lib/rails/mailers_controller.rb | 6 ++-- railties/test/commands/dbconsole_test.rb | 6 ++-- railties/test/env_helpers.rb | 12 +++---- .../test/generators/app_generator_test.rb | 6 ++-- 56 files changed, 188 insertions(+), 267 deletions(-) diff --git a/.rubocop.yml b/.rubocop.yml index 15a16a54c95d1..d92b9a9f77d30 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -143,6 +143,9 @@ Style/DefWithParentheses: Style/MethodDefParentheses: Enabled: true +Style/ExplicitBlockArgument: + Enabled: true + Style/FrozenStringLiteralComment: Enabled: true EnforcedStyle: always diff --git a/actioncable/lib/action_cable/connection/tagged_logger_proxy.rb b/actioncable/lib/action_cable/connection/tagged_logger_proxy.rb index 85831806a94c8..c7a0f07b19eb6 100644 --- a/actioncable/lib/action_cable/connection/tagged_logger_proxy.rb +++ b/actioncable/lib/action_cable/connection/tagged_logger_proxy.rb @@ -18,10 +18,10 @@ def add_tags(*tags) @tags = @tags.uniq end - def tag(logger) + def tag(logger, &block) if logger.respond_to?(:tagged) current_tags = tags - logger.formatter.current_tags - logger.tagged(*current_tags) { yield } + logger.tagged(*current_tags, &block) else yield end diff --git a/actioncable/lib/action_cable/server/worker.rb b/actioncable/lib/action_cable/server/worker.rb index e9b130e5f0040..e1b75d4a69f0f 100644 --- a/actioncable/lib/action_cable/server/worker.rb +++ b/actioncable/lib/action_cable/server/worker.rb @@ -36,12 +36,10 @@ def stopping? @executor.shuttingdown? end - def work(connection) + def work(connection, &block) self.connection = connection - run_callbacks :work do - yield - end + run_callbacks :work, &block ensure self.connection = nil end diff --git a/actioncable/lib/action_cable/server/worker/active_record_connection_management.rb b/actioncable/lib/action_cable/server/worker/active_record_connection_management.rb index 2e378d4bf317b..63f20fa34dd59 100644 --- a/actioncable/lib/action_cable/server/worker/active_record_connection_management.rb +++ b/actioncable/lib/action_cable/server/worker/active_record_connection_management.rb @@ -12,8 +12,8 @@ module ActiveRecordConnectionManagement end end - def with_database_connections - connection.logger.tag(ActiveRecord::Base.logger) { yield } + def with_database_connections(&block) + connection.logger.tag(ActiveRecord::Base.logger, &block) end end end diff --git a/actionpack/lib/abstract_controller/caching/fragments.rb b/actionpack/lib/abstract_controller/caching/fragments.rb index 18677ddd18ee5..4b0881814b3fd 100644 --- a/actionpack/lib/abstract_controller/caching/fragments.rb +++ b/actionpack/lib/abstract_controller/caching/fragments.rb @@ -142,8 +142,8 @@ def expire_fragment(key, options = nil) end end - def instrument_fragment_cache(name, key) # :nodoc: - ActiveSupport::Notifications.instrument("#{name}.#{instrument_name}", instrument_payload(key)) { yield } + def instrument_fragment_cache(name, key, &block) # :nodoc: + ActiveSupport::Notifications.instrument("#{name}.#{instrument_name}", instrument_payload(key), &block) end end end diff --git a/actionpack/lib/action_controller/metal/strong_parameters.rb b/actionpack/lib/action_controller/metal/strong_parameters.rb index 9a2655afee86e..ac5601452c2cc 100644 --- a/actionpack/lib/action_controller/metal/strong_parameters.rb +++ b/actionpack/lib/action_controller/metal/strong_parameters.rb @@ -940,7 +940,7 @@ def convert_value_to_parameters(value) def each_element(object, &block) case object when Array - object.grep(Parameters).filter_map { |el| yield el } + object.grep(Parameters).filter_map(&block) when Parameters if object.nested_attributes? object.each_nested_attribute(&block) diff --git a/actionpack/lib/action_dispatch/http/mime_type.rb b/actionpack/lib/action_dispatch/http/mime_type.rb index a5bde2dc87f2f..57d12e73f0a13 100644 --- a/actionpack/lib/action_dispatch/http/mime_type.rb +++ b/actionpack/lib/action_dispatch/http/mime_type.rb @@ -13,8 +13,8 @@ def initialize @symbols = [] end - def each - @mimes.each { |x| yield x } + def each(&block) + @mimes.each(&block) end def <<(type) @@ -42,9 +42,9 @@ def [](type) Type.lookup_by_extension(type) end - def fetch(type) + def fetch(type, &block) return type if type.is_a?(Type) - EXTENSION_LOOKUP.fetch(type.to_s) { |k| yield k } + EXTENSION_LOOKUP.fetch(type.to_s, &block) end end diff --git a/actionpack/lib/action_dispatch/middleware/stack.rb b/actionpack/lib/action_dispatch/middleware/stack.rb index 2136b2a5b2787..8b154bd326c92 100644 --- a/actionpack/lib/action_dispatch/middleware/stack.rb +++ b/actionpack/lib/action_dispatch/middleware/stack.rb @@ -83,8 +83,8 @@ def initialize(*args) yield(self) if block_given? end - def each - @middlewares.each { |x| yield x } + def each(&block) + @middlewares.each(&block) end def size diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 4aa26b675b693..7851b9eb1e5d6 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -922,7 +922,7 @@ def controller(controller) # namespace :admin, as: "sekret" do # resources :posts # end - def namespace(path, options = {}) + def namespace(path, options = {}, &block) path = path.to_s defaults = { @@ -933,7 +933,7 @@ def namespace(path, options = {}) } path_scope(options.delete(:path) { path }) do - scope(defaults.merge!(options)) { yield } + scope(defaults.merge!(options), &block) end end @@ -992,8 +992,8 @@ def namespace(path, options = {}) # constraints(Iphone) do # resources :iphones # end - def constraints(constraints = {}) - scope(constraints: constraints) { yield } + def constraints(constraints = {}, &block) + scope(constraints: constraints, &block) end # Allows you to set default parameters for a route, such as this: @@ -1493,15 +1493,13 @@ def resources(*resources, &block) # with GET, and route to the search action of +PhotosController+. It will also # create the search_photos_url and search_photos_path # route helpers. - def collection + def collection(&block) unless resource_scope? raise ArgumentError, "can't use collection outside resource(s) scope" end with_scope_level(:collection) do - path_scope(parent_resource.collection_scope) do - yield - end + path_scope(parent_resource.collection_scope, &block) end end @@ -1516,7 +1514,7 @@ def collection # This will recognize /photos/1/preview with GET, and route to the # preview action of +PhotosController+. It will also create the # preview_photo_url and preview_photo_path helpers. - def member + def member(&block) unless resource_scope? raise ArgumentError, "can't use member outside resource(s) scope" end @@ -1524,27 +1522,25 @@ def member with_scope_level(:member) do if shallow? shallow_scope { - path_scope(parent_resource.member_scope) { yield } + path_scope(parent_resource.member_scope, &block) } else - path_scope(parent_resource.member_scope) { yield } + path_scope(parent_resource.member_scope, &block) end end end - def new + def new(&block) unless resource_scope? raise ArgumentError, "can't use new outside resource(s) scope" end with_scope_level(:new) do - path_scope(parent_resource.new_scope(action_path(:new))) do - yield - end + path_scope(parent_resource.new_scope(action_path(:new)), &block) end end - def nested + def nested(&block) unless resource_scope? raise ArgumentError, "can't use nested outside resource(s) scope" end @@ -1553,12 +1549,12 @@ def nested if shallow? && shallow_nesting_depth >= 1 shallow_scope do path_scope(parent_resource.nested_scope) do - scope(nested_options) { yield } + scope(nested_options, &block) end end else path_scope(parent_resource.nested_scope) do - scope(nested_options) { yield } + scope(nested_options, &block) end end end @@ -1744,10 +1740,10 @@ def with_scope_level(kind) # :doc: @scope = @scope.parent end - def resource_scope(resource) + def resource_scope(resource, &block) @scope = @scope.new(scope_level_resource: resource) - controller(resource.resource_scope) { yield } + controller(resource.resource_scope, &block) ensure @scope = @scope.parent end diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index 3906e936ad494..8cda69274fbf8 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -131,8 +131,8 @@ def key?(name) alias [] get alias clear clear! - def each - routes.each { |name, route| yield name, route } + def each(&block) + routes.each(&block) self end diff --git a/actionpack/test/controller/live_stream_test.rb b/actionpack/test/controller/live_stream_test.rb index a9c73236553b3..d6f9ad9f69246 100644 --- a/actionpack/test/controller/live_stream_test.rb +++ b/actionpack/test/controller/live_stream_test.rb @@ -314,8 +314,8 @@ def capture_log_output def setup super - def @controller.new_controller_thread - Thread.new { yield } + def @controller.new_controller_thread(&block) + Thread.new(&block) end end diff --git a/actionpack/test/controller/render_test.rb b/actionpack/test/controller/render_test.rb index f33b6e458acf3..3416f1e072668 100644 --- a/actionpack/test/controller/render_test.rb +++ b/actionpack/test/controller/render_test.rb @@ -987,8 +987,8 @@ class LiveHeadRenderTest < ActionController::TestCase def setup super - def @controller.new_controller_thread - Thread.new { yield } + def @controller.new_controller_thread(&block) + Thread.new(&block) end def @controller.response_body=(body) diff --git a/actionpack/test/controller/request_forgery_protection_test.rb b/actionpack/test/controller/request_forgery_protection_test.rb index 6951147600487..265dae382a966 100644 --- a/actionpack/test/controller/request_forgery_protection_test.rb +++ b/actionpack/test/controller/request_forgery_protection_test.rb @@ -634,14 +634,12 @@ def assert_not_blocked(&block) assert_response :success end - def assert_cross_origin_blocked - assert_raises(ActionController::InvalidCrossOriginRequest) do - yield - end + def assert_cross_origin_blocked(&block) + assert_raises(ActionController::InvalidCrossOriginRequest, &block) end - def assert_cross_origin_not_blocked - assert_not_blocked { yield } + def assert_cross_origin_not_blocked(&block) + assert_not_blocked(&block) end def forgery_protection_origin_check @@ -701,10 +699,8 @@ def setup class RequestForgeryProtectionControllerUsingExceptionTest < ActionController::TestCase include RequestForgeryProtectionTests - def assert_blocked - assert_raises(ActionController::InvalidAuthenticityToken) do - yield - end + def assert_blocked(&block) + assert_raises(ActionController::InvalidAuthenticityToken, &block) end def test_raised_exception_message_explains_why_it_occurred @@ -1105,10 +1101,8 @@ def test_should_allow_post_without_token_when_skipping assert_not_blocked { post :index } end - def assert_blocked - assert_raises(ActionController::InvalidAuthenticityToken) do - yield - end + def assert_blocked(&block) + assert_raises(ActionController::InvalidAuthenticityToken, &block) end def assert_not_blocked(&block) diff --git a/actionview/lib/action_view/helpers/text_helper.rb b/actionview/lib/action_view/helpers/text_helper.rb index db8e2bc43f9c9..98d28bd5b59be 100644 --- a/actionview/lib/action_view/helpers/text_helper.rb +++ b/actionview/lib/action_view/helpers/text_helper.rb @@ -133,7 +133,7 @@ def truncate(text, options = {}, &block) # # highlight('ruby on rails', 'rails', sanitize: false) # # => ruby on rails - def highlight(text, phrases, options = {}) + def highlight(text, phrases, options = {}, &block) text = sanitize(text) if options.fetch(:sanitize, true) if text.blank? || phrases.blank? @@ -144,7 +144,7 @@ def highlight(text, phrases, options = {}) end.join("|") if block_given? - text.gsub(/(#{match})(?![^<]*?>)/i) { |found| yield found } + text.gsub(/(#{match})(?![^<]*?>)/i, &block) else highlighter = options.fetch(:highlighter, '\1') text.gsub(/(#{match})(?![^<]*?>)/i, highlighter) diff --git a/actionview/test/lib/controller/fake_models.rb b/actionview/test/lib/controller/fake_models.rb index f8b7ddaecca4e..1a93b5253bb75 100644 --- a/actionview/test/lib/controller/fake_models.rb +++ b/actionview/test/lib/controller/fake_models.rb @@ -183,9 +183,9 @@ class ArelLike def to_ary true end - def each + def each(&block) a = Array.new(2) { |id| Comment.new(id + 1) } - a.each { |i| yield i } + a.each(&block) end end diff --git a/activejob/lib/active_job/logging.rb b/activejob/lib/active_job/logging.rb index 68eed8e179d40..65f89e863fed7 100644 --- a/activejob/lib/active_job/logging.rb +++ b/activejob/lib/active_job/logging.rb @@ -19,10 +19,10 @@ def perform_now end private - def tag_logger(*tags) + def tag_logger(*tags, &block) if logger.respond_to?(:tagged) tags.unshift "ActiveJob" unless logger_tagged_by_active_job? - logger.tagged(*tags) { yield } + logger.tagged(*tags, &block) else yield end diff --git a/activejob/test/cases/logging_test.rb b/activejob/test/cases/logging_test.rb index d012002839f5d..ae70bfad43023 100644 --- a/activejob/test/cases/logging_test.rb +++ b/activejob/test/cases/logging_test.rb @@ -49,11 +49,9 @@ def set_logger(logger) ActiveJob::Base.logger = logger end - def subscribed + def subscribed(&block) [].tap do |events| - ActiveSupport::Notifications.subscribed(-> (*args) { events << args }, /enqueue.*\.active_job/) do - yield - end + ActiveSupport::Notifications.subscribed(-> (*args) { events << args }, /enqueue.*\.active_job/, &block) end end diff --git a/activerecord/lib/active_record/associations/has_one_association.rb b/activerecord/lib/active_record/associations/has_one_association.rb index f1ee999c8616c..5254bed90f148 100644 --- a/activerecord/lib/active_record/associations/has_one_association.rb +++ b/activerecord/lib/active_record/associations/has_one_association.rb @@ -115,9 +115,9 @@ def nullify_owner_attributes(record) record[reflection.foreign_key] = nil end - def transaction_if(value) + def transaction_if(value, &block) if value - reflection.klass.transaction { yield } + reflection.klass.transaction(&block) else yield end diff --git a/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb b/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb index 82e0d8e6134b1..82249159b91ab 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb @@ -306,14 +306,14 @@ def truncate_tables(*table_names) # :nodoc: # # The mysql2 and postgresql adapters support setting the transaction # isolation level. - def transaction(requires_new: nil, isolation: nil, joinable: true) + def transaction(requires_new: nil, isolation: nil, joinable: true, &block) if !requires_new && current_transaction.joinable? if isolation raise ActiveRecord::TransactionIsolationError, "cannot set isolation when joining a transaction" end yield else - transaction_manager.within_new_transaction(isolation: isolation, joinable: joinable) { yield } + transaction_manager.within_new_transaction(isolation: isolation, joinable: joinable, &block) end rescue ActiveRecord::Rollback # rollbacks are silently swallowed diff --git a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb index afc89c2b593ef..84052d4ecdcd8 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb @@ -723,7 +723,7 @@ def translate_exception_class(e, sql, binds) exception end - def log(sql, name = "SQL", binds = [], type_casted_binds = [], statement_name = nil, async: false) # :doc: + def log(sql, name = "SQL", binds = [], type_casted_binds = [], statement_name = nil, async: false, &block) # :doc: @instrumenter.instrument( "sql.active_record", sql: sql, @@ -733,9 +733,7 @@ def log(sql, name = "SQL", binds = [], type_casted_binds = [], statement_name = statement_name: statement_name, async: async, connection: self) do - @lock.synchronize do - yield - end + @lock.synchronize(&block) rescue => e raise translate_exception_class(e, sql, binds) end diff --git a/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb index 1d13fcc477876..9b915f44125b9 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb @@ -89,11 +89,9 @@ def supports_lazy_transactions? # HELPER METHODS =========================================== - def each_hash(result) # :nodoc: + def each_hash(result, &block) # :nodoc: if block_given? - result.each(as: :hash, symbolize_keys: true) do |row| - yield row - end + result.each(as: :hash, symbolize_keys: true, &block) else to_enum(:each_hash, result) end diff --git a/activerecord/lib/active_record/fixtures.rb b/activerecord/lib/active_record/fixtures.rb index 1ce5ee5f6f74e..de796c22741c0 100644 --- a/activerecord/lib/active_record/fixtures.rb +++ b/activerecord/lib/active_record/fixtures.rb @@ -764,8 +764,8 @@ def class_name model_class.name if model_class end - def each - fixture.each { |item| yield item } + def each(&block) + fixture.each(&block) end def [](key) diff --git a/activerecord/lib/active_record/middleware/database_selector/resolver.rb b/activerecord/lib/active_record/middleware/database_selector/resolver.rb index 7d255d4d61d12..ef5a7aedca232 100644 --- a/activerecord/lib/active_record/middleware/database_selector/resolver.rb +++ b/activerecord/lib/active_record/middleware/database_selector/resolver.rb @@ -51,21 +51,17 @@ def update_context(response) private def read_from_primary(&blk) ActiveRecord::Base.connected_to(role: ActiveRecord.writing_role, prevent_writes: true) do - instrumenter.instrument("database_selector.active_record.read_from_primary") do - yield - end + instrumenter.instrument("database_selector.active_record.read_from_primary", &blk) end end def read_from_replica(&blk) ActiveRecord::Base.connected_to(role: ActiveRecord.reading_role, prevent_writes: true) do - instrumenter.instrument("database_selector.active_record.read_from_replica") do - yield - end + instrumenter.instrument("database_selector.active_record.read_from_replica", &blk) end end - def write_to_primary(&blk) + def write_to_primary ActiveRecord::Base.connected_to(role: ActiveRecord.writing_role, prevent_writes: false) do instrumenter.instrument("database_selector.active_record.wrote_to_primary") do yield diff --git a/activerecord/lib/active_record/migration.rb b/activerecord/lib/active_record/migration.rb index 99357f3f1af52..4b571ce68f14a 100644 --- a/activerecord/lib/active_record/migration.rb +++ b/activerecord/lib/active_record/migration.rb @@ -728,16 +728,16 @@ def initialize(name = self.class.name, version = nil) # end # # This command can be nested. - def revert(*migration_classes) + def revert(*migration_classes, &block) run(*migration_classes.reverse, revert: true) unless migration_classes.empty? if block_given? if connection.respond_to? :revert - connection.revert { yield } + connection.revert(&block) else recorder = command_recorder @connection = recorder suppress_messages do - connection.revert { yield } + connection.revert(&block) end @connection = recorder.delegate recorder.replay(self) @@ -804,8 +804,8 @@ def reversible # end # end # end - def up_only - execute_block { yield } unless reverting? + def up_only(&block) + execute_block(&block) unless reverting? end # Runs the given migration classes. @@ -1106,9 +1106,9 @@ def forward(steps = 1) # :nodoc: move(:up, steps) end - def up(target_version = nil) # :nodoc: + def up(target_version = nil, &block) # :nodoc: selected_migrations = if block_given? - migrations.select { |m| yield m } + migrations.select(&block) else migrations end @@ -1116,9 +1116,9 @@ def up(target_version = nil) # :nodoc: Migrator.new(:up, selected_migrations, schema_migration, target_version).migrate end - def down(target_version = nil) # :nodoc: + def down(target_version = nil, &block) # :nodoc: selected_migrations = if block_given? - migrations.select { |m| yield m } + migrations.select(&block) else migrations end @@ -1405,9 +1405,9 @@ def down? end # Wrap the migration in a transaction only if supported by the adapter. - def ddl_transaction(migration) + def ddl_transaction(migration, &block) if use_transaction?(migration) - Base.transaction { yield } + Base.transaction(&block) else yield end @@ -1438,12 +1438,12 @@ def with_advisory_lock end end - def with_advisory_lock_connection + def with_advisory_lock_connection(&block) pool = ActiveRecord::ConnectionAdapters::ConnectionHandler.new.establish_connection( ActiveRecord::Base.connection_db_config ) - pool.with_connection { |connection| yield(connection) } + pool.with_connection(&block) ensure pool&.disconnect! end diff --git a/activerecord/lib/active_record/migration/command_recorder.rb b/activerecord/lib/active_record/migration/command_recorder.rb index 9732f171b7329..4208d80d7418a 100644 --- a/activerecord/lib/active_record/migration/command_recorder.rb +++ b/activerecord/lib/active_record/migration/command_recorder.rb @@ -154,9 +154,9 @@ def invert_#{method}(args, &block) # def invert_create_table(args, &block) include StraightReversions - def invert_transaction(args) + def invert_transaction(args, &block) sub_recorder = CommandRecorder.new(delegate) - sub_recorder.revert { yield } + sub_recorder.revert(&block) invertions_proc = proc { sub_recorder.replay(self) diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb index 9fc8e45efd12e..0dc3406c4cb61 100644 --- a/activerecord/lib/active_record/relation.rb +++ b/activerecord/lib/active_record/relation.rb @@ -424,14 +424,14 @@ def cache_key_with_version # # Please check unscoped if you want to remove all previous scopes (including # the default_scope) during the execution of a block. - def scoping(all_queries: nil) + def scoping(all_queries: nil, &block) registry = klass.scope_registry if global_scope?(registry) && all_queries == false raise ArgumentError, "Scoping is set to apply to all queries and cannot be unset in a nested block." elsif already_in_scope?(registry) yield else - _scoping(self, registry, all_queries) { yield } + _scoping(self, registry, all_queries, &block) end end @@ -935,11 +935,9 @@ def instantiate_records(rows, &block) end end - def skip_query_cache_if_necessary + def skip_query_cache_if_necessary(&block) if skip_query_cache_value - uncached do - yield - end + uncached(&block) else yield end diff --git a/activerecord/lib/active_record/relation/batches.rb b/activerecord/lib/active_record/relation/batches.rb index bce3862a7f11b..6d8bdccb67ec4 100644 --- a/activerecord/lib/active_record/relation/batches.rb +++ b/activerecord/lib/active_record/relation/batches.rb @@ -65,10 +65,10 @@ module Batches # # NOTE: By its nature, batch processing is subject to race conditions if # other processes are modifying the database. - def find_each(start: nil, finish: nil, batch_size: 1000, error_on_ignore: nil, order: :asc) + def find_each(start: nil, finish: nil, batch_size: 1000, error_on_ignore: nil, order: :asc, &block) if block_given? find_in_batches(start: start, finish: finish, batch_size: batch_size, error_on_ignore: error_on_ignore, order: order) do |records| - records.each { |record| yield record } + records.each(&block) end else enum_for(:find_each, start: start, finish: finish, batch_size: batch_size, error_on_ignore: error_on_ignore, order: order) do diff --git a/activerecord/lib/active_record/relation/batches/batch_enumerator.rb b/activerecord/lib/active_record/relation/batches/batch_enumerator.rb index 5f33df7d8b730..8b734da62a947 100644 --- a/activerecord/lib/active_record/relation/batches/batch_enumerator.rb +++ b/activerecord/lib/active_record/relation/batches/batch_enumerator.rb @@ -47,11 +47,11 @@ def batch_size # Person.in_batches.each_record.with_index do |person, index| # person.award_trophy(index + 1) # end - def each_record + def each_record(&block) return to_enum(:each_record) unless block_given? @relation.to_enum(:in_batches, of: @of, start: @start, finish: @finish, load: true).each do |relation| - relation.records.each { |record| yield record } + relation.records.each(&block) end end @@ -89,9 +89,9 @@ def destroy_all # Person.in_batches.each do |relation| # relation.update_all(awesome: true) # end - def each + def each(&block) enum = @relation.to_enum(:in_batches, of: @of, start: @start, finish: @finish, load: false) - return enum.each { |relation| yield relation } if block_given? + return enum.each(&block) if block_given? enum end end diff --git a/activerecord/lib/active_record/relation/query_methods.rb b/activerecord/lib/active_record/relation/query_methods.rb index ef3dc7e476043..b60d8b0932507 100644 --- a/activerecord/lib/active_record/relation/query_methods.rb +++ b/activerecord/lib/active_record/relation/query_methods.rb @@ -1295,11 +1295,9 @@ def lookup_table_klass_from_join_dependencies(table_name) nil end - def each_join_dependencies(join_dependencies = build_join_dependencies) + def each_join_dependencies(join_dependencies = build_join_dependencies, &block) join_dependencies.each do |join_dependency| - join_dependency.each do |join| - yield join - end + join_dependency.each(&block) end end diff --git a/activerecord/lib/active_record/result.rb b/activerecord/lib/active_record/result.rb index c00665ad79256..eeab8aae61095 100644 --- a/activerecord/lib/active_record/result.rb +++ b/activerecord/lib/active_record/result.rb @@ -64,9 +64,9 @@ def length # row as parameter. # # Returns an +Enumerator+ if no block is given. - def each + def each(&block) if block_given? - hash_rows.each { |row| yield row } + hash_rows.each(&block) else hash_rows.to_enum { @rows.size } end diff --git a/activerecord/lib/active_record/scoping/default.rb b/activerecord/lib/active_record/scoping/default.rb index 5ce7571fd57fe..ba1d5a8ed0bda 100644 --- a/activerecord/lib/active_record/scoping/default.rb +++ b/activerecord/lib/active_record/scoping/default.rb @@ -39,8 +39,8 @@ module ClassMethods # Post.unscoped { # Post.limit(10) # Fires "SELECT * FROM posts LIMIT 10" # } - def unscoped - block_given? ? relation.scoping { yield } : relation + def unscoped(&block) + block_given? ? relation.scoping(&block) : relation end # Are there attributes associated with this scope? diff --git a/activerecord/test/cases/explain_test.rb b/activerecord/test/cases/explain_test.rb index 2ee8c8f4c60d6..59e73aeea5f5a 100644 --- a/activerecord/test/cases/explain_test.rb +++ b/activerecord/test/cases/explain_test.rb @@ -64,12 +64,10 @@ def test_exec_explain_with_binds end private - def stub_explain_for_query_plans(query_plans = ["query plan foo", "query plan bar"]) + def stub_explain_for_query_plans(query_plans = ["query plan foo", "query plan bar"], &block) explain_called = 0 - connection.stub(:explain, proc { explain_called += 1; query_plans[explain_called - 1] }) do - yield - end + connection.stub(:explain, proc { explain_called += 1; query_plans[explain_called - 1] }, &block) end def bind_param(name, value) diff --git a/activerecord/test/cases/locking_test.rb b/activerecord/test/cases/locking_test.rb index 06075a77fa09a..d523718bf4045 100644 --- a/activerecord/test/cases/locking_test.rb +++ b/activerecord/test/cases/locking_test.rb @@ -755,7 +755,7 @@ def test_no_locks_no_wait end private - def duel(zzz = 5) + def duel(zzz = 5, &block) t0, t1, t2, t3 = nil, nil, nil, nil a = Thread.new do @@ -770,7 +770,7 @@ def duel(zzz = 5) b = Thread.new do sleep zzz / 2.0 # ensure thread 1 tx starts first t2 = Time.now - Person.transaction { yield } + Person.transaction(&block) t3 = Time.now end diff --git a/activerecord/test/cases/migration_test.rb b/activerecord/test/cases/migration_test.rb index 57afea8ef6969..530f1f783361e 100644 --- a/activerecord/test/cases/migration_test.rb +++ b/activerecord/test/cases/migration_test.rb @@ -1376,13 +1376,11 @@ def test_changing_index end private - def with_bulk_change_table + def with_bulk_change_table(&block) # Reset columns/indexes cache as we're changing the table @columns = @indexes = nil - Person.connection.change_table(:delete_me, bulk: true) do |t| - yield t - end + Person.connection.change_table(:delete_me, bulk: true, &block) end def column(name) diff --git a/activerecord/test/cases/query_cache_test.rb b/activerecord/test/cases/query_cache_test.rb index ec0353ff110ab..40d23865e910b 100644 --- a/activerecord/test/cases/query_cache_test.rb +++ b/activerecord/test/cases/query_cache_test.rb @@ -759,13 +759,11 @@ def test_clear_query_cache_is_called_on_all_connections end private - def with_temporary_connection_pool + def with_temporary_connection_pool(&block) pool_config = ActiveRecord::Base.connection_handler.send(:owner_to_pool_manager).fetch("ActiveRecord::Base").get_pool_config(ActiveRecord.writing_role, :default) new_pool = ActiveRecord::ConnectionAdapters::ConnectionPool.new(pool_config) - pool_config.stub(:pool, new_pool) do - yield - end + pool_config.stub(:pool, new_pool, &block) end def middleware(&app) diff --git a/activerecord/test/cases/tasks/database_tasks_test.rb b/activerecord/test/cases/tasks/database_tasks_test.rb index 6f0cd7f944ac2..9ba730f02236f 100644 --- a/activerecord/test/cases/tasks/database_tasks_test.rb +++ b/activerecord/test/cases/tasks/database_tasks_test.rb @@ -30,12 +30,10 @@ def teardown $stdout, $stderr = @original_stdout, @original_stderr end - def with_stubbed_new + def with_stubbed_new(&block) ActiveRecord::Tasks::MySQLDatabaseTasks.stub(:new, @mysql_tasks) do ActiveRecord::Tasks::PostgreSQLDatabaseTasks.stub(:new, @postgresql_tasks) do - ActiveRecord::Tasks::SQLiteDatabaseTasks.stub(:new, @sqlite_tasks) do - yield - end + ActiveRecord::Tasks::SQLiteDatabaseTasks.stub(:new, @sqlite_tasks, &block) end end end @@ -154,13 +152,11 @@ def test_current_config_read_after_set end private - def with_stubbed_configurations + def with_stubbed_configurations(&block) old_configurations = ActiveRecord::Base.configurations ActiveRecord::Base.configurations = { "production" => { "exists" => { "database" => "my-db" } } } - assert_deprecated do - yield - end + assert_deprecated(&block) ensure ActiveRecord::Base.configurations = old_configurations assert_deprecated do @@ -392,15 +388,13 @@ def test_creates_configurations_with_blank_hosts end private - def with_stubbed_configurations_establish_connection + def with_stubbed_configurations_establish_connection(&block) old_configurations = ActiveRecord::Base.configurations ActiveRecord::Base.configurations = @configurations # To refrain from connecting to a newly created empty DB in # sqlite3_mem tests - ActiveRecord::Base.connection_handler.stub(:establish_connection, nil) do - yield - end + ActiveRecord::Base.connection_handler.stub(:establish_connection, nil, &block) ensure ActiveRecord::Base.configurations = old_configurations end @@ -520,13 +514,11 @@ def config_for(env_name, name) ActiveRecord::Base.configurations.configs_for(env_name: env_name, name: name) end - def with_stubbed_configurations_establish_connection + def with_stubbed_configurations_establish_connection(&block) old_configurations = ActiveRecord::Base.configurations ActiveRecord::Base.configurations = @configurations - ActiveRecord::Base.connection_handler.stub(:establish_connection, nil) do - yield - end + ActiveRecord::Base.connection_handler.stub(:establish_connection, nil, &block) ensure ActiveRecord::Base.configurations = old_configurations end @@ -637,13 +629,11 @@ def config_for(env_name, name) ActiveRecord::Base.configurations.configs_for(env_name: env_name, name: name) end - def with_stubbed_configurations_establish_connection + def with_stubbed_configurations_establish_connection(&block) old_configurations = ActiveRecord::Base.configurations ActiveRecord::Base.configurations = @configurations - ActiveRecord::Base.connection_handler.stub(:establish_connection, nil) do - yield - end + ActiveRecord::Base.connection_handler.stub(:establish_connection, nil, &block) ensure ActiveRecord::Base.configurations = old_configurations end diff --git a/activerecord/test/cases/tasks/mysql_rake_test.rb b/activerecord/test/cases/tasks/mysql_rake_test.rb index cf87f00c8a4b8..8996e0460901a 100644 --- a/activerecord/test/cases/tasks/mysql_rake_test.rb +++ b/activerecord/test/cases/tasks/mysql_rake_test.rb @@ -107,11 +107,9 @@ def test_create_when_database_exists_outputs_info_to_stderr end private - def with_stubbed_connection_establish_connection + def with_stubbed_connection_establish_connection(&block) ActiveRecord::Base.stub(:establish_connection, nil) do - ActiveRecord::Base.stub(:connection, @connection) do - yield - end + ActiveRecord::Base.stub(:connection, @connection, &block) end end end @@ -188,11 +186,9 @@ def test_when_database_dropped_successfully_outputs_info_to_stdout end private - def with_stubbed_connection_establish_connection + def with_stubbed_connection_establish_connection(&block) ActiveRecord::Base.stub(:establish_connection, nil) do - ActiveRecord::Base.stub(:connection, @connection) do - yield - end + ActiveRecord::Base.stub(:connection, @connection, &block) end end end @@ -242,11 +238,9 @@ def test_recreates_database_with_the_given_options end private - def with_stubbed_connection_establish_connection + def with_stubbed_connection_establish_connection(&block) ActiveRecord::Base.stub(:establish_connection, nil) do - ActiveRecord::Base.stub(:connection, @connection) do - yield - end + ActiveRecord::Base.stub(:connection, @connection, &block) end end end diff --git a/activerecord/test/cases/tasks/postgresql_rake_test.rb b/activerecord/test/cases/tasks/postgresql_rake_test.rb index 38efdb45d11d0..e077778f2f405 100644 --- a/activerecord/test/cases/tasks/postgresql_rake_test.rb +++ b/activerecord/test/cases/tasks/postgresql_rake_test.rb @@ -138,11 +138,9 @@ def test_create_when_database_exists_outputs_info_to_stderr end private - def with_stubbed_connection_establish_connection + def with_stubbed_connection_establish_connection(&block) ActiveRecord::Base.stub(:connection, @connection) do - ActiveRecord::Base.stub(:establish_connection, nil) do - yield - end + ActiveRecord::Base.stub(:establish_connection, nil, &block) end end end @@ -199,11 +197,9 @@ def test_when_database_dropped_successfully_outputs_info_to_stdout end private - def with_stubbed_connection_establish_connection + def with_stubbed_connection_establish_connection(&block) ActiveRecord::Base.stub(:connection, @connection) do - ActiveRecord::Base.stub(:establish_connection, nil) do - yield - end + ActiveRecord::Base.stub(:establish_connection, nil, &block) end end end @@ -297,10 +293,8 @@ def test_establishes_connection end private - def with_stubbed_connection - ActiveRecord::Base.stub(:connection, @connection) do - yield - end + def with_stubbed_connection(&block) + ActiveRecord::Base.stub(:connection, @connection, &block) end end diff --git a/activerecord/test/cases/test_case.rb b/activerecord/test/cases/test_case.rb index b101a3020befc..2c110e8046c00 100644 --- a/activerecord/test/cases/test_case.rb +++ b/activerecord/test/cases/test_case.rb @@ -37,8 +37,8 @@ def capture_sql SQLCounter.log.dup end - def assert_sql(*patterns_to_match) - capture_sql { yield } + def assert_sql(*patterns_to_match, &block) + capture_sql(&block) ensure failed_patterns = [] patterns_to_match.each do |pattern| diff --git a/activestorage/test/models/attachment_test.rb b/activestorage/test/models/attachment_test.rb index 66c973c502f32..a4f828ae206db 100644 --- a/activestorage/test/models/attachment_test.rb +++ b/activestorage/test/models/attachment_test.rb @@ -156,7 +156,7 @@ def assert_blob_identified_before_owner_validated(owner, blob, content_type) assert_equal content_type, blob.reload.content_type end - def assert_blob_identified_outside_transaction(blob) + def assert_blob_identified_outside_transaction(blob, &block) baseline_transaction_depth = ActiveRecord::Base.connection.open_transactions max_transaction_depth = -1 @@ -164,9 +164,7 @@ def assert_blob_identified_outside_transaction(blob) max_transaction_depth = [ActiveRecord::Base.connection.open_transactions, max_transaction_depth].max end - blob.stub(:identify_without_saving, track_transaction_depth) do - yield - end + blob.stub(:identify_without_saving, track_transaction_depth, &block) assert_equal 0, (max_transaction_depth - baseline_transaction_depth) end diff --git a/activesupport/lib/active_support/benchmarkable.rb b/activesupport/lib/active_support/benchmarkable.rb index abd0d59d9ee5a..4060784f6756c 100644 --- a/activesupport/lib/active_support/benchmarkable.rb +++ b/activesupport/lib/active_support/benchmarkable.rb @@ -34,13 +34,13 @@ module Benchmarkable # <% benchmark 'Process data files', level: :info, silence: true do %> # <%= expensive_and_chatty_files_operation %> # <% end %> - def benchmark(message = "Benchmarking", options = {}) + def benchmark(message = "Benchmarking", options = {}, &block) if logger options.assert_valid_keys(:level, :silence) options[:level] ||= :info result = nil - ms = Benchmark.ms { result = options[:silence] ? logger.silence { yield } : yield } + ms = Benchmark.ms { result = options[:silence] ? logger.silence(&block) : yield } logger.public_send(options[:level], "%s (%.1fms)" % [ message, ms ]) result else diff --git a/activesupport/lib/active_support/cache/strategy/local_cache.rb b/activesupport/lib/active_support/cache/strategy/local_cache.rb index 5224eb0841c9c..20b08e494e391 100644 --- a/activesupport/lib/active_support/cache/strategy/local_cache.rb +++ b/activesupport/lib/active_support/cache/strategy/local_cache.rb @@ -66,8 +66,8 @@ def fetch_entry(key) # :nodoc: end # Use a local cache for the duration of block. - def with_local_cache - use_temporary_local_cache(LocalStore.new) { yield } + def with_local_cache(&block) + use_temporary_local_cache(LocalStore.new, &block) end # Middleware class can be inserted as a Rack handler to be local cache for the @@ -170,8 +170,8 @@ def local_cache LocalCacheRegistry.cache_for(local_cache_key) end - def bypass_local_cache - use_temporary_local_cache(nil) { yield } + def bypass_local_cache(&block) + use_temporary_local_cache(nil, &block) end def use_temporary_local_cache(temporary_cache) diff --git a/activesupport/lib/active_support/concurrency/load_interlock_aware_monitor.rb b/activesupport/lib/active_support/concurrency/load_interlock_aware_monitor.rb index 480c34c640170..9af2bd94b809a 100644 --- a/activesupport/lib/active_support/concurrency/load_interlock_aware_monitor.rb +++ b/activesupport/lib/active_support/concurrency/load_interlock_aware_monitor.rb @@ -17,14 +17,12 @@ def mon_enter ActiveSupport::Dependencies.interlock.permit_concurrent_loads { super } end - def synchronize + def synchronize(&block) Thread.handle_interrupt(EXCEPTION_NEVER) do mon_enter begin - Thread.handle_interrupt(EXCEPTION_IMMEDIATE) do - yield - end + Thread.handle_interrupt(EXCEPTION_IMMEDIATE, &block) ensure mon_exit end diff --git a/activesupport/lib/active_support/concurrency/share_lock.rb b/activesupport/lib/active_support/concurrency/share_lock.rb index eae7d4469fd2a..fef87c74985b3 100644 --- a/activesupport/lib/active_support/concurrency/share_lock.rb +++ b/activesupport/lib/active_support/concurrency/share_lock.rb @@ -215,9 +215,9 @@ def eligible_waiters?(compatible) @waiting.any? { |t, (p, _)| compatible.include?(p) && @waiting.all? { |t2, (_, c2)| t == t2 || c2.include?(p) } } end - def wait_for(method) + def wait_for(method, &block) @sleeping[Thread.current] = method - @cv.wait_while { yield } + @cv.wait_while(&block) ensure @sleeping.delete Thread.current end diff --git a/activesupport/lib/active_support/core_ext/array/grouping.rb b/activesupport/lib/active_support/core_ext/array/grouping.rb index 67e760bc4b080..36993e01dc148 100644 --- a/activesupport/lib/active_support/core_ext/array/grouping.rb +++ b/activesupport/lib/active_support/core_ext/array/grouping.rb @@ -19,7 +19,7 @@ class Array # ["1", "2"] # ["3", "4"] # ["5"] - def in_groups_of(number, fill_with = nil) + def in_groups_of(number, fill_with = nil, &block) if number.to_i <= 0 raise ArgumentError, "Group size must be a positive integer, was #{number.inspect}" @@ -36,7 +36,7 @@ def in_groups_of(number, fill_with = nil) end if block_given? - collection.each_slice(number) { |slice| yield(slice) } + collection.each_slice(number, &block) else collection.each_slice(number).to_a end @@ -59,7 +59,7 @@ def in_groups_of(number, fill_with = nil) # ["1", "2", "3"] # ["4", "5"] # ["6", "7"] - def in_groups(number, fill_with = nil) + def in_groups(number, fill_with = nil, &block) # size.div number gives minor group size; # size % number gives how many objects need extra accommodation; # each group hold either division or division + 1 items. @@ -79,7 +79,7 @@ def in_groups(number, fill_with = nil) end if block_given? - groups.each { |g| yield(g) } + groups.each(&block) else groups end @@ -90,11 +90,11 @@ def in_groups(number, fill_with = nil) # # [1, 2, 3, 4, 5].split(3) # => [[1, 2], [4, 5]] # (1..10).to_a.split { |i| i % 3 == 0 } # => [[1, 2], [4, 5], [7, 8], [10]] - def split(value = nil) + def split(value = nil, &block) arr = dup result = [] if block_given? - while (idx = arr.index { |i| yield i }) + while (idx = arr.index(&block)) result << arr.shift(idx) arr.shift end diff --git a/activesupport/lib/active_support/core_ext/kernel/reporting.rb b/activesupport/lib/active_support/core_ext/kernel/reporting.rb index 9155bd6c10a92..1ae1ae8e48574 100644 --- a/activesupport/lib/active_support/core_ext/kernel/reporting.rb +++ b/activesupport/lib/active_support/core_ext/kernel/reporting.rb @@ -11,14 +11,14 @@ module Kernel # end # # noisy_call # warning voiced - def silence_warnings - with_warnings(nil) { yield } + def silence_warnings(&block) + with_warnings(nil, &block) end # Sets $VERBOSE to +true+ for the duration of the block and back to its # original value afterwards. - def enable_warnings - with_warnings(true) { yield } + def enable_warnings(&block) + with_warnings(true, &block) end # Sets $VERBOSE for the duration of the block and back to its original diff --git a/activesupport/lib/active_support/dependencies.rb b/activesupport/lib/active_support/dependencies.rb index 7535aab76cd88..bb1fc4697f90d 100644 --- a/activesupport/lib/active_support/dependencies.rb +++ b/activesupport/lib/active_support/dependencies.rb @@ -14,22 +14,22 @@ module Dependencies # :nodoc: # Execute the supplied block without interference from any # concurrent loads. - def self.run_interlock - interlock.running { yield } + def self.run_interlock(&block) + interlock.running(&block) end # Execute the supplied block while holding an exclusive lock, # preventing any other thread from being inside a #run_interlock # block at the same time. - def self.load_interlock - interlock.loading { yield } + def self.load_interlock(&block) + interlock.loading(&block) end # Execute the supplied block while holding an exclusive lock, # preventing any other thread from being inside a #run_interlock # block at the same time. - def self.unload_interlock - interlock.unloading { yield } + def self.unload_interlock(&block) + interlock.unloading(&block) end # :nodoc: diff --git a/activesupport/lib/active_support/dependencies/interlock.rb b/activesupport/lib/active_support/dependencies/interlock.rb index 78852dea6ce7e..e0e32e821c918 100644 --- a/activesupport/lib/active_support/dependencies/interlock.rb +++ b/activesupport/lib/active_support/dependencies/interlock.rb @@ -9,16 +9,12 @@ def initialize # :nodoc: @lock = ActiveSupport::Concurrency::ShareLock.new end - def loading - @lock.exclusive(purpose: :load, compatible: [:load], after_compatible: [:load]) do - yield - end + def loading(&block) + @lock.exclusive(purpose: :load, compatible: [:load], after_compatible: [:load], &block) end - def unloading - @lock.exclusive(purpose: :unload, compatible: [:load, :unload], after_compatible: [:load, :unload]) do - yield - end + def unloading(&block) + @lock.exclusive(purpose: :unload, compatible: [:load, :unload], after_compatible: [:load, :unload], &block) end def start_unloading @@ -37,16 +33,12 @@ def done_running @lock.stop_sharing end - def running - @lock.sharing do - yield - end + def running(&block) + @lock.sharing(&block) end - def permit_concurrent_loads - @lock.yield_shares(compatible: [:load]) do - yield - end + def permit_concurrent_loads(&block) + @lock.yield_shares(compatible: [:load], &block) end def raw_state(&block) # :nodoc: diff --git a/activesupport/lib/active_support/test_case.rb b/activesupport/lib/active_support/test_case.rb index 1a60f8b9b360d..a2b205c14bb88 100644 --- a/activesupport/lib/active_support/test_case.rb +++ b/activesupport/lib/active_support/test_case.rb @@ -99,9 +99,7 @@ def parallelize(workers: :number_of_processors, with: :processes, threshold: Act # end # end def parallelize_setup(&block) - ActiveSupport::Testing::Parallelization.after_fork_hook do |worker| - yield worker - end + ActiveSupport::Testing::Parallelization.after_fork_hook(&block) end # Clean up hook for parallel testing. This can be used to drop databases @@ -118,9 +116,7 @@ def parallelize_setup(&block) # end # end def parallelize_teardown(&block) - ActiveSupport::Testing::Parallelization.run_cleanup_hook do |worker| - yield worker - end + ActiveSupport::Testing::Parallelization.run_cleanup_hook(&block) end end diff --git a/activesupport/lib/active_support/testing/method_call_assertions.rb b/activesupport/lib/active_support/testing/method_call_assertions.rb index 4854b8786900c..1d016b096a849 100644 --- a/activesupport/lib/active_support/testing/method_call_assertions.rb +++ b/activesupport/lib/active_support/testing/method_call_assertions.rb @@ -6,10 +6,10 @@ module ActiveSupport module Testing module MethodCallAssertions # :nodoc: private - def assert_called(object, method_name, message = nil, times: 1, returns: nil) + def assert_called(object, method_name, message = nil, times: 1, returns: nil, &block) times_called = 0 - object.stub(method_name, proc { times_called += 1; returns }) { yield } + object.stub(method_name, proc { times_called += 1; returns }, &block) error = "Expected #{method_name} to be called #{times} times, " \ "but was called #{times_called} times" @@ -17,7 +17,7 @@ def assert_called(object, method_name, message = nil, times: 1, returns: nil) assert_equal times, times_called, error end - def assert_called_with(object, method_name, args, returns: nil) + def assert_called_with(object, method_name, args, returns: nil, &block) mock = Minitest::Mock.new if args.all?(Array) @@ -26,7 +26,7 @@ def assert_called_with(object, method_name, args, returns: nil) mock.expect(:call, returns, args) end - object.stub(method_name, mock) { yield } + object.stub(method_name, mock, &block) mock.verify end diff --git a/activesupport/lib/active_support/testing/stream.rb b/activesupport/lib/active_support/testing/stream.rb index 76e0c3414219a..55017d3535989 100644 --- a/activesupport/lib/active_support/testing/stream.rb +++ b/activesupport/lib/active_support/testing/stream.rb @@ -14,11 +14,9 @@ def silence_stream(stream) old_stream.close end - def quietly + def quietly(&block) silence_stream(STDOUT) do - silence_stream(STDERR) do - yield - end + silence_stream(STDERR, &block) end end diff --git a/activesupport/test/core_ext/enumerable_test.rb b/activesupport/test/core_ext/enumerable_test.rb index b5279079c8f5d..202da47321fe9 100644 --- a/activesupport/test/core_ext/enumerable_test.rb +++ b/activesupport/test/core_ext/enumerable_test.rb @@ -19,8 +19,8 @@ def initialize(values = [1, 2, 3]) @values = values end - def each - @values.each { |v| yield v } + def each(&block) + @values.each(&block) end end diff --git a/railties/lib/rails/mailers_controller.rb b/railties/lib/rails/mailers_controller.rb index 0627153ae48dd..29586a0f9d098 100644 --- a/railties/lib/rails/mailers_controller.rb +++ b/railties/lib/rails/mailers_controller.rb @@ -93,9 +93,7 @@ def locale_query(locale) request.query_parameters.merge(locale: locale).to_query end - def set_locale - I18n.with_locale(params[:locale] || I18n.default_locale) do - yield - end + def set_locale(&block) + I18n.with_locale(params[:locale] || I18n.default_locale, &block) end end diff --git a/railties/test/commands/dbconsole_test.rb b/railties/test/commands/dbconsole_test.rb index 1d87df3cd3f4f..cb420572fb3f1 100644 --- a/railties/test/commands/dbconsole_test.rb +++ b/railties/test/commands/dbconsole_test.rb @@ -293,10 +293,8 @@ def test_print_help_long private :aborted, :output private - def app_db_config(results) - Rails.application.config.stub(:database_configuration, results || {}) do - yield - end + def app_db_config(results, &block) + Rails.application.config.stub(:database_configuration, results || {}, &block) end def make_dbconsole diff --git a/railties/test/env_helpers.rb b/railties/test/env_helpers.rb index e3157e0c779e2..a9b4d98f80663 100644 --- a/railties/test/env_helpers.rb +++ b/railties/test/env_helpers.rb @@ -4,21 +4,17 @@ module EnvHelpers private - def with_rails_env(env) + def with_rails_env(env, &block) Rails.instance_variable_set :@_env, nil switch_env "RAILS_ENV", env do - switch_env "RACK_ENV", nil do - yield - end + switch_env "RACK_ENV", nil, &block end end - def with_rack_env(env) + def with_rack_env(env, &block) Rails.instance_variable_set :@_env, nil switch_env "RACK_ENV", env do - switch_env "RAILS_ENV", nil do - yield - end + switch_env "RAILS_ENV", nil, &block end end diff --git a/railties/test/generators/app_generator_test.rb b/railties/test/generators/app_generator_test.rb index bd9432f2720ae..5bb6eae244f54 100644 --- a/railties/test/generators/app_generator_test.rb +++ b/railties/test/generators/app_generator_test.rb @@ -1026,11 +1026,9 @@ def test_minimal_rails_app end private - def stub_rails_application(root) + def stub_rails_application(root, &block) Rails.application.config.root = root - Rails.application.class.stub(:name, "Myapp") do - yield - end + Rails.application.class.stub(:name, "Myapp", &block) end def action(*args, &block)